Subversion Repositories SmartDukaan

Rev

Rev 9242 | Rev 9299 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
94 ashish 1
'''
2
Created on 23-Mar-2010
3
 
4
@author: ashish
5
'''
6
from elixir import *
5393 mandeep.dh 7
from functools import partial
5944 mandeep.dh 8
from shop2020.clients.CatalogClient import CatalogClient
4748 mandeep.dh 9
from shop2020.clients.HelperClient import HelperClient
5944 mandeep.dh 10
from shop2020.clients.InventoryClient import InventoryClient
4748 mandeep.dh 11
from shop2020.config.client.ConfigClient import ConfigClient
94 ashish 12
from shop2020.model.v1.catalog.impl import DataService
4748 mandeep.dh 13
from shop2020.model.v1.catalog.impl.CategoryManager import CategoryManager
8274 amit.gupta 14
from shop2020.model.v1.catalog.impl.Convertors import to_t_item, to_t_source, \
15
    to_t_brand_info
5944 mandeep.dh 16
from shop2020.model.v1.catalog.impl.DataService import Item, ItemChangeLog, \
17
    Category, EntityIDGenerator, SimilarItems, ProductNotification, Source, \
6531 vikram.rag 18
    SourceItemPricing, AuthorizationLog, VoucherItemMapping, CategoryVatMaster, \
7340 amit.gupta 19
    OOSTracker, EntityTag, ItemInsurerMapping, Insurer, Banner, BannerMap, \
7977 kshitij.so 20
    FreebieItem, BrandInfo, Amazonlisted, StorePricing, ItemVatMaster, \
9242 kshitij.so 21
    PageViewEvents, CartEvents, EbayItem, BannerUriMapping, Campaign, SnapdealItem, \
22
    SnapdealItemUpdateHistory
5944 mandeep.dh 23
from shop2020.thriftpy.model.v1.catalog.ttypes import status, ItemShippingInfo, \
7340 amit.gupta 24
    ItemType, PremiumType, FreebieItem as t_FreebieItem, \
9155 kshitij.so 25
    StorePricing as tStorePricing, CatalogServiceException, \
26
    BannerType
5944 mandeep.dh 27
from shop2020.thriftpy.model.v1.inventory.ttypes import \
6531 vikram.rag 28
    InventoryServiceException, IgnoredInventoryUpdateItems
4873 mandeep.dh 29
from shop2020.utils import EmailAttachmentSender
4748 mandeep.dh 30
from shop2020.utils.EmailAttachmentSender import mail
5318 rajveer 31
from shop2020.utils.Utils import to_py_date, log_risky_flag
621 chandransh 32
from sqlalchemy import desc, asc
6039 amit.gupta 33
from sqlalchemy.sql.expression import or_, distinct, func, and_
3086 rajveer 34
from string import Template
4748 mandeep.dh 35
import datetime
8274 amit.gupta 36
import math
4748 mandeep.dh 37
import sys
5393 mandeep.dh 38
import threading
3924 rajveer 39
import urllib2
94 ashish 40
 
5978 rajveer 41
sourceId = int(ConfigClient().get_property("sourceid"))
7777 kshitij.so 42
to_addresses = ["khushal.bhatia@shop2020.in", "chandan.kumar@shop2020.in",  "chaitnaya.vats@shop2020.in"]
43
to_store_addresses = ["rajveer.singh@shop2020.in"]
6029 rajveer 44
mail_user = "cnc.center@shop2020.in"
45
mail_password = "5h0p2o2o"
46
source_name = "Saholic"
47
source_url = "www.saholic.com"
5885 mandeep.dh 48
skippedItems = { 175 : [27, 2160, 2175, 2163, 2158, 7128, 26, 2154],
49
                 193 : [5839] }
5047 amit.gupta 50
 
5295 rajveer 51
def initialize(dbname='catalog', db_hostname="localhost"):
52
    DataService.initialize(dbname, db_hostname)
7770 kshitij.so 53
 
3849 chandransh 54
def get_all_items_by_status(status, offset=0, limit=None):
55
    query = Item.query
4539 rajveer 56
    if status is not None:
3849 chandransh 57
        query = query.filter_by(status=status)
58
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
59
    if limit:
60
        query = query.limit(limit)
61
    items = query.all()
62
    return items
63
 
6821 amar.kumar 64
def get_all_alive_items():
65
    query = Item.query
7095 amar.kumar 66
    query = query.filter(or_(Item.status==status.ACTIVE, Item.status==status.PAUSED, Item.status==status.PAUSED_BY_RISK))
6821 amar.kumar 67
    items = query.all()
68
    return items
69
 
70
 
3849 chandransh 71
def get_all_items(is_active, offset=0, limit=None):
103 ashish 72
    if is_active:
3849 chandransh 73
        items = get_all_items_by_status(status.ACTIVE, offset, limit)
103 ashish 74
    else:
3849 chandransh 75
        items = get_all_items_by_status(None, offset, limit)
766 rajveer 76
    return items
77
 
3849 chandransh 78
def get_item_count_by_status(use_status, status):
79
    if use_status:
80
        return Item.query.filter_by(status=status).count()
103 ashish 81
    else:
3849 chandransh 82
        return Item.query.count()
103 ashish 83
 
635 rajveer 84
def get_item(item_id):
766 rajveer 85
    item = Item.get_by(id=item_id)
86
    return item
94 ashish 87
 
635 rajveer 88
def get_items_by_catalog_id(catalog_id):
447 rajveer 89
    query = Item.query.filter_by(catalog_item_id=catalog_id)
437 rajveer 90
    try:
635 rajveer 91
        items = query.all()
4934 amit.gupta 92
        return items
1399 rajveer 93
    except Exception as ex:
94
        print ex
437 rajveer 95
        raise InventoryServiceException(109, "Item not found")
5586 phani.kuma 96
 
97
def is_valid_catalog_id(catalog_id):
98
    item = Item.query.filter_by(catalog_item_id=catalog_id).first()
99
    if item is not None:
100
        return True
101
    else:
102
        return False
103
 
576 chandransh 104
def is_active(item_id):
2983 chandransh 105
    t_item_shipping_info = ItemShippingInfo()
576 chandransh 106
    try:
635 rajveer 107
        item = get_item(item_id)
3281 chandransh 108
        t_item_shipping_info.isRisky = item.risky
5944 mandeep.dh 109
        client = InventoryClient().get_client()
5978 rajveer 110
        itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)
5944 mandeep.dh 111
        warehouse_id = itemInfo[0]
5393 mandeep.dh 112
        if item.risky and item.status == status.ACTIVE:
5944 mandeep.dh 113
            availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item_id)
114
            if availability <= 0:
5393 mandeep.dh 115
                add_status_change_log(item, status.PAUSED_BY_RISK)
116
                item.status = status.PAUSED_BY_RISK
117
                item.status_description = "This item is currently out of stock"
118
                session.commit()
119
                __send_mail_for_oos_item(item)
120
                #This will clear cache from tomcat
121
                __clear_homepage_cache()
122
        else:
5944 mandeep.dh 123
            availability = itemInfo[4]
2983 chandransh 124
        t_item_shipping_info.isActive = (item.status == status.ACTIVE)
3281 chandransh 125
        t_item_shipping_info.quantity = availability
576 chandransh 126
    except InventoryServiceException:
2983 chandransh 127
        print "[ERROR] Unexpected error:", sys.exc_info()[0]
128
    return t_item_shipping_info
129
 
7438 amit.gupta 130
def get_items_status(item_ids):
131
    itemsStatus = dict()
132
    for item_id in item_ids:
133
        try:
134
            item = get_item(item_id)
7520 amit.gupta 135
            if item is None:
136
                continue
7438 amit.gupta 137
            client = InventoryClient().get_client()
138
            itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)
139
            warehouse_id = itemInfo[0]
140
            if item.risky and item.status == status.ACTIVE:
141
                availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item_id)
142
                if availability <= 0:
143
                    item.status = status.PAUSED_BY_RISK
144
            itemsStatus[item_id] = (item.status == status.ACTIVE)
145
        except InventoryServiceException:
146
            print "[ERROR] Unexpected error:", sys.exc_info()[0]
147
    return itemsStatus
148
 
2035 rajveer 149
def get_item_status_description(itemId):
150
    item = get_item(itemId)
151
    return item.status_description
94 ashish 152
 
122 ashish 153
def update_item(item):
154
    if not item:
155
        raise InventoryServiceException(108, "Bad item in request")
7770 kshitij.so 156
 
122 ashish 157
    if not item.id:
609 chandransh 158
        raise InventoryServiceException(101, "Missing id for update")
7770 kshitij.so 159
 
2120 ankur.sing 160
    validate_item_prices(item)
7770 kshitij.so 161
 
635 rajveer 162
    ds_item = get_item(item.id)
5047 amit.gupta 163
    message = ""
7384 rajveer 164
    store_message = ""
122 ashish 165
    if not ds_item:
609 chandransh 166
        raise InventoryServiceException(101, "Item missing in our database")
7770 kshitij.so 167
 
963 chandransh 168
    if item.productGroup:
7770 kshitij.so 169
        ds_item.product_group = item.productGroup
963 chandransh 170
    if item.brand:
171
        ds_item.brand = item.brand
511 rajveer 172
    if item.modelNumber:
173
        ds_item.model_number = item.modelNumber
2497 ankur.sing 174
    ds_item.color = item.color
175
    ds_item.model_name = item.modelName
176
    ds_item.category = item.category
9253 rajveer 177
    if item.category == 10006:
6903 anupam.sin 178
        ds_item.preferredInsurer = 1
7770 kshitij.so 179
 
2497 ankur.sing 180
    ds_item.comments = item.comments
7770 kshitij.so 181
 
2497 ankur.sing 182
    ds_item.catalog_item_id = item.catalogItemId
483 rajveer 183
 
7384 rajveer 184
    if ds_item.activeOnStore and ds_item.mrp and item.mrp and ds_item.mrp != item.mrp:
185
        sp = get_store_pricing(item.id)
186
        if sp.maxPrice > item.mrp:
187
            sp.maxPrice = item.mrp
188
            store_message += "MRP is changed from {0} to {1}.\n".format(sp.maxPrice, item.mrp)
7770 kshitij.so 189
 
7384 rajveer 190
 
191
    if ds_item.activeOnStore and ds_item.sellingPrice and item.sellingPrice and ds_item.sellingPrice != item.sellingPrice:
192
        sp = get_store_pricing(item.id)
193
        if sp.minPrice < item.sellingPrice:
194
            store_message += "Saholic MOP Changed. DP {0} is less than Saholic MOP.\n".format(sp.minPrice)
7770 kshitij.so 195
 
2129 ankur.sing 196
    ds_item.mrp = item.mrp
5047 amit.gupta 197
    if ds_item.sellingPrice or item.sellingPrice:
198
        if ds_item.sellingPrice != item.sellingPrice:
7761 kshitij.so 199
            amazonItem = get_amazon_item_details(item.id)
200
            if amazonItem is not None:
201
                amazonItem.fbaPrice = item.sellingPrice
202
                amazonItem.sellingPrice=item.sellingPrice
7770 kshitij.so 203
                amazonItem.mfnPriceLastUpdatedOn = datetime.datetime.now()
204
                amazonItem.fbaPriceLastUpdatedOn = datetime.datetime.now()
7774 kshitij.so 205
                message +="Amazon Prices Synced."
5047 amit.gupta 206
            message += "Selling Price is changed from {0} to {1}.\n".format(ds_item.sellingPrice, item.sellingPrice)
7770 kshitij.so 207
 
2129 ankur.sing 208
    ds_item.sellingPrice = item.sellingPrice
2174 ankur.sing 209
    ds_item.weight = item.weight
6241 amit.gupta 210
    ds_item.showSellingPrice = item.showSellingPrice
7770 kshitij.so 211
 
7291 vikram.rag 212
    if item.asin:
213
        ds_item.asin = item.asin
214
    ds_item.holdInventory = item.holdInventory
215
    ds_item.defaultInventory = item.defaultInventory
7770 kshitij.so 216
 
6826 amit.gupta 217
    if item.startDate:
218
        ds_item.startDate = to_py_date(item.startDate)
219
        ds_item.startDate = ds_item.startDate.replace(hour=0,second=0,minute=0)
220
        if item.itemStatus == status.COMING_SOON and ds_item.startDate < datetime.datetime.now()  :
221
            item.itemStatus = status.ACTIVE
222
            item.status_description = "This item is active"
223
    else:
224
        ds_item.startDate = None
225
 
2358 ankur.sing 226
    if ds_item.status != item.itemStatus:
2402 rajveer 227
        add_status_change_log(ds_item, item.itemStatus)
5047 amit.gupta 228
        if item.itemStatus == status.PHASED_OUT:
229
            message += "Item is phased out."
2358 ankur.sing 230
        ds_item.status = item.itemStatus
2035 rajveer 231
    if item.status_description:
232
        ds_item.status_description = item.status_description
7770 kshitij.so 233
 
511 rajveer 234
    if item.retireDate:
2116 ankur.sing 235
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 236
    else:
237
        ds_item.retireDate = None
5217 amit.gupta 238
 
239
    if item.expectedArrivalDate:
240
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)
241
    else:
242
        ds_item.expectedArrivalDate = None
7770 kshitij.so 243
 
5217 amit.gupta 244
    if item.comingSoonStartDate:
245
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
6696 rajveer 246
        ds_item.comingSoonStartDate = ds_item.comingSoonStartDate.replace(hour=0,second=0,minute=0)
5217 amit.gupta 247
    else:
248
        ds_item.comingSoonStartDate = None
7770 kshitij.so 249
 
