Subversion Repositories SmartDukaan

Rev

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