Subversion Repositories SmartDukaan

Rev

Rev 7265 | Rev 7271 | 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
5318 rajveer 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, \
7256 rajveer 18
    OOSTracker,EntityTag,ItemInsurerMapping, Insurer, Banner, BannerMap, FreebieItem,\
19
    StorePricing
5944 mandeep.dh 20
from shop2020.thriftpy.model.v1.catalog.ttypes import status, ItemShippingInfo, \
7256 rajveer 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
 
6826 amit.gupta 167
    if item.startDate:
168
        ds_item.startDate = to_py_date(item.startDate)
169
        ds_item.startDate = ds_item.startDate.replace(hour=0,second=0,minute=0)
170
        if item.itemStatus == status.COMING_SOON and ds_item.startDate < datetime.datetime.now()  :
171
            item.itemStatus = status.ACTIVE
172
            item.status_description = "This item is active"
173
    else:
174
        ds_item.startDate = None
175
 
2358 ankur.sing 176
    if ds_item.status != item.itemStatus:
2402 rajveer 177
        add_status_change_log(ds_item, item.itemStatus)
5047 amit.gupta 178
        if item.itemStatus == status.PHASED_OUT:
179
            message += "Item is phased out."
2358 ankur.sing 180
        ds_item.status = item.itemStatus
2035 rajveer 181
    if item.status_description:
182
        ds_item.status_description = item.status_description
122 ashish 183
 
511 rajveer 184
    if item.retireDate:
2116 ankur.sing 185
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 186
    else:
187
        ds_item.retireDate = None
5217 amit.gupta 188
 
189
    if item.expectedArrivalDate:
190
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)
191
    else:
192
        ds_item.expectedArrivalDate = None
511 rajveer 193
 
5217 amit.gupta 194
    if item.comingSoonStartDate:
195
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
6696 rajveer 196
        ds_item.comingSoonStartDate = ds_item.comingSoonStartDate.replace(hour=0,second=0,minute=0)
5217 amit.gupta 197
    else:
198
        ds_item.comingSoonStartDate = None
199
 
200
 
2497 ankur.sing 201
    ds_item.feature_id = item.featureId
202
    ds_item.feature_description = item.featureDescription
122 ashish 203
 
5047 amit.gupta 204
    if ds_item.bestDealText or item.bestDealText:
205
        if item.bestDealText != ds_item.bestDealText:
5080 amit.gupta 206
            message += "Promotion text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealText, item.bestDealText)
2129 ankur.sing 207
    ds_item.bestDealText = item.bestDealText
208
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 209
    ds_item.bestSellingRank = item.bestSellingRank
2497 ankur.sing 210
 
6777 vikram.rag 211
    if ds_item.bestDealsDetailsText or item.bestDealsDetailsText:
212
        if item.bestDealsDetailsText != ds_item.bestDealsDetailsText:
213
            message += "Best deals details text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealsDetailsText, item.bestDealsDetailsText)
214
    ds_item.bestDealsDetailsText = item.bestDealsDetailsText
215
 
216
    if ds_item.bestDealsDetailsLink or item.bestDealsDetailsLink:
217
        if item.bestDealsDetailsLink != ds_item.bestDealsDetailsLink:
218
            message += "Best deals details link is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealsDetailsLink, item.bestDealsDetailsLink)
219
    ds_item.bestDealsDetailsLink = item.bestDealsDetailsLink
220
 
221
 
2065 ankur.sing 222
    ds_item.defaultForEntity = item.defaultForEntity
5047 amit.gupta 223
 
224
    if ds_item.risky or item.risky:
225
        if ds_item.risky != item.risky:
5080 amit.gupta 226
            message += "Risky flag is changed to '{0}'.\n".format(set)
5047 amit.gupta 227
 
2251 ankur.sing 228
    ds_item.risky = item.risky
3359 chandransh 229
 
5385 phani.kuma 230
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
231
    ds_item.hasItemNo = item.hasItemNo
232
 
3459 chandransh 233
    if item.expectedDelay is not None:
3359 chandransh 234
        ds_item.expectedDelay = item.expectedDelay
