Subversion Repositories SmartDukaan

Rev

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