Subversion Repositories SmartDukaan

Rev

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