Subversion Repositories SmartDukaan

Rev

Rev 11592 | Rev 11614 | 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, \
11592 amit.gupta 15
    to_t_brand_info, to_t_private_deal
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, \
9242 kshitij.so 21
    PageViewEvents, CartEvents, EbayItem, BannerUriMapping, Campaign, SnapdealItem, \
10097 kshitij.so 22
    ProductFeedSubmit, MarketplaceItems, MarketPlaceItemPrice, \
11606 vikram.rag 23
    SourcePercentageMaster, SourceItemPercentage, FlipkartItem, MarketPlaceUpdateHistory, \
24
    SourceCategoryPercentage, MarketPlaceHistory, PrivateDeals
5944 mandeep.dh 25
from shop2020.thriftpy.model.v1.catalog.ttypes import status, ItemShippingInfo, \
7340 amit.gupta 26
    ItemType, PremiumType, FreebieItem as t_FreebieItem, \
11606 vikram.rag 27
    StorePricing as tStorePricing, CatalogServiceException, \
28
    BannerType, InsurerType, Banner as t_banner
5944 mandeep.dh 29
from shop2020.thriftpy.model.v1.inventory.ttypes import \
11606 vikram.rag 30
    InventoryServiceException, IgnoredInventoryUpdateItems,SnapdealInventoryItem
10097 kshitij.so 31
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
4873 mandeep.dh 32
from shop2020.utils import EmailAttachmentSender
4748 mandeep.dh 33
from shop2020.utils.EmailAttachmentSender import mail
5318 rajveer 34
from shop2020.utils.Utils import to_py_date, log_risky_flag
621 chandransh 35
from sqlalchemy import desc, asc
6039 amit.gupta 36
from sqlalchemy.sql.expression import or_, distinct, func, and_
3086 rajveer 37
from string import Template
4748 mandeep.dh 38
import datetime
8274 amit.gupta 39
import math
4748 mandeep.dh 40
import sys
5393 mandeep.dh 41
import threading
3924 rajveer 42
import urllib2
94 ashish 43
 
5978 rajveer 44
sourceId = int(ConfigClient().get_property("sourceid"))
10687 rajveer 45
to_addresses = ["khushal.bhatia@shop2020.in", "chandan.kumar@shop2020.in",  "chaitnaya.vats@shop2020.in",'manoj.kumar@shop2020.in']
7777 kshitij.so 46
to_store_addresses = ["rajveer.singh@shop2020.in"]
6029 rajveer 47
mail_user = "cnc.center@shop2020.in"
48
mail_password = "5h0p2o2o"
49
source_name = "Saholic"
50
source_url = "www.saholic.com"
5885 mandeep.dh 51
skippedItems = { 175 : [27, 2160, 2175, 2163, 2158, 7128, 26, 2154],
52
                 193 : [5839] }
5047 amit.gupta 53
 
5295 rajveer 54
def initialize(dbname='catalog', db_hostname="localhost"):
55
    DataService.initialize(dbname, db_hostname)
7770 kshitij.so 56
 
3849 chandransh 57
def get_all_items_by_status(status, offset=0, limit=None):
58
    query = Item.query
4539 rajveer 59
    if status is not None:
3849 chandransh 60
        query = query.filter_by(status=status)
61
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
62
    if limit:
63
        query = query.limit(limit)
64
    items = query.all()
65
    return items
66
 
6821 amar.kumar 67
def get_all_alive_items():
68
    query = Item.query
10403 rajveer 69
    query = query.filter(or_(Item.status==status.ACTIVE, Item.status==status.PAUSED, Item.status==status.PAUSED_BY_RISK, Item.status==status.PARTIALLY_ACTIVE))
6821 amar.kumar 70
    items = query.all()
71
    return items
72
 
73
 
3849 chandransh 74
def get_all_items(is_active, offset=0, limit=None):
103 ashish 75
    if is_active:
3849 chandransh 76
        items = get_all_items_by_status(status.ACTIVE, offset, limit)
103 ashish 77
    else:
3849 chandransh 78
        items = get_all_items_by_status(None, offset, limit)
766 rajveer 79
    return items
80
 
3849 chandransh 81
def get_item_count_by_status(use_status, status):
82
    if use_status:
83
        return Item.query.filter_by(status=status).count()
103 ashish 84
    else:
3849 chandransh 85
        return Item.query.count()
103 ashish 86
 
635 rajveer 87
def get_item(item_id):
766 rajveer 88
    item = Item.get_by(id=item_id)
89
    return item
94 ashish 90
 
635 rajveer 91
def get_items_by_catalog_id(catalog_id):
447 rajveer 92
    query = Item.query.filter_by(catalog_item_id=catalog_id)
437 rajveer 93
    try:
635 rajveer 94
        items = query.all()
4934 amit.gupta 95
        return items
1399 rajveer 96
    except Exception as ex:
97
        print ex
437 rajveer 98
        raise InventoryServiceException(109, "Item not found")
5586 phani.kuma 99
 
100
def is_valid_catalog_id(catalog_id):
101
    item = Item.query.filter_by(catalog_item_id=catalog_id).first()
102
    if item is not None:
103
        return True
104
    else:
105
        return False
106
 
576 chandransh 107
def is_active(item_id):
2983 chandransh 108
    t_item_shipping_info = ItemShippingInfo()
576 chandransh 109
    try:
635 rajveer 110
        item = get_item(item_id)
3281 chandransh 111
        t_item_shipping_info.isRisky = item.risky
5944 mandeep.dh 112
        client = InventoryClient().get_client()
5978 rajveer 113
        itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)
5944 mandeep.dh 114
        warehouse_id = itemInfo[0]
5393 mandeep.dh 115
        if item.risky and item.status == status.ACTIVE:
5944 mandeep.dh 116
            availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item_id)
117
            if availability <= 0:
5393 mandeep.dh 118
                add_status_change_log(item, status.PAUSED_BY_RISK)
119
                item.status = status.PAUSED_BY_RISK
120
                item.status_description = "This item is currently out of stock"
121
                session.commit()
122
                __send_mail_for_oos_item(item)
123
                #This will clear cache from tomcat
10223 amit.gupta 124
                #__clear_homepage_cache()
5393 mandeep.dh 125
        else:
5944 mandeep.dh 126
            availability = itemInfo[4]
2983 chandransh 127
        t_item_shipping_info.isActive = (item.status == status.ACTIVE)
3281 chandransh 128
        t_item_shipping_info.quantity = availability
576 chandransh 129
    except InventoryServiceException:
2983 chandransh 130
        print "[ERROR] Unexpected error:", sys.exc_info()[0]
131
    return t_item_shipping_info
132
 
7438 amit.gupta 133
def get_items_status(item_ids):
134
    itemsStatus = dict()
135
    for item_id in item_ids:
136
        try:
137
            item = get_item(item_id)
7520 amit.gupta 138
            if item is None:
139
                continue
7438 amit.gupta 140
            client = InventoryClient().get_client()
141
            itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)
142
            warehouse_id = itemInfo[0]
143
            if item.risky and item.status == status.ACTIVE:
144
                availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item_id)
145
                if availability <= 0:
146
                    item.status = status.PAUSED_BY_RISK
147
            itemsStatus[item_id] = (item.status == status.ACTIVE)
148
        except InventoryServiceException:
149
            print "[ERROR] Unexpected error:", sys.exc_info()[0]
150
    return itemsStatus
151
 
2035 rajveer 152
def get_item_status_description(itemId):
153
    item = get_item(itemId)
154
    return item.status_description
94 ashish 155
 
122 ashish 156
def update_item(item):
157
    if not item:
158
        raise InventoryServiceException(108, "Bad item in request")
7770 kshitij.so 159
 
122 ashish 160
    if not item.id:
609 chandransh 161
        raise InventoryServiceException(101, "Missing id for update")
7770 kshitij.so 162
 
2120 ankur.sing 163
    validate_item_prices(item)
7770 kshitij.so 164
 
635 rajveer 165
    ds_item = get_item(item.id)
5047 amit.gupta 166
    message = ""
7384 rajveer 167
    store_message = ""
122 ashish 168
    if not ds_item:
609 chandransh 169
        raise InventoryServiceException(101, "Item missing in our database")
7770 kshitij.so 170
 
963 chandransh 171
    if item.productGroup:
7770 kshitij.so 172
        ds_item.product_group = item.productGroup
963 chandransh 173
    if item.brand:
174
        ds_item.brand = item.brand
511 rajveer 175
    if item.modelNumber:
176
        ds_item.model_number = item.modelNumber
2497 ankur.sing 177
    ds_item.color = item.color
178
    ds_item.model_name = item.modelName
179
    ds_item.category = item.category
9253 rajveer 180
    if item.category == 10006:
9299 kshitij.so 181
        itemInsurerMapping = ItemInsurerMapping.query.filter(ItemInsurerMapping.itemId == item.id).filter(ItemInsurerMapping.insurerType == InsurerType._NAMES_TO_VALUES.get("DEVICE")).first()
182
        if itemInsurerMapping is None:
183
            itemInsurerMapping = ItemInsurerMapping()
184
            itemInsurerMapping.itemId = item.id
185
            itemInsurerMapping.insurerId = 1
186
            itemInsurerMapping.insurerType = 1
7770 kshitij.so 187
 
2497 ankur.sing 188
    ds_item.comments = item.comments
7770 kshitij.so 189
 
2497 ankur.sing 190
    ds_item.catalog_item_id = item.catalogItemId
483 rajveer 191
 
7384 rajveer 192
    if ds_item.activeOnStore and ds_item.mrp and item.mrp and ds_item.mrp != item.mrp:
193
        sp = get_store_pricing(item.id)
194
        if sp.maxPrice > item.mrp:
195
            sp.maxPrice = item.mrp
196
            store_message += "MRP is changed from {0} to {1}.\n".format(sp.maxPrice, item.mrp)
7770 kshitij.so 197
 
7384 rajveer 198
 
199
    if ds_item.activeOnStore and ds_item.sellingPrice and item.sellingPrice and ds_item.sellingPrice != item.sellingPrice:
200
        sp = get_store_pricing(item.id)
201
        if sp.minPrice < item.sellingPrice:
202
            store_message += "Saholic MOP Changed. DP {0} is less than Saholic MOP.\n".format(sp.minPrice)
7770 kshitij.so 203
 
2129 ankur.sing 204
    ds_item.mrp = item.mrp
5047 amit.gupta 205
    if ds_item.sellingPrice or item.sellingPrice:
206
        if ds_item.sellingPrice != item.sellingPrice:
7761 kshitij.so 207
            amazonItem = get_amazon_item_details(item.id)
208
            if amazonItem is not None:
209
                amazonItem.fbaPrice = item.sellingPrice
210
                amazonItem.sellingPrice=item.sellingPrice
7770 kshitij.so 211
                amazonItem.mfnPriceLastUpdatedOn = datetime.datetime.now()
212
                amazonItem.fbaPriceLastUpdatedOn = datetime.datetime.now()
7774 kshitij.so 213
                message +="Amazon Prices Synced."
5047 amit.gupta 214
            message += "Selling Price is changed from {0} to {1}.\n".format(ds_item.sellingPrice, item.sellingPrice)
7770 kshitij.so 215
 
2129 ankur.sing 216
    ds_item.sellingPrice = item.sellingPrice
2174 ankur.sing 217
    ds_item.weight = item.weight
6241 amit.gupta 218
    ds_item.showSellingPrice = item.showSellingPrice
7770 kshitij.so 219
 
7291 vikram.rag 220
    if item.asin:
221
        ds_item.asin = item.asin
222
    ds_item.holdInventory = item.holdInventory
223
    ds_item.defaultInventory = item.defaultInventory
9841 rajveer 224
    ds_item.holdOverride = item.holdOverride 
7770 kshitij.so 225
 
6826 amit.gupta 226
    if item.startDate:
227
        ds_item.startDate = to_py_date(item.startDate)
228
        ds_item.startDate = ds_item.startDate.replace(hour=0,second=0,minute=0)
229
        if item.itemStatus == status.COMING_SOON and ds_item.startDate < datetime.datetime.now()  :
230
            item.itemStatus = status.ACTIVE
231
            item.status_description = "This item is active"
232
    else:
233
        ds_item.startDate = None
234
 
2358 ankur.sing 235
    if ds_item.status != item.itemStatus:
2402 rajveer 236
        add_status_change_log(ds_item, item.itemStatus)
5047 amit.gupta 237
        if item.itemStatus == status.PHASED_OUT:
238
            message += "Item is phased out."
2358 ankur.sing 239
        ds_item.status = item.itemStatus
2035 rajveer 240
    if item.status_description:
241
        ds_item.status_description = item.status_description
7770 kshitij.so 242
 
511 rajveer 243
    if item.retireDate:
2116 ankur.sing 244
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 245
    else:
246
        ds_item.retireDate = None
5217 amit.gupta 247
 
248
    if item.expectedArrivalDate:
249
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)
250
    else:
251
        ds_item.expectedArrivalDate = None
7770 kshitij.so 252
 
5217 amit.gupta 253
    if item.comingSoonStartDate:
254
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
6696 rajveer 255
        ds_item.comingSoonStartDate = ds_item.comingSoonStartDate.replace(hour=0,second=0,minute=0)
5217 amit.gupta 256
    else:
257
        ds_item.comingSoonStartDate = None
7770 kshitij.so 258
 
259
 
2497 ankur.sing 260
    ds_item.feature_id = item.featureId
261
    ds_item.feature_description = item.featureDescription
7770 kshitij.so 262
 
5047 amit.gupta 263
    if ds_item.bestDealText or item.bestDealText:
264
        if item.bestDealText != ds_item.bestDealText:
5080 amit.gupta 265
            message += "Promotion text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealText, item.bestDealText)
2129 ankur.sing 266
    ds_item.bestDealText = item.bestDealText
267
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 268
    ds_item.bestSellingRank = item.bestSellingRank
7770 kshitij.so 269
 
6777 vikram.rag 270
    if ds_item.bestDealsDetailsText or item.bestDealsDetailsText:
271
        if item.bestDealsDetailsText != ds_item.bestDealsDetailsText:
272
            message += "Best deals details text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealsDetailsText, item.bestDealsDetailsText)
273
    ds_item.bestDealsDetailsText = item.bestDealsDetailsText
7770 kshitij.so 274
 
6777 vikram.rag 275
    if ds_item.bestDealsDetailsLink or item.bestDealsDetailsLink:
276
        if item.bestDealsDetailsLink != ds_item.bestDealsDetailsLink:
277
            message += "Best deals details link is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealsDetailsLink, item.bestDealsDetailsLink)
278
    ds_item.bestDealsDetailsLink = item.bestDealsDetailsLink
7770 kshitij.so 279
 
280
 
2065 ankur.sing 281
    ds_item.defaultForEntity = item.defaultForEntity
7770 kshitij.so 282
 
5047 amit.gupta 283
    if ds_item.risky or item.risky:
284
        if ds_item.risky != item.risky:
5080 amit.gupta 285
            message += "Risky flag is changed to '{0}'.\n".format(set)
7770 kshitij.so 286
 
2251 ankur.sing 287
    ds_item.risky = item.risky
7770 kshitij.so 288
 
5385 phani.kuma 289
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
290
    ds_item.hasItemNo = item.hasItemNo
7770 kshitij.so 291
 
3459 chandransh 292
    if item.expectedDelay is not None:
3359 chandransh 293
        ds_item.expectedDelay = item.expectedDelay
7770 kshitij.so 294
 
4506 phani.kuma 295
    if item.preferredVendor:
5080 amit.gupta 296
        if item.preferredVendor != ds_item.preferredVendor:
5944 mandeep.dh 297
            inventoryClient = InventoryClient().get_client()
298
            newPreferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
5080 amit.gupta 299
            oldPreferredVendorName = 'None'
300
            if ds_item.preferredVendor:
5944 mandeep.dh 301
                oldPreferredVendorName = inventoryClient.getVendor(ds_item.preferredVendor).name
7770 kshitij.so 302
            message += "Preferred vendor is changed from '{0}' to '{1}'.\n".format(oldPreferredVendorName, newPreferredVendorName)       
4506 phani.kuma 303
        ds_item.preferredVendor = item.preferredVendor
7770 kshitij.so 304
 
5080 amit.gupta 305
    if item.isWarehousePreferenceSticky != ds_item.isWarehousePreferenceSticky:
306
        flag = "ON" if item.isWarehousePreferenceSticky else "OFF"
307
        message += "Warehouse preference sticky is {0}.\n".format(flag)
308
 
4413 anupam.sin 309
    ds_item.isWarehousePreferenceSticky = item.isWarehousePreferenceSticky
7770 kshitij.so 310
 
7296 amit.gupta 311
    ds_item.updatedOn = datetime.datetime.now()
7770 kshitij.so 312
 
7382 rajveer 313
 
7519 rajveer 314
    ds_item.activeOnStore = item.activeOnStore
122 ashish 315
    session.commit();
8867 rajveer 316
 
317
#    subject = "Item '{0}' is updated in Catalog. Id is {1}".format(__get_product_name(ds_item),ds_item.id)
318
#    if message:
319
#        __send_mail(subject, message)
320
#    if store_message:
321
#        __send_mail(subject, store_message, to_store_addresses)
322
 
122 ashish 323
    return ds_item.id
94 ashish 324
 
103 ashish 325
def add_item(item):
326
    if not item:
122 ashish 327
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 328
    if get_item(item.id):
122 ashish 329
        raise InventoryServiceException(101, "Item already exists")
7770 kshitij.so 330
 
2120 ankur.sing 331
    validate_item_prices(item)
7770 kshitij.so 332
 
103 ashish 333
    ds_item = Item()
