Subversion Repositories SmartDukaan

Rev

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