Subversion Repositories SmartDukaan

Rev

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