963 chandransh 334
    if item.productGroup:
335
        ds_item.product_group = item.productGroup
336
    if item.brand:
337
        ds_item.brand = item.brand
515 rajveer 338
    if item.modelName:
339
        ds_item.model_name = item.modelName
340
    if item.modelNumber:
341
        ds_item.model_number = item.modelNumber
609 chandransh 342
    if item.color:
343
        ds_item.color = item.color
483 rajveer 344
    if item.category:
345
        ds_item.category = item.category
346
    if item.comments:
347
        ds_item.comments = item.comments
7291 vikram.rag 348
    if item.asin:
349
        ds_item.asin = item.asin
350
    ds_item.holdInventory = item.holdInventory
9841 rajveer 351
    ds_item.defaultInventory = item.defaultInventory
352
    ds_item.holdOverride = item.holdOverride   
7296 amit.gupta 353
    ds_item.addedOn = datetime.datetime.now()
354
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 355
    if item.startDate:
356
        ds_item.startDate = to_py_date(item.startDate)
6696 rajveer 357
        ds_item.startDate = ds_item.startDate.replace(hour=0,second=0,minute=0)
2116 ankur.sing 358
    if item.retireDate:
359
        ds_item.retireDate = to_py_date(item.retireDate)
5217 amit.gupta 360
    if item.comingSoonStartDate:
361
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
362
    if item.expectedArrivalDate:
7770 kshitij.so 363
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)   
483 rajveer 364
    if item.mrp:
365
        ds_item.mrp = item.mrp
366
    if item.sellingPrice:
367
        ds_item.sellingPrice = item.sellingPrice
122 ashish 368
    if item.weight:
369
        ds_item.weight = item.weight
7770 kshitij.so 370
 
122 ashish 371
    if item.featureId:
372
        ds_item.feature_id = item.featureId
373
    if item.featureDescription:
374
        ds_item.feature_description = item.featureDescription
7770 kshitij.so 375
 
376
 
103 ashish 377
    #check if categories present. If yes, add them to system
7770 kshitij.so 378
 
609 chandransh 379
    if item.bestDealValue:
380
        ds_item.bestDealValue = item.bestDealValue
381
    if item.bestDealText:
382
        ds_item.bestDealText = item.bestDealText
6777 vikram.rag 383
    if item.bestDealsDetailsText:
384
        ds_item.bestDealsDetailsText = item.bestDealsDetailsText
385
    if item.bestDealsDetailsLink:
7770 kshitij.so 386
        ds_item.bestDealsDetailsLink = item.bestDealsDetailsLink   
2116 ankur.sing 387
    if item.bestSellingRank:
388
        ds_item.bestSellingRank = item.bestSellingRank
389
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 390
    ds_item.risky = item.risky
7770 kshitij.so 391
 
5385 phani.kuma 392
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
393
    ds_item.hasItemNo = item.hasItemNo
7256 rajveer 394
    ds_item.activeOnStore = item.activeOnStore
7770 kshitij.so 395
 
3467 chandransh 396
    if item.expectedDelay is not None:
3359 chandransh 397
        ds_item.expectedDelay = item.expectedDelay
3467 chandransh 398
    else:
399
        ds_item.expectedDelay = 0
7770 kshitij.so 400
 
5408 amit.gupta 401
    preferredVendorName = "None"
4881 phani.kuma 402
    if item.preferredVendor:
403
        ds_item.preferredVendor = item.preferredVendor
5944 mandeep.dh 404
        inventoryClient = InventoryClient().get_client()
6838 vikram.rag 405
        preferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
7770 kshitij.so 406
 
6838 vikram.rag 407
    if item.preferredInsurer is not None:
7770 kshitij.so 408
        ds_item.preferredInsurer = item.preferredInsurer            
409
 
5586 phani.kuma 410
    if item.catalogItemId:
411
        catalog_client = CatalogClient("catalog_service_server_host_master", "catalog_service_server_port").get_client()
412
        master_items = catalog_client.getItemsByCatalogId(item.catalogItemId)
413
        itemStatus = status.IN_PROCESS
414
        for masterItem in master_items:
415
            if masterItem.itemStatus in [status.CONTENT_COMPLETE, status.COMING_SOON, status.ACTIVE, status.PAUSED]:
416
                itemStatus = status.CONTENT_COMPLETE
417
                ds_item.category = masterItem.category
418
                break
419
        ds_item.catalog_item_id = item.catalogItemId
420
        ds_item.status = itemStatus
2116 ankur.sing 421
        ds_item.status_description = "This item is in process."
422
    else:
5586 phani.kuma 423
        # Check if a similar item already exists in our database
424
        similar_item = Item.query.filter_by(brand=item.brand, model_number=item.modelNumber, model_name=item.modelName).first()
425
        print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2}".format(item.brand, item.modelNumber, item.modelName)
7770 kshitij.so 426
 
5586 phani.kuma 427
        if similar_item is None or similar_item.catalog_item_id is None:
428
            # If there is no similar item in the database from before,
429
            # use the entity_id_generator
430
            entity_id = EntityIDGenerator.query.first()
431
            ds_item.catalog_item_id = entity_id.id + 1
432
            ds_item.status = status.IN_PROCESS
433
            ds_item.status_description = "This item is in process."
434
            entity_id.id = entity_id.id  + 1
435
            if similar_item is not None and similar_item.catalog_item_id is None:
436
                similar_item.catalog_item_id = entity_id.id
437
        else:
438
            #If a similar item already exists for a product group, brand and model_number, set it as same.
439
            ds_item.catalog_item_id = similar_item.catalog_item_id
440
            ds_item.category = similar_item.category
441
            ds_item.product_group = similar_item.product_group
442
            ds_item.status = similar_item.status
443
            ds_item.status_description = similar_item.status_description
7770 kshitij.so 444
 
103 ashish 445
    session.commit();
5052 amit.gupta 446
    subject = "New item is added. Id is {0}".format(str(ds_item.id))
6777 vikram.rag 447
    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 448
    __send_mail(subject, message)
3325 chandransh 449
    return ds_item.id
450
 
103 ashish 451
def retire_item(item_id):
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")
457
    item.status = status.PHASED_OUT
458
    item.retireDate = datetime.datetime.now()
103 ashish 459
    session.commit()
7770 kshitij.so 460
 
122 ashish 461
#need to implement threads based solution here
103 ashish 462
def start_item_on(item_id, timestamp):
463
    if not item_id:
122 ashish 464
        raise InventoryServiceException(101, "bad item id")
635 rajveer 465
    item = get_item(item_id)
103 ashish 466
    if not item:
122 ashish 467
        raise InventoryServiceException(108, "item id not present")
7770 kshitij.so 468
 
122 ashish 469
    item.status = status.ACTIVE
470
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
471
    add_status_change_log(item, status.ACTIVE)
103 ashish 472
    session.commit()
7770 kshitij.so 473
 
122 ashish 474
#need to implement threads here
103 ashish 475
def retire_item_on(item_id, timestamp):
476
    if not item_id:
122 ashish 477
        raise InventoryServiceException(101, "bad item id")
635 rajveer 478
    item = get_item(item_id)
103 ashish 479
    if not item:
122 ashish 480
        raise InventoryServiceException(108, "item id not present")
7770 kshitij.so 481
 
122 ashish 482
    item.status = status.PHASED_OUT
483
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
484
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 485
    session.commit()
7770 kshitij.so 486
 
103 ashish 487
def add_status_change_log(item, new_status):
488
    item_change_log = ItemChangeLog()
489
    item_change_log.new_status = new_status
490
    item_change_log.old_status = item.status
491
    item_change_log.timestamp = datetime.datetime.now()
492
    item_change_log.item = item
493
    session.commit()
7770 kshitij.so 494
 
103 ashish 495
def change_item_status(item_id, new_status):
496
    if not item_id:
122 ashish 497
        raise InventoryServiceException(101, "bad item id")
635 rajveer 498
    item = get_item(item_id)
103 ashish 499
    if not item:
122 ashish 500
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 501
    add_status_change_log(item, new_status)
122 ashish 502
    item.status = new_status
2251 ankur.sing 503
    if item.status == status.PHASED_OUT:
504
        item.status_description = "This item has been phased out"
5047 amit.gupta 505
        __send_mail("Item '{0}' is Phased-Out. Item id is {1}".format(__get_product_name(item), item_id), "")
2251 ankur.sing 506
    elif item.status == status.DELETED:
507
        item.status_description = "This item has been deleted"
3924 rajveer 508
    elif item.status == status.PAUSED:
7770 kshitij.so 509
        item.status_description = "This item is currently out of stock"     
3924 rajveer 510
    elif item.status == status.PAUSED_BY_RISK:
511
        item.status_description = "This item is currently out of stock"
512
        #This will clear cache from tomcat
10223 amit.gupta 513
        #__clear_homepage_cache() 
2251 ankur.sing 514
    elif item.status == status.ACTIVE:
515
        item.status_description = "This item is active"
516
    elif item.status == status.IN_PROCESS:
517
        item.status_description = "This item is in process"
518
    elif item.status == status.CONTENT_COMPLETE:
519
        item.status_description = "This item is in process"
103 ashish 520
    session.commit()
7770 kshitij.so 521
 
5944 mandeep.dh 522
def check_risky_item(item_id):
635 rajveer 523
    item = get_item(item_id)
2251 ankur.sing 524
    if not item.risky:
525
        return
5944 mandeep.dh 526
    client = InventoryClient().get_client()
7770 kshitij.so 527
    itemInfo = client.getItemAvailabilityAtLocation(item.id, sourceId)   
5944 mandeep.dh 528
    warehouse_id = itemInfo[0]
529
    availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item.id)
530
    if availability <= 0:
2251 ankur.sing 531
        if item.status == status.ACTIVE:
2984 rajveer 532
            change_item_status(item.id, status.PAUSED_BY_RISK)
4797 rajveer 533
            __send_mail_for_oos_item(item)
2251 ankur.sing 534
    else:
2984 rajveer 535
        if item.status == status.PAUSED_BY_RISK:
2251 ankur.sing 536
            change_item_status(item.id, status.ACTIVE)
6255 rajveer 537
            __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 538
    session.commit()
7770 kshitij.so 539
 
9253 rajveer 540
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber, isAndroid):
2828 rajveer 541
    '''
542
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
543
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
544
    '''
723 chandransh 545
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 546
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 547
    current_timestamp = datetime.datetime.now()
548
    for item in items:
2828 rajveer 549
        if item.status == status.IN_PROCESS:
550
            item.status = content_complete_status
551
            item_change_log = ItemChangeLog()
552
            item_change_log.old_status = item.status
553
            item_change_log.new_status = content_complete_status
554
            item_change_log.timestamp = current_timestamp
555
            item_change_log.item = item
9299 kshitij.so 556
            if isAndroid:
557
                itemInsurerMapping = ItemInsurerMapping.query.filter(ItemInsurerMapping.itemId == item.id).filter(ItemInsurerMapping.insurerType == InsurerType._NAMES_TO_VALUES.get("DATA")).first()
558
                if itemInsurerMapping is None:
559
                    itemInsurerMapping = ItemInsurerMapping()
560
                    itemInsurerMapping.itemId = item.id
561
                    itemInsurerMapping.insurerId = 2
562
                    itemInsurerMapping.insurerType = 2
7770 kshitij.so 563
 
4762 phani.kuma 564
        category_object = get_category(category)
565
        if category_object is not None:
566
            item.category = category
567
            item.product_group = category_object.display_name
2075 rajveer 568
        item.brand = brand
2081 rajveer 569
        item.model_name = modelName
570
        item.model_number = modelNumber
723 chandransh 571
        item.updatedOn = current_timestamp
572
    session.commit()
573
    return True
1294 chandransh 574
 
2404 chandransh 575
def get_child_categories(category):
576
    cm = CategoryManager()
2621 varun.gupt 577
    cat = cm.getCategory(category)
578
    return cat.children_category_ids if cat else None
2404 chandransh 579
 
626 chandransh 580
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 581
    '''
582
    Returns the Best Sellers between the start and the stop index in the given category
583
    '''
1926 rajveer 584
    query = get_best_sellers_query(category, None)
1098 chandransh 585
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 586
    return get_thrift_item_list(best_sellers)
587
 
2093 chandransh 588
def get_best_sellers_count(category=-1):
2404 chandransh 589
    '''
590
    Returns the number of best sellers in the given category
591
    '''
1926 rajveer 592
    count = get_best_sellers_query(category, None).count()
1120 rajveer 593
    if count is None:
594
        count = 0
766 rajveer 595
    return count
621 chandransh 596
 
1926 rajveer 597
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 598
    '''
599
    Returns the Best sellers for the given brand and category between the start and the stop index.
7770 kshitij.so 600
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
2404 chandransh 601
    '''
1926 rajveer 602
    query = get_best_sellers_query(category, brand)
1098 chandransh 603
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 604
    return [item.catalog_item_id for item in best_sellers]
7770 kshitij.so 605
 
1926 rajveer 606
def get_best_sellers_query(category, brand):
2404 chandransh 607
    '''
608
    Returns the query to be used for getting Best Sellers.
609
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
610
    '''
1098 chandransh 611
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 612
    if category != -1:
1970 rajveer 613
        all_categories = [category]
614
        child_categories = get_child_categories(category)
615
        if child_categories is not None:
7770 kshitij.so 616
            all_categories = all_categories + child_categories
1970 rajveer 617
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 618
    if brand is not None:
619
        query = query.filter_by(brand=brand)
7202 amit.gupta 620
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.bestSellingRank))
621 chandransh 621
    return query
609 chandransh 622
 
1098 chandransh 623
def get_best_deals(category=-1):
2404 chandransh 624
    '''
625
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
626
    '''
627
    query = get_best_deals_query(Item, category, None)
1098 chandransh 628
    items = query.all()
609 chandransh 629
    return get_thrift_item_list(items)
630
 
1098 chandransh 631
def get_best_deals_count(category=-1):
2404 chandransh 632
    '''
633
    Returns the count of best deals in the given category.
634
    Ignores the category if it's -1.
635
    '''
636
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 637
    if count is None:
638
        count = 0
766 rajveer 639
    return count
7770 kshitij.so 640
 
1926 rajveer 641
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 642
    '''
643
    Returns the catalog_item_ids of best deal items for the given brand and category.
644
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
645
    '''
646
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 647
    best_deal_items = query.all()[start_index:stop_index]
648
    return [item.catalog_item_id for item in best_deal_items]
649
 
2404 chandransh 650
def get_best_deals_counting_query(obj, category, brand):
651
    '''
652
    Returns the query to be used to select the best deals in the given brand and category.
7770 kshitij.so 653
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
2404 chandransh 654
    '''
655
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 656
    if category != -1:
1970 rajveer 657
        all_categories = [category]
658
        child_categories = get_child_categories(category)
659
        if child_categories is not None:
7770 kshitij.so 660
            all_categories = all_categories + child_categories
1970 rajveer 661
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 662
    if brand is not None:
663
        query = query.filter_by(brand=brand)
2404 chandransh 664
    return query
665
 
666
def get_best_deals_query(obj, category, brand):
667
    '''
668
    Returns the query to be used to get the best deals in the given category and brand.
669
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
670
    '''
671
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 672
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
673
    return query
609 chandransh 674
 
5217 amit.gupta 675
def get_coming_soon(category=-1):
676
    '''
677
    Returns the Coming Soon items in the given category. Ignores the category if it's passed as -1.
678
    '''
679
    query = get_coming_soon_query(Item, category, None)
680
    items = query.all()
681
    return get_thrift_item_list(items)
682
 
683
def get_coming_soon_count(category=-1):
684
    '''
685
    Returns the count of coming in the given category.
686
    Ignores the category if it's -1.
687
    '''
688
    count = get_coming_soon_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
689
    if count is None:
690
        count = 0
691
    return count
692
 
693
def get_coming_soon_catalog_ids(start_index, stop_index, brand, category=-1):
694
    '''
695
    Returns the catalog_item_ids of coming soon items for the given brand and category.
696
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
697
    '''
698
    query = get_coming_soon_query(Item, category, brand)
699
    coming_soon_items = query.all()[start_index:stop_index]
700
    return [item.catalog_item_id for item in coming_soon_items]
701
 
702
def get_coming_soon_counting_query(obj, category, brand):
703
    '''
704
    Returns the query to be used to select the coming soon product in the given brand and category.
7770 kshitij.so 705
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
5217 amit.gupta 706
    '''
707
    query = session.query(obj).filter_by(status=status.COMING_SOON)
708
    if category != -1:
709
        all_categories = [category]
710
        child_categories = get_child_categories(category)
711
        if child_categories is not None:
7770 kshitij.so 712
            all_categories = all_categories + child_categories
5217 amit.gupta 713
        query = query.filter(Item.category.in_(all_categories))
714
    if brand is not None:
715
        query = query.filter_by(brand=brand)
716
    return query
717
 
718
def get_coming_soon_query(obj, category, brand):
719
    '''
720
    Returns the query to be used to get the coming soon products in the given category and brand.
721
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
722
    '''
723
    query = get_coming_soon_counting_query(obj, category, brand)
724
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.comingSoonStartDate))
725
    return query
726
 
1098 chandransh 727
def get_latest_arrivals(limit, category=-1):
2404 chandransh 728
    '''
729
    Returns up to limit number of Latest Arrivals in the given category.
730
    '''
2975 chandransh 731
    categories = []
732
    if category != -1:
733
        categories = [category]
734
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 735
    items = query.all()[0:limit]
609 chandransh 736
    return get_thrift_item_list(items)
7770 kshitij.so 737
 
1098 chandransh 738
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 739
    '''
740
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 741
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 742
    '''
2975 chandransh 743
    categories = []
