Subversion Repositories SmartDukaan

Rev

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