Subversion Repositories SmartDukaan

Rev

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