Subversion Repositories SmartDukaan

Rev

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