744
    if category != -1:
745
        categories = [category]
746
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 747
    if count is None:
748
        count = 0
749
    count = min(count, limit)
766 rajveer 750
    return count
7770 kshitij.so 751
 
2975 chandransh 752
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 753
    '''
754
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 755
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 756
    '''
2975 chandransh 757
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 758
    latest_arrivals = query.all()[start_index:stop_index]
759
    return [item.catalog_item_id for item in latest_arrivals]
760
 
2975 chandransh 761
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 762
    '''
763
    Returns the query to be used to count Latest arrivals.
3016 chandransh 764
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 765
    '''
766
    query = session.query(obj).filter_by(status=status.ACTIVE)
7770 kshitij.so 767
 
2975 chandransh 768
    all_categories = []
769
    for category in categories:
770
        all_categories.append(category)
1970 rajveer 771
        child_categories = get_child_categories(category)
2975 chandransh 772
        if child_categories:
773
            all_categories = all_categories + child_categories
7770 kshitij.so 774
    if all_categories:
1970 rajveer 775
        query = query.filter(Item.category.in_(all_categories))
7770 kshitij.so 776
 
1926 rajveer 777
    if brand is not None:
778
        query = query.filter_by(brand=brand)
2404 chandransh 779
    return query
780
 
2975 chandransh 781
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 782
    '''
783
    Returns the query to be used to retrieve Latest Arrivals.
784
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
785
    '''
2975 chandransh 786
    query = get_latest_arrivals_counting_query(obj, categories, brand)
5167 rajveer 787
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate)).order_by(Item.catalog_item_id)
1098 chandransh 788
    return query
609 chandransh 789
 
790
def get_thrift_item_list(items):
1098 chandransh 791
    return [to_t_item(item) for item in items if item != None]
635 rajveer 792
 
1155 rajveer 793
def generate_new_entity_id():
794
    generator =  EntityIDGenerator.query.one()
795
    id = generator.id + 1
796
    generator.id = id
797
    session.commit()
798
    return id
799
 
635 rajveer 800
def put_category_object(object):
801
    category = Category.get_by(id=1)
802
    if category is None:
803
        category = Category()
7770 kshitij.so 804
    category.object = object   
635 rajveer 805
    session.commit()
806
    return True
807
 
808
def get_category_object():
766 rajveer 809
    object = Category.get_by(id=1).object
810
    return object
811
 
1970 rajveer 812
def add_category(t_category):
813
    category = Category.get_by(id=t_category.id)
814
    if category is None:
815
        category = Category()
7770 kshitij.so 816
    category.id = t_category.id
1970 rajveer 817
    category.label = t_category.label
818
    category.description = t_category.description
4762 phani.kuma 819
    category.display_name = t_category.display_name
7770 kshitij.so 820
    category.parent_category_id = t_category.parent_category_id
1970 rajveer 821
    session.commit()
822
    return True
823
 
824
def get_category(id):
825
    return Category.query.filter_by(id=id).first()
826
 
827
def get_all_categories():
828
    return Category.query.all()
829
 
2120 ankur.sing 830
def validate_item_prices(item):
2129 ankur.sing 831
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
832
        return
833
    if item.mrp < item.sellingPrice:
2120 ankur.sing 834
        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))
835
        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 836
    return
7770 kshitij.so 837
 
2120 ankur.sing 838
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 839
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 840
        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))
841
        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)))
842
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
843
        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))
844
        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)))
845
    return
2065 ankur.sing 846
 
4725 phani.kuma 847
def check_color_valid(color):
848
    if color is not None:
849
        color = color.strip().lower()
850
        if color != '' and color != 'na' and color != 'blank' and color != '(blank)':
851
            return True
852
    return False
853
 
854
def check_similar_item(brand, model_number, model_name, color):
2129 ankur.sing 855
    query = Item.query
2428 ankur.sing 856
    query = query.filter_by(brand=brand)
857
    query = query.filter_by(model_number=model_number)
4725 phani.kuma 858
    query = query.filter_by(model_name=model_name)
859
    similar_items = query.all()
860
    item = None
861
    # Check if a similar item already exists in our database
862
    for old_item in similar_items:
863
        if old_item.color != None and old_item.color.strip().lower() == color.strip().lower():
864
            item = old_item
865
            break
7770 kshitij.so 866
 
4725 phani.kuma 867
    # 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 868
    if item is None:
4725 phani.kuma 869
        for old_item in similar_items:
870
            if not check_color_valid(old_item.color):
871
                item = old_item
872
                break
873
    i = 0
874
    color_of_similar_item = None
875
    # Check if a similar item already exists in our database to be used to get catalog_item_id
876
    for old_item in similar_items:
877
        # get a similar item already existing in our database with valid color
878
        if check_color_valid(old_item.color):
879
            similar_item = old_item
880
            color_of_similar_item = similar_item.color
881
            break
882
        i = i + 1
883
        # get a similar item already existing in our database if similar item with valid color is not found
884
        if i == len(similar_items):
885
            similar_item = old_item
886
            color_of_similar_item = similar_item.color
7770 kshitij.so 887
 
4725 phani.kuma 888
    # Check if a similar item that is obtained above is having a valid color
889
    if check_color_valid(color_of_similar_item):
890
        # 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.
891
        # 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.
892
        if item is None and not check_color_valid(color):
893
            return similar_item.id
7770 kshitij.so 894
 
4725 phani.kuma 895
    if item is None:
2116 ankur.sing 896
        return 0
897
    else:
898
        return item.id
7770 kshitij.so 899
 
2286 ankur.sing 900
def change_risky_flag(item_id, risky):
901
    item = get_item(item_id)
902
    if not item:
903
        raise InventoryServiceException(101, "Item missing in our database")
904
    try:
905
        log_risky_flag(item_id, risky)
906
    except:
907
        print "Not able to log risky flag change"
908
    item.risky = risky
4295 varun.gupt 909
    if not risky and item.status == status.PAUSED_BY_RISK:
2368 ankur.sing 910
        change_item_status(item.id, status.ACTIVE)
6255 rajveer 911
        __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 912
    session.commit()
5047 amit.gupta 913
    flag = "ON" if risky else "OFF"
914
    subject = "Risky flag is {0} for Item {1}.".format(flag, __get_product_name(item))
915
    __send_mail(subject,"")
7770 kshitij.so 916
 
4957 phani.kuma 917
def get_items_for_mastersheet(categoryName, brand):
918
    if not categoryName or not brand:
919
        raise InventoryServiceException(101, "Invalid category or brand in request")
7770 kshitij.so 920
 
4762 phani.kuma 921
    categories = ["Handsets", "Tablets", "Laptops"]
4957 phani.kuma 922
    query = Item.query.filter(Item.status != status.PHASED_OUT)
923
    if categoryName == "ALL":
924
        pass
925
    elif categoryName == "ALL Accessories":
926
        query = query.filter(~Item.product_group.in_(categories))
927
    elif categoryName == "ALL Handsets":
928
        query = query.filter(Item.product_group.in_(categories))
929
    elif categoryName == "Mobile Accessories":
930
        child_categories = get_child_categories(10011)
931
        if child_categories is not None:
932
            child_categories.append(0)
933
            query = query.filter(Item.category.in_(child_categories))
934
    elif categoryName == "Laptop Accessories":
935
        child_categories = get_child_categories(10070)
936
        if child_categories is not None:
937
            child_categories.append(0)
938
            query = query.filter(Item.category.in_(child_categories))
939
    else:
940
        query = query.filter(Item.product_group == categoryName)
7770 kshitij.so 941
 
4957 phani.kuma 942
    if brand == "ALL":
943
        pass
944
    else:
945
        query = query.filter(Item.brand == brand)
2358 ankur.sing 946
    items = query.all()
947
    return items
2116 ankur.sing 948
 
2358 ankur.sing 949
def get_risky_items():
950
    items = Item.query.filter_by(risky=True).all()
951
    return items
3008 rajveer 952
 
2809 rajveer 953
def get_similar_items_catalog_ids(start_index, stop_index, itemId):
3008 rajveer 954
    query = SimilarItems.query.filter_by(item_id=itemId).limit(stop_index-start_index)
955
    similar_items = query.all()
3289 rajveer 956
    return_list = []
957
    for similar_item in similar_items:
958
        isActive = False
959
        try:
960
            all_items = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).all()
961
        except:
962
            continue
963
        for item in all_items:
964
            isActive = isActive or item.status == status.ACTIVE
965
        if isActive:
966
            return_list.append(similar_item.catalog_item_id)
967
    return return_list
4423 phani.kuma 968
 
969
def get_all_similar_items_catalog_ids(itemId):
970
    query = SimilarItems.query.filter_by(item_id=itemId)
971
    similar_items = query.all()
972
    return_list = []
973
    for similar_item in similar_items:
974
        item_query = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).limit(1)
975
        item = item_query.one()
976
        return_list.append(item)
7770 kshitij.so 977
 
4423 phani.kuma 978
    return get_thrift_item_list(return_list)
979
 
980
def add_similar_item_catalog_id(itemId, catalog_item_id):
981
    if not itemId or not catalog_item_id:
982
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
983
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
984
    if not len(items_for_entity):
985
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
7770 kshitij.so 986
 
4423 phani.kuma 987
    s_items = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
988
    if not len(s_items):
989
        s_item = SimilarItems()
990
        s_item.item_id=itemId
991
        s_item.catalog_item_id=catalog_item_id
992
        session.commit()
993
        return items_for_entity[0]
994
    else:
995
        raise InventoryServiceException(101, "Already exists")
7770 kshitij.so 996
 
4423 phani.kuma 997
def delete_similar_item_catalog_id(itemId, catalog_item_id):
998
    if not itemId or not catalog_item_id:
999
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
7770 kshitij.so 1000
 
4423 phani.kuma 1001
    similar_item = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1002
    if len(similar_item):
1003
        similar_item[0].delete()
1004
    session.commit()
1005
    return True
5504 phani.kuma 1006
 
1007
def get_all_vouchers_for_item(itemId):
1008
    vouchers = VoucherItemMapping.query.filter_by(item_id=itemId).all()
1009
    return vouchers
1010
 
1011
def get_voucher_amount(itemId, voucher_type):
1012
    voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
1013
    if len(voucher):
1014
        return voucher[0].amount
1015
    else:
5518 rajveer 1016
        return 0
5504 phani.kuma 1017
 
1018
def add_update_voucher_for_item(catalog_item_id, voucher_type, voucher_amount):
1019
    if not catalog_item_id or not voucher_type or not voucher_amount:
1020
        raise InventoryServiceException(101, "Bad catalogItemId or voucherType or voucherAmount in request")
7770 kshitij.so 1021
 
5504 phani.kuma 1022
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1023
    if not len(items_for_entity):
1024
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
7770 kshitij.so 1025
 
5504 phani.kuma 1026
    for item in items_for_entity:
1027
        itemId = item.id
1028
        voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
1029
        if not len(voucher):
1030
            voucher = VoucherItemMapping()
1031
            voucher.item_id=itemId
1032
            voucher.voucherType=voucher_type
1033
            voucher.amount=voucher_amount
1034
        else:
1035
            voucher[0].amount=voucher_amount
1036
    session.commit()
1037
    return True
7770 kshitij.so 1038
 
5504 phani.kuma 1039
def delete_voucher_for_item(catalog_item_id, voucher_type):
1040
    if not catalog_item_id or not voucher_type:
1041
        raise InventoryServiceException(101, "Bad catalogItemId or voucherType in request")
7770 kshitij.so 1042
 
5504 phani.kuma 1043
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1044
    if not len(items_for_entity):
1045
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
7770 kshitij.so 1046
 
5504 phani.kuma 1047
    for item in items_for_entity:
1048
        itemId = item.id
1049
        voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
1050
        if len(voucher):
1051
            voucher[0].delete()
1052
    session.commit()
1053
    return True
1054
 
3079 rajveer 1055
def add_product_notification(itemId, email):
1056
    try:
3470 rajveer 1057
        try:
1058
            product_notification = ProductNotification.query.filter_by(item_id=itemId, email=email).one()
1059
        except:
1060
            product_notification = ProductNotification()
1061
            product_notification.email = email
1062
            product_notification.item_id = itemId
3079 rajveer 1063
        product_notification.addedOn = datetime.datetime.now()
1064
        session.commit()
1065
        return True
1066
    except:
1067
        return False
3086 rajveer 1068
 
1069
 
1070
def send_product_notifications():
7134 rajveer 1071
    product_notifications = ProductNotification.query.order_by(ProductNotification.addedOn).all()
1072
    itemcountmap = {}
1073
    itemstatusmap = {}
8182 amar.kumar 1074
    #print "size of prduct notifications = " + str(len(product_notifications))
3086 rajveer 1075
    for product_notification in product_notifications:
1076
        item = product_notification.item
7134 rajveer 1077
        if itemcountmap.has_key(item.id):
1078
            itemcountmap[item.id] = itemcountmap.get(item.id) + 1
1079
        else:
1080
            client = InventoryClient().get_client()
1081
            availability = client.getItemAvailabilityAtLocation(item.id, sourceId)[4]
8182 amar.kumar 1082
            #print "Item status " + str(item.status) + " item.risky " + str(item.risky) + " availability = " + str(availability)
1083
            if item.status == status.ACTIVE and (not item.risky or availability > 0):  
1084
                #print "item status map has new entry " + str(item.id)     
7134 rajveer 1085
                itemstatusmap[item.id] = True
1086
            else:
1087
                itemstatusmap[item.id] = False
1088
            itemcountmap[item.id] = 1
1089
        if itemcountmap[item.id] > 1000:
1090
            continue
7770 kshitij.so 1091
 
7134 rajveer 1092
        if itemstatusmap[item.id]:
8182 amar.kumar 1093
            #print product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id
3086 rajveer 1094
            __enque_product_notification_email(product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id)
1095
            product_notification.delete()
1096
    session.commit()
1097
    return True
7770 kshitij.so 1098
 
3086 rajveer 1099
def __get_product_name(item):
1100
    product_name = item.brand + " " + item.model_name + " " + item.model_number
1101
    color = item.color
1102
    if color is not None and color != 'NA':
1103
        product_name = product_name + " (" + color + ")"
3201 rajveer 1104
    product_name = product_name.replace("  "," ")
3086 rajveer 1105
    return product_name
1106
 
1107
 
1108
def __get_product_url(item):
6029 rajveer 1109
    product_url = "http://" + source_url + "/mobile-phones/" + item.brand + "-" + item.model_name + "-" + item.model_number + "-" + str(item.catalog_item_id)
3086 rajveer 1110
    product_url = product_url.replace("--","-")
1111
    product_url = product_url.replace(" ","")
1112
    return product_url
1113
 
3348 varun.gupt 1114
def get_all_brands_by_category(category_id):
1115
    catm = CategoryManager()
1116
    child_categories = catm.getCategory(category_id).children_category_ids
1117
    brands = session.query(distinct(Item.brand)).filter(Item.category.in_(child_categories)).all()
7770 kshitij.so 1118
 
3348 varun.gupt 1119
    return [brand[0] for brand in brands]
3086 rajveer 1120
 
4957 phani.kuma 1121
def get_all_brands():
1122
    brands = session.query(distinct(Item.brand)).order_by(Item.brand).all()
7770 kshitij.so 1123
 
4957 phani.kuma 1124
    return [brand[0] for brand in brands]
1125
 
3086 rajveer 1126
def __enque_product_notification_email(email, product, date, url, itemId):
7770 kshitij.so 1127
 
3086 rajveer 1128
    html = """
1129
        <html>
1130
        <body>
1131
        <div>
1132
        <p>
1133
            Hi,<br /><br />
6029 rajveer 1134
            The product requested by you on $date is now available on $source_url.
7103 amar.kumar 1135
            <br />
1136
            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 1137
        </p>
7770 kshitij.so 1138
 
1139
        <p>   
3086 rajveer 1140
        <strong>Product: $product </strong>
1141
        </p>
7770 kshitij.so 1142
 
3086 rajveer 1143
        <p>
7770 kshitij.so 1144
        Click the link below to visit the product:
3086 rajveer 1145
        <br/>
1146
        $url
1147
        </p>
1148
        <p>
1149
        Regards,<br/>
6029 rajveer 1150
        $source_name Customer Support Team<br/>
1151
        $source_url<br/>
3086 rajveer 1152
        Email: help@saholic.com<br/>
1153
        </p>
1154
        </div>
1155
        </body>
1156
        </html>
1157
        """
1158
 
6029 rajveer 1159
    html = Template(html).substitute(dict(product=product,date=date,url=url,source_url=source_url,source_name=source_name))
7770 kshitij.so 1160
 
3086 rajveer 1161
    try:
1162
        helper_client = HelperClient().get_client()
8464 amar.kumar 1163
        helper_client.saveUserEmailForSending([email], "", "Product requested by you is available now.", html, str(itemId), "ProductNotification", [], [],sourceId)
3086 rajveer 1164
    except Exception as e:
1165
        print e
8182 amar.kumar 1166
        print sys.exc_info()[0]
3086 rajveer 1167
 
3557 rajveer 1168
def get_all_sources():
1169
    sources = Source.query.all()
1170
    return [to_t_source(source) for source in sources]
3086 rajveer 1171
 
3557 rajveer 1172
def get_item_pricing_by_source(itemId, sourceId):
1173
    item = Item.query.filter_by(id=itemId).first()
1174
    if item is None:
1175
        raise InventoryServiceException(101, "Bad Item")
7770 kshitij.so 1176
 
3557 rajveer 1177
    source = Source.query.filter_by(id=sourceId).first()
1178
    if source is None:
1179
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
7770 kshitij.so 1180
 
