Subversion Repositories SmartDukaan

Rev

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