Subversion Repositories SmartDukaan

Rev

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