Subversion Repositories SmartDukaan

Rev

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