3557 rajveer 1181
    item_pricing = SourceItemPricing.query.filter_by(source=source, item=item).first()
1182
    if item_pricing is None:
1183
        raise InventoryServiceException(101, "Pricing information not found for sourceId " + str(sourceId))
1184
    return item_pricing
7770 kshitij.so 1185
 
3557 rajveer 1186
def add_source_item_pricing(sourceItemPricing):
1187
    if not sourceItemPricing:
1188
        raise InventoryServiceException(108, "Bad sourceItemPricing in request")
7770 kshitij.so 1189
 
3557 rajveer 1190
    if not sourceItemPricing.sellingPrice:
4326 mandeep.dh 1191
        raise InventoryServiceException(101, "Selling Price is not defined for sourceId " + str(sourceItemPricing.sourceId))
7770 kshitij.so 1192
 
3557 rajveer 1193
    sourceId = sourceItemPricing.sourceId
1194
    itemId = sourceItemPricing.itemId
7770 kshitij.so 1195
 
3557 rajveer 1196
    item = Item.query.filter_by(id=itemId).first()
1197
    if item is None:
1198
        raise InventoryServiceException(101, "Bad Item")
7770 kshitij.so 1199
 
3557 rajveer 1200
    source = Source.query.filter_by(id=sourceId).first()
1201
    if source is None:
1202
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
7770 kshitij.so 1203
 
3564 rajveer 1204
    ds_sourceItemPricing = SourceItemPricing.get_by(source=source, item=item)
3557 rajveer 1205
    if ds_sourceItemPricing is None:
1206
        ds_sourceItemPricing = SourceItemPricing()
1207
        ds_sourceItemPricing.source = source
1208
        ds_sourceItemPricing.item = item
7770 kshitij.so 1209
 
3557 rajveer 1210
    if sourceItemPricing.mrp:
1211
        ds_sourceItemPricing.mrp = sourceItemPricing.mrp
1212
    ds_sourceItemPricing.sellingPrice = sourceItemPricing.sellingPrice
1213
 
1214
    session.commit()
1215
    return
1216
 
1217
def get_all_source_pricing(itemId):
1218
    item = Item.query.filter_by(id=itemId).first()
1219
    if item is None:
1220
        raise InventoryServiceException(101, "Bad Item")
1221
    source_pricing = SourceItemPricing.query.filter_by(item=item).all()
1222
    return source_pricing
7770 kshitij.so 1223
 
3557 rajveer 1224
 
1225
def get_item_for_source(item_id, sourceId):
1226
    item = get_item(item_id)
1227
    if sourceId == -1:
1228
        return item
1229
    try:
1230
        sip = get_item_pricing_by_source(item_id, sourceId)
1231
        item.sellingPrice = sip.sellingPrice
1232
        if sip.mrp:
1233
            item.mrp = sip.mrp
1234
    except:
1235
        print "No source pricing"
1236
    return item
1237
 
3872 chandransh 1238
def search_items(search_terms, offset, limit):
1239
    query = Item.query
7770 kshitij.so 1240
 
3872 chandransh 1241
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
8139 kshitij.so 1242
    print search_terms
7770 kshitij.so 1243
 
3872 chandransh 1244
    for search_term in search_terms:
6661 rajveer 1245
        query_clause = []
3872 chandransh 1246
        query_clause.append(Item.brand.like(search_term))
1247
        query_clause.append(Item.model_number.like(search_term))
1248
        query_clause.append(Item.model_name.like(search_term))
6661 rajveer 1249
        query = query.filter(or_(*query_clause))
8139 kshitij.so 1250
 
1251
    print query
3872 chandransh 1252
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
1253
    if limit:
1254
        query = query.limit(limit)
1255
    items = query.all()
1256
    return items
1257
 
1258
def get_search_result_count(search_terms):
1259
    query = Item.query
7770 kshitij.so 1260
 
3872 chandransh 1261
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
7770 kshitij.so 1262
 
3872 chandransh 1263
    for search_term in search_terms:
6661 rajveer 1264
        query_clause = []
3872 chandransh 1265
        query_clause.append(Item.brand.like(search_term))
1266
        query_clause.append(Item.model_number.like(search_term))
1267
        query_clause.append(Item.model_name.like(search_term))
6661 rajveer 1268
        query = query.filter(or_(*query_clause))
7770 kshitij.so 1269
 
3872 chandransh 1270
    return query.count()
1271
 
3924 rajveer 1272
def __clear_homepage_cache():
1273
    try:
1274
        # create a password manager
1275
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
1276
        # Add the username and password.
1277
        configclient = ConfigClient()
4310 rajveer 1278
        ips = configclient.get_property("production_servers_private_ips");
3924 rajveer 1279
        ips = ips.split(" ")
7770 kshitij.so 1280
 
3924 rajveer 1281
        for ip in ips:
4310 rajveer 1282
            try:
1283
                top_level_url = "http://" + ip + ":8080/"
1284
                password_mgr.add_password(None, top_level_url, "saholic", "shop2020")
1285
                handler = urllib2.HTTPBasicAuthHandler(password_mgr)
7770 kshitij.so 1286
 
4310 rajveer 1287
                opener = urllib2.build_opener(handler)
7770 kshitij.so 1288
 
4310 rajveer 1289
                # use the opener to fetch a URL
1290
                res = opener.open(top_level_url + "cache-admin/HomePageSnippets?_method=delete")
1291
                print "Successfully cleared home page cache" + res.read()
1292
            except:
1293
                print "Unable to clear home page cache" + res.read()
3924 rajveer 1294
    except:
1295
        print "Unable to clear cache, still should continue with other operations"
7770 kshitij.so 1296
 
4295 varun.gupt 1297
def get_product_notifications(start_datetime):
1298
    '''
1299
    Returns a list of Product Notification objects each representing user requests for notification
1300
    '''
1301
    query = ProductNotification.query
7770 kshitij.so 1302
 
4295 varun.gupt 1303
    if start_datetime:
1304
        query = query.filter(ProductNotification.addedOn > start_datetime)
7770 kshitij.so 1305
 
4295 varun.gupt 1306
    notifications = query.order_by(desc('addedOn')).all()
1307
    return notifications
1308
 
7897 amar.kumar 1309
def get_product_notification_request_count(start_datetime, categoryId):
4295 varun.gupt 1310
    '''
1311
    Returns list of items and the counts of product notification requests
1312
    '''
7897 amar.kumar 1313
    if categoryId:
1314
        categories = get_child_categories(categoryId)
1315
        items = Item.query.filter(Item.category.in_(categories)).all()
1316
        item_ids = [item.id for item in items]
1317
 
4295 varun.gupt 1318
    print start_datetime
1319
    query = session.query(ProductNotification, func.count(ProductNotification.email).label('count'))
7770 kshitij.so 1320
 
4295 varun.gupt 1321
    if start_datetime:
1322
        query = query.filter(ProductNotification.addedOn > start_datetime)
7897 amar.kumar 1323
    if categoryId:
1324
        query = query.filter(ProductNotification.item_id.in_(item_ids))
4295 varun.gupt 1325
    counts = query.group_by(ProductNotification.item_id).order_by(desc('count')).all()
1326
    return counts
1327
 
766 rajveer 1328
def close_session():
1329
    if session.is_active:
1330
        print "session is active. closing it."
1399 rajveer 1331
        session.close()
3376 rajveer 1332
 
1333
def is_alive():
1334
    try:
1335
        session.query(Item.id).limit(1).one()
1336
        return True
1337
    except:
1338
        return False
4332 anupam.sin 1339
 
4649 phani.kuma 1340
def add_authorization_log_for_item(itemId, username, reason):
1341
    if not itemId or not username:
1342
        raise InventoryServiceException(101, "Bad itemId or Invalid username in request")
1343
    authorize_log = AuthorizationLog()
1344
    authorize_log.item_id = itemId
1345
    authorize_log.username = username
1346
    authorize_log.reason = reason
1347
    session.commit()
4797 rajveer 1348
    return True
1349
 
6255 rajveer 1350
def __send_mail_for_oos_item(item):
1351
    oos = OOSTracker.get_by(itemId = item.id)
1352
    if oos is None:
1353
        oos = OOSTracker()
1354
        oos.itemId = item.id
1355
        session.commit()
1356
        try:
6962 rajveer 1357
            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 1358
        except Exception as e:
1359
            print e
4985 mandeep.dh 1360
 
6255 rajveer 1361
def __send_mail_for_active_item(itemId, subject, message):
1362
    oos = OOSTracker.get_by(itemId = itemId)
1363
    if oos is not None:
1364
        oos.delete()
1365
        session.commit()
1366
    __send_mail(subject, message)
1367
 
7384 rajveer 1368
def __send_mail(subject, message, send_to  = to_addresses):
5080 amit.gupta 1369
    try:
7384 rajveer 1370
        thread = threading.Thread(target=partial(mail, mail_user, mail_password, send_to, subject, message))
5080 amit.gupta 1371
        thread.start()
1372
    except Exception as ex:
7770 kshitij.so 1373
        print ex   
5185 mandeep.dh 1374
 
6039 amit.gupta 1375
def get_vat_amount_for_item(itemId, price):
1376
    item = Item.query.filter_by(id=itemId).first()
1377
    vatPercentage = item.vatPercentage
1378
    if vatPercentage is None:
1379
        vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price)).first()
1380
        vatPercentage = vatMaster.vatPercent
1381
        if  vatPercentage is None:
1382
            vatPercentage = 0
1383
    return (price*vatPercentage)/100
7770 kshitij.so 1384
 
7340 amit.gupta 1385
def get_vat_percentage_for_item(itemId, stateId, price):
7330 amit.gupta 1386
    itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==itemId, ItemVatMaster.stateId==stateId)).first()
7340 amit.gupta 1387
    if itemVatMaster is None:
7330 amit.gupta 1388
            item = Item.query.filter_by(id=itemId).first()
7340 amit.gupta 1389
            if item is None:
1390
                raise CatalogServiceException(itemId, "Could not find item in catalog")
1391
            vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price,  CategoryVatMaster.stateId == stateId)).first()
7330 amit.gupta 1392
            if vatMaster is None:
8589 amar.kumar 1393
                raise CatalogServiceException(stateId, "Could not find vat rate for this state." + str(stateId) + " for " + str(itemId))
7340 amit.gupta 1394
            return vatMaster.vatPercent
7330 amit.gupta 1395
    else:
7340 amit.gupta 1396
        return itemVatMaster.vatPercentage
6511 kshitij.so 1397
 
6531 vikram.rag 1398
def get_all_ignored_inventoryupdate_items_list(offset,limit):
1399
    client = InventoryClient().get_client()
1400
    itemids = client.getIgnoredInventoryUpdateItemids(offset,limit)
6532 amit.gupta 1401
    result = []
1402
    if itemids is not None and len(itemids)>0:
1403
        query = Item.query.filter(Item.id.in_(itemids))
1404
        query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name)
1405
        result = [to_t_item(item) for item in query.all()]
1406
    return result
6531 vikram.rag 1407
 
1408
 
6511 kshitij.so 1409
def add_tag (displayName, catalogId):
1410
    ent_tag = None
7770 kshitij.so 1411
    if catalogId is None or (not is_valid_catalog_id(catalogId)):           
6511 kshitij.so 1412
        raise InventoryServiceException(id, "Invalid CatalogId")
1413
    else:
1414
        ent_tag = EntityTag()
1415
        ent_tag.entityId = catalogId
1416
    if displayName is None:
1417
        raise InventoryServiceException(id, "Tag should not be empty")
7770 kshitij.so 1418
    else:
6511 kshitij.so 1419
        ent_tag.tag = displayName
1420
    session.commit()
1421
    return True
1422
 
8590 kshitij.so 1423
def add_banner(bannerCongregate):
1424
    banner = bannerCongregate.banner
9155 kshitij.so 1425
    antecedent = bannerCongregate.antecedent
8590 kshitij.so 1426
    t_bannerMaps = bannerCongregate.bannerMaps
1427
    t_bannerUriMappings = bannerCongregate.bannerUriMappings
9178 kshitij.so 1428
    if antecedent.bannerName is not None :
1429
        delete_banner(antecedent.bannerName,antecedent.bannerType)
9155 kshitij.so 1430
    try:
1431
        banner_details=Banner()
1432
        banner_details.bannerName=banner.bannerName
1433
        banner_details.imageName=banner.imageName
1434
        banner_details.link=banner.link
1435
        banner_details.hasMap=banner.hasMap
1436
        banner_details.priority = banner.priority
1437
        banner_details.bannerType = banner.bannerType
10097 kshitij.so 1438
        add_banner_map(t_bannerMaps,banner.bannerType)
1439
        add_banner_uri(t_bannerUriMappings,banner.bannerType)
9155 kshitij.so 1440
        session.commit()
10097 kshitij.so 1441
        return True
9155 kshitij.so 1442
    except:
10097 kshitij.so 1443
        return False
6848 kshitij.so 1444
def get_all_banners():
8579 kshitij.so 1445
    return session.query(Banner).all()
6848 kshitij.so 1446
 
9155 kshitij.so 1447
def delete_banner(name,bType):
8579 kshitij.so 1448
    try:
9155 kshitij.so 1449
        session.query(Banner.bannerName).filter_by(bannerName=name).filter_by(bannerType=bType).delete()
1450
        delete_banner_map(name,bType)
1451
        delete_uri_mapping(name,bType)
10097 kshitij.so 1452
        session.commit()
8579 kshitij.so 1453
        return True
1454
    except:
1455
        return False
6848 kshitij.so 1456
 
9155 kshitij.so 1457
def get_banner_details(name,bType):
1458
    banner = session.query(Banner).filter(Banner.bannerName==name).filter(Banner.bannerType==bType).one()
10097 kshitij.so 1459
    return banner
6848 kshitij.so 1460
 
10494 kshitij.so 1461
def __t_banner_details(banner,target):
10097 kshitij.so 1462
    bannerObj = t_banner()
1463
    bannerObj.bannerName = banner.bannerName
1464
    bannerObj.imageName = banner.imageName
1465
    bannerObj.link = banner.link
1466
    bannerObj.priority = banner.priority
1467
    bannerObj.hasMap = banner.hasMap
1468
    bannerObj.bannerType = banner.bannerType
1469
    bannerObj.target = target
1470
    return bannerObj
1471
 
1472
 
6848 kshitij.so 1473
def get_active_banners():
8579 kshitij.so 1474
    bannerUriMap = {}
9155 kshitij.so 1475
    bannerType = [1,2]
1476
    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 1477
    for bannerUriMapping in all_active:
1478
        bannerObj = []
9155 kshitij.so 1479
        if (bannerUriMapping[0].bannerType == BannerType.SIDE_BANNER):
1480
            if 'side-banner' in bannerUriMap:
1481
                for obj in bannerUriMap['side-banner']:
1482
                    bannerObj.append(obj)
10494 kshitij.so 1483
            bannerObj.append(__t_banner_details(bannerUriMapping[1],bannerUriMapping[0].target))
9155 kshitij.so 1484
            bannerUriMap['side-banner'] = bannerObj
1485
            continue
8579 kshitij.so 1486
        if bannerUriMapping[0].uri not in bannerUriMap:
10494 kshitij.so 1487
            bannerObj.append(__t_banner_details(bannerUriMapping[1],bannerUriMapping[0].target))
8579 kshitij.so 1488
            bannerUriMap[bannerUriMapping[0].uri] = bannerObj
1489
        else:
1490
            for obj in bannerUriMap[bannerUriMapping[0].uri]:
1491
                bannerObj.append(obj)
10494 kshitij.so 1492
            bannerObj.append(__t_banner_details(bannerUriMapping[1],bannerUriMapping[0].target))
8579 kshitij.so 1493
            bannerUriMap[bannerUriMapping[0].uri] = bannerObj
1494
    return bannerUriMap
1495
 
6848 kshitij.so 1496
 
9155 kshitij.so 1497
def add_banner_map(bannerMaps,bannerType):
10097 kshitij.so 1498
    for bannerMap in bannerMaps:
1499
        banner_map_details=BannerMap()
1500
        banner_map_details.bannerName=bannerMap.bannerName
1501
        banner_map_details.mapLink=bannerMap.mapLink
1502
        banner_map_details.coordinates=bannerMap.coordinates
1503
        banner_map_details.bannerType = bannerType
8579 kshitij.so 1504
 
6848 kshitij.so 1505
 
9155 kshitij.so 1506
def delete_banner_map(name,bType):
10097 kshitij.so 1507
    session.query(BannerMap.bannerName).filter_by(bannerName=name).filter_by(bannerType=bType).delete()
6848 kshitij.so 1508
 
9155 kshitij.so 1509
def delete_uri_mapping(name,bType):
10097 kshitij.so 1510
    session.query(BannerUriMapping.bannerName).filter_by(bannerName=name).filter_by(bannerType=bType).delete()
8579 kshitij.so 1511
 
9155 kshitij.so 1512
def get_banner_map_details(name,bType):
6848 kshitij.so 1513
    query= session.query(BannerMap)
9155 kshitij.so 1514
    return query.filter_by(bannerName=name).filter_by(bannerType=bType).all()
8579 kshitij.so 1515
 
1516
def update_banner(banner):
1517
    banner_details = Banner.get_by(bannerName=banner.bannerName)
1518
    try:
1519
        if banner_details is not None:
1520
            banner_details.imageName = banner.imageName
1521
            banner_details.link = banner.link
1522
            banner_details.priority = banner.priority
1523
            banner_details.hasMap = banner.hasMap
1524
            session.commit()
1525
            return True
1526
        else:
1527
            return False
1528
    except:
1529
        return False
1530
 