4506 phani.kuma 235
 
236
    if item.preferredVendor:
5080 amit.gupta 237
        if item.preferredVendor != ds_item.preferredVendor:
5944 mandeep.dh 238
            inventoryClient = InventoryClient().get_client()
239
            newPreferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
5080 amit.gupta 240
            oldPreferredVendorName = 'None'
241
            if ds_item.preferredVendor:
5944 mandeep.dh 242
                oldPreferredVendorName = inventoryClient.getVendor(ds_item.preferredVendor).name
5408 amit.gupta 243
            message += "Preferred vendor is changed from '{0}' to '{1}'.\n".format(oldPreferredVendorName, newPreferredVendorName)        
4506 phani.kuma 244
        ds_item.preferredVendor = item.preferredVendor
6838 vikram.rag 245
 
5080 amit.gupta 246
    if item.isWarehousePreferenceSticky != ds_item.isWarehousePreferenceSticky:
247
        flag = "ON" if item.isWarehousePreferenceSticky else "OFF"
248
        message += "Warehouse preference sticky is {0}.\n".format(flag)
249
 
4413 anupam.sin 250
    ds_item.isWarehousePreferenceSticky = item.isWarehousePreferenceSticky
3359 chandransh 251
 
2347 ankur.sing 252
    ds_item.updatedOn = datetime.datetime.now()
2065 ankur.sing 253
 
7265 rajveer 254
    if item.activeOnStore and  not ds_item.activeOnStore:
255
        add_store_pricing(ds_item)
256
    ds_item.activeOnStore = item.activeOnStore
257
 
122 ashish 258
    session.commit();
5047 amit.gupta 259
    subject = "Item '{0}' is updated in Catalog. Id is {1}".format(__get_product_name(ds_item),ds_item.id)
260
    if message:
261
        __send_mail(subject, message)
122 ashish 262
    return ds_item.id
94 ashish 263
 
103 ashish 264
def add_item(item):
265
    if not item:
122 ashish 266
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 267
    if get_item(item.id):
122 ashish 268
        raise InventoryServiceException(101, "Item already exists")
2120 ankur.sing 269
 
270
    validate_item_prices(item)
271
 
103 ashish 272
    ds_item = Item()
963 chandransh 273
    if item.productGroup:
274
        ds_item.product_group = item.productGroup
275
    if item.brand:
276
        ds_item.brand = item.brand
515 rajveer 277
    if item.modelName:
278
        ds_item.model_name = item.modelName
279
    if item.modelNumber:
280
        ds_item.model_number = item.modelNumber
609 chandransh 281
    if item.color:
282
        ds_item.color = item.color
483 rajveer 283
    if item.category:
284
        ds_item.category = item.category
285
    if item.comments:
286
        ds_item.comments = item.comments
287
 
103 ashish 288
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 289
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 290
    if item.startDate:
291
        ds_item.startDate = to_py_date(item.startDate)
6696 rajveer 292
        ds_item.startDate = ds_item.startDate.replace(hour=0,second=0,minute=0)
2116 ankur.sing 293
    if item.retireDate:
294
        ds_item.retireDate = to_py_date(item.retireDate)
5217 amit.gupta 295
    if item.comingSoonStartDate:
296
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
297
    if item.expectedArrivalDate:
298
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)    
483 rajveer 299
    if item.mrp:
300
        ds_item.mrp = item.mrp
301
    if item.sellingPrice:
302
        ds_item.sellingPrice = item.sellingPrice
122 ashish 303
    if item.weight:
304
        ds_item.weight = item.weight
305
 
306
    if item.featureId:
307
        ds_item.feature_id = item.featureId
308
    if item.featureDescription:
309
        ds_item.feature_description = item.featureDescription
310
 
2116 ankur.sing 311
 
103 ashish 312
    #check if categories present. If yes, add them to system
122 ashish 313
 
609 chandransh 314
    if item.bestDealValue:
315
        ds_item.bestDealValue = item.bestDealValue
316
    if item.bestDealText:
317
        ds_item.bestDealText = item.bestDealText
6777 vikram.rag 318
    if item.bestDealsDetailsText:
319
        ds_item.bestDealsDetailsText = item.bestDealsDetailsText
320
    if item.bestDealsDetailsLink:
321
        ds_item.bestDealsDetailsLink = item.bestDealsDetailsLink    
2116 ankur.sing 322
    if item.bestSellingRank:
323
        ds_item.bestSellingRank = item.bestSellingRank
324
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 325
    ds_item.risky = item.risky
609 chandransh 326
 
5385 phani.kuma 327
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
328
    ds_item.hasItemNo = item.hasItemNo
7256 rajveer 329
    ds_item.activeOnStore = item.activeOnStore
5385 phani.kuma 330
 
3467 chandransh 331
    if item.expectedDelay is not None:
3359 chandransh 332
        ds_item.expectedDelay = item.expectedDelay
3467 chandransh 333
    else:
334
        ds_item.expectedDelay = 0
3359 chandransh 335
 
5408 amit.gupta 336
    preferredVendorName = "None"
4881 phani.kuma 337
    if item.preferredVendor:
338
        ds_item.preferredVendor = item.preferredVendor
5944 mandeep.dh 339
        inventoryClient = InventoryClient().get_client()
6838 vikram.rag 340
        preferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
341
 
342
    if item.preferredInsurer is not None:
343
        ds_item.preferredInsurer = item.preferredInsurer             
4881 phani.kuma 344
 
5586 phani.kuma 345
    if item.catalogItemId:
346
        catalog_client = CatalogClient("catalog_service_server_host_master", "catalog_service_server_port").get_client()
347
        master_items = catalog_client.getItemsByCatalogId(item.catalogItemId)
348
        itemStatus = status.IN_PROCESS
349
        for masterItem in master_items:
350
            if masterItem.itemStatus in [status.CONTENT_COMPLETE, status.COMING_SOON, status.ACTIVE, status.PAUSED]:
351
                itemStatus = status.CONTENT_COMPLETE
352
                ds_item.category = masterItem.category
353
                break
354
        ds_item.catalog_item_id = item.catalogItemId
355
        ds_item.status = itemStatus
2116 ankur.sing 356
        ds_item.status_description = "This item is in process."
357
    else:
5586 phani.kuma 358
        # Check if a similar item already exists in our database
359
        similar_item = Item.query.filter_by(brand=item.brand, model_number=item.modelNumber, model_name=item.modelName).first()
360
        print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2}".format(item.brand, item.modelNumber, item.modelName)
361
 
362
        if similar_item is None or similar_item.catalog_item_id is None:
363
            # If there is no similar item in the database from before,
364
            # use the entity_id_generator
365
            entity_id = EntityIDGenerator.query.first()
366
            ds_item.catalog_item_id = entity_id.id + 1
367
            ds_item.status = status.IN_PROCESS
368
            ds_item.status_description = "This item is in process."
369
            entity_id.id = entity_id.id  + 1
370
            if similar_item is not None and similar_item.catalog_item_id is None:
371
                similar_item.catalog_item_id = entity_id.id
372
        else:
373
            #If a similar item already exists for a product group, brand and model_number, set it as same.
374
            ds_item.catalog_item_id = similar_item.catalog_item_id
375
            ds_item.category = similar_item.category
376
            ds_item.product_group = similar_item.product_group
377
            ds_item.status = similar_item.status
378
            ds_item.status_description = similar_item.status_description
2116 ankur.sing 379
 
103 ashish 380
    session.commit();
5052 amit.gupta 381
    subject = "New item is added. Id is {0}".format(str(ds_item.id))
6777 vikram.rag 382
    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 383
    __send_mail(subject, message)
3325 chandransh 384
    return ds_item.id
385
 
103 ashish 386
def retire_item(item_id):
387
    if not item_id:
122 ashish 388
        raise InventoryServiceException(101, "bad item id")
635 rajveer 389
    item = get_item(item_id)
103 ashish 390
    if not item:
122 ashish 391
        raise InventoryServiceException(108, "item id not present")
392
    item.status = status.PHASED_OUT
393
    item.retireDate = datetime.datetime.now()
103 ashish 394
    session.commit()
