Subversion Repositories SmartDukaan

Rev

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