Subversion Repositories SmartDukaan

Rev

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