122 ashish 395
 
396
#need to implement threads based solution here
103 ashish 397
def start_item_on(item_id, timestamp):
398
    if not item_id:
122 ashish 399
        raise InventoryServiceException(101, "bad item id")
635 rajveer 400
    item = get_item(item_id)
103 ashish 401
    if not item:
122 ashish 402
        raise InventoryServiceException(108, "item id not present")
103 ashish 403
 
122 ashish 404
    item.status = status.ACTIVE
405
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
406
    add_status_change_log(item, status.ACTIVE)
103 ashish 407
    session.commit()
408
 
122 ashish 409
#need to implement threads here
103 ashish 410
def retire_item_on(item_id, timestamp):
411
    if not item_id:
122 ashish 412
        raise InventoryServiceException(101, "bad item id")
635 rajveer 413
    item = get_item(item_id)
103 ashish 414
    if not item:
122 ashish 415
        raise InventoryServiceException(108, "item id not present")
103 ashish 416
 
122 ashish 417
    item.status = status.PHASED_OUT
418
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
419
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 420
    session.commit()
421
 
422
def add_status_change_log(item, new_status):
423
    item_change_log = ItemChangeLog()
424
    item_change_log.new_status = new_status
425
    item_change_log.old_status = item.status
426
    item_change_log.timestamp = datetime.datetime.now()
427
    item_change_log.item = item
428
    session.commit()
429
 
430
def change_item_status(item_id, new_status):
431
    if not item_id:
122 ashish 432
        raise InventoryServiceException(101, "bad item id")
635 rajveer 433
    item = get_item(item_id)
103 ashish 434
    if not item:
122 ashish 435
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 436
    add_status_change_log(item, new_status)
122 ashish 437
    item.status = new_status
2251 ankur.sing 438
    if item.status == status.PHASED_OUT:
439
        item.status_description = "This item has been phased out"
5047 amit.gupta 440
        __send_mail("Item '{0}' is Phased-Out. Item id is {1}".format(__get_product_name(item), item_id), "")
2251 ankur.sing 441
    elif item.status == status.DELETED:
442
        item.status_description = "This item has been deleted"
3924 rajveer 443
    elif item.status == status.PAUSED:
444
        item.status_description = "This item is currently out of stock"      
445
    elif item.status == status.PAUSED_BY_RISK:
446
        item.status_description = "This item is currently out of stock"
447
        #This will clear cache from tomcat
448
        __clear_homepage_cache()  
2251 ankur.sing 449
    elif item.status == status.ACTIVE:
450
        item.status_description = "This item is active"
451
    elif item.status == status.IN_PROCESS:
452
        item.status_description = "This item is in process"
453
    elif item.status == status.CONTENT_COMPLETE:
454
        item.status_description = "This item is in process"
103 ashish 455
    session.commit()
456
 
5944 mandeep.dh 457
def check_risky_item(item_id):
635 rajveer 458
    item = get_item(item_id)
2251 ankur.sing 459
    if not item.risky:
460
        return
5944 mandeep.dh 461
    client = InventoryClient().get_client()
5978 rajveer 462
    itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)    
5944 mandeep.dh 463
    warehouse_id = itemInfo[0]
464
    availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item.id)
465
    if availability <= 0:
2251 ankur.sing 466
        if item.status == status.ACTIVE:
2984 rajveer 467
            change_item_status(item.id, status.PAUSED_BY_RISK)
4797 rajveer 468
            __send_mail_for_oos_item(item)
2251 ankur.sing 469
    else:
2984 rajveer 470
        if item.status == status.PAUSED_BY_RISK:
2251 ankur.sing 471
            change_item_status(item.id, status.ACTIVE)
6255 rajveer 472
            __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 473
    session.commit()
2983 chandransh 474
 
2075 rajveer 475
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
2828 rajveer 476
    '''
477
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
478
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
479
    '''
723 chandransh 480
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 481
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 482
    current_timestamp = datetime.datetime.now()
483
    for item in items:
2828 rajveer 484
        if item.status == status.IN_PROCESS:
485
            item.status = content_complete_status
