Subversion Repositories SmartDukaan

Rev

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

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