Subversion Repositories SmartDukaan

Rev

Rev 7368 | Rev 7384 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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