Subversion Repositories SmartDukaan

Rev

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