Subversion Repositories SmartDukaan

Rev

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