250
 
2497 ankur.sing 251
    ds_item.feature_id = item.featureId
252
    ds_item.feature_description = item.featureDescription
7770 kshitij.so 253
 
5047 amit.gupta 254
    if ds_item.bestDealText or item.bestDealText:
255
        if item.bestDealText != ds_item.bestDealText:
5080 amit.gupta 256
            message += "Promotion text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealText, item.bestDealText)
2129 ankur.sing 257
    ds_item.bestDealText = item.bestDealText
258
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 259
    ds_item.bestSellingRank = item.bestSellingRank
7770 kshitij.so 260
 
6777 vikram.rag 261
    if ds_item.bestDealsDetailsText or item.bestDealsDetailsText:
262
        if item.bestDealsDetailsText != ds_item.bestDealsDetailsText:
263
            message += "Best deals details text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealsDetailsText, item.bestDealsDetailsText)
264
    ds_item.bestDealsDetailsText = item.bestDealsDetailsText
7770 kshitij.so 265
 
6777 vikram.rag 266
    if ds_item.bestDealsDetailsLink or item.bestDealsDetailsLink:
267
        if item.bestDealsDetailsLink != ds_item.bestDealsDetailsLink:
268
            message += "Best deals details link is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealsDetailsLink, item.bestDealsDetailsLink)
269
    ds_item.bestDealsDetailsLink = item.bestDealsDetailsLink
7770 kshitij.so 270
 
271
 
2065 ankur.sing 272
    ds_item.defaultForEntity = item.defaultForEntity
7770 kshitij.so 273
 
5047 amit.gupta 274
    if ds_item.risky or item.risky:
275
        if ds_item.risky != item.risky:
5080 amit.gupta 276
            message += "Risky flag is changed to '{0}'.\n".format(set)
7770 kshitij.so 277
 
2251 ankur.sing 278
    ds_item.risky = item.risky
7770 kshitij.so 279
 
5385 phani.kuma 280
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
281
    ds_item.hasItemNo = item.hasItemNo
7770 kshitij.so 282
 
3459 chandransh 283
    if item.expectedDelay is not None:
3359 chandransh 284
        ds_item.expectedDelay = item.expectedDelay
7770 kshitij.so 285
 
4506 phani.kuma 286
    if item.preferredVendor:
5080 amit.gupta 287
        if item.preferredVendor != ds_item.preferredVendor:
5944 mandeep.dh 288
            inventoryClient = InventoryClient().get_client()
289
            newPreferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
5080 amit.gupta 290
            oldPreferredVendorName = 'None'
291
            if ds_item.preferredVendor:
5944 mandeep.dh 292
                oldPreferredVendorName = inventoryClient.getVendor(ds_item.preferredVendor).name
7770 kshitij.so 293
            message += "Preferred vendor is changed from '{0}' to '{1}'.\n".format(oldPreferredVendorName, newPreferredVendorName)       
4506 phani.kuma 294
        ds_item.preferredVendor = item.preferredVendor
7770 kshitij.so 295
 
5080 amit.gupta 296
    if item.isWarehousePreferenceSticky != ds_item.isWarehousePreferenceSticky:
297
        flag = "ON" if item.isWarehousePreferenceSticky else "OFF"
298
        message += "Warehouse preference sticky is {0}.\n".format(flag)
299
 
4413 anupam.sin 300
    ds_item.isWarehousePreferenceSticky = item.isWarehousePreferenceSticky
7770 kshitij.so 301
 
7296 amit.gupta 302
    ds_item.updatedOn = datetime.datetime.now()
7770 kshitij.so 303
 
7382 rajveer 304
 
7519 rajveer 305
    ds_item.activeOnStore = item.activeOnStore
122 ashish 306
    session.commit();
8867 rajveer 307
 
308
#    subject = "Item '{0}' is updated in Catalog. Id is {1}".format(__get_product_name(ds_item),ds_item.id)
309
#    if message:
310
#        __send_mail(subject, message)
311
#    if store_message:
312
#        __send_mail(subject, store_message, to_store_addresses)
313
 
122 ashish 314
    return ds_item.id
94 ashish 315
 
103 ashish 316
def add_item(item):
317
    if not item:
122 ashish 318
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 319
    if get_item(item.id):
122 ashish 320
        raise InventoryServiceException(101, "Item already exists")
7770 kshitij.so 321
 
2120 ankur.sing 322
    validate_item_prices(item)
7770 kshitij.so 323
 
103 ashish 324
    ds_item = Item()
963 chandransh 325
    if item.productGroup:
326
        ds_item.product_group = item.productGroup
327
    if item.brand:
328
        ds_item.brand = item.brand
515 rajveer 329
    if item.modelName:
330
        ds_item.model_name = item.modelName
331
    if item.modelNumber:
332
        ds_item.model_number = item.modelNumber
609 chandransh 333
    if item.color:
334
        ds_item.color = item.color
483 rajveer 335
    if item.category:
336
        ds_item.category = item.category
337
    if item.comments:
338
        ds_item.comments = item.comments
7291 vikram.rag 339
    if item.asin:
340
        ds_item.asin = item.asin
341
    ds_item.holdInventory = item.holdInventory
7770 kshitij.so 342
    ds_item.defaultInventory = item.defaultInventory   
7296 amit.gupta 343
    ds_item.addedOn = datetime.datetime.now()
344
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 345
    if item.startDate:
346
        ds_item.startDate = to_py_date(item.startDate)
6696 rajveer 347
        ds_item.startDate = ds_item.startDate.replace(hour=0,second=0,minute=0)
2116 ankur.sing 348
    if item.retireDate:
349
        ds_item.retireDate = to_py_date(item.retireDate)
5217 amit.gupta 350
    if item.comingSoonStartDate:
351
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
352
    if item.expectedArrivalDate:
7770 kshitij.so 353
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)   
483 rajveer 354
    if item.mrp:
355
        ds_item.mrp = item.mrp
356
    if item.sellingPrice:
357
        ds_item.sellingPrice = item.sellingPrice
122 ashish 358
    if item.weight:
359
        ds_item.weight = item.weight
7770 kshitij.so 360
 
122 ashish 361
    if item.featureId:
362
        ds_item.feature_id = item.featureId
363
    if item.featureDescription:
364
        ds_item.feature_description = item.featureDescription
7770 kshitij.so 365
 
366
 
103 ashish 367
    #check if categories present. If yes, add them to system
7770 kshitij.so 368
 
609 chandransh 369
    if item.bestDealValue:
370
        ds_item.bestDealValue = item.bestDealValue
371
    if item.bestDealText:
372
        ds_item.bestDealText = item.bestDealText
6777 vikram.rag 373
    if item.bestDealsDetailsText:
374
        ds_item.bestDealsDetailsText = item.bestDealsDetailsText
375
    if item.bestDealsDetailsLink:
7770 kshitij.so 376
        ds_item.bestDealsDetailsLink = item.bestDealsDetailsLink   
2116 ankur.sing 377
    if item.bestSellingRank:
378
        ds_item.bestSellingRank = item.bestSellingRank
379
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 380
    ds_item.risky = item.risky
7770 kshitij.so 381
 
5385 phani.kuma 382
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
383
    ds_item.hasItemNo = item.hasItemNo
7256 rajveer 384
    ds_item.activeOnStore = item.activeOnStore
7770 kshitij.so 385
 
3467 chandransh 386
    if item.expectedDelay is not None:
3359 chandransh 387
        ds_item.expectedDelay = item.expectedDelay
3467 chandransh 388
    else:
389
        ds_item.expectedDelay = 0
7770 kshitij.so 390
 
5408 amit.gupta 391
    preferredVendorName = "None"
4881 phani.kuma 392
    if item.preferredVendor:
393
        ds_item.preferredVendor = item.preferredVendor
5944 mandeep.dh 394
        inventoryClient = InventoryClient().get_client()
6838 vikram.rag 395
        preferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
7770 kshitij.so 396
 
6838 vikram.rag 397
    if item.preferredInsurer is not None:
7770 kshitij.so 398
        ds_item.preferredInsurer = item.preferredInsurer            
399
 
5586 phani.kuma 400
    if item.catalogItemId:
401
        catalog_client = CatalogClient("catalog_service_server_host_master", "catalog_service_server_port").get_client()
402
        master_items = catalog_client.getItemsByCatalogId(item.catalogItemId)
403
        itemStatus = status.IN_PROCESS
404
        for masterItem in master_items:
405
            if masterItem.itemStatus in [status.CONTENT_COMPLETE, status.COMING_SOON, status.ACTIVE, status.PAUSED]:
406
                itemStatus = status.CONTENT_COMPLETE
407
                ds_item.category = masterItem.category
408
                break
409
        ds_item.catalog_item_id = item.catalogItemId
410
        ds_item.status = itemStatus
2116 ankur.sing 411
        ds_item.status_description = "This item is in process."
412
    else:
5586 phani.kuma 413
        # Check if a similar item already exists in our database
414
        similar_item = Item.query.filter_by(brand=item.brand, model_number=item.modelNumber, model_name=item.modelName).first()
415
        print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2}".format(item.brand, item.modelNumber, item.modelName)
7770 kshitij.so 416
 
5586 phani.kuma 417
        if similar_item is None or similar_item.catalog_item_id is None:
418
            # If there is no similar item in the database from before,
419
            # use the entity_id_generator
420
            entity_id = EntityIDGenerator.query.first()
421
            ds_item.catalog_item_id = entity_id.id + 1
422
            ds_item.status = status.IN_PROCESS
423
            ds_item.status_description = "This item is in process."
424
            entity_id.id = entity_id.id  + 1
425
            if similar_item is not None and similar_item.catalog_item_id is None:
426
                similar_item.catalog_item_id = entity_id.id
427
        else:
428
            #If a similar item already exists for a product group, brand and model_number, set it as same.
429
            ds_item.catalog_item_id = similar_item.catalog_item_id
430
            ds_item.category = similar_item.category
431
            ds_item.product_group = similar_item.product_group
432
            ds_item.status = similar_item.status
433
            ds_item.status_description = similar_item.status_description
7770 kshitij.so 434
 
103 ashish 435
    session.commit();
5052 amit.gupta 436
    subject = "New item is added. Id is {0}".format(str(ds_item.id))
6777 vikram.rag 437
    message = "Category : {6}, Brand : {0}, Model : {1}, Model Number : {2}\nColor : {3}, Selling Price : {4}, Mrp : {5}, \nPromotion Text : {7}, Preferred Vendor: {8}".format(item.brand, item.modelNumber, item.modelName, item.color, item.sellingPrice, item.mrp, item.category, item.bestDealText,item.bestDealsDetailsText,item.bestDealsDetailsLink, preferredVendorName)
5047 amit.gupta 438
    __send_mail(subject, message)
3325 chandransh 439
    return ds_item.id
440
 
103 ashish 441
def retire_item(item_id):
442
    if not item_id:
122 ashish 443
        raise InventoryServiceException(101, "bad item id")
635 rajveer 444
    item = get_item(item_id)
103 ashish 445
    if not item:
122 ashish 446
        raise InventoryServiceException(108, "item id not present")
447
    item.status = status.PHASED_OUT
448
    item.retireDate = datetime.datetime.now()
103 ashish 449
    session.commit()
7770 kshitij.so 450
 
122 ashish 451
#need to implement threads based solution here
103 ashish 452
def start_item_on(item_id, timestamp):
453
    if not item_id:
122 ashish 454
        raise InventoryServiceException(101, "bad item id")
635 rajveer 455
    item = get_item(item_id)
103 ashish 456
    if not item:
122 ashish 457
        raise InventoryServiceException(108, "item id not present")
7770 kshitij.so 458
 
122 ashish 459
    item.status = status.ACTIVE
460
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
461
    add_status_change_log(item, status.ACTIVE)
103 ashish 462
    session.commit()
7770 kshitij.so 463
 
122 ashish 464
#need to implement threads here
103 ashish 465
def retire_item_on(item_id, timestamp):
466
    if not item_id:
122 ashish 467
        raise InventoryServiceException(101, "bad item id")
635 rajveer 468
    item = get_item(item_id)
103 ashish 469
    if not item:
122 ashish 470
        raise InventoryServiceException(108, "item id not present")
7770 kshitij.so 471
 
122 ashish 472
    item.status = status.PHASED_OUT
473
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
474
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 475
    session.commit()
7770 kshitij.so 476
 
103 ashish 477
def add_status_change_log(item, new_status):
478
    item_change_log = ItemChangeLog()
479
    item_change_log.new_status = new_status
480
    item_change_log.old_status = item.status
481
    item_change_log.timestamp = datetime.datetime.now()
482
    item_change_log.item = item
483
    session.commit()
7770 kshitij.so 484
 
103 ashish 485
def change_item_status(item_id, new_status):
486
    if not item_id:
122 ashish 487
        raise InventoryServiceException(101, "bad item id")
635 rajveer 488
    item = get_item(item_id)
103 ashish 489
    if not item:
122 ashish 490
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 491
    add_status_change_log(item, new_status)
122 ashish 492
    item.status = new_status
2251 ankur.sing 493
    if item.status == status.PHASED_OUT:
494
        item.status_description = "This item has been phased out"
5047 amit.gupta 495
        __send_mail("Item '{0}' is Phased-Out. Item id is {1}".format(__get_product_name(item), item_id), "")
2251 ankur.sing 496
    elif item.status == status.DELETED:
497
        item.status_description = "This item has been deleted"
3924 rajveer 498
    elif item.status == status.PAUSED:
7770 kshitij.so 499
        item.status_description = "This item is currently out of stock"     
