Subversion Repositories SmartDukaan

Rev

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