Subversion Repositories SmartDukaan

Rev

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