486
            item_change_log = ItemChangeLog()
487
            item_change_log.old_status = item.status
488
            item_change_log.new_status = content_complete_status
489
            item_change_log.timestamp = current_timestamp
490
            item_change_log.item = item
723 chandransh 491
 
4762 phani.kuma 492
        category_object = get_category(category)
493
        if category_object is not None:
494
            item.category = category
495
            item.product_group = category_object.display_name
2075 rajveer 496
        item.brand = brand
2081 rajveer 497
        item.model_name = modelName
498
        item.model_number = modelNumber
723 chandransh 499
        item.updatedOn = current_timestamp
500
    session.commit()
501
    return True
1294 chandransh 502
 
2404 chandransh 503
def get_child_categories(category):
504
    cm = CategoryManager()
2621 varun.gupt 505
    cat = cm.getCategory(category)
506
    return cat.children_category_ids if cat else None
2404 chandransh 507
 
626 chandransh 508
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 509
    '''
510
    Returns the Best Sellers between the start and the stop index in the given category
511
    '''
1926 rajveer 512
    query = get_best_sellers_query(category, None)
1098 chandransh 513
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 514
    return get_thrift_item_list(best_sellers)
515
 
2093 chandransh 516
def get_best_sellers_count(category=-1):
2404 chandransh 517
    '''
518
    Returns the number of best sellers in the given category
519
    '''
1926 rajveer 520
    count = get_best_sellers_query(category, None).count()
1120 rajveer 521
    if count is None:
522
        count = 0
766 rajveer 523
    return count
621 chandransh 524
 
1926 rajveer 525
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 526
    '''
527
    Returns the Best sellers for the given brand and category between the start and the stop index.
528
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
529
    '''
1926 rajveer 530
    query = get_best_sellers_query(category, brand)
1098 chandransh 531
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 532
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 533
 
1926 rajveer 534
def get_best_sellers_query(category, brand):
2404 chandransh 535
    '''
536
    Returns the query to be used for getting Best Sellers.
537
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
538
    '''
1098 chandransh 539
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 540
    if category != -1:
1970 rajveer 541
        all_categories = [category]
542
        child_categories = get_child_categories(category)
543
        if child_categories is not None:
544
            all_categories = all_categories + child_categories 
545
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 546
    if brand is not None:
547
        query = query.filter_by(brand=brand)
7202 amit.gupta 548
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.bestSellingRank))
621 chandransh 549
    return query
609 chandransh 550
 
1098 chandransh 551
def get_best_deals(category=-1):
2404 chandransh 552
    '''
553
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
554
    '''
555
    query = get_best_deals_query(Item, category, None)
1098 chandransh 556
    items = query.all()
609 chandransh 557
    return get_thrift_item_list(items)
558
 
1098 chandransh 559
def get_best_deals_count(category=-1):
2404 chandransh 560
    '''
561
    Returns the count of best deals in the given category.
562
    Ignores the category if it's -1.
563
    '''
564
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 565
    if count is None:
566
        count = 0
766 rajveer 567
    return count
501 rajveer 568
 
1926 rajveer 569
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 570
    '''
571
    Returns the catalog_item_ids of best deal items for the given brand and category.
572
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
573
    '''
574
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 575
    best_deal_items = query.all()[start_index:stop_index]
576
    return [item.catalog_item_id for item in best_deal_items]
577
 
2404 chandransh 578
def get_best_deals_counting_query(obj, category, brand):
579
    '''
580
    Returns the query to be used to select the best deals in the given brand and category.
581
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
582
    '''
583
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 584
    if category != -1:
1970 rajveer 585
        all_categories = [category]
586
        child_categories = get_child_categories(category)
587
        if child_categories is not None:
588
            all_categories = all_categories + child_categories 
589
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 590
    if brand is not None:
591
        query = query.filter_by(brand=brand)
2404 chandransh 592
    return query
593
 
594
def get_best_deals_query(obj, category, brand):
595
    '''
596
    Returns the query to be used to get the best deals in the given category and brand.
597
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
598
    '''
599
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 600
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
601
    return query
609 chandransh 602
 