3924 rajveer 500
    elif item.status == status.PAUSED_BY_RISK:
501
        item.status_description = "This item is currently out of stock"
502
        #This will clear cache from tomcat
7770 kshitij.so 503
        __clear_homepage_cache() 
2251 ankur.sing 504
    elif item.status == status.ACTIVE:
505
        item.status_description = "This item is active"
506
    elif item.status == status.IN_PROCESS:
507
        item.status_description = "This item is in process"
508
    elif item.status == status.CONTENT_COMPLETE:
509
        item.status_description = "This item is in process"
103 ashish 510
    session.commit()
7770 kshitij.so 511
 
5944 mandeep.dh 512
def check_risky_item(item_id):
635 rajveer 513
    item = get_item(item_id)
2251 ankur.sing 514
    if not item.risky:
515
        return
5944 mandeep.dh 516
    client = InventoryClient().get_client()
7770 kshitij.so 517
    itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)   
5944 mandeep.dh 518
    warehouse_id = itemInfo[0]
519
    availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item.id)
520
    if availability <= 0:
2251 ankur.sing 521
        if item.status == status.ACTIVE:
2984 rajveer 522
            change_item_status(item.id, status.PAUSED_BY_RISK)
4797 rajveer 523
            __send_mail_for_oos_item(item)
2251 ankur.sing 524
    else:
2984 rajveer 525
        if item.status == status.PAUSED_BY_RISK:
2251 ankur.sing 526
            change_item_status(item.id, status.ACTIVE)
6255 rajveer 527
            __send_mail_for_active_item(item.id, "Item '{0}' is Active. Item id is {1}".format(__get_product_name(item), item_id), "")
2368 ankur.sing 528
    session.commit()
7770 kshitij.so 529
 
9253 rajveer 530
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber, isAndroid):
2828 rajveer 531
    '''
532
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
533
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
534
    '''
723 chandransh 535
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 536
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 537
    current_timestamp = datetime.datetime.now()
538
    for item in items:
2828 rajveer 539
        if item.status == status.IN_PROCESS:
540
            item.status = content_complete_status
541
            item_change_log = ItemChangeLog()
542
            item_change_log.old_status = item.status
543
            item_change_log.new_status = content_complete_status
544
            item_change_log.timestamp = current_timestamp
545
            item_change_log.item = item
7770 kshitij.so 546
 
4762 phani.kuma 547
        category_object = get_category(category)
548
        if category_object is not None:
549
            item.category = category
550
            item.product_group = category_object.display_name
2075 rajveer 551
        item.brand = brand
2081 rajveer 552
        item.model_name = modelName
553
        item.model_number = modelNumber
723 chandransh 554
        item.updatedOn = current_timestamp
555
    session.commit()
556
    return True
1294 chandransh 557
 
2404 chandransh 558
def get_child_categories(category):
559
    cm = CategoryManager()
2621 varun.gupt 560
    cat = cm.getCategory(category)
561
    return cat.children_category_ids if cat else None
2404 chandransh 562
 
626 chandransh 563
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 564
    '''
565
    Returns the Best Sellers between the start and the stop index in the given category
566
    '''
1926 rajveer 567
    query = get_best_sellers_query(category, None)
1098 chandransh 568
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 569
    return get_thrift_item_list(best_sellers)
570
 
2093 chandransh 571
def get_best_sellers_count(category=-1):
2404 chandransh 572
    '''
573
    Returns the number of best sellers in the given category
574
    '''
1926 rajveer 575
    count = get_best_sellers_query(category, None).count()
1120 rajveer 576
    if count is None:
577
        count = 0
766 rajveer 578
    return count
621 chandransh 579
 
1926 rajveer 580
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 581
    '''
582
    Returns the Best sellers for the given brand and category between the start and the stop index.
7770 kshitij.so 583
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
2404 chandransh 584
    '''
1926 rajveer 585
    query = get_best_sellers_query(category, brand)
1098 chandransh 586
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 587
    return [item.catalog_item_id for item in best_sellers]
7770 kshitij.so 588
 
1926 rajveer 589
def get_best_sellers_query(category, brand):
2404 chandransh 590
    '''
591
    Returns the query to be used for getting Best Sellers.
592
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
593
    '''
1098 chandransh 594
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 595
    if category != -1:
1970 rajveer 596
        all_categories = [category]
597
        child_categories = get_child_categories(category)
598
        if child_categories is not None:
7770 kshitij.so 599
            all_categories = all_categories + child_categories
1970 rajveer 600
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 601
    if brand is not None:
602
        query = query.filter_by(brand=brand)
7202 amit.gupta 603
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.bestSellingRank))
621 chandransh 604
    return query
609 chandransh 605
 
1098 chandransh 606
def get_best_deals(category=-1):
2404 chandransh 607
    '''
608
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
609
    '''
610
    query = get_best_deals_query(Item, category, None)
1098 chandransh 611
    items = query.all()
609 chandransh 612
    return get_thrift_item_list(items)
613
 
1098 chandransh 614
def get_best_deals_count(category=-1):
2404 chandransh 615
    '''
616
    Returns the count of best deals in the given category.
617
    Ignores the category if it's -1.
618
    '''
619
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 620
    if count is None:
621
        count = 0
766 rajveer 622
    return count
7770 kshitij.so 623
 
1926 rajveer 624
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 625
    '''
626
    Returns the catalog_item_ids of best deal items for the given brand and category.
627
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
628
    '''
629
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 630
    best_deal_items = query.all()[start_index:stop_index]
631
    return [item.catalog_item_id for item in best_deal_items]
632
 
2404 chandransh 633
def get_best_deals_counting_query(obj, category, brand):
634
    '''
635
    Returns the query to be used to select the best deals in the given brand and category.
7770 kshitij.so 636
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
2404 chandransh 637
    '''
638
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 639
    if category != -1:
1970 rajveer 640
        all_categories = [category]
641
        child_categories = get_child_categories(category)
642
        if child_categories is not None:
7770 kshitij.so 643
            all_categories = all_categories + child_categories
1970 rajveer 644
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 645
    if brand is not None:
646
        query = query.filter_by(brand=brand)
2404 chandransh 647
    return query
648
 
649
def get_best_deals_query(obj, category, brand):
650
    '''
651
    Returns the query to be used to get the best deals in the given category and brand.
652
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
653
    '''
654
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 655
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
656
    return query
609 chandransh 657
 
5217 amit.gupta 658
def get_coming_soon(category=-1):
659
    '''
660
    Returns the Coming Soon items in the given category. Ignores the category if it's passed as -1.
661
    '''
662
    query = get_coming_soon_query(Item, category, None)
663
    items = query.all()
664
    return get_thrift_item_list(items)
665
 
666
def get_coming_soon_count(category=-1):
667
    '''
668
    Returns the count of coming in the given category.
669
    Ignores the category if it's -1.
670
    '''
671
    count = get_coming_soon_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
672
    if count is None:
673
        count = 0
674
    return count
675
 
676
def get_coming_soon_catalog_ids(start_index, stop_index, brand, category=-1):
677
    '''
678
    Returns the catalog_item_ids of coming soon items for the given brand and category.
679
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
680
    '''
681
    query = get_coming_soon_query(Item, category, brand)
682
    coming_soon_items = query.all()[start_index:stop_index]
683
    return [item.catalog_item_id for item in coming_soon_items]
684
 
685
def get_coming_soon_counting_query(obj, category, brand):
686
    '''
687
    Returns the query to be used to select the coming soon product in the given brand and category.
7770 kshitij.so 688
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
5217 amit.gupta 689
    '''
690
    query = session.query(obj).filter_by(status=status.COMING_SOON)
691
    if category != -1:
692
        all_categories = [category]
693
        child_categories = get_child_categories(category)
694
        if child_categories is not None:
7770 kshitij.so 695
            all_categories = all_categories + child_categories
5217 amit.gupta 696
        query = query.filter(Item.category.in_(all_categories))
697
    if brand is not None:
698
        query = query.filter_by(brand=brand)
699
    return query
700
 
701
def get_coming_soon_query(obj, category, brand):
702
    '''
703
    Returns the query to be used to get the coming soon products in the given category and brand.
704
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
705
    '''
706
    query = get_coming_soon_counting_query(obj, category, brand)
707
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.comingSoonStartDate))
708
    return query
709
 
1098 chandransh 710
def get_latest_arrivals(limit, category=-1):
2404 chandransh 711
    '''
712
    Returns up to limit number of Latest Arrivals in the given category.
713
    '''
2975 chandransh 714
    categories = []
715
    if category != -1:
716
        categories = [category]
717
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 718
    items = query.all()[0:limit]
609 chandransh 719
    return get_thrift_item_list(items)
7770 kshitij.so 720
 
1098 chandransh 721
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 722
    '''
723
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 724
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 725
    '''
2975 chandransh 726
    categories = []
727
    if category != -1:
728
        categories = [category]
729
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 730
    if count is None:
731
        count = 0
732
    count = min(count, limit)
766 rajveer 733
    return count
7770 kshitij.so 734
 
2975 chandransh 735
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 736
    '''
737
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 738
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 739
    '''
2975 chandransh 740
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 741
    latest_arrivals = query.all()[start_index:stop_index]
742
    return [item.catalog_item_id for item in latest_arrivals]
743
 
2975 chandransh 744
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 745
    '''
746
    Returns the query to be used to count Latest arrivals.
3016 chandransh 747
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 748
    '''
749
    query = session.query(obj).filter_by(status=status.ACTIVE)
7770 kshitij.so 750
 
2975 chandransh 751
    all_categories = []
752
    for category in categories:
753
        all_categories.append(category)
1970 rajveer 754
        child_categories = get_child_categories(category)
2975 chandransh 755
        if child_categories:
756
            all_categories = all_categories + child_categories
7770 kshitij.so 757
    if all_categories:
1970 rajveer 758
        query = query.filter(Item.category.in_(all_categories))
7770 kshitij.so 759
 
1926 rajveer 760
    if brand is not None:
761
        query = query.filter_by(brand=brand)
2404 chandransh 762
    return query
763
 
2975 chandransh 764
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 765
    '''
766
    Returns the query to be used to retrieve Latest Arrivals.
767
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
768
    '''
2975 chandransh 769
    query = get_latest_arrivals_counting_query(obj, categories, brand)
5167 rajveer 770
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate)).order_by(Item.catalog_item_id)
1098 chandransh 771
    return query
609 chandransh 772
 
773
def get_thrift_item_list(items):
1098 chandransh 774
    return [to_t_item(item) for item in items if item != None]
635 rajveer 775
 
1155 rajveer 776
def generate_new_entity_id():
777
    generator =  EntityIDGenerator.query.one()
778
    id = generator.id + 1
779
    generator.id = id
780
    session.commit()
781
    return id
782
 
635 rajveer 783
def put_category_object(object):
784
    category = Category.get_by(id=1)
785
    if category is None:
786
        category = Category()
7770 kshitij.so 787
    category.object = object   
635 rajveer 788
    session.commit()
789
    return True
790
 
791
def get_category_object():
766 rajveer 792
    object = Category.get_by(id=1).object
793
    return object
794
 
1970 rajveer 795
def add_category(t_category):
796
    category = Category.get_by(id=t_category.id)
797
    if category is None:
798
        category = Category()
7770 kshitij.so 799
    category.id = t_category.id
1970 rajveer 800
    category.label = t_category.label
801
    category.description = t_category.description
4762 phani.kuma 802
    category.display_name = t_category.display_name
7770 kshitij.so 803
    category.parent_category_id = t_category.parent_category_id
1970 rajveer 804
    session.commit()
805
    return True
806
 
807
def get_category(id):
808
    return Category.query.filter_by(id=id).first()
809
 
810
def get_all_categories():
811
    return Category.query.all()
812
 
2120 ankur.sing 813
def validate_item_prices(item):
2129 ankur.sing 814
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
815
        return
816
    if item.mrp < item.sellingPrice:
2120 ankur.sing 817
        print "[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}, SP={5}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(item.sellingPrice))
