Subversion Repositories SmartDukaan

Rev

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

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