5217 amit.gupta 603
def get_coming_soon(category=-1):
604
    '''
605
    Returns the Coming Soon items in the given category. Ignores the category if it's passed as -1.
606
    '''
607
    query = get_coming_soon_query(Item, category, None)
608
    items = query.all()
609
    return get_thrift_item_list(items)
610
 
611
def get_coming_soon_count(category=-1):
612
    '''
613
    Returns the count of coming in the given category.
614
    Ignores the category if it's -1.
615
    '''
616
    count = get_coming_soon_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
617
    if count is None:
618
        count = 0
619
    return count
620
 
621
def get_coming_soon_catalog_ids(start_index, stop_index, brand, category=-1):
622
    '''
623
    Returns the catalog_item_ids of coming soon 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_coming_soon_query(Item, category, brand)
627
    coming_soon_items = query.all()[start_index:stop_index]
628
    return [item.catalog_item_id for item in coming_soon_items]
629
 
630
def get_coming_soon_counting_query(obj, category, brand):
631
    '''
632
    Returns the query to be used to select the coming soon product in the given brand and category.
633
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
634
    '''
635
    query = session.query(obj).filter_by(status=status.COMING_SOON)
636
    if category != -1:
637
        all_categories = [category]
638
        child_categories = get_child_categories(category)
639
        if child_categories is not None:
640
            all_categories = all_categories + child_categories 
641
        query = query.filter(Item.category.in_(all_categories))
642
    if brand is not None:
643
        query = query.filter_by(brand=brand)
644
    return query
645
 
646
def get_coming_soon_query(obj, category, brand):
647
    '''
648
    Returns the query to be used to get the coming soon products 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_coming_soon_counting_query(obj, category, brand)
652
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.comingSoonStartDate))
653
    return query
654
 
1098 chandransh 655
def get_latest_arrivals(limit, category=-1):
2404 chandransh 656
    '''
657
    Returns up to limit number of Latest Arrivals in the given category.
658
    '''
2975 chandransh 659
    categories = []
660
    if category != -1:
661
        categories = [category]
662
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 663
    items = query.all()[0:limit]
609 chandransh 664
    return get_thrift_item_list(items)
598 chandransh 665
 
1098 chandransh 666
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 667
    '''
668
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 669
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 670
    '''
2975 chandransh 671
    categories = []
672
    if category != -1:
673
        categories = [category]
674
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 675
    if count is None:
676
        count = 0
677
    count = min(count, limit)
766 rajveer 678
    return count
602 chandransh 679
 
2975 chandransh 680
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 681
    '''
682
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 683
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 684
    '''
2975 chandransh 685
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 686
    latest_arrivals = query.all()[start_index:stop_index]
687
    return [item.catalog_item_id for item in latest_arrivals]
688
 
2975 chandransh 689
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 690
    '''
691
    Returns the query to be used to count Latest arrivals.
3016 chandransh 692
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 693
    '''
694
    query = session.query(obj).filter_by(status=status.ACTIVE)
2975 chandransh 695
 
696
    all_categories = []
697
    for category in categories:
698
        all_categories.append(category)
1970 rajveer 699
        child_categories = get_child_categories(category)
2975 chandransh 700
        if child_categories:
701
            all_categories = all_categories + child_categories
702
    if all_categories: 
1970 rajveer 703
        query = query.filter(Item.category.in_(all_categories))
2975 chandransh 704
 
1926 rajveer 705
    if brand is not None:
706
        query = query.filter_by(brand=brand)
2404 chandransh 707
    return query
708
 
2975 chandransh 709
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 710
    '''
711
    Returns the query to be used to retrieve Latest Arrivals.
712
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
713
    '''
2975 chandransh 714
    query = get_latest_arrivals_counting_query(obj, categories, brand)
5167 rajveer 715
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate)).order_by(Item.catalog_item_id)
1098 chandransh 716
    return query
609 chandransh 717
 
718
def get_thrift_item_list(items):
1098 chandransh 719
    return [to_t_item(item) for item in items if item != None]
635 rajveer 720
 
1155 rajveer 721
def generate_new_entity_id():
722
    generator =  EntityIDGenerator.query.one()