818
        raise InventoryServiceException(101, "[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}, SP={5}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(item.sellingPrice)))
2065 ankur.sing 819
    return
7770 kshitij.so 820
 
2120 ankur.sing 821
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 822
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 823
        print "[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(vendorPrices.mop), str(vendorPrices.vendorId))
824
        raise InventoryServiceException(101, "[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(vendorPrices.mop), str(vendorPrices.vendorId)))
825
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
826
        print "[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(vendorPrices.transferPrice), str(vendorPrices.mop), str(vendorPrices.vendorId))
827
        raise InventoryServiceException(101, "[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(vendorPrices.transferPrice), str(vendorPrices.mop), str(vendorPrices.vendorId)))
828
    return
2065 ankur.sing 829
 
4725 phani.kuma 830
def check_color_valid(color):
831
    if color is not None:
832
        color = color.strip().lower()
833
        if color != '' and color != 'na' and color != 'blank' and color != '(blank)':
834
            return True
835
    return False
836
 
837
def check_similar_item(brand, model_number, model_name, color):
2129 ankur.sing 838
    query = Item.query
2428 ankur.sing 839
    query = query.filter_by(brand=brand)
840
    query = query.filter_by(model_number=model_number)
4725 phani.kuma 841
    query = query.filter_by(model_name=model_name)
842
    similar_items = query.all()
843
    item = None
844
    # Check if a similar item already exists in our database
845
    for old_item in similar_items:
846
        if old_item.color != None and old_item.color.strip().lower() == color.strip().lower():
847
            item = old_item
848
            break
7770 kshitij.so 849
 
4725 phani.kuma 850
    # Check if a similar item already exists in our database with out valid color if similar item with same color is not found
2116 ankur.sing 851
    if item is None:
4725 phani.kuma 852
        for old_item in similar_items:
853
            if not check_color_valid(old_item.color):
854
                item = old_item
855
                break
856
    i = 0
857
    color_of_similar_item = None
858
    # Check if a similar item already exists in our database to be used to get catalog_item_id
859
    for old_item in similar_items:
860
        # get a similar item already existing in our database with valid color
861
        if check_color_valid(old_item.color):
862
            similar_item = old_item
863
            color_of_similar_item = similar_item.color
864
            break
865
        i = i + 1
866
        # get a similar item already existing in our database if similar item with valid color is not found
867
        if i == len(similar_items):
868
            similar_item = old_item
869
            color_of_similar_item = similar_item.color
7770 kshitij.so 870
 
4725 phani.kuma 871
    # Check if a similar item that is obtained above is having a valid color
872
    if check_color_valid(color_of_similar_item):
873
        # if a similar item that is obtained above is having a valid color and new item is about to be created with out valid color it is not done.
874
        # since for example if their is a item with red color in our database and we are creating a new item with no color for the same product which is wrong.
875
        if item is None and not check_color_valid(color):
876
            return similar_item.id
7770 kshitij.so 877
 
4725 phani.kuma 878
    if item is None:
2116 ankur.sing 879
        return 0
880
    else:
881
        return item.id
7770 kshitij.so 882
 
2286 ankur.sing 883
def change_risky_flag(item_id, risky):
884
    item = get_item(item_id)
885
    if not item:
886
        raise InventoryServiceException(101, "Item missing in our database")
887
    try:
888
        log_risky_flag(item_id, risky)
889
    except:
890
        print "Not able to log risky flag change"
891
    item.risky = risky
4295 varun.gupt 892
    if not risky and item.status == status.PAUSED_BY_RISK:
2368 ankur.sing 893
        change_item_status(item.id, status.ACTIVE)
6255 rajveer 894
        __send_mail_for_active_item(item.id, "Item '{0}' is Active. Item id is {1}".format(__get_product_name(item), item_id), "")
2286 ankur.sing 895
    session.commit()
5047 amit.gupta 896
    flag = "ON" if risky else "OFF"
897
    subject = "Risky flag is {0} for Item {1}.".format(flag, __get_product_name(item))
898
    __send_mail(subject,"")
7770 kshitij.so 899
 
4957 phani.kuma 900
def get_items_for_mastersheet(categoryName, brand):
901
    if not categoryName or not brand:
902
        raise InventoryServiceException(101, "Invalid category or brand in request")
7770 kshitij.so 903
 
4762 phani.kuma 904
    categories = ["Handsets", "Tablets", "Laptops"]
4957 phani.kuma 905
    query = Item.query.filter(Item.status != status.PHASED_OUT)
906
    if categoryName == "ALL":
907
        pass
908
    elif categoryName == "ALL Accessories":
909
        query = query.filter(~Item.product_group.in_(categories))
910
    elif categoryName == "ALL Handsets":
911
        query = query.filter(Item.product_group.in_(categories))
912
    elif categoryName == "Mobile Accessories":
913
        child_categories = get_child_categories(10011)
914
        if child_categories is not None:
915
            child_categories.append(0)
916
            query = query.filter(Item.category.in_(child_categories))
917
    elif categoryName == "Laptop Accessories":
918
        child_categories = get_child_categories(10070)
919
        if child_categories is not None:
920
            child_categories.append(0)
921
            query = query.filter(Item.category.in_(child_categories))
922
    else:
923
        query = query.filter(Item.product_group == categoryName)
7770 kshitij.so 924
 
4957 phani.kuma 925
    if brand == "ALL":
926
        pass
927
    else:
928
        query = query.filter(Item.brand == brand)
2358 ankur.sing 929
    items = query.all()
930
    return items
2116 ankur.sing 931
 
2358 ankur.sing 932
def get_risky_items():
933
    items = Item.query.filter_by(risky=True).all()
934
    return items
3008 rajveer 935
 
2809 rajveer 936
def get_similar_items_catalog_ids(start_index, stop_index, itemId):
3008 rajveer 937
    query = SimilarItems.query.filter_by(item_id=itemId).limit(stop_index-start_index)
938
    similar_items = query.all()
3289 rajveer 939
    return_list = []
940
    for similar_item in similar_items:
941
        isActive = False
942
        try:
943
            all_items = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).all()
944
        except:
945
            continue
946
        for item in all_items:
947
            isActive = isActive or item.status == status.ACTIVE
948
        if isActive:
949
            return_list.append(similar_item.catalog_item_id)
950
    return return_list
4423 phani.kuma 951
 
952
def get_all_similar_items_catalog_ids(itemId):
953
    query = SimilarItems.query.filter_by(item_id=itemId)
954
    similar_items = query.all()
955
    return_list = []
956
    for similar_item in similar_items:
957
        item_query = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).limit(1)
958
        item = item_query.one()
959
        return_list.append(item)
7770 kshitij.so 960
 
4423 phani.kuma 961
    return get_thrift_item_list(return_list)
962
 
963
def add_similar_item_catalog_id(itemId, catalog_item_id):
964
    if not itemId or not catalog_item_id:
965
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
966
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
967
    if not len(items_for_entity):
968
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
7770 kshitij.so 969
 
4423 phani.kuma 970
    s_items = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
971
    if not len(s_items):
972
        s_item = SimilarItems()
973
        s_item.item_id=itemId
974
        s_item.catalog_item_id=catalog_item_id
975
        session.commit()
976
        return items_for_entity[0]
977
    else:
978
        raise InventoryServiceException(101, "Already exists")
7770 kshitij.so 979
 
4423 phani.kuma 980
def delete_similar_item_catalog_id(itemId, catalog_item_id):
981
    if not itemId or not catalog_item_id:
982
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
7770 kshitij.so 983
 
4423 phani.kuma 984
    similar_item = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
985
    if len(similar_item):
986
        similar_item[0].delete()
987
    session.commit()
988
    return True
5504 phani.kuma 989
 
990
def get_all_vouchers_for_item(itemId):
991
    vouchers = VoucherItemMapping.query.filter_by(item_id=itemId).all()
992
    return vouchers
993
 
994
def get_voucher_amount(itemId, voucher_type):
995
    voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
996
    if len(voucher):
997
        return voucher[0].amount
998
    else:
5518 rajveer 999
        return 0
5504 phani.kuma 1000
 
1001
def add_update_voucher_for_item(catalog_item_id, voucher_type, voucher_amount):
1002
    if not catalog_item_id or not voucher_type or not voucher_amount:
1003
        raise InventoryServiceException(101, "Bad catalogItemId or voucherType or voucherAmount in request")
7770 kshitij.so 1004
 
5504 phani.kuma 1005
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1006
    if not len(items_for_entity):
1007
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
7770 kshitij.so 1008
 
5504 phani.kuma 1009
    for item in items_for_entity:
1010
        itemId = item.id
1011
        voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
1012
        if not len(voucher):
1013
            voucher = VoucherItemMapping()
1014
            voucher.item_id=itemId
1015
            voucher.voucherType=voucher_type
1016
            voucher.amount=voucher_amount
1017
        else:
1018
            voucher[0].amount=voucher_amount
1019
    session.commit()
1020
    return True
7770 kshitij.so 1021
 
5504 phani.kuma 1022
def delete_voucher_for_item(catalog_item_id, voucher_type):
1023
    if not catalog_item_id or not voucher_type:
1024
        raise InventoryServiceException(101, "Bad catalogItemId or voucherType in request")
7770 kshitij.so 1025
 
5504 phani.kuma 1026
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1027
    if not len(items_for_entity):
1028
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
7770 kshitij.so 1029
 
5504 phani.kuma 1030
    for item in items_for_entity:
1031
        itemId = item.id
1032
        voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
1033
        if len(voucher):
1034
            voucher[0].delete()
1035
    session.commit()
1036
    return True
1037
 
3079 rajveer 1038
def add_product_notification(itemId, email):
1039
    try:
3470 rajveer 1040
        try:
1041
            product_notification = ProductNotification.query.filter_by(item_id=itemId, email=email).one()
1042
        except:
1043
            product_notification = ProductNotification()
1044
            product_notification.email = email
1045
            product_notification.item_id = itemId
3079 rajveer 1046
        product_notification.addedOn = datetime.datetime.now()
1047
        session.commit()
1048
        return True
1049
    except:
1050
        return False
3086 rajveer 1051
 
1052
 
1053
def send_product_notifications():
7134 rajveer 1054
    product_notifications = ProductNotification.query.order_by(ProductNotification.addedOn).all()
1055
    itemcountmap = {}
1056
    itemstatusmap = {}
8182 amar.kumar 1057
    #print "size of prduct notifications = " + str(len(product_notifications))
3086 rajveer 1058
    for product_notification in product_notifications:
1059
        item = product_notification.item
7134 rajveer 1060
        if itemcountmap.has_key(item.id):
1061
            itemcountmap[item.id] = itemcountmap.get(item.id) + 1
1062
        else:
1063
            client = InventoryClient().get_client()
1064
            availability = client.getItemAvailabilityAtLocation(item.id, sourceId)[4]
8182 amar.kumar 1065
            #print "Item status " + str(item.status) + " item.risky " + str(item.risky) + " availability = " + str(availability)
1066
            if item.status == status.ACTIVE and (not item.risky or availability > 0):  
1067
                #print "item status map has new entry " + str(item.id)     
7134 rajveer 1068
                itemstatusmap[item.id] = True
1069
            else:
1070
                itemstatusmap[item.id] = False
1071
            itemcountmap[item.id] = 1
1072
        if itemcountmap[item.id] > 1000:
1073
            continue
7770 kshitij.so 1074
 
7134 rajveer 1075
        if itemstatusmap[item.id]:
8182 amar.kumar 1076
            #print product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id
3086 rajveer 1077
            __enque_product_notification_email(product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id)
1078
            product_notification.delete()
1079
    session.commit()
1080
    return True
7770 kshitij.so 1081
 
3086 rajveer 1082
def __get_product_name(item):
1083
    product_name = item.brand + " " + item.model_name + " " + item.model_number
1084
    color = item.color
1085
    if color is not None and color != 'NA':
1086
        product_name = product_name + " (" + color + ")"
3201 rajveer 1087
    product_name = product_name.replace("  "," ")
3086 rajveer 1088
    return product_name
1089
 
1090
 
1091
def __get_product_url(item):
6029 rajveer 1092
    product_url = "http://" + source_url + "/mobile-phones/" + item.brand + "-" + item.model_name + "-" + item.model_number + "-" + str(item.catalog_item_id)
3086 rajveer 1093
    product_url = product_url.replace("--","-")
1094
    product_url = product_url.replace(" ","")
1095
    return product_url
1096
 
3348 varun.gupt 1097
def get_all_brands_by_category(category_id):
1098
    catm = CategoryManager()
1099
    child_categories = catm.getCategory(category_id).children_category_ids
1100
    brands = session.query(distinct(Item.brand)).filter(Item.category.in_(child_categories)).all()
7770 kshitij.so 1101
 
3348 varun.gupt 1102
    return [brand[0] for brand in brands]
3086 rajveer 1103
 
4957 phani.kuma 1104
def get_all_brands():
1105
    brands = session.query(distinct(Item.brand)).order_by(Item.brand).all()
7770 kshitij.so 1106
 
4957 phani.kuma 1107
    return [brand[0] for brand in brands]
1108
 
3086 rajveer 1109
def __enque_product_notification_email(email, product, date, url, itemId):
7770 kshitij.so 1110
 
3086 rajveer 1111
    html = """
1112
        <html>
1113
        <body>
1114
        <div>
1115
        <p>
1116
            Hi,<br /><br />
6029 rajveer 1117
            The product requested by you on $date is now available on $source_url.
7103 amar.kumar 1118
            <br />
1119
            We have limited stocks of this model at this moment. If you don't want to miss out, please place your order as soon as possible.
3086 rajveer 1120
        </p>
7770 kshitij.so 1121
 
1122
        <p>   
3086 rajveer 1123
        <strong>Product: $product </strong>
1124
        </p>
7770 kshitij.so 1125
 
3086 rajveer 1126
        <p>
7770 kshitij.so 1127
        Click the link below to visit the product:
3086 rajveer 1128
        <br/>
1129
        $url
1130
        </p>
1131
        <p>
1132
        Regards,<br/>
6029 rajveer 1133
        $source_name Customer Support Team<br/>
1134
        $source_url<br/>
3086 rajveer 1135
        Email: help@saholic.com<br/>
1136
        </p>
1137
        </div>
1138
        </body>
1139
        </html>
1140
        """
1141
 
6029 rajveer 1142
    html = Template(html).substitute(dict(product=product,date=date,url=url,source_url=source_url,source_name=source_name))
7770 kshitij.so 1143
 
3086 rajveer 1144
    try:
1145
        helper_client = HelperClient().get_client()
8464 amar.kumar 1146
        helper_client.saveUserEmailForSending([email], "", "Product requested by you is available now.", html, str(itemId), "ProductNotification", [], [],sourceId)
3086 rajveer 1147
    except Exception as e:
1148
        print e
8182 amar.kumar 1149
        print sys.exc_info()[0]
3086 rajveer 1150
 
3557 rajveer 1151
def get_all_sources():
1152
    sources = Source.query.all()
1153
    return [to_t_source(source) for source in sources]
3086 rajveer 1154
 
3557 rajveer 1155
def get_item_pricing_by_source(itemId, sourceId):
1156
    item = Item.query.filter_by(id=itemId).first()
1157
    if item is None:
1158
        raise InventoryServiceException(101, "Bad Item")
7770 kshitij.so 1159
 
3557 rajveer 1160
    source = Source.query.filter_by(id=sourceId).first()
1161
    if source is None:
1162
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
7770 kshitij.so 1163
 
3557 rajveer 1164
    item_pricing = SourceItemPricing.query.filter_by(source=source, item=item).first()
1165
    if item_pricing is None:
1166
        raise InventoryServiceException(101, "Pricing information not found for sourceId " + str(sourceId))
1167
    return item_pricing
7770 kshitij.so 1168
 
3557 rajveer 1169
def add_source_item_pricing(sourceItemPricing):
1170
    if not sourceItemPricing:
1171
        raise InventoryServiceException(108, "Bad sourceItemPricing in request")
7770 kshitij.so 1172
 
3557 rajveer 1173
    if not sourceItemPricing.sellingPrice:
4326 mandeep.dh 1174
        raise InventoryServiceException(101, "Selling Price is not defined for sourceId " + str(sourceItemPricing.sourceId))
7770 kshitij.so 1175
 
3557 rajveer 1176
    sourceId = sourceItemPricing.sourceId
1177
    itemId = sourceItemPricing.itemId
7770 kshitij.so 1178
 
3557 rajveer 1179
    item = Item.query.filter_by(id=itemId).first()
1180
    if item is None:
1181
        raise InventoryServiceException(101, "Bad Item")
7770 kshitij.so 1182
 
3557 rajveer 1183
    source = Source.query.filter_by(id=sourceId).first()
1184
    if source is None:
1185
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
7770 kshitij.so 1186
 
3564 rajveer 1187
    ds_sourceItemPricing = SourceItemPricing.get_by(source=source, item=item)
3557 rajveer 1188
    if ds_sourceItemPricing is None:
1189
        ds_sourceItemPricing = SourceItemPricing()
1190
        ds_sourceItemPricing.source = source
1191
        ds_sourceItemPricing.item = item
7770 kshitij.so 1192
 
3557 rajveer 1193
    if sourceItemPricing.mrp:
1194
        ds_sourceItemPricing.mrp = sourceItemPricing.mrp
1195
    ds_sourceItemPricing.sellingPrice = sourceItemPricing.sellingPrice
1196
 
1197
    session.commit()
1198
    return
1199
 
1200
def get_all_source_pricing(itemId):
1201
    item = Item.query.filter_by(id=itemId).first()
1202
    if item is None:
1203
        raise InventoryServiceException(101, "Bad Item")
1204
    source_pricing = SourceItemPricing.query.filter_by(item=item).all()
1205
    return source_pricing
7770 kshitij.so 1206
 
3557 rajveer 1207
 
1208
def get_item_for_source(item_id, sourceId):
1209
    item = get_item(item_id)
1210
    if sourceId == -1:
1211
        return item
1212
    try:
1213
        sip = get_item_pricing_by_source(item_id, sourceId)
1214
        item.sellingPrice = sip.sellingPrice
1215
        if sip.mrp:
1216
            item.mrp = sip.mrp
1217
    except:
1218
        print "No source pricing"
1219
    return item
1220
 
3872 chandransh 1221
def search_items(search_terms, offset, limit):
1222
    query = Item.query
7770 kshitij.so 1223
 
3872 chandransh 1224
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
8139 kshitij.so 1225
    print search_terms
7770 kshitij.so 1226
 
3872 chandransh 1227
    for search_term in search_terms:
6661 rajveer 1228
        query_clause = []
3872 chandransh 1229
        query_clause.append(Item.brand.like(search_term))
1230
        query_clause.append(Item.model_number.like(search_term))
1231
        query_clause.append(Item.model_name.like(search_term))
6661 rajveer 1232
        query = query.filter(or_(*query_clause))
8139 kshitij.so 1233
 
1234
    print query
3872 chandransh 1235
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
1236
    if limit:
1237
        query = query.limit(limit)
1238
    items = query.all()
1239
    return items
1240
 
1241
def get_search_result_count(search_terms):
1242
    query = Item.query
7770 kshitij.so 1243
 
3872 chandransh 1244
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
7770 kshitij.so 1245
 
3872 chandransh 1246
    for search_term in search_terms:
6661 rajveer 1247
        query_clause = []
3872 chandransh 1248
        query_clause.append(Item.brand.like(search_term))
1249
        query_clause.append(Item.model_number.like(search_term))
1250
        query_clause.append(Item.model_name.like(search_term))
6661 rajveer 1251
        query = query.filter(or_(*query_clause))
7770 kshitij.so 1252
 
3872 chandransh 1253
    return query.count()
1254
 
3924 rajveer 1255
def __clear_homepage_cache():
1256
    try:
1257
        # create a password manager
1258
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
1259
        # Add the username and password.
1260
        configclient = ConfigClient()
4310 rajveer 1261
        ips = configclient.get_property("production_servers_private_ips");
3924 rajveer 1262
        ips = ips.split(" ")
7770 kshitij.so 1263
 
3924 rajveer 1264
        for ip in ips:
4310 rajveer 1265
            try:
1266
                top_level_url = "http://" + ip + ":8080/"
1267
                password_mgr.add_password(None, top_level_url, "saholic", "shop2020")
1268
                handler = urllib2.HTTPBasicAuthHandler(password_mgr)
7770 kshitij.so 1269
 
4310 rajveer 1270
                opener = urllib2.build_opener(handler)
7770 kshitij.so 1271
 
4310 rajveer 1272
                # use the opener to fetch a URL
1273
                res = opener.open(top_level_url + "cache-admin/HomePageSnippets?_method=delete")
1274
                print "Successfully cleared home page cache" + res.read()
1275
            except:
1276
                print "Unable to clear home page cache" + res.read()
3924 rajveer 1277
    except:
1278
        print "Unable to clear cache, still should continue with other operations"
7770 kshitij.so 1279
 
4295 varun.gupt 1280
def get_product_notifications(start_datetime):
1281
    '''
1282
    Returns a list of Product Notification objects each representing user requests for notification
1283
    '''
1284
    query = ProductNotification.query
7770 kshitij.so 1285
 
4295 varun.gupt 1286
    if start_datetime:
1287
        query = query.filter(ProductNotification.addedOn > start_datetime)
7770 kshitij.so 1288
 
4295 varun.gupt 1289
    notifications = query.order_by(desc('addedOn')).all()
1290
    return notifications
1291
 
7897 amar.kumar 1292
def get_product_notification_request_count(start_datetime, categoryId):
4295 varun.gupt 1293
    '''
1294
    Returns list of items and the counts of product notification requests
1295
    '''
7897 amar.kumar 1296
    if categoryId:
1297
        categories = get_child_categories(categoryId)
1298
        items = Item.query.filter(Item.category.in_(categories)).all()
1299
        item_ids = [item.id for item in items]
1300
 
4295 varun.gupt 1301
    print start_datetime
1302
    query = session.query(ProductNotification, func.count(ProductNotification.email).label('count'))
7770 kshitij.so 1303
 
4295 varun.gupt 1304
    if start_datetime:
1305
        query = query.filter(ProductNotification.addedOn > start_datetime)
7897 amar.kumar 1306
    if categoryId:
1307
        query = query.filter(ProductNotification.item_id.in_(item_ids))
4295 varun.gupt 1308
    counts = query.group_by(ProductNotification.item_id).order_by(desc('count')).all()
1309
    return counts
1310
 
766 rajveer 1311
def close_session():
1312
    if session.is_active:
1313
        print "session is active. closing it."
1399 rajveer 1314
        session.close()
3376 rajveer 1315
 
1316
def is_alive():
1317
    try:
1318
        session.query(Item.id).limit(1).one()
1319
        return True
1320
    except:
1321
        return False
4332 anupam.sin 1322
 
4649 phani.kuma 1323
def add_authorization_log_for_item(itemId, username, reason):
1324
    if not itemId or not username:
1325
        raise InventoryServiceException(101, "Bad itemId or Invalid username in request")
1326
    authorize_log = AuthorizationLog()
1327
    authorize_log.item_id = itemId
1328
    authorize_log.username = username
1329
    authorize_log.reason = reason
1330
    session.commit()
4797 rajveer 1331
    return True
1332
 
6255 rajveer 1333
def __send_mail_for_oos_item(item):
1334
    oos = OOSTracker.get_by(itemId = item.id)
1335
    if oos is None:
1336
        oos = OOSTracker()
1337
        oos.itemId = item.id
1338
        session.commit()
1339
        try:
6962 rajveer 1340
            EmailAttachmentSender.mail(mail_user, mail_password, to_addresses + ["pramit.singh@shop2020.in"], "Item is out of stock. ID: " + str(item.id)  + " " + str(item.brand) +  " " + str(item.model_name) + " " + str(item.model_number)+ " " + str(item.color), None)
6255 rajveer 1341
        except Exception as e:
1342
            print e
4985 mandeep.dh 1343
 
6255 rajveer 1344
def __send_mail_for_active_item(itemId, subject, message):
1345
    oos = OOSTracker.get_by(itemId = itemId)
1346
    if oos is not None:
1347
        oos.delete()
1348
        session.commit()
1349
    __send_mail(subject, message)
1350
 
7384 rajveer 1351
def __send_mail(subject, message, send_to  = to_addresses):
5080 amit.gupta 1352
    try:
7384 rajveer 1353
        thread = threading.Thread(target=partial(mail, mail_user, mail_password, send_to, subject, message))
5080 amit.gupta 1354
        thread.start()
1355
    except Exception as ex:
7770 kshitij.so 1356
        print ex   
5185 mandeep.dh 1357
 
6039 amit.gupta 1358
def get_vat_amount_for_item(itemId, price):
1359
    item = Item.query.filter_by(id=itemId).first()
1360
    vatPercentage = item.vatPercentage
1361
    if vatPercentage is None:
1362
        vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price)).first()
