Subversion Repositories SmartDukaan

Rev

Rev 11653 | Rev 11741 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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