723
    id = generator.id + 1
724
    generator.id = id
725
    session.commit()
726
    return id
727
 
635 rajveer 728
def put_category_object(object):
729
    category = Category.get_by(id=1)
730
    if category is None:
731
        category = Category()
732
    category.object = object    
733
    session.commit()
734
    return True
735
 
736
def get_category_object():
766 rajveer 737
    object = Category.get_by(id=1).object
738
    return object
739
 
1970 rajveer 740
def add_category(t_category):
741
    category = Category.get_by(id=t_category.id)
742
    if category is None:
743
        category = Category()
744
    category.id = t_category.id 
745
    category.label = t_category.label
746
    category.description = t_category.description
4762 phani.kuma 747
    category.display_name = t_category.display_name
1970 rajveer 748
    category.parent_category_id = t_category.parent_category_id 
749
    session.commit()
750
    return True
751
 
752
def get_category(id):
753
    return Category.query.filter_by(id=id).first()
754
 
755
def get_all_categories():
756
    return Category.query.all()
757
 
2120 ankur.sing 758
def validate_item_prices(item):
2129 ankur.sing 759
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
760
        return
761
    if item.mrp < item.sellingPrice:
2120 ankur.sing 762
        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))
763
        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)))
7257 rajveer 764
#    if minp < item.sellingPrice:
765
#        print "alert to store" 
766
#    if maxp > item.mrp:
767
#        print "reset to mrp"
768
#        print "alert to store"
2065 ankur.sing 769
    return
2120 ankur.sing 770
 
771
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 772
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 773
        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))
774
        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)))
775
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
776
        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))
777
        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)))
7257 rajveer 778
#    if change in dp:
779
#        print "alert to store" 
7256 rajveer 780
 
2120 ankur.sing 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
 
7265 rajveer 1465
def update_store_pricing(tsp):
1466
    sp = StorePricing.get_by(itemId = tsp.itemId)
1467
    if not sp:
1468
        sp = StorePricing()
1469
    sp.recommendedPrice = tsp.recommendedPrice
1470
    sp.minPrice = tsp.minPrice
1471
    sp.minAdvancePrice = tsp.minAdvancePrice
1472
    sp.maxPrice = tsp.maxPrice
1473
    sp.itemId = tsp.itemId
1474
    session.commit()
1475
 
1476
 
1477
def add_store_pricing(item):
7256 rajveer 1478
    inventoryClient = InventoryClient().get_client()
1479
    pricings = inventoryClient.getAllItemPricing(item.id)
1480
 
1481
    minp = 0
1482
    maxp = item.mrp
7265 rajveer 1483
    rp = item.sellingPrice
7256 rajveer 1484
    for pricing in pricings:
1485
        if not minp or minp > pricing.dealerPrice: 
1486
            minp = pricing.dealerPrice
1487
 
1488
    if minp < item.sellingPrice:
1489
        print "Alert to store"        
1490
 
1491
    if maxp < minp:
1492
        print "Alert to store"
1493
 
1494
    if rp < minp or rp > maxp:
1495
        print "Alert to store" 
1496
 
1497
    minap = min(max(500, 10%rp),rp)
7265 rajveer 1498
    sp = StorePricing.get_by(itemId = item.id)
1499
    if not sp:
1500
        sp = StorePricing()
7256 rajveer 1501
    sp.recommendedPrice = rp
1502
    sp.minPrice = minp
1503
    sp.minAdvancePrice = minap
1504
    sp.maxPrice = maxp
1505
    sp.itemId = item.id
1506
    session.commit()
1507
 
1508
def get_store_pricing(itemId):
7270 rajveer 1509
    store = StorePricing.get_by(item_id = itemId)
7256 rajveer 1510
    sp = tStorePricing()
1511
    sp.itemId = itemId
1512
    if store is None:
1513
        return sp
1514
 
1515
    sp.recommendedPrice = store.recommendedPrice
1516
    sp.minPrice = store.minPrice
1517
    sp.minAdvancePrice = store.minAdvancePrice
1518
    sp.maxPrice = store.maxPrice
1519
    return sp