9155 kshitij.so 1531
def add_banner_uri(bannerUriMappings,bannerType):
8579 kshitij.so 1532
    for bannerUriMapping in bannerUriMappings:
1533
        banner_uri = BannerUriMapping()
1534
        banner_uri.bannerName = bannerUriMapping.bannerName
1535
        banner_uri.uri = bannerUriMapping.uri
1536
        banner_uri.isActive = bannerUriMapping.isActive
9155 kshitij.so 1537
        banner_uri.bannerType = bannerType
10097 kshitij.so 1538
        banner_uri.target = bannerUriMapping.target
8579 kshitij.so 1539
 
9155 kshitij.so 1540
def get_uri_mapping(name,bType):
8579 kshitij.so 1541
    query= session.query(BannerUriMapping)
9155 kshitij.so 1542
    return query.filter_by(bannerName=name).filter_by(bannerType=bType).all()
8579 kshitij.so 1543
 
1544
def add_campaign(campaign):
1545
    new_campaign = Campaign()
1546
    new_campaign.campaignName = campaign.campaignName
1547
    new_campaign.imageName = campaign.imageName
1548
    session.commit() 
1549
 
1550
def get_campaigns(name):
1551
    query= session.query(Campaign)
1552
    return query.filter_by(campaignName=name).all()
1553
 
1554
def delete_campaign(campaign_id):
1555
    campaign = Campaign.get_by(id = campaign_id)
1556
    if campaign is not None:
1557
        campaign.delete()
1558
        session.commit()
1559
 
1560
def get_all_campaigns():
1561
    return session.query(distinct(Campaign.campaignName)).all()
1562
 
9155 kshitij.so 1563
def get_active_banners_for_mobile_site():
1564
    bannerType = [3]
1565
    bannerMap = {}
1566
    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()
1567
    for bannerUriMapping in all_active:
1568
        bannerObj = []
1569
        if bannerUriMapping[0].uri not in bannerMap:
1570
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
1571
            bannerMap[bannerUriMapping[0].uri] = bannerObj
1572
        else:
1573
            for obj in bannerMap[bannerUriMapping[0].uri]:
1574
                bannerObj.append(obj)
1575
            bannerObj.append(get_banner_details(bannerUriMapping[0].bannerName,bannerUriMapping[0].bannerType))
1576
            bannerMap[bannerUriMapping[0].uri] = bannerObj
1577
    return bannerMap
1578
 
1579
 
7770 kshitij.so 1580
 
6511 kshitij.so 1581
def get_all_tags ():
1582
    return [tuple[0] for tuple in session.query(EntityTag.tag).distinct().all()]
1583
 
1584
def get_all_entities_by_tag_name(displayName):
1585
    return [tuple[0] for tuple in session.query(EntityTag.entityId).filter_by(tag=displayName).all()]
7770 kshitij.so 1586
 
6511 kshitij.so 1587
def delete_tag(displayName):
1588
    session.query(EntityTag.entityId).filter_by(tag=displayName).delete()
1589
    session.commit()
1590
    return True
6518 kshitij.so 1591
 
1592
def delete_entity_tag(displayName, catalogId):
1593
    session.query(EntityTag.tag).filter_by(tag=displayName,entityId=catalogId).delete()
1594
    session.commit()
6805 anupam.sin 1595
    return True
1596
 
6921 anupam.sin 1597
def get_insurance_amount(itemId, price, insurerId, quantity):
9299 kshitij.so 1598
    if insurerId ==1:
1599
        #itemInsurerMapping = ItemInsurerMapping.query.filter(ItemInsurerMapping.itemId == itemId).filter(ItemInsurerMapping.insurerId == insurerId).first()
1600
        #if itemInsurerMapping:
1601
            #Default insurance premium is 1.5%
1602
        #    return round(price * (1.5/100) * quantity)
6921 anupam.sin 1603
        return round(price * (1.5/100) * quantity)
9299 kshitij.so 1604
        '''insuranceAmount = 0.0
1605
        if itemInsurerMapping.premiumType == PremiumType._NAMES_TO_VALUES.get("PERCENT"):
1606
            insuranceAmount = price * (itemInsurerMapping.premiumAmount/100) * quantity
1607
        else :
1608
            insuranceAmount = itemInsurerMapping.premiumAmount * quantity
1609
        '''
1610
    if insurerId ==2:
1611
        return 0.0 #FOR PROMOTION PURPOSE
1612
        #return 449.0 * quantity
7770 kshitij.so 1613
 
9299 kshitij.so 1614
    return 0.0
1615
 
1616
def get_preffered_insurer_for_item(itemId, insurerType):
1617
    itemInsurerMapping = ItemInsurerMapping.query.filter(ItemInsurerMapping.itemId == itemId).filter(ItemInsurerMapping.insurerType == insurerType).first()
1618
    if not itemInsurerMapping:
1619
        return 0
1620
    else:
1621
        return itemInsurerMapping.insurerId
1622
 
6805 anupam.sin 1623
def get_insurer(insurerId):
6838 vikram.rag 1624
    return Insurer.get_by(id = insurerId)
7770 kshitij.so 1625
 
6845 amit.gupta 1626
def get_all_entity_tags():
1627
    entitiesTag = EntityTag.query.all()
1628
    entityMap = {}
1629
    for e in entitiesTag:
1630
        if not entityMap.has_key(e.entityId):
1631
            entityMap[e.entityId] = []
7770 kshitij.so 1632
        entityMap[e.entityId].append(e.tag)  
6845 amit.gupta 1633
    return entityMap
6838 vikram.rag 1634
 
1635
 
1636
def get_all_insurers():
1637
    return session.query(Insurer).all()
7770 kshitij.so 1638
 
6962 rajveer 1639
def update_insurance_declared_amount(insurerId, amount):
1640
    insurer = Insurer.get_by(id = insurerId)
1641
    insurer.declaredAmount += amount
1642
    session.commit()
1643
    if insurer.declaredAmount > 0.9*insurer.creditedAmount:
7770 kshitij.so 1644
        __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 1645
    elif insurer.declaredAmount > 0.8*insurer.creditedAmount:
7770 kshitij.so 1646
        __send_mail("WARNING: Declared Insurance Amount is warning (Declared Amount - " + str(insurer.declaredAmount) + " and Credited Amount - " + str(insurer.creditedAmount) +")", "Please top up credited amount")   
1647
 
7190 amar.kumar 1648
def get_freebie_for_item(itemId):
1649
    freebie = FreebieItem.get_by(itemId = itemId)
1650
    if freebie is None:
1651
        return 0
1652
    else:
1653
        return freebie.freebieItemId
7770 kshitij.so 1654
 
7190 amar.kumar 1655
def add_or_update_freebie_for_item(freebieItem):
1656
    freebie = FreebieItem.get_by(itemId = freebieItem.itemId)
1657
    if freebie is None:
1658
        freebie = FreebieItem()
1659
        freebie.itemId = freebieItem.itemId
1660
    freebie.freebieItemId = freebieItem.freebieItemId
7256 rajveer 1661
    session.commit()
1662
 
7272 amit.gupta 1663
 
1664
def add_or_update_brand_info(brandInfo):
1665
    brandinfo = BrandInfo.get_by(name = brandInfo.name)
1666
    if brandinfo is None:
1667
        brandinfo = BrandInfo()
1668
        brandinfo.itemId = brandInfo.itemId
1669
        brandinfo.freebieItemId = brandInfo.freebieItemId
1670
    session.commit()
7770 kshitij.so 1671
 
7272 amit.gupta 1672
def get_brand_info():
1673
    brandInfoMap = dict()
8274 amit.gupta 1674
    brandInfoList = BrandInfo.query.all()
7272 amit.gupta 1675
    for brandInfo in brandInfoList:
1676
        brandInfoMap[brandInfo.name] = to_t_brand_info(brandInfo)
1677
    return brandInfoMap
1678
 
7382 rajveer 1679
def update_store_pricing(tsp, allColors):
7306 rajveer 1680
    validate_store_pricing(tsp)
7382 rajveer 1681
    item = get_item(tsp.itemId)
7419 rajveer 1682
    activeOnStore = item.activeOnStore
7382 rajveer 1683
    if allColors:
1684
        items = get_items_by_catalog_id(item.catalog_item_id)
1685
    else:
1686
        items = [item]
1687
    for item in items:
1688
        sp = StorePricing.get_by(item_id = item.id)
1689
        if not sp:
1690
            sp = StorePricing()
7419 rajveer 1691
        item.activeOnStore = activeOnStore
7382 rajveer 1692
        sp.recommendedPrice = tsp.recommendedPrice
1693
        sp.minPrice = tsp.minPrice
1694
        sp.minAdvancePrice = tsp.minAdvancePrice
1695
        sp.maxPrice = tsp.maxPrice
1696
        sp.item_id = item.id
1697
        sp.freebieItemId = tsp.freebieItemId
1698
        sp.bestDealText = tsp.bestDealText
1699
        sp.absoluteMinPrice = tsp.absoluteMinPrice
7265 rajveer 1700
    session.commit()
7770 kshitij.so 1701
 
1702
 
7306 rajveer 1703
def validate_store_pricing(tsp):
1704
    if tsp.minPrice > tsp.maxPrice:
7770 kshitij.so 1705
        raise InventoryServiceException(101, "DP is more than MRP")  
1706
 
7306 rajveer 1707
    item = get_item(tsp.itemId)
7770 kshitij.so 1708
 
7384 rajveer 1709
    if item.mrp and tsp.maxPrice > item.mrp:
1710
        raise InventoryServiceException(101, "MRP is more than Saholic MRP")
7770 kshitij.so 1711
 
7306 rajveer 1712
    if tsp.recommendedPrice < item.sellingPrice:
7770 kshitij.so 1713
        raise InventoryServiceException(101, "MOP is less than Saholic MOP.")  
1714
 
7306 rajveer 1715
    if tsp.recommendedPrice < tsp.minPrice or tsp.recommendedPrice >  tsp.maxPrice:
7770 kshitij.so 1716
        raise InventoryServiceException(101, "MOP price must be in the range")
8867 rajveer 1717
 
1718
#    if tsp.minPrice < item.sellingPrice:
1719
#        store_message = "Saholic MOP Changed. DP {0} is less than Saholic MOP.\n".format(tsp.minPrice)
1720
#        subject = "Item '{0}' is updated in Catalog. Id is {1}".format(__get_product_name(item),item.id)
1721
#        __send_mail(subject, store_message, to_store_addresses)
7770 kshitij.so 1722
 
7306 rajveer 1723
    return True
7770 kshitij.so 1724
 
1725
 
7306 rajveer 1726
 
1727
def get_defalut_store_pricing(itemId):
7256 rajveer 1728
    inventoryClient = InventoryClient().get_client()
7306 rajveer 1729
    pricings = inventoryClient.getAllItemPricing(itemId)
1730
    item = get_item(itemId)
7382 rajveer 1731
    maxp = item.sellingPrice
1732
    if item.mrp:
1733
        maxp = item.mrp
7770 kshitij.so 1734
 
7256 rajveer 1735
    minp = 0
7265 rajveer 1736
    rp = item.sellingPrice
7256 rajveer 1737
    for pricing in pricings:
7770 kshitij.so 1738
        if not minp or minp > pricing.dealerPrice:
7256 rajveer 1739
            minp = pricing.dealerPrice
1740
 
7770 kshitij.so 1741
 
7426 anupam.sin 1742
    minap = math.ceil(min(max(500, rp*0.1),rp))
7306 rajveer 1743
 
7431 rajveer 1744
    if minp > rp:
1745
        minp = rp
7306 rajveer 1746
    sp = tStorePricing()
1747
    sp.itemId = itemId
7256 rajveer 1748
    sp.recommendedPrice = rp
7351 rajveer 1749
    sp.absoluteMinPrice = minp
7256 rajveer 1750
    sp.minPrice = minp
1751
    sp.minAdvancePrice = minap
1752
    sp.maxPrice = maxp
7308 rajveer 1753
    sp.freebieItemId = 0
1754
    sp.bestDealText = ""
7306 rajveer 1755
    return sp
7770 kshitij.so 1756
 
1757
 
7256 rajveer 1758
def get_store_pricing(itemId):
7270 rajveer 1759
    store = StorePricing.get_by(item_id = itemId)
7306 rajveer 1760
    if store is None:
1761
        return get_defalut_store_pricing(itemId)
1762
 
7256 rajveer 1763
    sp = tStorePricing()
7770 kshitij.so 1764
    sp.itemId = itemId   
7256 rajveer 1765
    sp.recommendedPrice = store.recommendedPrice
1766
    sp.minPrice = store.minPrice
1767
    sp.minAdvancePrice = store.minAdvancePrice
1768
    sp.maxPrice = store.maxPrice
7351 rajveer 1769
    sp.absoluteMinPrice = store.absoluteMinPrice
7308 rajveer 1770
    sp.freebieItemId = store.freebieItemId
1771
    sp.bestDealText = store.bestDealText
7281 kshitij.so 1772
    return sp
1773
 
1774
def get_all_amazon_listed_items():
1775
    return session.query(Amazonlisted).all()
1776
 
1777
def get_amazon_item_details(amazonItemId):
1778
    amazonlisted = Amazonlisted.get_by(itemId=amazonItemId)
1779
    return amazonlisted
1780
 
8168 kshitij.so 1781
def update_amazon_item_details(amazonlisted):
1782
    amazon_listed = Amazonlisted.get_by(itemId = amazonlisted.itemid)
1783
    amazon_listed.isFba=amazonlisted.isFba
10909 vikram.rag 1784
    amazon_listed.isFbb=amazonlisted.isFbb
8168 kshitij.so 1785
    amazon_listed.isNonFba=amazonlisted.isNonFba
1786
    amazon_listed.isInventoryOverride=amazonlisted.isInventoryOverride
1787
    amazon_listed.handlingTime=amazonlisted.handlingTime
1788
    amazon_listed.isCustomTime=amazonlisted.isCustomTime
8619 kshitij.so 1789
    amazon_listed.taxCode=amazonlisted.taxCode
10909 vikram.rag 1790
    amazon_listed.fbbtaxCode=amazonlisted.fbbtaxCode
8619 kshitij.so 1791
    if (amazon_listed.sellingPrice != amazonlisted.sellingPrice) and amazonlisted.sellingPrice > 0:
8168 kshitij.so 1792
        amazon_listed.mfnPriceLastUpdatedOn = datetime.datetime.now()
1793
        amazon_listed.sellingPrice=amazonlisted.sellingPrice
8619 kshitij.so 1794
    if (amazon_listed.fbaPrice != amazonlisted.fbaPrice) and amazonlisted.fbaPrice > 0:
8168 kshitij.so 1795
        amazon_listed.fbaPriceLastUpdatedOn = datetime.datetime.now()
1796
        amazon_listed.fbaPrice=amazonlisted.fbaPrice
10909 vikram.rag 1797
    if (amazon_listed.fbbPrice != amazonlisted.fbbPrice) and amazonlisted.fbbPrice > 0:
1798
        amazon_listed.fbbPriceLastUpdatedOn = datetime.datetime.now()
1799
        amazon_listed.fbbPrice=amazonlisted.fbbPrice
8168 kshitij.so 1800
    amazon_listed.suppressMfnPriceUpdate=amazonlisted.suppressMfnPriceUpdate
10909 vikram.rag 1801
    amazon_listed.suppressFbaPriceUpdate=amazonlisted.suppressFbaPriceUpdate
1802
    amazon_listed.suppressFbbPriceUpdate=amazonlisted.suppressFbbPriceUpdate 
7281 kshitij.so 1803
    session.commit()
7770 kshitij.so 1804
 
7281 kshitij.so 1805
def add_amazon_item(amazonlisted):
1806
    if (not amazonlisted) or (not amazonlisted.itemid) or (not amazonlisted.asin):
1807
        return
7397 kshitij.so 1808
    amazonItem = Amazonlisted.get_by(itemId=amazonlisted.itemid)
1809
    if amazonItem is None:
1810
        amazon_item = Amazonlisted()
1811
        if amazonlisted.itemid:
1812
            amazon_item.itemId=amazonlisted.itemid
1813
        if amazonlisted.asin:
1814
            amazon_item.asin=amazonlisted.asin
1815
        if amazonlisted.brand:
1816
            amazon_item.brand=amazonlisted.brand
1817
        else:
1818
            amazon_item.brand=''
1819
        if amazonlisted.model:
1820
            amazon_item.model=amazonlisted.model
1821
        else:
1822
            amazon_item.model=''
1823
        if amazonlisted.manufacturer_name:
1824
            amazon_item.manufacturer_name=amazonlisted.manufacturer_name
1825
        else:
1826
            amazon_item.manufacturer_name=''
1827
        if amazonlisted.name:
1828
            amazon_item.name=amazonlisted.name
1829
        else:
1830
            amazon_item.name=''
1831
        if amazonlisted.part_number:
1832
            amazon_item.part_number=amazonlisted.part_number
1833
        else:
1834
            amazon_item.part_number=''
1835
        if amazonlisted.ean:
1836
            amazon_item.ean=amazonlisted.ean
1837
        else:
1838
            amazon_item.ean=''
1839
        if amazonlisted.upc:
1840
            amazon_item.upc=amazonlisted.upc
1841
        else:
1842
            amazon_item.upc=''
7770 kshitij.so 1843
        if amazonlisted.fbaPrice:
1844
            amazon_item.fbaPrice=amazonlisted.fbaPrice
7782 kshitij.so 1845
            amazon_item.fbaPriceLastUpdatedOnSc =  datetime.datetime.now()
7770 kshitij.so 1846
            amazon_item.fbaPriceLastUpdatedOn = datetime.datetime.now()
7397 kshitij.so 1847
        if amazonlisted.sellingPrice:
1848
            amazon_item.sellingPrice=amazonlisted.sellingPrice
7782 kshitij.so 1849
            amazon_item.mfnPriceLastUpdatedOnSc = datetime.datetime.now()
7770 kshitij.so 1850
            amazon_item.mfnPriceLastUpdatedOn = datetime.datetime.now()
7397 kshitij.so 1851
        if amazonlisted.category:
1852
            amazon_item.category=amazonlisted.category
1853
        else:
1854
            amazon_item.category=''
1855
        if amazonlisted.color:
1856
            amazon_item.color=amazonlisted.color
1857
        else:
7404 kshitij.so 1858
            amazon_item.color=''
8139 kshitij.so 1859
        amazon_item.suppressMfnPriceUpdate=False
8140 kshitij.so 1860
        amazon_item.suppressFbaPriceUpdate=False
8379 vikram.rag 1861
        amazon_item.isFba = False
1862
        amazon_item.isNonFba = False
1863
        amazon_item.isInventoryOverride = False
10947 vikram.rag 1864
        if amazonlisted.fbbPrice: 
1865
            amazon_item.fbbPrice = amazonlisted.fbbPrice 
1866
            amazon_item.fbbPriceLastUpdatedOnSc = datetime.datetime.now()
1867
            amazon_item.fbbPriceLastUpdatedOn = datetime.datetime.now()
10921 vikram.rag 1868
        amazon_item.isFbb = False
10909 vikram.rag 1869
        amazon_item.suppressFbbPriceUpdate = False
1870
 
7397 kshitij.so 1871
    elif (amazonItem.asin!=amazonlisted.asin):
1872
        if amazonlisted.asin:
1873
            amazonItem.asin=amazonlisted.asin
1874
        if amazonlisted.brand:
1875
            amazonItem.brand=amazonlisted.brand
1876
        else:
1877
            amazonItem.brand=''
1878
        if amazonlisted.model:
1879
            amazonItem.model=amazonlisted.model
1880
        else:
1881
            amazonItem.model=''
1882
        if amazonlisted.manufacturer_name:
1883
            amazonItem.manufacturer_name=amazonlisted.manufacturer_name
1884
        else:
1885
            amazonItem.manufacturer_name=''
1886
        if amazonlisted.name:
1887
            amazonItem.name=amazonlisted.name
1888
        else:
1889
            amazonItem.name=''
1890
        if amazonlisted.part_number:
1891
            amazonItem.part_number=amazonlisted.part_number
1892
        else:
1893
            amazonItem.part_number=''
1894
        if amazonlisted.ean:
1895
            amazonItem.ean=amazonlisted.ean
1896
        else:
1897
            amazonItem.ean=''
1898
        if amazonlisted.upc:
1899
            amazonItem.upc=amazonlisted.upc
1900
        else:
1901
            amazonItem.upc=''
1902
        if amazonlisted.sellingPrice:
8188 kshitij.so 1903
            amazonItem.sellingPrice=amazonlisted.sellingPrice
7397 kshitij.so 1904
        if amazonlisted.fbaPrice:
8188 kshitij.so 1905
            amazonItem.fbaPrice=amazonlisted.fbaPrice
7397 kshitij.so 1906
        if amazonlisted.isFba:
1907
            amazonItem.isFba=amazonlisted.isFba
1908
        if amazonlisted.isNonFba:
1909
            amazonItem.isNonFba=amazonlisted.isNonFba
1910
        if amazonlisted.isInventoryOverride:
1911
            amazonItem.isInventoryOverride=amazonlisted.isInventoryOverride
1912
        if amazonlisted.category:
1913
            amazonItem.category=amazonlisted.category
1914
        else:
1915
            amazonItem.category=''
1916
        if amazonlisted.color:
1917
            amazonItem.color=amazonlisted.color
1918
        else:
7404 kshitij.so 1919
            amazonItem.color=''
7316 kshitij.so 1920
    else:
7397 kshitij.so 1921
        return
7281 kshitij.so 1922
    session.commit()
7770 kshitij.so 1923
 
7291 vikram.rag 1924
def get_asin_items():
7296 amit.gupta 1925
    from_date=datetime.datetime.now() - datetime.timedelta(days=10)
7291 vikram.rag 1926
    return Item.query.filter(Item.updatedOn > from_date).all()
7770 kshitij.so 1927
 
7291 vikram.rag 1928
def get_all_fba_listed_items():
1929
    return Amazonlisted.query.filter(Amazonlisted.isFba==True).all()
7770 kshitij.so 1930
 
7291 vikram.rag 1931
def get_all_nonfba_listed_items():
1932
    return Amazonlisted.query.filter(Amazonlisted.isNonFba==True).all()
7460 kshitij.so 1933
 
1934
def update_item_inventory(itemId,holdInventory,defaultInventory):
1935
    item = get_item(itemId)
1936
    item.holdInventory = holdInventory
1937
    item.defaultInventory = defaultInventory
1938
    session.commit()
7770 kshitij.so 1939
 
1940
def update_timestamp_for_amazon_feeds(feedType,skuList,timestamp):
1941
    #amazonListed = get_all_amazon_listed_items()
7782 kshitij.so 1942
    #fbaItems = []
1943
    #mfnItems = []
7770 kshitij.so 1944
    if feedType == 'NonFbaPricing':
7782 kshitij.so 1945
        for sku in skuList:
7770 kshitij.so 1946
            amazonItem = Amazonlisted.get_by(itemId=sku)
1947
            amazonItem.mfnPriceLastUpdatedOnSc = to_py_date(timestamp)
1948
            session.commit()
1949
        return True
1950
    elif feedType == 'FbaPricing':
7782 kshitij.so 1951
        for sku in skuList:
7770 kshitij.so 1952
            amazonItem = Amazonlisted.get_by(itemId=sku)
1953
            amazonItem.fbaPriceLastUpdatedOnSc = to_py_date(timestamp)
1954
            session.commit()
1955
        return True
10924 vikram.rag 1956
    elif feedType == 'FbbPricing':
1957
        for sku in skuList:
1958
            amazonItem = Amazonlisted.get_by(itemId=sku)
1959
            amazonItem.fbbPriceLastUpdatedOnSc = to_py_date(timestamp)
1960
            session.commit()
1961
        return True
7770 kshitij.so 1962
    elif feedType== 'FullFbaPricing':
7782 kshitij.so 1963
        for sku in skuList:
7770 kshitij.so 1964
            amazonItem = Amazonlisted.get_by(itemId=sku)
1965
            amazonItem.fbaPriceLastUpdatedOnSc = to_py_date(timestamp)
1966
            session.commit()
1967
        return True
1968
    elif feedType== 'FullNonFbaPricing':
7782 kshitij.so 1969
        for sku in skuList:
7770 kshitij.so 1970
            amazonItem = Amazonlisted.get_by(itemId=sku)
1971
            amazonItem.mfnPriceLastUpdatedOnSc = to_py_date(timestamp)
1972
            session.commit()
8386 vikram.rag 1973
    elif (feedType=='FbaListingFeed'):
1974
        for sku in skuList:
1975
            amazonItem = Amazonlisted.get_by(itemId=sku)
1976
            amazonItem.isFba = True
1977
            session.commit()
1978
    elif (feedType=='NonFbaListingFeed'):
1979
        for sku in skuList:
1980
            amazonItem = Amazonlisted.get_by(itemId=sku)
1981
            amazonItem.isNonFba = True 
1982
            session.commit()
10920 vikram.rag 1983
    elif (feedType=='FbbListingFeed'):
1984
        for sku in skuList:
1985
            amazonItem = Amazonlisted.get_by(itemId=sku)
1986
            amazonItem.fbbListedOn = to_py_date(timestamp) 
1987
            session.commit()
7770 kshitij.so 1988
    else:
1989
        return False
7281 kshitij.so 1990
 
7897 amar.kumar 1991
def get_all_parent_categories():
1992
    return Category.query.filter_by(parent_category_id=10000).all()
7977 kshitij.so 1993
 
1994
def add_page_view_event(pageEvent):
1995
    page_view_event = PageViewEvents()
1996
    page_view_event.catalogId = pageEvent.catalogId
1997
    page_view_event.url = pageEvent.url
1998
    page_view_event.sellingPrice = pageEvent.sellingPrice
1999
    page_view_event.ip = pageEvent.ip
2000
    page_view_event.sessionId = pageEvent.sessionId
2001
    page_view_event.comingSoon = pageEvent.comingSoon
2002
    page_view_event.eventTimestamp = to_py_date(pageEvent.eventDate)
2003
    session.commit()
2004
 
2005
def add_cart_event(cartEvent):
2006
    cart_event = CartEvents()
2007
    cart_event.catalogId = cartEvent.catalogId
2008
    cart_event.itemId = cartEvent.itemId
2009
    cart_event.inStock = cartEvent.inStock
2010
    cart_event.ip = cartEvent.ip
2011
    cart_event.sessionId = cartEvent.sessionId
2012
    cart_event.comingSoon = cartEvent.comingSoon
2013
    cart_event.sellingPrice = cartEvent.sellingPrice
2014
    cart_event.eventTimestamp = to_py_date(cartEvent.eventDate)
2015
    session.commit()
8168 kshitij.so 2016
 
2017
def update_amazon_attributes_in_bulk(amazonlistedMap):
2018
    for itemId,amazonlisted in amazonlistedMap.iteritems():
2019
        amazon_item = get_amazon_item_details(itemId)
2020
        if amazon_item is not None:
2021
            if amazon_item.sellingPrice != amazonlisted.sellingPrice:
2022
                amazon_item.mfnPriceLastUpdatedOn = datetime.datetime.now()
2023
                amazon_item.sellingPrice = amazonlisted.sellingPrice
2024
            if amazon_item.fbaPrice != amazonlisted.fbaPrice:
2025
                amazon_item.fbaPriceLastUpdatedOn = datetime.datetime.now()
2026
                amazon_item.fbaPrice = amazonlisted.fbaPrice
10909 vikram.rag 2027
            if amazon_item.fbbPrice != amazonlisted.fbbPrice:
2028
                amazon_item.fbbPriceLastUpdatedOn = datetime.datetime.now()
2029
                amazon_item.fbbPrice = amazonlisted.fbbPrice
10929 vikram.rag 2030
            amazon_item.fbbtaxCode = amazonlisted.fbbtaxCode    
8619 kshitij.so 2031
            amazon_item.taxCode = amazonlisted.taxCode
10909 vikram.rag 2032
            amazon_item.isFbb = amazonlisted.isFbb
8168 kshitij.so 2033
            amazon_item.isFba = amazonlisted.isFba
2034
            amazon_item.isNonFba = amazonlisted.isNonFba
2035
            amazon_item.isInventoryOverride = amazonlisted.isInventoryOverride
2036
            amazon_item.suppressMfnPriceUpdate = amazonlisted.suppressMfnPriceUpdate
2037
            amazon_item.suppressFbaPriceUpdate = amazonlisted.suppressFbaPriceUpdate
10909 vikram.rag 2038
            amazon_item.suppressFbbPriceUpdate = amazonlisted.suppressFbbPriceUpdate
8168 kshitij.so 2039
            session.commit()
2040
    return True
2041
 
7977 kshitij.so 2042
 
8182 amar.kumar 2043
def insert_ebay_item(ebayItem):
8241 amar.kumar 2044
    ebay_item = EbayItem.get_by(ebayListingId = ebayItem.ebayListingId)
2045
    if ebay_item is None:
2046
        ebay_item = EbayItem()
8182 amar.kumar 2047
    ebay_item.ebayListingId = ebayItem.ebayListingId
2048
    ebay_item.itemId = ebayItem.itemId
2049
    ebay_item.listingName = ebayItem.listingName
2050
    ebay_item.listingPrice = ebayItem.listingPrice
8281 amar.kumar 2051
    ebay_item.listingExpiryDate = to_py_date(ebayItem.listingExpiryDate)
8182 amar.kumar 2052
    ebay_item.subsidy = ebayItem.subsidy
2053
    ebay_item.defaultWarehouseId = ebayItem.defaultWarehouseId
2054
    session.commit()
2055
 
7977 kshitij.so 2056
 
8182 amar.kumar 2057
def get_ebay_item(listing_id):
2058
    ebay_item = EbayItem.get_by(ebayListingId = listing_id)
2059
    return ebay_item
7977 kshitij.so 2060
 
8182 amar.kumar 2061
 
2062
def update_ebay_item(ebayItem):
2063
    ebay_item = EbayItem.get_by(ebayListingId = ebayItem.ebayListingId)
2064
    #if ebay_item.listingExpiryDate < datetime.datetime.now():
2065
    ebay_item.listingName = ebayItem.listingName
2066
    ebay_item.listingPrice = ebayItem.listingPrice
2067
    ebay_item.listingExpiryDate = ebayItem.listingExpiryDate
2068
    ebay_item.subsidy = ebayItem.subsidy
2069
    ebay_item.defaultWarehouseId = ebayItem.defaultWarehouseId
2070
    session.commit()
8379 vikram.rag 2071
 
2072
def get_all_items_to_list_on_fba():
2073
    return Amazonlisted.query.filter(Amazonlisted.isFba==False).all()
2074
 
2075
def get_all_items_to_list_on_nonfba():
2076
    return Amazonlisted.query.filter(Amazonlisted.isNonFba==False).all()
8182 amar.kumar 2077
 
8619 kshitij.so 2078
def get_amazon_listed_items(offset,limit):
2079
    return session.query(Amazonlisted).offset(offset).limit(limit).all()
2080
 
2081
def search_amazon_items(search_terms, offset, limit):
2082
    query = Amazonlisted.query
2083
 
2084
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2085
 
2086
    for search_term in search_terms:
2087
        query_clause = []
2088
        query_clause.append(Amazonlisted.itemId.like(search_term))
2089
        query_clause.append(Amazonlisted.brand.like(search_term))
2090
        query_clause.append(Amazonlisted.model.like(search_term))
2091
        query_clause.append(Amazonlisted.name.like(search_term))
2092
        query_clause.append(Amazonlisted.asin.like(search_term))
2093
        query = query.filter(or_(*query_clause))
2094
 
2095
    query = query.offset(offset)
2096
    if limit:
2097
        query = query.limit(limit)
2098
    amazon_items = query.all()
2099
    return amazon_items
2100
 
2101
def get_amazon_search_result_count(search_terms):
2102
    query = Amazonlisted.query
2103
 
2104
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2105
 
2106
    for search_term in search_terms:
2107
        query_clause = []
2108
        query_clause.append(Amazonlisted.itemId.like(search_term))
2109
        query_clause.append(Amazonlisted.brand.like(search_term))
2110
        query_clause.append(Amazonlisted.model.like(search_term))
2111
        query_clause.append(Amazonlisted.name.like(search_term))
2112
        query_clause.append(Amazonlisted.asin.like(search_term))
2113
        query = query.filter(or_(*query_clause))
2114
 
2115
    return query.count()
2116
 
2117
def get_count_for_amazonlisted_items():
2118
    return session.query(func.count(Amazonlisted.itemId)).scalar()
2119
 
8739 vikram.rag 2120
def add_or_update_snapdeal_item(snapdealitem):
2121
    item = SnapdealItem.get_by(item_id=snapdealitem.item_id)
9779 kshitij.so 2122
    if not __validateSnapdealObject(snapdealitem):
2123
        print "Bad object"
2124
        return False
8739 vikram.rag 2125
    try:
2126
        if item is not None:
10097 kshitij.so 2127
            itemHistory = MarketPlaceUpdateHistory()
9242 kshitij.so 2128
            itemHistory.item_id = snapdealitem.item_id
10097 kshitij.so 2129
            itemHistory.source = OrderSource.SNAPDEAL
9242 kshitij.so 2130
            itemHistory.exceptionPrice = item.exceptionPrice
2131
            itemHistory.warehouseId = item.warehouseId
10097 kshitij.so 2132
            itemHistory.isListedOnSource = item.isListedOnSnapdeal
9242 kshitij.so 2133
            itemHistory.transferPrice = item.transferPrice
2134
            itemHistory.sellingPrice = item.sellingPrice
2135
            itemHistory.courierCost = item.courierCost
2136
            itemHistory.commission = item.commission
2137
            itemHistory.serviceTax = item.serviceTax
2138
            itemHistory.suppressPriceFeed = item.suppressPriceFeed
2139
            itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
2140
            itemHistory.updatedOn = item.updatedOn
9478 kshitij.so 2141
            itemHistory.maxNlc = item.maxNlc
10097 kshitij.so 2142
            itemHistory.skuAtSource = item.skuAtSnapdeal
2143
            itemHistory.marketPlaceSerialNumber = item.supc
9779 kshitij.so 2144
            itemHistory.priceUpdatedBy = item.priceUpdatedBy
11095 kshitij.so 2145
            itemHistory.courierCostMarketplace = item.courierCostMarketplace
9242 kshitij.so 2146
 
9779 kshitij.so 2147
            if (item.sellingPrice!=snapdealitem.sellingPrice):
2148
                item.priceUpdatedBy = snapdealitem.updatedBy
2149
 
8739 vikram.rag 2150
            if snapdealitem.exceptionPrice is not None:
2151
                item.exceptionPrice = snapdealitem.exceptionPrice
2152
            if snapdealitem.warehouseId is not None:     
2153
                item.warehouseId = snapdealitem.warehouseId
2154
            if snapdealitem.isListedOnSnapdeal is not None:    
9242 kshitij.so 2155
                item.isListedOnSnapdeal = snapdealitem.isListedOnSnapdeal
2156
            if snapdealitem.transferPrice is not None:
2157
                item.transferPrice = snapdealitem.transferPrice
2158
            if snapdealitem.sellingPrice is not None:
2159
                item.sellingPrice = snapdealitem.sellingPrice
2160
            if snapdealitem.courierCost is not None:
2161
                item.courierCost = snapdealitem.courierCost    
2162
            if snapdealitem.commission is not None:
2163
                item.commission = snapdealitem.commission
2164
            if snapdealitem.serviceTax is not None:
2165
                item.serviceTax = snapdealitem.serviceTax
2166
            item.suppressPriceFeed =snapdealitem.suppressPriceFeed
9478 kshitij.so 2167
            item.suppressInventoryFeed =snapdealitem.suppressInventoryFeed
9581 kshitij.so 2168
            if snapdealitem.maxNlc is not None:
2169
                item.maxNlc = snapdealitem.maxNlc
9478 kshitij.so 2170
            item.skuAtSnapdeal = snapdealitem.skuAtSnapdeal
9242 kshitij.so 2171
            item.updatedOn = datetime.datetime.now()
9568 kshitij.so 2172
            item.supc = snapdealitem.supc
11095 kshitij.so 2173
            item.courierCostMarketplace = snapdealitem.courierCostMarketplace
9779 kshitij.so 2174
            __markStatusForMarketplaceItems(snapdealitem,item)
2175
            return update_marketplace_attributes_for_item(snapdealitem.marketplaceItems)
8739 vikram.rag 2176
        else:
2177
            item = SnapdealItem()
2178
            if snapdealitem.item_id is not None:
2179
                item.item_id = snapdealitem.item_id
2180
                if snapdealitem.exceptionPrice is not None:
2181
                    item.exceptionPrice = snapdealitem.exceptionPrice
2182
                if snapdealitem.warehouseId is not None:    
2183
                    item.warehouseId = snapdealitem.warehouseId
2184
                if snapdealitem.isListedOnSnapdeal is not None: 
9242 kshitij.so 2185
                    item.isListedOnSnapdeal = snapdealitem.isListedOnSnapdeal
2186
                if snapdealitem.transferPrice is not None:
2187
                    item.transferPrice = snapdealitem.transferPrice
2188
                if snapdealitem.sellingPrice is not None:
2189
                    item.sellingPrice = snapdealitem.sellingPrice
2190
                if snapdealitem.courierCost is not None:
2191
                    item.courierCost = snapdealitem.courierCost    
2192
                if snapdealitem.commission is not None:
2193
                    item.commission = snapdealitem.commission
2194
                if snapdealitem.serviceTax is not None:
2195
                    item.serviceTax = snapdealitem.serviceTax
2196
                item.suppressPriceFeed =snapdealitem.suppressPriceFeed
2197
                item.suppressInventoryFeed =snapdealitem.suppressInventoryFeed 
9595 kshitij.so 2198
                item.maxNlc = snapdealitem.maxNlc
9478 kshitij.so 2199
                item.skuAtSnapdeal = snapdealitem.skuAtSnapdeal
9568 kshitij.so 2200
                item.supc = snapdealitem.supc
9779 kshitij.so 2201
                item.updatedOn = datetime.datetime.now()  
2202
                item.priceUpdatedBy = snapdealitem.updatedBy
11095 kshitij.so 2203
                item.courierCostMarketplace = snapdealitem.courierCostMarketplace
9779 kshitij.so 2204
                __markStatusForMarketplaceItems(snapdealitem,item)
2205
                return update_marketplace_attributes_for_item(snapdealitem.marketplaceItems)  
2206
    except Exception as ex:
2207
        print "Unable to addOrupdate snapdealItem"
2208
        print ex
9242 kshitij.so 2209
        return False
8739 vikram.rag 2210
 
2211
def get_snapdeal_item(itemid):
8755 vikram.rag 2212
    item = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).filter(SnapdealItem.item_id==itemid).first()
8747 vikram.rag 2213
    return item
9724 kshitij.so 2214
 
2215
def get_snapdeal_item_detail(itemid):
2216
    item = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).filter(SnapdealItem.item_id==itemid).first()
2217
    try:
2218
        client = InventoryClient().get_client()
2219
        SnapdealInventoryItem = client.getSnapdealInventoryForItem(itemid)
2220
        return item, SnapdealInventoryItem
2221
    except Exception as e:
2222
        print e
2223
        return item,None
8739 vikram.rag 2224
 
2225
def get_all_snapdeal_items():
8754 vikram.rag 2226
    items = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).all()
8739 vikram.rag 2227
    return items
2228
 
9242 kshitij.so 2229
def get_snapdeal_items(offset,limit):
2230
    return session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).offset(offset).limit(limit).all()
2231
 
8619 kshitij.so 2232
def update_asin(amazonAsinMap):
2233
    for item_id,t_item in amazonAsinMap.iteritems():
2234
        item = get_item(item_id)
2235
        item.asin=t_item.asin
2236
        item.defaultInventory = t_item.defaultInventory
2237
        item.holdInventory = t_item.holdInventory
2238
        item.updatedOn = datetime.datetime.now()
2239
    session.commit()
9242 kshitij.so 2240
 
2241
def search_snapdeal_items(search_terms,offset,limit):
2242
    query = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id))
2243
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2244
    for search_term in search_terms:
2245
        query_clause = []
2246
        query_clause.append(Item.id.like(search_term))
2247
        query_clause.append(Item.brand.like(search_term))
2248
        query_clause.append(Item.model_name.like(search_term))
2249
        query_clause.append(Item.model_number.like(search_term))
2250
        query_clause.append(Item.color.like(search_term))
2251
        query = query.filter(or_(*query_clause))
2252
 
2253
    query = query.offset(offset)
2254
    if limit:
2255
        query = query.limit(limit)
2256
    snapdeal_items = query.all()
2257
    return snapdeal_items
2258
 
2259
def get_snapdeal_search_result_count(search_terms):
2260
    query = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id))
2261
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2262
    for search_term in search_terms:
2263
        query_clause = []
2264
        query_clause.append(Item.id.like(search_term))
2265
        query_clause.append(Item.brand.like(search_term))
2266
        query_clause.append(Item.model_name.like(search_term))
2267
        query_clause.append(Item.model_number.like(search_term))
2268
        query_clause.append(Item.color.like(search_term))
2269
        query = query.filter(or_(*query_clause))
2270
    return query.count()
2271
 
2272
def get_count_for_snapdeal_items():
2273
    return session.query(func.count(SnapdealItem.item_id)).scalar()
2274
 
9456 vikram.rag 2275
def get_snapdealitem_by_skuatsnapdeal(sku):
2276
    snapdeal_item = SnapdealItem.get_by(skuAtSnapdeal=sku)
2277
    if snapdeal_item is not None: 
2278
        item = session.query(SnapdealItem,Item).join((Item,SnapdealItem.item_id==Item.id)).filter(SnapdealItem.item_id==snapdeal_item.item_id).first()
2279
    else:
2280
        return None    
2281
    return item
9242 kshitij.so 2282
 
9621 manish.sha 2283
def get_product_feed_submit(catalog_itemId):
2284
    product_feedsubmit = ProductFeedSubmit.get_by(catalogItemId=catalog_itemId)
2285
    return product_feedsubmit
9456 vikram.rag 2286
 
9621 manish.sha 2287
def add_product_feed_submit(productFeedSubmit):
2288
    feedSubmit = ProductFeedSubmit()
2289
    feedSubmit.catalogItemId = productFeedSubmit.catalogItemId
2290
    feedSubmit.stockLinkedFeed = productFeedSubmit.stockLinkedFeed
2291
    session.commit()
2292
    return True
2293
 
2294
def update_product_feed_submit(productFeedSubmit):
2295
    feedSubmit = get_product_feed_submit(productFeedSubmit.catalogItemId)
2296
    if feedSubmit:
2297
        feedSubmit.catalogItemId = productFeedSubmit.catalogItemId
2298
        feedSubmit.stockLinkedFeed = productFeedSubmit.stockLinkedFeed
2299
        session.commit()
2300
        return True
2301
    return False
2302
 
2303
def delete_product_feed_submit(catalog_itemId):
2304
    feedSubmit = get_product_feed_submit(catalog_itemId)
2305
    if feedSubmit:
2306
        feedSubmit.delete()
2307
        session.commit()
2308
        return True
2309
    return False
2310
 
2311
def get_all_product_feed_submit():
2312
    print session.query(ProductFeedSubmit).all()
2313
    return session.query(ProductFeedSubmit).all()
2314
 
9724 kshitij.so 2315
def get_marketplace_details_for_item(item_id, sourceId):
2316
    return MarketplaceItems.get_by(itemId=item_id,source=sourceId)
2317
 
2318
def update_marketplace_attributes_for_item(t_marketplaceItem):
2319
    if t_marketplaceItem.source is None or t_marketplaceItem.itemId is None:
2320
        return False
2321
    try:
2322
        marketplaceItem = get_marketplace_details_for_item(t_marketplaceItem.itemId,t_marketplaceItem.source)
2323
        if marketplaceItem is None:
2324
            marketplaceItem = MarketplaceItems()
2325
            marketplaceItem.itemId = t_marketplaceItem.itemId
2326
            marketplaceItem.source = t_marketplaceItem.source
9779 kshitij.so 2327
            marketplaceItem.emiFee = t_marketplaceItem.emiFee
2328
            marketplaceItem.closingFee = t_marketplaceItem.closingFee
2329
            marketplaceItem.returnProvision = t_marketplaceItem.returnProvision
2330
            marketplaceItem.commission = t_marketplaceItem.commission
9724 kshitij.so 2331
            marketplaceItem.vat = t_marketplaceItem.vat
2332
            marketplaceItem.packagingCost = 15.0
9779 kshitij.so 2333
            marketplaceItem.serviceTax = t_marketplaceItem.serviceTax
9724 kshitij.so 2334
            marketplaceItem.courierCost = t_marketplaceItem.courierCost
2335
            marketplaceItem.otherCost = t_marketplaceItem.otherCost
2336
            marketplaceItem.autoIncrement = t_marketplaceItem.autoIncrement
2337
            marketplaceItem.autoDecrement = t_marketplaceItem.autoDecrement
2338
            marketplaceItem.manualFavourite = t_marketplaceItem.manualFavourite
2339
            marketplaceItem.currentSp = t_marketplaceItem.currentSp
2340
            marketplaceItem.currentTp = t_marketplaceItem.currentTp
2341
            marketplaceItem.minimumPossibleSp = t_marketplaceItem.minimumPossibleSp
2342
            marketplaceItem.minimumPossibleTp = t_marketplaceItem.minimumPossibleTp
9923 kshitij.so 2343
            marketplaceItem.maximumSellingPrice = t_marketplaceItem.maximumSellingPrice
10287 kshitij.so 2344
            marketplaceItem.pgFee = t_marketplaceItem.pgFee
11095 kshitij.so 2345
            marketplaceItem.courierCostMarketplace = t_marketplaceItem.courierCostMarketplace
9724 kshitij.so 2346
        else:
2347
            marketplaceItem.courierCost = t_marketplaceItem.courierCost
2348
            marketplaceItem.otherCost = t_marketplaceItem.otherCost
2349
            marketplaceItem.autoIncrement = t_marketplaceItem.autoIncrement
2350
            marketplaceItem.autoDecrement = t_marketplaceItem.autoDecrement
2351
            marketplaceItem.manualFavourite = t_marketplaceItem.manualFavourite
2352
            marketplaceItem.currentSp = t_marketplaceItem.currentSp
2353
            marketplaceItem.currentTp = t_marketplaceItem.currentTp
2354
            marketplaceItem.minimumPossibleSp = t_marketplaceItem.minimumPossibleSp
2355
            marketplaceItem.minimumPossibleTp = t_marketplaceItem.minimumPossibleTp
9779 kshitij.so 2356
            marketplaceItem.emiFee = t_marketplaceItem.emiFee
2357
            marketplaceItem.closingFee = t_marketplaceItem.closingFee
2358
            marketplaceItem.returnProvision = t_marketplaceItem.returnProvision
2359
            marketplaceItem.commission = t_marketplaceItem.commission
2360
            marketplaceItem.vat = t_marketplaceItem.vat
2361
            marketplaceItem.serviceTax = t_marketplaceItem.serviceTax
9923 kshitij.so 2362
            marketplaceItem.maximumSellingPrice = t_marketplaceItem.maximumSellingPrice
10287 kshitij.so 2363
            marketplaceItem.pgFee = t_marketplaceItem.pgFee
11095 kshitij.so 2364
            marketplaceItem.courierCostMarketplace = t_marketplaceItem.courierCostMarketplace
9724 kshitij.so 2365
        session.commit()
2366
        return True
2367
    except Exception as ex:
9779 kshitij.so 2368
        print "Unable to addOrupdate MarketplaceItem"
9724 kshitij.so 2369
        print ex
2370
        return False
9779 kshitij.so 2371
 
2372
def __markStatusForMarketplaceItems(snapdealItem,item):
2373
    try:
2374
        marketplaceItem = snapdealItem.marketplaceItems
2375
        markUpdatedItem = MarketPlaceItemPrice.query.filter(MarketPlaceItemPrice.item_id==snapdealItem.item_id).filter(MarketPlaceItemPrice.source==marketplaceItem.source).first()
2376
        if markUpdatedItem is None:
2377
            marketPlaceItemPrice = MarketPlaceItemPrice()
2378
            marketPlaceItemPrice.item_id = snapdealItem.item_id
2379
            marketPlaceItemPrice.source = marketplaceItem.source
2380
            marketPlaceItemPrice.lastUpdatedOn = item.updatedOn
2381
            marketPlaceItemPrice.sellingPrice = item.sellingPrice 
2382
            marketPlaceItemPrice.suppressPriceFeed = item.suppressPriceFeed
2383
            marketPlaceItemPrice.isListedOnSource = item.isListedOnSnapdeal
2384
        else:
2385
            if (markUpdatedItem.sellingPrice!=snapdealItem.sellingPrice or markUpdatedItem.suppressPriceFeed!=item.suppressPriceFeed or markUpdatedItem.isListedOnSource!=item.isListedOnSnapdeal):
2386
                markUpdatedItem.lastUpdatedOn = item.updatedOn
2387
            markUpdatedItem.sellingPrice = snapdealItem.sellingPrice
2388
            markUpdatedItem.suppressPriceFeed = item.suppressPriceFeed
2389
            markUpdatedItem.isListedOnSource = item.isListedOnSnapdeal
2390
        return True
2391
    except Exception as e:
2392
        print e
2393
        return False
9724 kshitij.so 2394
 
10097 kshitij.so 2395
def __markStatusForFlipkartItems(flipkartItem,item):
2396
    try:
2397
        marketplaceItem = flipkartItem.marketplaceItems
2398
        markUpdatedItem = MarketPlaceItemPrice.query.filter(MarketPlaceItemPrice.item_id==flipkartItem.item_id).filter(MarketPlaceItemPrice.source==marketplaceItem.source).first()
2399
        if markUpdatedItem is None:
2400
            marketPlaceItemPrice = MarketPlaceItemPrice()
2401
            marketPlaceItemPrice.item_id = flipkartItem.item_id
2402
            marketPlaceItemPrice.source = marketplaceItem.source
2403
            marketPlaceItemPrice.lastUpdatedOn = item.updatedOn
2404
            marketPlaceItemPrice.sellingPrice = marketplaceItem.currentSp 
2405
            marketPlaceItemPrice.suppressPriceFeed = item.suppressPriceFeed
2406
            marketPlaceItemPrice.isListedOnSource = item.isListedOnFlipkart
2407
        else:
2408
            if (markUpdatedItem.sellingPrice!=marketplaceItem.currentSp or markUpdatedItem.suppressPriceFeed!=item.suppressPriceFeed or markUpdatedItem.isListedOnSource!=item.isListedOnFlipkart):
2409
                markUpdatedItem.lastUpdatedOn = item.updatedOn
2410
            markUpdatedItem.sellingPrice = marketplaceItem.currentSp
2411
            markUpdatedItem.suppressPriceFeed = item.suppressPriceFeed
2412
            markUpdatedItem.isListedOnSource = item.isListedOnFlipkart
2413
        return True
2414
    except Exception as e:
2415
        print e
2416
        return False
2417
 
2418
 
9779 kshitij.so 2419
def get_costing_for_marketplace(source_id,itemId):
10097 kshitij.so 2420
    time = datetime.datetime.now()
2421
    sip = SourceItemPercentage.query.filter(SourceItemPercentage.item_id==itemId).filter(SourceItemPercentage.source==source_id).filter(SourceItemPercentage.startDate<=time).filter(SourceItemPercentage.expiryDate>=time).first()
2422
    if sip is not None:
2423
        return sip
9779 kshitij.so 2424
    else:
10097 kshitij.so 2425
        item = get_item(itemId)
2426
        scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==item.category).filter(SourceCategoryPercentage.source==source_id).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
2427
        if scp is not None:
2428
            return scp
2429
        else:
2430
            spm = SourcePercentageMaster.get_by(source=source_id)
2431
            return spm
9779 kshitij.so 2432
 
2433
def __validateSnapdealObject(snapdealItem):
2434
    if len(snapdealItem.supc)==0 or snapdealItem.supc is None or len(snapdealItem.skuAtSnapdeal)==0 or snapdealItem.skuAtSnapdeal is None or snapdealItem.sellingPrice==0 or snapdealItem.maxNlc==0:
2435
        return False
2436
    else:
2437
        return True
10097 kshitij.so 2438
 
2439
def __validateFlipkartObject(flipkartitem):
2440
    mpItem = flipkartitem.marketplaceItems
2441
    print mpItem
10116 kshitij.so 2442
    if mpItem.currentSp==0 or flipkartitem.maxNlc==0 or len(flipkartitem.flipkartSerialNumber)==0 or flipkartitem.flipkartSerialNumber is None or len(flipkartitem.skuAtFlipkart)==0 or flipkartitem.skuAtFlipkart is None:
10097 kshitij.so 2443
        return False
2444
    else:
2445
        return True
9779 kshitij.so 2446
 
2447
 
9776 vikram.rag 2448
def get_all_marketplace_items_for_priceupdate(source):
2449
    marketPlaceItemsPrices = MarketPlaceItemPrice.query.filter(MarketPlaceItemPrice.source == source).filter(MarketPlaceItemPrice.lastUpdatedOn > MarketPlaceItemPrice.lastUpdatedOnMarketplace).all()
2450
    return marketPlaceItemsPrices
9724 kshitij.so 2451
 
9816 kshitij.so 2452
def update_marketplace_priceupdate_status(skuList,timestamp,source_id):
9776 vikram.rag 2453
    for sku in skuList:
9816 kshitij.so 2454
            item = MarketPlaceItemPrice.get_by(item_id=sku,source=source_id)
9776 vikram.rag 2455
            if item is not None:
2456
                item.lastUpdatedOnMarketplace = to_py_date(timestamp)
9816 kshitij.so 2457
                mp_item = get_marketplace_details_for_item(sku,source_id)
2458
                if mp_item is not None:
2459
                    mp_item.lastCheckedTimestamp = to_py_date(timestamp)
9776 vikram.rag 2460
    session.commit()
9895 vikram.rag 2461
 
9907 vikram.rag 2462
def update_item_hold_inventory(itemHoldMap):
2463
    items = get_all_alive_items()
2464
    for item in items:
2465
        if item.holdOverride:
2466
            continue
2467
        if itemHoldMap.__contains__(item.id):
2468
            item.holdInventory = itemHoldMap[item.id]
2469
        else:
2470
            item.holdInventory = 1
2471
    session.commit()
2472
 
9895 vikram.rag 2473
def update_nlc_at_marketplaces(itemid,vendor_id,nlc):
2474
    try:
2475
        item = SnapdealItem.get_by(item_id=itemid)
2476
        if item is not None:
2477
            marketplaceitem =  MarketplaceItems.get_by(itemId=itemid,source=7)
2478
            ic = InventoryClient().get_client()
2479
            warehouse = ic.getWarehouse(item.warehouseId)
2480
            if(warehouse.vendor.id==vendor_id):
2481
                item.maxNlc = nlc
2482
                vat = (item.sellingPrice/(1+(marketplaceitem.vat/100))-(nlc/(1+(marketplaceitem.vat/100))))*(marketplaceitem.vat/100)
2483
                inHouseCost = 15 + vat + (marketplaceitem.returnProvision/100)*item.sellingPrice + marketplaceitem.otherCost
2484
                marketplaceitem.minimumPossibleTp  = nlc + inHouseCost
10287 kshitij.so 2485
                if (marketplaceitem.pgFee/100)*item.sellingPrice>=20:
11095 kshitij.so 2486
                    marketplaceitem.minimumPossibleSp = (nlc+(item.courierCostMarketplace+marketplaceitem.closingFee)*(1+(marketplaceitem.serviceTax/100))*(1+(marketplaceitem.vat/100))+(15+marketplaceitem.otherCost)*(1+(marketplaceitem.vat)/100))/(1-(marketplaceitem.commission/100+marketplaceitem.emiFee/100+marketplaceitem.pgFee/100)*(1+(marketplaceitem.serviceTax/100))*(1+(marketplaceitem.vat)/100)-(marketplaceitem.returnProvision/100)*(1+(marketplaceitem.vat)/100))
10287 kshitij.so 2487
                else:
11095 kshitij.so 2488
                    marketplaceitem.minimumPossibleSp = (nlc+(item.courierCostMarketplace+marketplaceitem.closingFee+20)*(1+(marketplaceitem.serviceTax/100))*(1+(marketplaceitem.vat/100))+(15+marketplaceitem.otherCost)*(1+(marketplaceitem.vat)/100))/(1-(marketplaceitem.commission/100+marketplaceitem.emiFee/100)*(1+(marketplaceitem.serviceTax/100))*(1+(marketplaceitem.vat)/100)-(marketplaceitem.returnProvision/100)*(1+(marketplaceitem.vat)/100))
9895 vikram.rag 2489
                session.commit()
10287 kshitij.so 2490
        flipkartitem = FlipkartItem.get_by(item_id=itemid)
2491
        if flipkartitem is not None:
2492
            ic = InventoryClient().get_client()
2493
            fmarketplaceitem =  MarketplaceItems.get_by(itemId=itemid,source=8)
2494
            warehouse = ic.getWarehouse(flipkartitem.warehouseId)
2495
            if(warehouse.vendor.id==vendor_id):
2496
                print 'Inside Flipkart maxnlc change'
2497
                flipkartitem.maxNlc = nlc
2498
                vat = (fmarketplaceitem.currentSp/(1+(fmarketplaceitem.vat/100))-(nlc/(1+(fmarketplaceitem.vat/100))))*(fmarketplaceitem.vat/100)
2499
                inHouseCost = 15 + vat + (fmarketplaceitem.returnProvision/100)*fmarketplaceitem.currentSp + fmarketplaceitem.otherCost
2500
                fmarketplaceitem.minimumPossibleTp  = nlc + inHouseCost
2501
                fmarketplaceitem.minimumPossibleSp = (nlc+(fmarketplaceitem.courierCost+fmarketplaceitem.closingFee)*(1+(fmarketplaceitem.serviceTax/100))*(1+(fmarketplaceitem.vat/100))+(15+fmarketplaceitem.otherCost)*(1+(fmarketplaceitem.vat)/100))/(1-(fmarketplaceitem.commission/100+fmarketplaceitem.emiFee/100)*(1+(fmarketplaceitem.serviceTax/100))*(1+(fmarketplaceitem.vat)/100)-(fmarketplaceitem.returnProvision/100)*(1+(fmarketplaceitem.vat)/100))
2502
                session.commit()
9895 vikram.rag 2503
    finally:
9945 vikram.rag 2504
        close_session()
2505
 
2506
def get_all_flipkart_items():
10103 kshitij.so 2507
    return session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id)).all()
10097 kshitij.so 2508
 
2509
def get_flipkart_item(itemid):
2510
    item = session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id)).filter(FlipkartItem.item_id==itemid).first()
2511
    return item
2512
 
2513
def add_or_update_flipkart_item(flipkartitem):
2514
    item = FlipkartItem.get_by(item_id=flipkartitem.item_id)
2515
    mpItem = get_marketplace_details_for_item(flipkartitem.item_id,OrderSource.FLIPKART)
2516
    t_mpItem = flipkartitem.marketplaceItems
2517
    if not __validateFlipkartObject(flipkartitem):
2518
        return False
2519
    try:
2520
        if item is not None:
2521
            itemHistory = MarketPlaceUpdateHistory()
2522
            itemHistory.item_id = flipkartitem.item_id
2523
            itemHistory.source = OrderSource.FLIPKART
2524
            itemHistory.exceptionPrice = item.exceptionPrice
2525
            itemHistory.warehouseId = item.warehouseId
2526
            itemHistory.isListedOnSource = item.isListedOnFlipkart
2527
            itemHistory.transferPrice = mpItem.currentTp
2528
            itemHistory.sellingPrice = mpItem.currentSp
2529
            itemHistory.courierCost = mpItem.courierCost
2530
            itemHistory.commission = item.commissionValue
2531
            itemHistory.serviceTax = item.serviceTaxValue
2532
            itemHistory.suppressPriceFeed = item.suppressPriceFeed
2533
            itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
2534
            itemHistory.updatedOn = item.updatedOn
2535
            itemHistory.maxNlc = item.maxNlc
2536
            itemHistory.skuAtSource = item. skuAtFlipkart
2537
            itemHistory.marketPlaceSerialNumber = item.flipkartSerialNumber
2538
            itemHistory.priceUpdatedBy = item.updatedBy
2539
            if (mpItem.currentSp!=t_mpItem.currentSp):
2540
                item.updatedBy = flipkartitem.updatedBy
2541
            item.exceptionPrice = flipkartitem.exceptionPrice
2542
            item.warehouseId = flipkartitem.warehouseId
2543
            item.isListedOnFlipkart = flipkartitem.isListedOnFlipkart
2544
            item.commissionValue = flipkartitem.commissionValue
2545
            item.serviceTaxValue = flipkartitem.serviceTaxValue
2546
            item.suppressPriceFeed =flipkartitem.suppressPriceFeed
2547
            item.suppressInventoryFeed =flipkartitem.suppressInventoryFeed
2548
            item.maxNlc = flipkartitem.maxNlc
2549
            item.skuAtFlipkart = flipkartitem.skuAtFlipkart
2550
            item.flipkartSerialNumber = flipkartitem.flipkartSerialNumber
2551
            item.updatedOn = datetime.datetime.now()
2552
            __markStatusForFlipkartItems(flipkartitem,item)
2553
            return update_marketplace_attributes_for_item(flipkartitem.marketplaceItems)
2554
        else:
2555
            item = FlipkartItem()
2556
            if flipkartitem.item_id is not None:
2557
                item.item_id = flipkartitem.item_id
2558
                item.exceptionPrice = flipkartitem.exceptionPrice
2559
                item.warehouseId = flipkartitem.warehouseId
2560
                item.isListedOnFlipkart = flipkartitem.isListedOnFlipkart
2561
                item.commissionValue = flipkartitem.commissionValue
2562
                item.serviceTaxValue = flipkartitem.serviceTaxValue
2563
                item.suppressPriceFeed =flipkartitem.suppressPriceFeed
2564
                item.suppressInventoryFeed =flipkartitem.suppressInventoryFeed 
2565
                item.maxNlc = flipkartitem.maxNlc
2566
                item.skuAtFlipkart = flipkartitem.skuAtFlipkart
2567
                item.flipkartSerialNumber = flipkartitem.flipkartSerialNumber
2568
                item.updatedOn = datetime.datetime.now()  
2569
                item.updatedBy = flipkartitem.updatedBy
2570
                __markStatusForFlipkartItems(flipkartitem,item)
2571
                return update_marketplace_attributes_for_item(flipkartitem.marketplaceItems)  
2572
    except Exception as ex:
2573
        print "Unable to addOrupdate flipkart"
2574
        print ex
2575
        return False
2576
 
2577
def get_flipkart_item_detail(itemid):
2578
    item = session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id)).filter(FlipkartItem.item_id==itemid).first()
2579
    try:
2580
        client = InventoryClient().get_client()
2581
        FlipkartInventoryItem = client.getFlipkartlInventoryForItem(itemid)
2582
        return item, FlipkartInventoryItem
2583
    except Exception as e:
2584
        print e
2585
        return item,None
2586
 
2587
def get_flipkart_items(offset,limit):
2588
    return session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id)).offset(offset).limit(limit).all()
2589
 
2590
def search_flipkart_items(search_terms,offset,limit):
2591
    query = session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id))
2592
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2593
    for search_term in search_terms:
2594
        query_clause = []
2595
        query_clause.append(Item.id.like(search_term))
2596
        query_clause.append(Item.brand.like(search_term))
2597
        query_clause.append(Item.model_name.like(search_term))
2598
        query_clause.append(Item.model_number.like(search_term))
2599
        query_clause.append(Item.color.like(search_term))
2600
        query = query.filter(or_(*query_clause))
2601
 
2602
    query = query.offset(offset)
2603
    if limit:
2604
        query = query.limit(limit)
2605
    flipkart_items = query.all()
2606
    return flipkart_items
2607
 
2608
def get_flipkart_search_result_count(search_terms):
2609
    query = session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id))
2610
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
2611
    for search_term in search_terms:
2612
        query_clause = []
2613
        query_clause.append(Item.id.like(search_term))
2614
        query_clause.append(Item.brand.like(search_term))
2615
        query_clause.append(Item.model_name.like(search_term))
2616
        query_clause.append(Item.model_number.like(search_term))
2617
        query_clause.append(Item.color.like(search_term))
2618
        query = query.filter(or_(*query_clause))
2619
    return query.count()
2620
 
2621
def get_count_for_flipkart_items():
2622
    return session.query(func.count(FlipkartItem.item_id)).scalar()
2623
 
2624
def get_all_fk_items():
2625
    return session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id)).all()
2626
 
10140 vikram.rag 2627
def get_flipkart_item_by_sku_at_flipkart(sku):
10141 vikram.rag 2628
    return session.query(FlipkartItem,Item).join((Item,FlipkartItem.item_id==Item.id)).filter(FlipkartItem.skuAtFlipkart==sku).first()
10909 vikram.rag 2629
 
11015 kshitij.so 2630
def get_marketplace_history(source,offset,itemId):
2631
    return session.query(MarketPlaceHistory).filter(MarketPlaceHistory.item_id==itemId).filter(MarketPlaceHistory.source==source).filter(or_(MarketPlaceHistory.toGroup==True,MarketPlaceHistory.toGroup==None)).order_by(desc(MarketPlaceHistory.timestamp)).limit(11).offset(offset).all()
2632
 
10909 vikram.rag 2633
def get_all_fbb_listed_items():
10927 vikram.rag 2634
    return Amazonlisted.query.filter(Amazonlisted.isFbb==True).filter(Amazonlisted.fbbListedOn==None).all()
11015 kshitij.so 2635
 
10924 vikram.rag 2636
def get_all_fbb_pricing_items():
10927 vikram.rag 2637
    return Amazonlisted.query.filter(Amazonlisted.isFbb==True).filter(Amazonlisted.suppressFbbPriceUpdate==False).filter(Amazonlisted.fbbPriceLastUpdatedOn > Amazonlisted.fbbPriceLastUpdatedOnSc).filter(Amazonlisted.fbbListedOn != None).all()
11015 kshitij.so 2638
 
2639
 
2640
def get_count_for_marketplaceHistory(source,itemId):
2641
    return len(session.query(MarketPlaceHistory).filter(MarketPlaceHistory.item_id==itemId).filter(MarketPlaceHistory.source==source).filter(or_(MarketPlaceHistory.toGroup==True,MarketPlaceHistory.toGroup==None)).all())   
2642
 
2643
def get_marketplace_history_by_date(source,startDate,endDate,offset,limit,itemId):
2644
    return session.query(MarketPlaceHistory).filter(MarketPlaceHistory.item_id==itemId).filter(MarketPlaceHistory.source==source).filter(MarketPlaceHistory.timestamp > to_py_date(startDate)).filter(MarketPlaceHistory.timestamp < to_py_date(endDate)).order_by(desc(MarketPlaceHistory.timestamp)).all()
2645
 
11531 vikram.rag 2646
def get_private_deal_details(itemid):
2647
    return PrivateDeals.get_by(item_id=itemid)
2648
 
2649
def get_private_deal_items(offset,limit):
2650
    print session.query(Item).join((PrivateDeals,Item.id==PrivateDeals.item_id)).offset(offset).limit(limit).all()
2651
    return session.query(Item).join((PrivateDeals,Item.id==PrivateDeals.item_id)).offset(offset).limit(limit).all()
2652
 
11592 amit.gupta 2653
def get_all_active_private_deals():
2654
        dealsMap = dict() 
2655
        all_active_private_deals = session.query(PrivateDeals).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate + datetime.timedelta(days=1))).all()
2656
        if all_active_private_deals is not None:
2657
            for active_private_deal in all_active_private_deals:
2658
                dealsMap[active_private_deal.item_id] = to_t_private_deal(active_private_deal)
2659
        return dealsMap 
2660
 
11531 vikram.rag 2661
def add_or_update_private_deal(privatedeal):
11606 vikram.rag 2662
    print 'Inside update private deals'
11531 vikram.rag 2663
    try:
2664
        deal =  PrivateDeals.get_by(item_id=privatedeal.item_id)
2665
        if deal is None:
2666
            deal = PrivateDeals()
2667
            deal.item_id = privatedeal.item_id
2668
            deal.dealFreebieItemId = privatedeal.dealFreebieItemId  
2669
            deal.dealPrice = privatedeal.dealPrice
11577 vikram.rag 2670
            deal.startDate =  to_py_date(privatedeal.startDate)
2671
            deal.endDate = to_py_date(privatedeal.endDate)
11566 vikram.rag 2672
            deal.dealTextOption = privatedeal.dealTextOption
11531 vikram.rag 2673
            deal.dealText = privatedeal.dealText
2674
            deal.isCod =  privatedeal.isCod
2675
            deal.rank = privatedeal.rank
11566 vikram.rag 2676
            deal.dealFreebieOption = privatedeal.dealFreebieOption
11606 vikram.rag 2677
            deal.isActive = privatedeal.isActive  
11531 vikram.rag 2678
        else:
2679
            deal.dealFreebieItemId = privatedeal.dealFreebieItemId  
2680
            deal.dealPrice = privatedeal.dealPrice
11577 vikram.rag 2681
            deal.startDate =  to_py_date(privatedeal.startDate)
2682
            deal.endDate = to_py_date(privatedeal.endDate)
11606 vikram.rag 2683
            deal.dealTextOption = privatedeal.dealTextOption
11531 vikram.rag 2684
            deal.dealText = privatedeal.dealText
2685
            deal.isCod =  privatedeal.isCod
2686
            deal.rank = privatedeal.rank
11566 vikram.rag 2687
            deal.dealFreebieOption = privatedeal.dealFreebieOption
11606 vikram.rag 2688
            deal.isActive = privatedeal.isActive
11531 vikram.rag 2689
        session.commit()
2690
        return True
2691
    except Exception as e:
11606 vikram.rag 2692
        print 'Exception in updating private deals'
11531 vikram.rag 2693
        print e
11606 vikram.rag 2694
        return False