1363
        vatPercentage = vatMaster.vatPercent
1364
        if  vatPercentage is None:
1365
            vatPercentage = 0
1366
    return (price*vatPercentage)/100
7770 kshitij.so 1367
 
7340 amit.gupta 1368
def get_vat_percentage_for_item(itemId, stateId, price):
7330 amit.gupta 1369
    itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==itemId, ItemVatMaster.stateId==stateId)).first()
7340 amit.gupta 1370
    if itemVatMaster is None:
7330 amit.gupta 1371
            item = Item.query.filter_by(id=itemId).first()
7340 amit.gupta 1372
            if item is None:
1373
                raise CatalogServiceException(itemId, "Could not find item in catalog")
1374
            vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price,  CategoryVatMaster.stateId == stateId)).first()
7330 amit.gupta 1375
            if vatMaster is None:
8589 amar.kumar 1376
                raise CatalogServiceException(stateId, "Could not find vat rate for this state." + str(stateId) + " for " + str(itemId))
7340 amit.gupta 1377
            return vatMaster.vatPercent
7330 amit.gupta 1378
    else:
7340 amit.gupta 1379
        return itemVatMaster.vatPercentage
6511 kshitij.so 1380
 
6531 vikram.rag 1381
def get_all_ignored_inventoryupdate_items_list(offset,limit):
1382
    client = InventoryClient().get_client()
1383
    itemids = client.getIgnoredInventoryUpdateItemids(offset,limit)
6532 amit.gupta 1384
    result = []
1385
    if itemids is not None and len(itemids)>0:
1386
        query = Item.query.filter(Item.id.in_(itemids))
1387
        query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name)
1388
        result = [to_t_item(item) for item in query.all()]
1389
    return result
6531 vikram.rag 1390
 
1391
 
6511 kshitij.so 1392
def add_tag (displayName, catalogId):
1393
    ent_tag = None
7770 kshitij.so 1394
    if catalogId is None or (not is_valid_catalog_id(catalogId)):           
6511 kshitij.so 1395
        raise InventoryServiceException(id, "Invalid CatalogId")
1396
    else:
1397
        ent_tag = EntityTag()
1398
        ent_tag.entityId = catalogId
1399
    if displayName is None:
1400
        raise InventoryServiceException(id, "Tag should not be empty")
7770 kshitij.so 1401
    else:
6511 kshitij.so 1402
        ent_tag.tag = displayName
1403
    session.commit()
1404
    return True
1405
 
8590 kshitij.so 1406
def add_banner(bannerCongregate):
1407
    banner = bannerCongregate.banner
9155 kshitij.so 1408
    antecedent = bannerCongregate.antecedent
8590 kshitij.so 1409
    t_bannerMaps = bannerCongregate.bannerMaps
1410
    t_bannerUriMappings = bannerCongregate.bannerUriMappings
9178 kshitij.so 1411
    if antecedent.bannerName is not None :
1412
        delete_banner(antecedent.bannerName,antecedent.bannerType)
9155 kshitij.so 1413
    try:
1414
        banner_details=Banner()
1415
        banner_details.bannerName=banner.bannerName
1416
        banner_details.imageName=banner.imageName
1417
        banner_details.link=banner.link
1418
        banner_details.hasMap=banner.hasMap
1419
        banner_details.priority = banner.priority
1420
        banner_details.bannerType = banner.bannerType
1421
        session.commit()
1422
    except:
1423
        return
1424
    add_banner_map(t_bannerMaps,banner.bannerType)
1425
    add_banner_uri(t_bannerUriMappings,banner.bannerType)
6848 kshitij.so 1426
 
1427
def get_all_banners():
8579 kshitij.so 1428
    return session.query(Banner).all()
6848 kshitij.so 1429
 
9155 kshitij.so 1430
def delete_banner(name,bType):
8579 kshitij.so 1431
    try:
9155 kshitij.so 1432
        session.query(Banner.bannerName).filter_by(bannerName=name).filter_by(bannerType=bType).delete()
8579 kshitij.so 1433
        session.commit()
9155 kshitij.so 1434
        delete_banner_map(name,bType)
1435
        delete_uri_mapping(name,bType)
8579 kshitij.so 1436
        return True
1437
    except:
1438
        return False
6848 kshitij.so 1439
 
9155 kshitij.so 1440
def get_banner_details(name,bType):
1441
    banner = session.query(Banner).filter(Banner.bannerName==name).filter(Banner.bannerType==bType).one()
7770 kshitij.so 1442
    return banner  
6848 kshitij.so 1443
 
1444
def get_active_banners():
8579 kshitij.so 1445
    bannerUriMap = {}
9155 kshitij.so 1446
    bannerType = [1,2]
1447
    all_active = session.query(BannerUriMapping,Banner).filter(BannerUriMapping.bannerType.in_(bannerType)).filter(BannerUriMapping.isActive==True).filter(BannerUriMapping.bannerName==Banner.bannerName).filter(BannerUriMapping.bannerType==Banner.bannerType).order_by(desc(Banner.priority)).all()
8579 kshitij.so 1448
    for bannerUriMapping in all_active:
1449
        bannerObj = []
9155 kshitij.so 1450
        if (bannerUriMapping[0].bannerType == BannerType.SIDE_BANNER):
1451
            if 'side-banner' in bannerUriMap:
1452
                for obj in bannerUriMap['side-banner']:
1453
                    bannerObj.append(obj)
1454
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
1455
            bannerUriMap['side-banner'] = bannerObj
1456
            continue
8579 kshitij.so 1457
        if bannerUriMapping[0].uri not in bannerUriMap:
9155 kshitij.so 1458
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
8579 kshitij.so 1459
            bannerUriMap[bannerUriMapping[0].uri] = bannerObj
1460
        else:
1461
            for obj in bannerUriMap[bannerUriMapping[0].uri]:
1462
                bannerObj.append(obj)
9155 kshitij.so 1463
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
8579 kshitij.so 1464
            bannerUriMap[bannerUriMapping[0].uri] = bannerObj
1465
    return bannerUriMap
1466
 
6848 kshitij.so 1467
 
9155 kshitij.so 1468
def add_banner_map(bannerMaps,bannerType):
8579 kshitij.so 1469
    try:
1470
        for bannerMap in bannerMaps:
1471
            banner_map_details=BannerMap()
1472
            banner_map_details.bannerName=bannerMap.bannerName
1473
            banner_map_details.mapLink=bannerMap.mapLink
1474
            banner_map_details.coordinates=bannerMap.coordinates
9155 kshitij.so 1475
            banner_map_details.bannerType = bannerType
8579 kshitij.so 1476
            session.commit()
1477
        return True
1478
    except:
1479
        return False
1480
 
6848 kshitij.so 1481
 
9155 kshitij.so 1482
def delete_banner_map(name,bType):
8579 kshitij.so 1483
    try:
9155 kshitij.so 1484
        session.query(BannerMap.bannerName).filter_by(bannerName=name).filter_by(bannerType=bType).delete()
8579 kshitij.so 1485
        session.commit()
1486
        return True
1487
    except:
1488
        return False
6848 kshitij.so 1489
 
9155 kshitij.so 1490
def delete_uri_mapping(name,bType):
8579 kshitij.so 1491
    try:
9155 kshitij.so 1492
        session.query(BannerUriMapping.bannerName).filter_by(bannerName=name).filter_by(bannerType=bType).delete()
8579 kshitij.so 1493
        session.commit()
1494
    except:
1495
        return False
1496
 
9155 kshitij.so 1497
def get_banner_map_details(name,bType):
6848 kshitij.so 1498
    query= session.query(BannerMap)
9155 kshitij.so 1499
    return query.filter_by(bannerName=name).filter_by(bannerType=bType).all()
8579 kshitij.so 1500
 
1501
def update_banner(banner):
1502
    banner_details = Banner.get_by(bannerName=banner.bannerName)
1503
    try:
1504
        if banner_details is not None:
1505
            banner_details.imageName = banner.imageName
1506
            banner_details.link = banner.link
1507
            banner_details.priority = banner.priority
1508
            banner_details.hasMap = banner.hasMap
1509
            session.commit()
1510
            return True
1511
        else:
1512
            return False
1513
    except:
1514
        return False
1515
 
9155 kshitij.so 1516
def add_banner_uri(bannerUriMappings,bannerType):
8579 kshitij.so 1517
    for bannerUriMapping in bannerUriMappings:
1518
        banner_uri = BannerUriMapping()
1519
        banner_uri.bannerName = bannerUriMapping.bannerName
1520
        banner_uri.uri = bannerUriMapping.uri
1521
        banner_uri.isActive = bannerUriMapping.isActive
9155 kshitij.so 1522
        banner_uri.bannerType = bannerType
8579 kshitij.so 1523
        session.commit()
1524
 
9155 kshitij.so 1525
def get_uri_mapping(name,bType):
8579 kshitij.so 1526
    query= session.query(BannerUriMapping)
9155 kshitij.so 1527
    return query.filter_by(bannerName=name).filter_by(bannerType=bType).all()
8579 kshitij.so 1528
 
1529
def add_campaign(campaign):
1530
    new_campaign = Campaign()
1531
    new_campaign.campaignName = campaign.campaignName
1532
    new_campaign.imageName = campaign.imageName
1533
    session.commit() 
1534
 
1535
def get_campaigns(name):
1536
    query= session.query(Campaign)
1537
    return query.filter_by(campaignName=name).all()
1538
 
1539
def delete_campaign(campaign_id):
1540
    campaign = Campaign.get_by(id = campaign_id)
1541
    if campaign is not None:
1542
        campaign.delete()
1543
        session.commit()
1544
 
1545
def get_all_campaigns():
1546
    return session.query(distinct(Campaign.campaignName)).all()
1547
 
9155 kshitij.so 1548
def get_active_banners_for_mobile_site():
1549
    bannerType = [3]
1550
    bannerMap = {}
1551
    all_active = session.query(BannerUriMapping,Banner).filter(BannerUriMapping.bannerType.in_(bannerType)).filter(BannerUriMapping.isActive==True).filter(BannerUriMapping.bannerName==Banner.bannerName).filter(BannerUriMapping.bannerType==Banner.bannerType).order_by(desc(Banner.priority)).all()
1552
    for bannerUriMapping in all_active:
1553
        bannerObj = []
1554
        if bannerUriMapping[0].uri not in bannerMap:
1555
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
1556
            bannerMap[bannerUriMapping[0].uri] = bannerObj
1557
        else:
1558
            for obj in bannerMap[bannerUriMapping[0].uri]:
1559
                bannerObj.append(obj)
1560
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
1561
            bannerMap[bannerUriMapping[0].uri] = bannerObj
1562
    return bannerMap
1563
 
1564
 
7770 kshitij.so 1565
 
6511 kshitij.so 1566
def get_all_tags ():
1567
    return [tuple[0] for tuple in session.query(EntityTag.tag).distinct().all()]
1568
 
1569
def get_all_entities_by_tag_name(displayName):
1570
    return [tuple[0] for tuple in session.query(EntityTag.entityId).filter_by(tag=displayName).all()]
7770 kshitij.so 1571
 
6511 kshitij.so 1572
def delete_tag(displayName):
1573
    session.query(EntityTag.entityId).filter_by(tag=displayName).delete()
1574
    session.commit()
1575
    return True
6518 kshitij.so 1576
 
1577
def delete_entity_tag(displayName, catalogId):
1578
    session.query(EntityTag.tag).filter_by(tag=displayName,entityId=catalogId).delete()
1579
    session.commit()
6805 anupam.sin 1580
    return True
1581
 
6921 anupam.sin 1582
def get_insurance_amount(itemId, price, insurerId, quantity):
6805 anupam.sin 1583
    itemInsurerMapping = ItemInsurerMapping.query.filter(ItemInsurerMapping.itemId == itemId).filter(ItemInsurerMapping.insurerId == insurerId).first()
1584
    if not itemInsurerMapping:
6903 anupam.sin 1585
        #Default insurance premium is 1.5%
6921 anupam.sin 1586
        return round(price * (1.5/100) * quantity)
6805 anupam.sin 1587
    insuranceAmount = 0.0
1588
    if itemInsurerMapping.premiumType == PremiumType._NAMES_TO_VALUES.get("PERCENT"):
6921 anupam.sin 1589
        insuranceAmount = price * (itemInsurerMapping.premiumAmount/100) * quantity
6805 anupam.sin 1590
    else :
1591
        insuranceAmount = itemInsurerMapping.premiumAmount * quantity
7770 kshitij.so 1592
 
6805 anupam.sin 1593
    return insuranceAmount
7770 kshitij.so 1594
 
6805 anupam.sin 1595
def get_insurer(insurerId):
6838 vikram.rag 1596
    return Insurer.get_by(id = insurerId)
7770 kshitij.so 1597
 
6845 amit.gupta 1598
def get_all_entity_tags():
1599
    entitiesTag = EntityTag.query.all()
1600
    entityMap = {}
1601
    for e in entitiesTag:
1602
        if not entityMap.has_key(e.entityId):
1603
            entityMap[e.entityId] = []
7770 kshitij.so 1604
        entityMap[e.entityId].append(e.tag)  
6845 amit.gupta 1605
    return entityMap
6838 vikram.rag 1606
 
1607
 
1608
def get_all_insurers():
1609
    print session.query(Insurer).all()
1610
    return session.query(Insurer).all()
7770 kshitij.so 1611
 
6962 rajveer 1612
def update_insurance_declared_amount(insurerId, amount):
1613
    insurer = Insurer.get_by(id = insurerId)
1614
    insurer.declaredAmount += amount
1615
    session.commit()
1616
    if insurer.declaredAmount > 0.9*insurer.creditedAmount:
7770 kshitij.so 1617
        __send_mail("CRITICAL: Declared Insurance Amount is critical (Declared Amount - " + str(insurer.declaredAmount) + " and Credited Amount - " + str(insurer.creditedAmount) +")", "Please top up credited amount")   
6962 rajveer 1618
    elif insurer.declaredAmount > 0.8*insurer.creditedAmount:
7770 kshitij.so 1619
        __send_mail("WARNING: Declared Insurance Amount is warning (Declared Amount - " + str(insurer.declaredAmount) + " and Credited Amount - " + str(insurer.creditedAmount) +")", "Please top up credited amount")   
1620
 
7190 amar.kumar 1621
def get_freebie_for_item(itemId):
1622
    freebie = FreebieItem.get_by(itemId = itemId)
1623
    if freebie is None:
1624
        return 0
1625
    else:
1626
        return freebie.freebieItemId
7770 kshitij.so 1627
 
7190 amar.kumar 1628
def add_or_update_freebie_for_item(freebieItem):
1629
    freebie = FreebieItem.get_by(itemId = freebieItem.itemId)
1630
    if freebie is None:
1631
        freebie = FreebieItem()
1632
        freebie.itemId = freebieItem.itemId
1633
    freebie.freebieItemId = freebieItem.freebieItemId
7256 rajveer 1634
    session.commit()
1635
 
7272 amit.gupta 1636
 
1637
def add_or_update_brand_info(brandInfo):
1638
    brandinfo = BrandInfo.get_by(name = brandInfo.name)
1639
    if brandinfo is None:
1640
        brandinfo = BrandInfo()
1641
        brandinfo.itemId = brandInfo.itemId
1642
        brandinfo.freebieItemId = brandInfo.freebieItemId
1643
    session.commit()
7770 kshitij.so 1644
 
7272 amit.gupta 1645
def get_brand_info():
1646
    brandInfoMap = dict()
8274 amit.gupta 1647
    brandInfoList = BrandInfo.query.all()
7272 amit.gupta 1648
    for brandInfo in brandInfoList:
1649
        brandInfoMap[brandInfo.name] = to_t_brand_info(brandInfo)
1650
    return brandInfoMap
1651
 
7382 rajveer 1652
def update_store_pricing(tsp, allColors):
7306 rajveer 1653
    validate_store_pricing(tsp)
7382 rajveer 1654
    item = get_item(tsp.itemId)
7419 rajveer 1655
    activeOnStore = item.activeOnStore
7382 rajveer 1656
    if allColors:
1657
        items = get_items_by_catalog_id(item.catalog_item_id)
1658
    else:
1659
        items = [item]
1660
    for item in items:
1661
        sp = StorePricing.get_by(item_id = item.id)
1662
        if not sp:
1663
            sp = StorePricing()
7419 rajveer 1664
        item.activeOnStore = activeOnStore
7382 rajveer 1665
        sp.recommendedPrice = tsp.recommendedPrice
1666
        sp.minPrice = tsp.minPrice
1667
        sp.minAdvancePrice = tsp.minAdvancePrice
1668
        sp.maxPrice = tsp.maxPrice
1669
        sp.item_id = item.id
1670
        sp.freebieItemId = tsp.freebieItemId
1671
        sp.bestDealText = tsp.bestDealText
1672
        sp.absoluteMinPrice = tsp.absoluteMinPrice
7265 rajveer 1673
    session.commit()
7770 kshitij.so 1674
 
1675
 
7306 rajveer 1676
def validate_store_pricing(tsp):
1677
    if tsp.minPrice > tsp.maxPrice:
7770 kshitij.so 1678
        raise InventoryServiceException(101, "DP is more than MRP")  
1679
 
7306 rajveer 1680
    item = get_item(tsp.itemId)
7770 kshitij.so 1681
 
7384 rajveer 1682
    if item.mrp and tsp.maxPrice > item.mrp:
1683
        raise InventoryServiceException(101, "MRP is more than Saholic MRP")
7770 kshitij.so 1684
 
7306 rajveer 1685
    if tsp.recommendedPrice < item.sellingPrice:
7770 kshitij.so 1686
        raise InventoryServiceException(101, "MOP is less than Saholic MOP.")  
1687
 
7306 rajveer 1688
    if tsp.recommendedPrice < tsp.minPrice or tsp.recommendedPrice >  tsp.maxPrice:
7770 kshitij.so 1689
        raise InventoryServiceException(101, "MOP price must be in the range")
8867 rajveer 1690
 
1691
#    if tsp.minPrice < item.sellingPrice:
1692
#        store_message = "Saholic MOP Changed. DP {0} is less than Saholic MOP.\n".format(tsp.minPrice)
1693
#        subject = "Item '{0}' is updated in Catalog. Id is {1}".format(__get_product_name(item),item.id)
1694
#        __send_mail(subject, store_message, to_store_addresses)
7770 kshitij.so 1695
 
7306 rajveer 1696
    return True
7770 kshitij.so 1697
 
1698
 
7306 rajveer 1699
 
1700
def get_defalut_store_pricing(itemId):
7256 rajveer 1701
    inventoryClient = InventoryClient().get_client()
7306 rajveer 1702
    pricings = inventoryClient.getAllItemPricing(itemId)
1703
    item = get_item(itemId)
7382 rajveer 1704
    maxp = item.sellingPrice
1705
    if item.mrp:
1706
        maxp = item.mrp
7770 kshitij.so 1707
 
7256 rajveer 1708
    minp = 0
7265 rajveer 1709
    rp = item.sellingPrice
7256 rajveer 1710
    for pricing in pricings:
7770 kshitij.so 1711
        if not minp or minp > pricing.dealerPrice:
7256 rajveer 1712
            minp = pricing.dealerPrice
1713
 
7770 kshitij.so 1714
 
7426 anupam.sin 1715
    minap = math.ceil(min(max(500, rp*0.1),rp))
7306 rajveer 1716
 
7431 rajveer 1717
    if minp > rp:
1718
        minp = rp
7306 rajveer 1719
    sp = tStorePricing()
1720
    sp.itemId = itemId
7256 rajveer 1721
    sp.recommendedPrice = rp
7351 rajveer 1722
    sp.absoluteMinPrice = minp
7256 rajveer 1723
    sp.minPrice = minp
1724
    sp.minAdvancePrice = minap
1725
    sp.maxPrice = maxp
7308 rajveer 1726
    sp.freebieItemId = 0
1727
    sp.bestDealText = ""
7306 rajveer 1728
    return sp
7770 kshitij.so 1729
 
1730
 
7256 rajveer 1731
def get_store_pricing(itemId):
7270 rajveer 1732
    store = StorePricing.get_by(item_id = itemId)
7306 rajveer 1733
    if store is None:
1734
        return get_defalut_store_pricing(itemId)
1735
 
7256 rajveer 1736
    sp = tStorePricing()
7770 kshitij.so 1737
    sp.itemId = itemId   
7256 rajveer 1738
    sp.recommendedPrice = store.recommendedPrice
1739
    sp.minPrice = store.minPrice
1740
    sp.minAdvancePrice = store.minAdvancePrice
1741
    sp.maxPrice = store.maxPrice
7351 rajveer 1742
    sp.absoluteMinPrice = store.absoluteMinPrice
7308 rajveer 1743
    sp.freebieItemId = store.freebieItemId
1744
    sp.bestDealText = store.bestDealText
7281 kshitij.so 1745
    return sp
1746
 
1747
def get_all_amazon_listed_items():
1748
    return session.query(Amazonlisted).all()
1749
 
1750
def get_amazon_item_details(amazonItemId):
1751
    amazonlisted = Amazonlisted.get_by(itemId=amazonItemId)
1752
    return amazonlisted
1753
 
8168 kshitij.so 1754
def update_amazon_item_details(amazonlisted):
1755
    amazon_listed = Amazonlisted.get_by(itemId = amazonlisted.itemid)
1756
    amazon_listed.isFba=amazonlisted.isFba
1757
    amazon_listed.isNonFba=amazonlisted.isNonFba
1758
    amazon_listed.isInventoryOverride=amazonlisted.isInventoryOverride
1759
    amazon_listed.handlingTime=amazonlisted.handlingTime
1760
    amazon_listed.isCustomTime=amazonlisted.isCustomTime
8619 kshitij.so 1761
    amazon_listed.taxCode=amazonlisted.taxCode
1762
    if (amazon_listed.sellingPrice != amazonlisted.sellingPrice) and amazonlisted.sellingPrice > 0:
8168 kshitij.so 1763
        amazon_listed.mfnPriceLastUpdatedOn = datetime.datetime.now()
1764
        amazon_listed.sellingPrice=amazonlisted.sellingPrice
8619 kshitij.so 1765
    if (amazon_listed.fbaPrice != amazonlisted.fbaPrice) and amazonlisted.fbaPrice > 0:
8168 kshitij.so 1766
        amazon_listed.fbaPriceLastUpdatedOn = datetime.datetime.now()
1767
        amazon_listed.fbaPrice=amazonlisted.fbaPrice
1768
    amazon_listed.suppressMfnPriceUpdate=amazonlisted.suppressMfnPriceUpdate
1769
    amazon_listed.suppressFbaPriceUpdate=amazonlisted.suppressFbaPriceUpdate 
7281 kshitij.so 1770
    session.commit()
7770 kshitij.so 1771
 
7281 kshitij.so 1772
def add_amazon_item(amazonlisted):
1773
    if (not amazonlisted) or (not amazonlisted.itemid) or (not amazonlisted.asin):
1774
        return
7397 kshitij.so 1775
    amazonItem = Amazonlisted.get_by(itemId=amazonlisted.itemid)
1776
    if amazonItem is None:
1777
        amazon_item = Amazonlisted()
1778
        if amazonlisted.itemid:
1779
            amazon_item.itemId=amazonlisted.itemid
1780
        if amazonlisted.asin:
1781
            amazon_item.asin=amazonlisted.asin
1782
        if amazonlisted.brand:
1783
            amazon_item.brand=amazonlisted.brand
1784
        else:
1785
            amazon_item.brand=''
1786
        if amazonlisted.model:
1787
            amazon_item.model=amazonlisted.model
1788
        else:
1789
            amazon_item.model=''
1790
        if amazonlisted.manufacturer_name:
1791
            amazon_item.manufacturer_name=amazonlisted.manufacturer_name
1792
        else:
1793
            amazon_item.manufacturer_name=''
1794
        if amazonlisted.name:
1795
            amazon_item.name=amazonlisted.name
1796
        else:
1797
            amazon_item.name=''
1798
        if amazonlisted.part_number:
1799
            amazon_item.part_number=amazonlisted.part_number
1800
        else:
1801
            amazon_item.part_number=''
1802
        if amazonlisted.ean:
1803
            amazon_item.ean=amazonlisted.ean
1804
        else:
1805
            amazon_item.ean=''
1806
        if amazonlisted.upc:
1807
            amazon_item.upc=amazonlisted.upc
1808
        else:
1809
            amazon_item.upc=''
7770 kshitij.so 1810
        if amazonlisted.fbaPrice:
1811
            amazon_item.fbaPrice=amazonlisted.fbaPrice
7782 kshitij.so 1812
            amazon_item.fbaPriceLastUpdatedOnSc =  datetime.datetime.now()
7770 kshitij.so 1813
            amazon_item.fbaPriceLastUpdatedOn = datetime.datetime.now()
7397 kshitij.so 1814
        if amazonlisted.sellingPrice:
1815
            amazon_item.sellingPrice=amazonlisted.sellingPrice
7782 kshitij.so 1816
            amazon_item.mfnPriceLastUpdatedOnSc = datetime.datetime.now()
7770 kshitij.so 1817
            amazon_item.mfnPriceLastUpdatedOn = datetime.datetime.now()
7397 kshitij.so 1818
        if amazonlisted.category:
1819
            amazon_item.category=amazonlisted.category
1820
        else:
1821
            amazon_item.category=''
1822
        if amazonlisted.color:
1823
            amazon_item.color=amazonlisted.color
1824
        else:
7404 kshitij.so 1825
            amazon_item.color=''
8139 kshitij.so 1826
        amazon_item.suppressMfnPriceUpdate=False
8140 kshitij.so 1827
        amazon_item.suppressFbaPriceUpdate=False
8379 vikram.rag 1828
        amazon_item.isFba = False
1829
        amazon_item.isNonFba = False
1830
        amazon_item.isInventoryOverride = False
7397 kshitij.so 1831
    elif (amazonItem.asin!=amazonlisted.asin):
1832
        if amazonlisted.asin:
1833
            amazonItem.asin=amazonlisted.asin
1834
        if amazonlisted.brand:
1835
            amazonItem.brand=amazonlisted.brand
1836
        else:
1837
            amazonItem.brand=''
1838
        if amazonlisted.model:
1839
            amazonItem.model=amazonlisted.model
1840
        else:
1841
            amazonItem.model=''
1842
        if amazonlisted.manufacturer_name:
1843
            amazonItem.manufacturer_name=amazonlisted.manufacturer_name
1844
        else:
1845
            amazonItem.manufacturer_name=''
1846
        if amazonlisted.name:
1847
            amazonItem.name=amazonlisted.name
1848
        else:
1849
            amazonItem.name=''
1850
        if amazonlisted.part_number:
1851
            amazonItem.part_number=amazonlisted.part_number
1852
        else:
1853
            amazonItem.part_number=''
1854
        if amazonlisted.ean:
1855
            amazonItem.ean=amazonlisted.ean
1856
        else:
1857
            amazonItem.ean=''
1858
        if amazonlisted.upc:
1859
            amazonItem.upc=amazonlisted.upc
1860
        else:
1861
            amazonItem.upc=''
1862
        if amazonlisted.sellingPrice:
8188 kshitij.so 1863
            amazonItem.sellingPrice=amazonlisted.sellingPrice
7397 kshitij.so 1864
        if amazonlisted.fbaPrice:
8188 kshitij.so 1865
            amazonItem.fbaPrice=amazonlisted.fbaPrice
7397 kshitij.so 1866
        if amazonlisted.isFba:
1867
            amazonItem.isFba=amazonlisted.isFba
1868
        if amazonlisted.isNonFba:
1869
            amazonItem.isNonFba=amazonlisted.isNonFba
1870
        if amazonlisted.isInventoryOverride:
1871
            amazonItem.isInventoryOverride=amazonlisted.isInventoryOverride
1872
        if amazonlisted.category:
1873
            amazonItem.category=amazonlisted.category
1874
        else:
1875
            amazonItem.category=''
1876
        if amazonlisted.color:
1877
            amazonItem.color=amazonlisted.color
1878
        else:
7404 kshitij.so 1879
            amazonItem.color=''
7316 kshitij.so 1880
    else:
7397 kshitij.so 1881
        return
7281 kshitij.so 1882
    session.commit()
7770 kshitij.so 1883
 
7291 vikram.rag 1884
def get_asin_items():
7296 amit.gupta 1885
    from_date=datetime.datetime.now() - datetime.timedelta(days=10)
7291 vikram.rag 1886
    return Item.query.filter(Item.updatedOn > from_date).all()
7770 kshitij.so 1887
 
7291 vikram.rag 1888
def get_all_fba_listed_items():
1889
    return Amazonlisted.query.filter(Amazonlisted.isFba==True).all()
7770 kshitij.so 1890
 
7291 vikram.rag 1891
def get_all_nonfba_listed_items():
1892
    return Amazonlisted.query.filter(Amazonlisted.isNonFba==True).all()
7460 kshitij.so 1893
 
1894
def update_item_inventory(itemId,holdInventory,defaultInventory):
1895
    item = get_item(itemId)
1896
    item.holdInventory = holdInventory
1897
    item.defaultInventory = defaultInventory
1898
    session.commit()
7770 kshitij.so 1899
 
1900
def update_timestamp_for_amazon_feeds(feedType,skuList,timestamp):
1901
    #amazonListed = get_all_amazon_listed_items()
7782 kshitij.so 1902
    #fbaItems = []
1903
    #mfnItems = []
7770 kshitij.so 1904
    if feedType == 'NonFbaPricing':
7782 kshitij.so 1905
        for sku in skuList:
7770 kshitij.so 1906
            amazonItem = Amazonlisted.get_by(itemId=sku)
1907
            amazonItem.mfnPriceLastUpdatedOnSc = to_py_date(timestamp)
1908
            session.commit()
1909
        return True
1910
    elif feedType == 'FbaPricing':
7782 kshitij.so 1911
        for sku in skuList:
7770 kshitij.so 1912
            amazonItem = Amazonlisted.get_by(itemId=sku)
1913
            amazonItem.fbaPriceLastUpdatedOnSc = to_py_date(timestamp)
1914
            session.commit()
1915
        return True
1916
    elif feedType== 'FullFbaPricing':
7782 kshitij.so 1917
        for sku in skuList:
7770 kshitij.so 1918
            amazonItem = Amazonlisted.get_by(itemId=sku)
1919
            amazonItem.fbaPriceLastUpdatedOnSc = to_py_date(timestamp)
1920
            session.commit()
1921
        return True
1922
    elif feedType== 'FullNonFbaPricing':
7782 kshitij.so 1923
        for sku in skuList:
7770 kshitij.so 1924
            amazonItem = Amazonlisted.get_by(itemId=sku)
1925
            amazonItem.mfnPriceLastUpdatedOnSc = to_py_date(timestamp)
