Subversion Repositories SmartDukaan

Rev

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