1926
            session.commit()
8386 vikram.rag 1927
    elif (feedType=='FbaListingFeed'):
1928
        for sku in skuList:
1929
            amazonItem = Amazonlisted.get_by(itemId=sku)
1930
            amazonItem.isFba = True
1931
            session.commit()
1932
    elif (feedType=='NonFbaListingFeed'):
1933
        for sku in skuList:
1934
            amazonItem = Amazonlisted.get_by(itemId=sku)
1935
            amazonItem.isNonFba = True 
1936
            session.commit()
7770 kshitij.so 1937
    else:
1938
        return False
7281 kshitij.so 1939
 
7897 amar.kumar 1940
def get_all_parent_categories():
1941
    return Category.query.filter_by(parent_category_id=10000).all()
7977 kshitij.so 1942
 
1943
def add_page_view_event(pageEvent):
1944
    page_view_event = PageViewEvents()
1945
    page_view_event.catalogId = pageEvent.catalogId
1946
    page_view_event.url = pageEvent.url
1947
    page_view_event.sellingPrice = pageEvent.sellingPrice
1948
    page_view_event.ip = pageEvent.ip
1949
    page_view_event.sessionId = pageEvent.sessionId
1950
    page_view_event.comingSoon = pageEvent.comingSoon
1951
    page_view_event.eventTimestamp = to_py_date(pageEvent.eventDate)
1952
    session.commit()
1953
 
1954
def add_cart_event(cartEvent):
1955
    cart_event = CartEvents()
1956
    cart_event.catalogId = cartEvent.catalogId
1957
    cart_event.itemId = cartEvent.itemId
1958
    cart_event.inStock = cartEvent.inStock
1959
    cart_event.ip = cartEvent.ip
1960
    cart_event.sessionId = cartEvent.sessionId
1961
    cart_event.comingSoon = cartEvent.comingSoon
1962
    cart_event.sellingPrice = cartEvent.sellingPrice
1963
    cart_event.eventTimestamp = to_py_date(cartEvent.eventDate)
1964
    session.commit()
8168 kshitij.so 1965
 
1966
def update_amazon_attributes_in_bulk(amazonlistedMap):
1967
    for itemId,amazonlisted in amazonlistedMap.iteritems():
1968
        amazon_item = get_amazon_item_details(itemId)
1969
        if amazon_item is not None:
1970
            if amazon_item.sellingPrice != amazonlisted.sellingPrice:
1971
                amazon_item.mfnPriceLastUpdatedOn = datetime.datetime.now()
1972
                amazon_item.sellingPrice = amazonlisted.sellingPrice
1973
            if amazon_item.fbaPrice != amazonlisted.fbaPrice:
1974
                amazon_item.fbaPriceLastUpdatedOn = datetime.datetime.now()
1975
                amazon_item.fbaPrice = amazonlisted.fbaPrice
8619 kshitij.so 1976
            amazon_item.taxCode = amazonlisted.taxCode
8168 kshitij.so 1977
            amazon_item.isFba = amazonlisted.isFba
1978
            amazon_item.isNonFba = amazonlisted.isNonFba
1979
            amazon_item.isInventoryOverride = amazonlisted.isInventoryOverride
1980
            amazon_item.suppressMfnPriceUpdate = amazonlisted.suppressMfnPriceUpdate
1981
            amazon_item.suppressFbaPriceUpdate = amazonlisted.suppressFbaPriceUpdate
1982
            session.commit()
1983
    return True
1984
 
7977 kshitij.so 1985
 
8182 amar.kumar 1986
def insert_ebay_item(ebayItem):
8241 amar.kumar 1987
    ebay_item = EbayItem.get_by(ebayListingId = ebayItem.ebayListingId)
1988
    if ebay_item is None:
1989
        ebay_item = EbayItem()
8182 amar.kumar 1990
    ebay_item.ebayListingId = ebayItem.ebayListingId
1991
    ebay_item.itemId = ebayItem.itemId
1992
    ebay_item.listingName = ebayItem.listingName
1993
    ebay_item.listingPrice = ebayItem.listingPrice
8281 amar.kumar 1994
    ebay_item.listingExpiryDate = to_py_date(ebayItem.listingExpiryDate)
8182 amar.kumar 1995
    ebay_item.subsidy = ebayItem.subsidy
1996
    ebay_item.defaultWarehouseId = ebayItem.defaultWarehouseId
1997
    session.commit()
1998
 
7977 kshitij.so 1999
 
8182 amar.kumar 2000
def get_ebay_item(listing_id):
2001
    ebay_item = EbayItem.get_by(ebayListingId = listing_id)
2002
    return ebay_item
7977 kshitij.so 2003
 
8182 amar.kumar 2004
 
2005
def update_ebay_item(ebayItem):
2006
    ebay_item = EbayItem.get_by(ebayListingId = ebayItem.ebayListingId)
2007
    #if ebay_item.listingExpiryDate < datetime.datetime.now():
2008
    ebay_item.listingName = ebayItem.listingName
2009
    ebay_item.listingPrice = ebayItem.listingPrice
2010
    ebay_item.listingExpiryDate = ebayItem.listingExpiryDate
2011
    ebay_item.subsidy = ebayItem.subsidy
2012
    ebay_item.defaultWarehouseId = ebayItem.defaultWarehouseId
2013
    session.commit()
8379 vikram.rag 2014
 
2015
def get_all_items_to_list_on_fba():
2016
    return Amazonlisted.query.filter(Amazonlisted.isFba==False).all()
2017
 
2018
def get_all_items_to_list_on_nonfba():
2019
    return Amazonlisted.query.filter(Amazonlisted.isNonFba==False).all()
8182 amar.kumar 2020
 
8619 kshitij.so 2021
def get_amazon_listed_items(offset,limit):
2022
    return session.query(Amazonlisted).offset(offset).limit(limit).all()
2023
 
2024
def search_amazon_items(search_terms, offset, limit):
2025
    query = Amazonlisted.query
2026
 
2027
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2028
 
2029
    for search_term in search_terms:
2030
        query_clause = []
2031
        query_clause.append(Amazonlisted.itemId.like(search_term))
2032
        query_clause.append(Amazonlisted.brand.like(search_term))
2033
        query_clause.append(Amazonlisted.model.like(search_term))
2034
        query_clause.append(Amazonlisted.name.like(search_term))
2035
        query_clause.append(Amazonlisted.asin.like(search_term))
2036
        query = query.filter(or_(*query_clause))
2037
 
2038
    query = query.offset(offset)
2039
    if limit:
2040
        query = query.limit(limit)
2041
    amazon_items = query.all()
2042
    return amazon_items
2043
 
2044
def get_amazon_search_result_count(search_terms):
2045
    query = Amazonlisted.query
2046
 
2047
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2048
 
2049
    for search_term in search_terms:
2050
        query_clause = []
2051
        query_clause.append(Amazonlisted.itemId.like(search_term))
2052
        query_clause.append(Amazonlisted.brand.like(search_term))
2053
        query_clause.append(Amazonlisted.model.like(search_term))
2054
        query_clause.append(Amazonlisted.name.like(search_term))
2055
        query_clause.append(Amazonlisted.asin.like(search_term))
2056
        query = query.filter(or_(*query_clause))
2057
 
2058
    return query.count()
2059
 
2060
def get_count_for_amazonlisted_items():
2061
    return session.query(func.count(Amazonlisted.itemId)).scalar()
2062
 
8739 vikram.rag 2063
def add_or_update_snapdeal_item(snapdealitem):
2064
    item = SnapdealItem.get_by(item_id=snapdealitem.item_id)
2065
    try:
2066
        if item is not None:
9242 kshitij.so 2067
            itemHistory = SnapdealItemUpdateHistory()
2068
            itemHistory.item_id = snapdealitem.item_id
2069
            itemHistory.exceptionPrice = item.exceptionPrice
2070
            itemHistory.warehouseId = item.warehouseId
2071
            itemHistory.isListedOnSnapdeal = item.isListedOnSnapdeal
2072
            itemHistory.transferPrice = item.transferPrice
2073
            itemHistory.sellingPrice = item.sellingPrice
2074
            itemHistory.courierCost = item.courierCost
2075
            itemHistory.commission = item.commission
2076
            itemHistory.serviceTax = item.serviceTax
2077
            itemHistory.suppressPriceFeed = item.suppressPriceFeed
2078
            itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
2079
            itemHistory.updatedOn = item.updatedOn
2080
 
8739 vikram.rag 2081
            if snapdealitem.exceptionPrice is not None:
2082
                item.exceptionPrice = snapdealitem.exceptionPrice
2083
            if snapdealitem.warehouseId is not None:     
2084
                item.warehouseId = snapdealitem.warehouseId
2085
            if snapdealitem.isListedOnSnapdeal is not None:    
9242 kshitij.so 2086
                item.isListedOnSnapdeal = snapdealitem.isListedOnSnapdeal
2087
            if snapdealitem.transferPrice is not None:
2088
                item.transferPrice = snapdealitem.transferPrice
2089
            if snapdealitem.sellingPrice is not None:
2090
                item.sellingPrice = snapdealitem.sellingPrice
2091
            if snapdealitem.courierCost is not None:
2092
                item.courierCost = snapdealitem.courierCost    
2093
            if snapdealitem.commission is not None:
2094
                item.commission = snapdealitem.commission
2095
            if snapdealitem.serviceTax is not None:
2096
                item.serviceTax = snapdealitem.serviceTax
2097
            item.suppressPriceFeed =snapdealitem.suppressPriceFeed
2098
            item.suppressInventoryFeed =snapdealitem.suppressInventoryFeed 
2099
            item.updatedOn = datetime.datetime.now()
2100
            session.commit()
2101
            return True
8739 vikram.rag 2102
        else:
2103
            item = SnapdealItem()
2104
            if snapdealitem.item_id is not None:
2105
                item.item_id = snapdealitem.item_id
2106
                if snapdealitem.exceptionPrice is not None:
2107
                    item.exceptionPrice = snapdealitem.exceptionPrice
2108
                if snapdealitem.warehouseId is not None:    
2109
                    item.warehouseId = snapdealitem.warehouseId
2110
                if snapdealitem.isListedOnSnapdeal is not None: 
9242 kshitij.so 2111
                    item.isListedOnSnapdeal = snapdealitem.isListedOnSnapdeal
2112
                if snapdealitem.transferPrice is not None:
2113
                    item.transferPrice = snapdealitem.transferPrice
2114
                if snapdealitem.sellingPrice is not None:
2115
                    item.sellingPrice = snapdealitem.sellingPrice
2116
                if snapdealitem.courierCost is not None:
2117
                    item.courierCost = snapdealitem.courierCost    
2118
                if snapdealitem.commission is not None:
2119
                    item.commission = snapdealitem.commission
2120
                if snapdealitem.serviceTax is not None:
2121
                    item.serviceTax = snapdealitem.serviceTax
2122
                item.suppressPriceFeed =snapdealitem.suppressPriceFeed
2123
                item.suppressInventoryFeed =snapdealitem.suppressInventoryFeed 
2124
                item.updatedOn = datetime.datetime.now()    
2125
                session.commit()
2126
                return True
2127
        return False
8739 vikram.rag 2128
    except:
2129
        return False
2130
 
2131
def get_snapdeal_item(itemid):
8755 vikram.rag 2132
    item = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).filter(SnapdealItem.item_id==itemid).first()
8747 vikram.rag 2133
    print item
2134
    return item
8739 vikram.rag 2135
 
2136
def get_all_snapdeal_items():
8754 vikram.rag 2137
    items = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).all()
8739 vikram.rag 2138
    print items
2139
    return items
2140
 
9242 kshitij.so 2141
def get_snapdeal_items(offset,limit):
2142
    return session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).offset(offset).limit(limit).all()
2143
 
8619 kshitij.so 2144
def update_asin(amazonAsinMap):
2145
    for item_id,t_item in amazonAsinMap.iteritems():
2146
        item = get_item(item_id)
2147
        item.asin=t_item.asin
2148
        item.defaultInventory = t_item.defaultInventory
2149
        item.holdInventory = t_item.holdInventory
2150
        item.updatedOn = datetime.datetime.now()
2151
    session.commit()
9242 kshitij.so 2152
 
2153
def search_snapdeal_items(search_terms,offset,limit):
2154
    query = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id))
2155
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2156
    for search_term in search_terms:
2157
        query_clause = []
2158
        query_clause.append(Item.id.like(search_term))
2159
        query_clause.append(Item.brand.like(search_term))
2160
        query_clause.append(Item.model_name.like(search_term))
2161
        query_clause.append(Item.model_number.like(search_term))
2162
        query_clause.append(Item.color.like(search_term))
2163
        query = query.filter(or_(*query_clause))
2164
 
2165
    query = query.offset(offset)
2166
    if limit:
2167
        query = query.limit(limit)
2168
    snapdeal_items = query.all()
2169
    return snapdeal_items
2170
 
2171
def get_snapdeal_search_result_count(search_terms):
2172
    query = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id))
2173
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2174
    for search_term in search_terms:
2175
        query_clause = []
2176
        query_clause.append(Item.id.like(search_term))
2177
        query_clause.append(Item.brand.like(search_term))
2178
        query_clause.append(Item.model_name.like(search_term))
2179
        query_clause.append(Item.model_number.like(search_term))
2180
        query_clause.append(Item.color.like(search_term))
2181
        query = query.filter(or_(*query_clause))
2182
    return query.count()
2183
 
2184
def get_count_for_snapdeal_items():
2185
    return session.query(func.count(SnapdealItem.item_id)).scalar()
2186
 
2187
 
2188