Subversion Repositories SmartDukaan

Rev

Rev 5885 | Rev 5978 | 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
5318 rajveer 14
from shop2020.model.v1.catalog.impl.Convertors import to_t_item, to_t_source
5944 mandeep.dh 15
from shop2020.model.v1.catalog.impl.DataService import Item, ItemChangeLog, \
16
    Category, EntityIDGenerator, SimilarItems, ProductNotification, Source, \
17
    SourceItemPricing, AuthorizationLog, VoucherItemMapping
18
from shop2020.thriftpy.model.v1.catalog.ttypes import status, ItemShippingInfo, \
19
    ItemType
20
from shop2020.thriftpy.model.v1.inventory.ttypes import \
21
    InventoryServiceException
4873 mandeep.dh 22
from shop2020.utils import EmailAttachmentSender
4748 mandeep.dh 23
from shop2020.utils.EmailAttachmentSender import mail
5318 rajveer 24
from shop2020.utils.Utils import to_py_date, log_risky_flag
621 chandransh 25
from sqlalchemy import desc, asc
5944 mandeep.dh 26
from sqlalchemy.sql.expression import or_, distinct, func
3086 rajveer 27
from string import Template
4748 mandeep.dh 28
import datetime
29
import sys
5393 mandeep.dh 30
import threading
3924 rajveer 31
import urllib2
94 ashish 32
 
5047 amit.gupta 33
to_addresses = ["cnc.center@shop2020.in", "ashutosh.saxena@shop2020.in"]
34
from_user = "cnc.center@shop2020.in"
35
from_pwd = "5h0p2o2o"
5885 mandeep.dh 36
skippedItems = { 175 : [27, 2160, 2175, 2163, 2158, 7128, 26, 2154],
37
                 193 : [5839] }
5047 amit.gupta 38
 
5295 rajveer 39
def initialize(dbname='catalog', db_hostname="localhost"):
40
    DataService.initialize(dbname, db_hostname)
5336 rajveer 41
 
3849 chandransh 42
def get_all_items_by_status(status, offset=0, limit=None):
43
    query = Item.query
4539 rajveer 44
    if status is not None:
3849 chandransh 45
        query = query.filter_by(status=status)
46
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
47
    if limit:
48
        query = query.limit(limit)
49
    items = query.all()
50
    return items
51
 
52
def get_all_items(is_active, offset=0, limit=None):
103 ashish 53
    if is_active:
3849 chandransh 54
        items = get_all_items_by_status(status.ACTIVE, offset, limit)
103 ashish 55
    else:
3849 chandransh 56
        items = get_all_items_by_status(None, offset, limit)
766 rajveer 57
    return items
58
 
3849 chandransh 59
def get_item_count_by_status(use_status, status):
60
    if use_status:
61
        return Item.query.filter_by(status=status).count()
103 ashish 62
    else:
3849 chandransh 63
        return Item.query.count()
103 ashish 64
 
635 rajveer 65
def get_item(item_id):
766 rajveer 66
    item = Item.get_by(id=item_id)
67
    return item
94 ashish 68
 
635 rajveer 69
def get_items_by_catalog_id(catalog_id):
447 rajveer 70
    query = Item.query.filter_by(catalog_item_id=catalog_id)
437 rajveer 71
    try:
635 rajveer 72
        items = query.all()
4934 amit.gupta 73
        return items
1399 rajveer 74
    except Exception as ex:
75
        print ex
437 rajveer 76
        raise InventoryServiceException(109, "Item not found")
5586 phani.kuma 77
 
78
def is_valid_catalog_id(catalog_id):
79
    item = Item.query.filter_by(catalog_item_id=catalog_id).first()
80
    if item is not None:
81
        return True
82
    else:
83
        return False
84
 
576 chandransh 85
def is_active(item_id):
2983 chandransh 86
    t_item_shipping_info = ItemShippingInfo()
576 chandransh 87
    try:
635 rajveer 88
        item = get_item(item_id)
3281 chandransh 89
        t_item_shipping_info.isRisky = item.risky
5944 mandeep.dh 90
        client = InventoryClient().get_client()
91
        itemInfo = client.getItemAvailabilityAtLocation(item.id)
92
        warehouse_id = itemInfo[0]
5393 mandeep.dh 93
        if item.risky and item.status == status.ACTIVE:
5944 mandeep.dh 94
            availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item_id)
95
            if availability <= 0:
5393 mandeep.dh 96
                add_status_change_log(item, status.PAUSED_BY_RISK)
97
                item.status = status.PAUSED_BY_RISK
98
                item.status_description = "This item is currently out of stock"
99
                session.commit()
100
                __send_mail_for_oos_item(item)
101
                #This will clear cache from tomcat
102
                __clear_homepage_cache()
103
        else:
5944 mandeep.dh 104
            availability = itemInfo[4]
2983 chandransh 105
        t_item_shipping_info.isActive = (item.status == status.ACTIVE)
3281 chandransh 106
        t_item_shipping_info.quantity = availability
576 chandransh 107
    except InventoryServiceException:
2983 chandransh 108
        print "[ERROR] Unexpected error:", sys.exc_info()[0]
109
    return t_item_shipping_info
110
 
2035 rajveer 111
def get_item_status_description(itemId):
112
    item = get_item(itemId)
113
    return item.status_description
94 ashish 114
 
122 ashish 115
def update_item(item):
116
    if not item:
117
        raise InventoryServiceException(108, "Bad item in request")
118
 
119
    if not item.id:
609 chandransh 120
        raise InventoryServiceException(101, "Missing id for update")
122 ashish 121
 
2120 ankur.sing 122
    validate_item_prices(item)
2065 ankur.sing 123
 
635 rajveer 124
    ds_item = get_item(item.id)
5047 amit.gupta 125
    message = ""
122 ashish 126
    if not ds_item:
609 chandransh 127
        raise InventoryServiceException(101, "Item missing in our database")
122 ashish 128
 
963 chandransh 129
    if item.productGroup:
130
        ds_item.product_group = item.productGroup 
131
    if item.brand:
132
        ds_item.brand = item.brand
511 rajveer 133
    if item.modelNumber:
134
        ds_item.model_number = item.modelNumber
2497 ankur.sing 135
    ds_item.color = item.color
136
    ds_item.model_name = item.modelName
137
    ds_item.category = item.category
138
    ds_item.comments = item.comments
511 rajveer 139
 
2497 ankur.sing 140
    ds_item.catalog_item_id = item.catalogItemId
483 rajveer 141
 
2129 ankur.sing 142
    ds_item.mrp = item.mrp
5047 amit.gupta 143
    if ds_item.sellingPrice or item.sellingPrice:
144
        if ds_item.sellingPrice != item.sellingPrice:
145
            message += "Selling Price is changed from {0} to {1}.\n".format(ds_item.sellingPrice, item.sellingPrice)
146
 
2129 ankur.sing 147
    ds_item.sellingPrice = item.sellingPrice
2497 ankur.sing 148
 
2174 ankur.sing 149
    ds_item.weight = item.weight
2129 ankur.sing 150
 
2358 ankur.sing 151
    if ds_item.status != item.itemStatus:
2402 rajveer 152
        add_status_change_log(ds_item, item.itemStatus)
5047 amit.gupta 153
        if item.itemStatus == status.PHASED_OUT:
154
            message += "Item is phased out."
2358 ankur.sing 155
        ds_item.status = item.itemStatus
2035 rajveer 156
    if item.status_description:
157
        ds_item.status_description = item.status_description
122 ashish 158
 
511 rajveer 159
    if item.startDate:
2116 ankur.sing 160
        ds_item.startDate = to_py_date(item.startDate)
2497 ankur.sing 161
    else:
162
        ds_item.startDate = None
511 rajveer 163
    if item.retireDate:
2116 ankur.sing 164
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 165
    else:
166
        ds_item.retireDate = None
5217 amit.gupta 167
 
168
    if item.expectedArrivalDate:
169
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)
170
    else:
171
        ds_item.expectedArrivalDate = None
511 rajveer 172
 
5217 amit.gupta 173
    if item.comingSoonStartDate:
174
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
175
    else:
176
        ds_item.comingSoonStartDate = None
177
 
178
 
2497 ankur.sing 179
    ds_item.feature_id = item.featureId
180
    ds_item.feature_description = item.featureDescription
122 ashish 181
 
5047 amit.gupta 182
    if ds_item.bestDealText or item.bestDealText:
183
        if item.bestDealText != ds_item.bestDealText:
5080 amit.gupta 184
            message += "Promotion text is changed from '{0}' to '{1}'.\n".format(ds_item.bestDealText, item.bestDealText)
2129 ankur.sing 185
    ds_item.bestDealText = item.bestDealText
186
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 187
    ds_item.bestSellingRank = item.bestSellingRank
2497 ankur.sing 188
 
2065 ankur.sing 189
    ds_item.defaultForEntity = item.defaultForEntity
5047 amit.gupta 190
 
191
    if ds_item.risky or item.risky:
192
        if ds_item.risky != item.risky:
5080 amit.gupta 193
            message += "Risky flag is changed to '{0}'.\n".format(set)
5047 amit.gupta 194
 
2251 ankur.sing 195
    ds_item.risky = item.risky
3359 chandransh 196
 
5385 phani.kuma 197
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
198
    ds_item.hasItemNo = item.hasItemNo
5460 phani.kuma 199
    ds_item.clearance = item.clearance
5385 phani.kuma 200
 
3459 chandransh 201
    if item.expectedDelay is not None:
3359 chandransh 202
        ds_item.expectedDelay = item.expectedDelay
4506 phani.kuma 203
 
204
    if item.preferredVendor:
5080 amit.gupta 205
        if item.preferredVendor != ds_item.preferredVendor:
5944 mandeep.dh 206
            inventoryClient = InventoryClient().get_client()
207
            newPreferredVendorName = inventoryClient.getVendor(item.preferredVendor).name
5080 amit.gupta 208
            oldPreferredVendorName = 'None'
209
            if ds_item.preferredVendor:
5944 mandeep.dh 210
                oldPreferredVendorName = inventoryClient.getVendor(ds_item.preferredVendor).name
5408 amit.gupta 211
            message += "Preferred vendor is changed from '{0}' to '{1}'.\n".format(oldPreferredVendorName, newPreferredVendorName)        
4506 phani.kuma 212
        ds_item.preferredVendor = item.preferredVendor
5080 amit.gupta 213
 
214
    if item.isWarehousePreferenceSticky != ds_item.isWarehousePreferenceSticky:
215
        flag = "ON" if item.isWarehousePreferenceSticky else "OFF"
216
        message += "Warehouse preference sticky is {0}.\n".format(flag)
217
 
4413 anupam.sin 218
    ds_item.isWarehousePreferenceSticky = item.isWarehousePreferenceSticky
3359 chandransh 219
 
2347 ankur.sing 220
    ds_item.updatedOn = datetime.datetime.now()
2065 ankur.sing 221
 
122 ashish 222
    session.commit();
5047 amit.gupta 223
    subject = "Item '{0}' is updated in Catalog. Id is {1}".format(__get_product_name(ds_item),ds_item.id)
224
    if message:
225
        __send_mail(subject, message)
122 ashish 226
    return ds_item.id
94 ashish 227
 
103 ashish 228
def add_item(item):
229
    if not item:
122 ashish 230
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 231
    if get_item(item.id):
122 ashish 232
        raise InventoryServiceException(101, "Item already exists")
2120 ankur.sing 233
 
234
    validate_item_prices(item)
235
 
103 ashish 236
    ds_item = Item()
963 chandransh 237
    if item.productGroup:
238
        ds_item.product_group = item.productGroup
239
    if item.brand:
240
        ds_item.brand = item.brand
515 rajveer 241
    if item.modelName:
242
        ds_item.model_name = item.modelName
243
    if item.modelNumber:
244
        ds_item.model_number = item.modelNumber
609 chandransh 245
    if item.color:
246
        ds_item.color = item.color
483 rajveer 247
    if item.category:
248
        ds_item.category = item.category
249
    if item.comments:
250
        ds_item.comments = item.comments
251
 
103 ashish 252
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 253
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 254
    if item.startDate:
255
        ds_item.startDate = to_py_date(item.startDate)
256
    if item.retireDate:
257
        ds_item.retireDate = to_py_date(item.retireDate)
5217 amit.gupta 258
    if item.comingSoonStartDate:
259
        ds_item.comingSoonStartDate = to_py_date(item.comingSoonStartDate)
260
    if item.expectedArrivalDate:
261
        ds_item.expectedArrivalDate = to_py_date(item.expectedArrivalDate)    
483 rajveer 262
    if item.mrp:
263
        ds_item.mrp = item.mrp
264
    if item.sellingPrice:
265
        ds_item.sellingPrice = item.sellingPrice
122 ashish 266
    if item.weight:
267
        ds_item.weight = item.weight
268
 
269
    if item.featureId:
270
        ds_item.feature_id = item.featureId
271
    if item.featureDescription:
272
        ds_item.feature_description = item.featureDescription
273
 
2116 ankur.sing 274
 
103 ashish 275
    #check if categories present. If yes, add them to system
122 ashish 276
 
609 chandransh 277
    if item.bestDealValue:
278
        ds_item.bestDealValue = item.bestDealValue
279
    if item.bestDealText:
280
        ds_item.bestDealText = item.bestDealText
2116 ankur.sing 281
    if item.bestSellingRank:
282
        ds_item.bestSellingRank = item.bestSellingRank
283
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 284
    ds_item.risky = item.risky
609 chandransh 285
 
5385 phani.kuma 286
    ds_item.type = ItemType._VALUES_TO_NAMES[item.type]
287
    ds_item.hasItemNo = item.hasItemNo
5460 phani.kuma 288
    ds_item.clearance = item.clearance
5385 phani.kuma 289
 
3467 chandransh 290
    if item.expectedDelay is not None:
3359 chandransh 291
        ds_item.expectedDelay = item.expectedDelay
3467 chandransh 292
    else:
293
        ds_item.expectedDelay = 0
3359 chandransh 294
 
5408 amit.gupta 295
    preferredVendorName = "None"
4881 phani.kuma 296
    if item.preferredVendor:
297
        ds_item.preferredVendor = item.preferredVendor
5944 mandeep.dh 298
        inventoryClient = InventoryClient().get_client()
299
        preferredVendorName = inventoryClient.getVendor(item.preferredVendor).name        
4881 phani.kuma 300
 
5586 phani.kuma 301
    if item.catalogItemId:
302
        catalog_client = CatalogClient("catalog_service_server_host_master", "catalog_service_server_port").get_client()
303
        master_items = catalog_client.getItemsByCatalogId(item.catalogItemId)
304
        itemStatus = status.IN_PROCESS
305
        for masterItem in master_items:
306
            if masterItem.itemStatus in [status.CONTENT_COMPLETE, status.COMING_SOON, status.ACTIVE, status.PAUSED]:
307
                itemStatus = status.CONTENT_COMPLETE
308
                ds_item.category = masterItem.category
309
                break
310
        ds_item.catalog_item_id = item.catalogItemId
311
        ds_item.status = itemStatus
2116 ankur.sing 312
        ds_item.status_description = "This item is in process."
313
    else:
5586 phani.kuma 314
        # Check if a similar item already exists in our database
315
        similar_item = Item.query.filter_by(brand=item.brand, model_number=item.modelNumber, model_name=item.modelName).first()
316
        print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2}".format(item.brand, item.modelNumber, item.modelName)
317
 
318
        if similar_item is None or similar_item.catalog_item_id is None:
319
            # If there is no similar item in the database from before,
320
            # use the entity_id_generator
321
            entity_id = EntityIDGenerator.query.first()
322
            ds_item.catalog_item_id = entity_id.id + 1
323
            ds_item.status = status.IN_PROCESS
324
            ds_item.status_description = "This item is in process."
325
            entity_id.id = entity_id.id  + 1
326
            if similar_item is not None and similar_item.catalog_item_id is None:
327
                similar_item.catalog_item_id = entity_id.id
328
        else:
329
            #If a similar item already exists for a product group, brand and model_number, set it as same.
330
            ds_item.catalog_item_id = similar_item.catalog_item_id
331
            ds_item.category = similar_item.category
332
            ds_item.product_group = similar_item.product_group
333
            ds_item.status = similar_item.status
334
            ds_item.status_description = similar_item.status_description
2116 ankur.sing 335
 
103 ashish 336
    session.commit();
5052 amit.gupta 337
    subject = "New item is added. Id is {0}".format(str(ds_item.id))
5408 amit.gupta 338
    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, preferredVendorName)
5047 amit.gupta 339
    __send_mail(subject, message)
3325 chandransh 340
    return ds_item.id
341
 
103 ashish 342
def retire_item(item_id):
343
    if not item_id:
122 ashish 344
        raise InventoryServiceException(101, "bad item id")
635 rajveer 345
    item = get_item(item_id)
103 ashish 346
    if not item:
122 ashish 347
        raise InventoryServiceException(108, "item id not present")
348
    item.status = status.PHASED_OUT
349
    item.retireDate = datetime.datetime.now()
103 ashish 350
    session.commit()
122 ashish 351
 
352
#need to implement threads based solution here
103 ashish 353
def start_item_on(item_id, timestamp):
354
    if not item_id:
122 ashish 355
        raise InventoryServiceException(101, "bad item id")
635 rajveer 356
    item = get_item(item_id)
103 ashish 357
    if not item:
122 ashish 358
        raise InventoryServiceException(108, "item id not present")
103 ashish 359
 
122 ashish 360
    item.status = status.ACTIVE
361
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
362
    add_status_change_log(item, status.ACTIVE)
103 ashish 363
    session.commit()
364
 
122 ashish 365
#need to implement threads here
103 ashish 366
def retire_item_on(item_id, timestamp):
367
    if not item_id:
122 ashish 368
        raise InventoryServiceException(101, "bad item id")
635 rajveer 369
    item = get_item(item_id)
103 ashish 370
    if not item:
122 ashish 371
        raise InventoryServiceException(108, "item id not present")
103 ashish 372
 
122 ashish 373
    item.status = status.PHASED_OUT
374
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
375
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 376
    session.commit()
377
 
378
def add_status_change_log(item, new_status):
379
    item_change_log = ItemChangeLog()
380
    item_change_log.new_status = new_status
381
    item_change_log.old_status = item.status
382
    item_change_log.timestamp = datetime.datetime.now()
383
    item_change_log.item = item
384
    session.commit()
385
 
386
def change_item_status(item_id, new_status):
387
    if not item_id:
122 ashish 388
        raise InventoryServiceException(101, "bad item id")
635 rajveer 389
    item = get_item(item_id)
103 ashish 390
    if not item:
122 ashish 391
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 392
    add_status_change_log(item, new_status)
122 ashish 393
    item.status = new_status
2251 ankur.sing 394
    if item.status == status.PHASED_OUT:
395
        item.status_description = "This item has been phased out"
5047 amit.gupta 396
        __send_mail("Item '{0}' is Phased-Out. Item id is {1}".format(__get_product_name(item), item_id), "")
2251 ankur.sing 397
    elif item.status == status.DELETED:
398
        item.status_description = "This item has been deleted"
3924 rajveer 399
    elif item.status == status.PAUSED:
400
        item.status_description = "This item is currently out of stock"      
401
    elif item.status == status.PAUSED_BY_RISK:
402
        item.status_description = "This item is currently out of stock"
403
        #This will clear cache from tomcat
404
        __clear_homepage_cache()  
2251 ankur.sing 405
    elif item.status == status.ACTIVE:
406
        item.status_description = "This item is active"
5047 amit.gupta 407
        __send_mail("Item '{0}' is Active. Item id is {1}".format(__get_product_name(item), item_id), "")
2251 ankur.sing 408
    elif item.status == status.IN_PROCESS:
409
        item.status_description = "This item is in process"
410
    elif item.status == status.CONTENT_COMPLETE:
411
        item.status_description = "This item is in process"
103 ashish 412
    session.commit()
413
 
5944 mandeep.dh 414
def check_risky_item(item_id):
635 rajveer 415
    item = get_item(item_id)
2251 ankur.sing 416
    if not item.risky:
417
        return
5944 mandeep.dh 418
    client = InventoryClient().get_client()
419
    itemInfo = client.getItemAvailabilityAtLocation(item.id)    
420
    warehouse_id = itemInfo[0]
421
    availability = client.getItemAvailibilityAtWarehouse(warehouse_id, item.id)
422
    if availability <= 0:
2251 ankur.sing 423
        if item.status == status.ACTIVE:
2984 rajveer 424
            change_item_status(item.id, status.PAUSED_BY_RISK)
4797 rajveer 425
            __send_mail_for_oos_item(item)
2251 ankur.sing 426
    else:
2984 rajveer 427
        if item.status == status.PAUSED_BY_RISK:
2251 ankur.sing 428
            change_item_status(item.id, status.ACTIVE)
2368 ankur.sing 429
    session.commit()
2983 chandransh 430
 
2075 rajveer 431
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
2828 rajveer 432
    '''
433
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
434
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
435
    '''
723 chandransh 436
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 437
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 438
    current_timestamp = datetime.datetime.now()
439
    for item in items:
2828 rajveer 440
        if item.status == status.IN_PROCESS:
441
            item.status = content_complete_status
442
            item_change_log = ItemChangeLog()
443
            item_change_log.old_status = item.status
444
            item_change_log.new_status = content_complete_status
445
            item_change_log.timestamp = current_timestamp
446
            item_change_log.item = item
723 chandransh 447
 
4762 phani.kuma 448
        category_object = get_category(category)
449
        if category_object is not None:
450
            item.category = category
451
            item.product_group = category_object.display_name
2075 rajveer 452
        item.brand = brand
2081 rajveer 453
        item.model_name = modelName
454
        item.model_number = modelNumber
723 chandransh 455
        item.updatedOn = current_timestamp
456
    session.commit()
457
    return True
1294 chandransh 458
 
2404 chandransh 459
def get_child_categories(category):
460
    cm = CategoryManager()
2621 varun.gupt 461
    cat = cm.getCategory(category)
462
    return cat.children_category_ids if cat else None
2404 chandransh 463
 
626 chandransh 464
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 465
    '''
466
    Returns the Best Sellers between the start and the stop index in the given category
467
    '''
1926 rajveer 468
    query = get_best_sellers_query(category, None)
1098 chandransh 469
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 470
    return get_thrift_item_list(best_sellers)
471
 
2093 chandransh 472
def get_best_sellers_count(category=-1):
2404 chandransh 473
    '''
474
    Returns the number of best sellers in the given category
475
    '''
1926 rajveer 476
    count = get_best_sellers_query(category, None).count()
1120 rajveer 477
    if count is None:
478
        count = 0
766 rajveer 479
    return count
621 chandransh 480
 
1926 rajveer 481
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 482
    '''
483
    Returns the Best sellers for the given brand and category between the start and the stop index.
484
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
485
    '''
1926 rajveer 486
    query = get_best_sellers_query(category, brand)
1098 chandransh 487
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 488
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 489
 
1926 rajveer 490
def get_best_sellers_query(category, brand):
2404 chandransh 491
    '''
492
    Returns the query to be used for getting Best Sellers.
493
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
494
    '''
1098 chandransh 495
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 496
    if category != -1:
1970 rajveer 497
        all_categories = [category]
498
        child_categories = get_child_categories(category)
499
        if child_categories is not None:
500
            all_categories = all_categories + child_categories 
501
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 502
    if brand is not None:
503
        query = query.filter_by(brand=brand)
1098 chandransh 504
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 505
    return query
609 chandransh 506
 
1098 chandransh 507
def get_best_deals(category=-1):
2404 chandransh 508
    '''
509
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
510
    '''
511
    query = get_best_deals_query(Item, category, None)
1098 chandransh 512
    items = query.all()
609 chandransh 513
    return get_thrift_item_list(items)
514
 
1098 chandransh 515
def get_best_deals_count(category=-1):
2404 chandransh 516
    '''
517
    Returns the count of best deals in the given category.
518
    Ignores the category if it's -1.
519
    '''
520
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 521
    if count is None:
522
        count = 0
766 rajveer 523
    return count
501 rajveer 524
 
1926 rajveer 525
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 526
    '''
527
    Returns the catalog_item_ids of best deal items for the given brand and category.
528
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
529
    '''
530
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 531
    best_deal_items = query.all()[start_index:stop_index]
532
    return [item.catalog_item_id for item in best_deal_items]
533
 
2404 chandransh 534
def get_best_deals_counting_query(obj, category, brand):
535
    '''
536
    Returns the query to be used to select the best deals in the given brand and category.
537
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
538
    '''
539
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 540
    if category != -1:
1970 rajveer 541
        all_categories = [category]
542
        child_categories = get_child_categories(category)
543
        if child_categories is not None:
544
            all_categories = all_categories + child_categories 
545
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 546
    if brand is not None:
547
        query = query.filter_by(brand=brand)
2404 chandransh 548
    return query
549
 
550
def get_best_deals_query(obj, category, brand):
551
    '''
552
    Returns the query to be used to get the best deals in the given category and brand.
553
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
554
    '''
555
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 556
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
557
    return query
609 chandransh 558
 
5217 amit.gupta 559
def get_coming_soon(category=-1):
560
    '''
561
    Returns the Coming Soon items in the given category. Ignores the category if it's passed as -1.
562
    '''
563
    query = get_coming_soon_query(Item, category, None)
564
    items = query.all()
565
    return get_thrift_item_list(items)
566
 
567
def get_coming_soon_count(category=-1):
568
    '''
569
    Returns the count of coming in the given category.
570
    Ignores the category if it's -1.
571
    '''
572
    count = get_coming_soon_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
573
    if count is None:
574
        count = 0
575
    return count
576
 
577
def get_coming_soon_catalog_ids(start_index, stop_index, brand, category=-1):
578
    '''
579
    Returns the catalog_item_ids of coming soon items for the given brand and category.
580
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
581
    '''
582
    query = get_coming_soon_query(Item, category, brand)
583
    coming_soon_items = query.all()[start_index:stop_index]
584
    return [item.catalog_item_id for item in coming_soon_items]
585
 
586
def get_coming_soon_counting_query(obj, category, brand):
587
    '''
588
    Returns the query to be used to select the coming soon product in the given brand and category.
589
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
590
    '''
591
    query = session.query(obj).filter_by(status=status.COMING_SOON)
592
    if category != -1:
593
        all_categories = [category]
594
        child_categories = get_child_categories(category)
595
        if child_categories is not None:
596
            all_categories = all_categories + child_categories 
597
        query = query.filter(Item.category.in_(all_categories))
598
    if brand is not None:
599
        query = query.filter_by(brand=brand)
600
    return query
601
 
602
def get_coming_soon_query(obj, category, brand):
603
    '''
604
    Returns the query to be used to get the coming soon products in the given category and brand.
605
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
606
    '''
607
    query = get_coming_soon_counting_query(obj, category, brand)
608
    query = query.group_by(Item.catalog_item_id).order_by(asc(Item.comingSoonStartDate))
609
    return query
610
 
1098 chandransh 611
def get_latest_arrivals(limit, category=-1):
2404 chandransh 612
    '''
613
    Returns up to limit number of Latest Arrivals in the given category.
614
    '''
2975 chandransh 615
    categories = []
616
    if category != -1:
617
        categories = [category]
618
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 619
    items = query.all()[0:limit]
609 chandransh 620
    return get_thrift_item_list(items)
598 chandransh 621
 
1098 chandransh 622
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 623
    '''
624
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 625
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 626
    '''
2975 chandransh 627
    categories = []
628
    if category != -1:
629
        categories = [category]
630
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 631
    if count is None:
632
        count = 0
633
    count = min(count, limit)
766 rajveer 634
    return count
602 chandransh 635
 
2975 chandransh 636
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 637
    '''
638
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 639
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 640
    '''
2975 chandransh 641
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 642
    latest_arrivals = query.all()[start_index:stop_index]
643
    return [item.catalog_item_id for item in latest_arrivals]
644
 
2975 chandransh 645
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 646
    '''
647
    Returns the query to be used to count Latest arrivals.
3016 chandransh 648
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 649
    '''
650
    query = session.query(obj).filter_by(status=status.ACTIVE)
2975 chandransh 651
 
652
    all_categories = []
653
    for category in categories:
654
        all_categories.append(category)
1970 rajveer 655
        child_categories = get_child_categories(category)
2975 chandransh 656
        if child_categories:
657
            all_categories = all_categories + child_categories
658
    if all_categories: 
1970 rajveer 659
        query = query.filter(Item.category.in_(all_categories))
2975 chandransh 660
 
1926 rajveer 661
    if brand is not None:
662
        query = query.filter_by(brand=brand)
2404 chandransh 663
    return query
664
 
2975 chandransh 665
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 666
    '''
667
    Returns the query to be used to retrieve Latest Arrivals.
668
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
669
    '''
2975 chandransh 670
    query = get_latest_arrivals_counting_query(obj, categories, brand)
5167 rajveer 671
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate)).order_by(Item.catalog_item_id)
1098 chandransh 672
    return query
609 chandransh 673
 
674
def get_thrift_item_list(items):
1098 chandransh 675
    return [to_t_item(item) for item in items if item != None]
635 rajveer 676
 
1155 rajveer 677
def generate_new_entity_id():
678
    generator =  EntityIDGenerator.query.one()
679
    id = generator.id + 1
680
    generator.id = id
681
    session.commit()
682
    return id
683
 
635 rajveer 684
def put_category_object(object):
685
    category = Category.get_by(id=1)
686
    if category is None:
687
        category = Category()
688
    category.object = object    
689
    session.commit()
690
    return True
691
 
692
def get_category_object():
766 rajveer 693
    object = Category.get_by(id=1).object
694
    return object
695
 
1970 rajveer 696
def add_category(t_category):
697
    category = Category.get_by(id=t_category.id)
698
    if category is None:
699
        category = Category()
700
    category.id = t_category.id 
701
    category.label = t_category.label
702
    category.description = t_category.description
4762 phani.kuma 703
    category.display_name = t_category.display_name
1970 rajveer 704
    category.parent_category_id = t_category.parent_category_id 
705
    session.commit()
706
    return True
707
 
708
def get_category(id):
709
    return Category.query.filter_by(id=id).first()
710
 
711
def get_all_categories():
712
    return Category.query.all()
713
 
2120 ankur.sing 714
def validate_item_prices(item):
2129 ankur.sing 715
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
716
        return
717
    if item.mrp < item.sellingPrice:
2120 ankur.sing 718
        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))
719
        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 720
    return
2120 ankur.sing 721
 
722
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 723
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 724
        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))
725
        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)))
726
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
727
        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))
728
        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)))
729
    return
2065 ankur.sing 730
 
4725 phani.kuma 731
def check_color_valid(color):
732
    if color is not None:
733
        color = color.strip().lower()
734
        if color != '' and color != 'na' and color != 'blank' and color != '(blank)':
735
            return True
736
    return False
737
 
738
def check_similar_item(brand, model_number, model_name, color):
2129 ankur.sing 739
    query = Item.query
2428 ankur.sing 740
    query = query.filter_by(brand=brand)
741
    query = query.filter_by(model_number=model_number)
4725 phani.kuma 742
    query = query.filter_by(model_name=model_name)
743
    similar_items = query.all()
744
    item = None
745
    # Check if a similar item already exists in our database
746
    for old_item in similar_items:
747
        if old_item.color != None and old_item.color.strip().lower() == color.strip().lower():
748
            item = old_item
749
            break
750
 
751
    # 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 752
    if item is None:
4725 phani.kuma 753
        for old_item in similar_items:
754
            if not check_color_valid(old_item.color):
755
                item = old_item
756
                break
757
    i = 0
758
    color_of_similar_item = None
759
    # Check if a similar item already exists in our database to be used to get catalog_item_id
760
    for old_item in similar_items:
761
        # get a similar item already existing in our database with valid color
762
        if check_color_valid(old_item.color):
763
            similar_item = old_item
764
            color_of_similar_item = similar_item.color
765
            break
766
        i = i + 1
767
        # get a similar item already existing in our database if similar item with valid color is not found
768
        if i == len(similar_items):
769
            similar_item = old_item
770
            color_of_similar_item = similar_item.color
771
 
772
    # Check if a similar item that is obtained above is having a valid color
773
    if check_color_valid(color_of_similar_item):
774
        # 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.
775
        # 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.
776
        if item is None and not check_color_valid(color):
777
            return similar_item.id
778
 
779
    if item is None:
2116 ankur.sing 780
        return 0
781
    else:
782
        return item.id
2286 ankur.sing 783
 
784
def change_risky_flag(item_id, risky):
785
    item = get_item(item_id)
786
    if not item:
787
        raise InventoryServiceException(101, "Item missing in our database")
788
    try:
789
        log_risky_flag(item_id, risky)
790
    except:
791
        print "Not able to log risky flag change"
792
    item.risky = risky
4295 varun.gupt 793
    if not risky and item.status == status.PAUSED_BY_RISK:
2368 ankur.sing 794
        change_item_status(item.id, status.ACTIVE)
2286 ankur.sing 795
    session.commit()
5047 amit.gupta 796
    flag = "ON" if risky else "OFF"
797
    subject = "Risky flag is {0} for Item {1}.".format(flag, __get_product_name(item))
798
    __send_mail(subject,"")
2286 ankur.sing 799
 
4957 phani.kuma 800
def get_items_for_mastersheet(categoryName, brand):
801
    if not categoryName or not brand:
802
        raise InventoryServiceException(101, "Invalid category or brand in request")
803
 
4762 phani.kuma 804
    categories = ["Handsets", "Tablets", "Laptops"]
4957 phani.kuma 805
    query = Item.query.filter(Item.status != status.PHASED_OUT)
806
    if categoryName == "ALL":
807
        pass
808
    elif categoryName == "ALL Accessories":
809
        query = query.filter(~Item.product_group.in_(categories))
810
    elif categoryName == "ALL Handsets":
811
        query = query.filter(Item.product_group.in_(categories))
812
    elif categoryName == "Mobile Accessories":
813
        child_categories = get_child_categories(10011)
814
        if child_categories is not None:
815
            child_categories.append(0)
816
            query = query.filter(Item.category.in_(child_categories))
817
    elif categoryName == "Laptop Accessories":
818
        child_categories = get_child_categories(10070)
819
        if child_categories is not None:
820
            child_categories.append(0)
821
            query = query.filter(Item.category.in_(child_categories))
822
    else:
823
        query = query.filter(Item.product_group == categoryName)
824
 
825
    if brand == "ALL":
826
        pass
827
    else:
828
        query = query.filter(Item.brand == brand)
2358 ankur.sing 829
    items = query.all()
830
    return items
2116 ankur.sing 831
 
2358 ankur.sing 832
def get_risky_items():
833
    items = Item.query.filter_by(risky=True).all()
834
    return items
3008 rajveer 835
 
2809 rajveer 836
def get_similar_items_catalog_ids(start_index, stop_index, itemId):
3008 rajveer 837
    query = SimilarItems.query.filter_by(item_id=itemId).limit(stop_index-start_index)
838
    similar_items = query.all()
3289 rajveer 839
    return_list = []
840
    for similar_item in similar_items:
841
        isActive = False
842
        try:
843
            all_items = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).all()
844
        except:
845
            continue
846
        for item in all_items:
847
            isActive = isActive or item.status == status.ACTIVE
848
        if isActive:
849
            return_list.append(similar_item.catalog_item_id)
850
    return return_list
4423 phani.kuma 851
 
852
def get_all_similar_items_catalog_ids(itemId):
853
    query = SimilarItems.query.filter_by(item_id=itemId)
854
    similar_items = query.all()
855
    return_list = []
856
    for similar_item in similar_items:
857
        item_query = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).limit(1)
858
        item = item_query.one()
859
        return_list.append(item)
2809 rajveer 860
 
4423 phani.kuma 861
    return get_thrift_item_list(return_list)
862
 
863
def add_similar_item_catalog_id(itemId, catalog_item_id):
864
    if not itemId or not catalog_item_id:
865
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
866
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
867
    if not len(items_for_entity):
868
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
869
 
870
    s_items = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
871
    if not len(s_items):
872
        s_item = SimilarItems()
873
        s_item.item_id=itemId
874
        s_item.catalog_item_id=catalog_item_id
875
        session.commit()
876
        return items_for_entity[0]
877
    else:
878
        raise InventoryServiceException(101, "Already exists")
879
 
880
def delete_similar_item_catalog_id(itemId, catalog_item_id):
881
    if not itemId or not catalog_item_id:
882
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
883
 
884
    similar_item = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
885
    if len(similar_item):
886
        similar_item[0].delete()
887
    session.commit()
888
    return True
5504 phani.kuma 889
 
890
def get_all_vouchers_for_item(itemId):
891
    vouchers = VoucherItemMapping.query.filter_by(item_id=itemId).all()
892
    return vouchers
893
 
894
def get_voucher_amount(itemId, voucher_type):
895
    voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
896
    if len(voucher):
897
        return voucher[0].amount
898
    else:
5518 rajveer 899
        return 0
5504 phani.kuma 900
 
901
def add_update_voucher_for_item(catalog_item_id, voucher_type, voucher_amount):
902
    if not catalog_item_id or not voucher_type or not voucher_amount:
903
        raise InventoryServiceException(101, "Bad catalogItemId or voucherType or voucherAmount in request")
904
 
905
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
906
    if not len(items_for_entity):
907
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
908
 
909
    for item in items_for_entity:
910
        itemId = item.id
911
        voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
912
        if not len(voucher):
913
            voucher = VoucherItemMapping()
914
            voucher.item_id=itemId
915
            voucher.voucherType=voucher_type
916
            voucher.amount=voucher_amount
917
        else:
918
            voucher[0].amount=voucher_amount
919
    session.commit()
920
    return True
4423 phani.kuma 921
 
5504 phani.kuma 922
def delete_voucher_for_item(catalog_item_id, voucher_type):
923
    if not catalog_item_id or not voucher_type:
924
        raise InventoryServiceException(101, "Bad catalogItemId or voucherType in request")
925
 
926
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
927
    if not len(items_for_entity):
928
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
929
 
930
    for item in items_for_entity:
931
        itemId = item.id
932
        voucher = VoucherItemMapping.query.filter_by(item_id=itemId, voucherType=voucher_type).all()
933
        if len(voucher):
934
            voucher[0].delete()
935
    session.commit()
936
    return True
937
 
3079 rajveer 938
def add_product_notification(itemId, email):
939
    try:
3470 rajveer 940
        try:
941
            product_notification = ProductNotification.query.filter_by(item_id=itemId, email=email).one()
942
        except:
943
            product_notification = ProductNotification()
944
            product_notification.email = email
945
            product_notification.item_id = itemId
3079 rajveer 946
        product_notification.addedOn = datetime.datetime.now()
947
        session.commit()
948
        return True
949
    except:
950
        return False
3086 rajveer 951
 
952
 
953
def send_product_notifications():
954
    product_notifications = ProductNotification.query.all()
955
    for product_notification in product_notifications:
956
        item = product_notification.item
5944 mandeep.dh 957
        client = InventoryClient().get_client()
958
        availability = client.getItemAvailabilityAtLocation(item.id)[4]
5125 mandeep.dh 959
        if item.status == status.ACTIVE and (not item.risky or availability > 0):
3086 rajveer 960
            __enque_product_notification_email(product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id)
961
            product_notification.delete()
962
    session.commit()
963
    return True
964
 
965
def __get_product_name(item):
966
    product_name = item.brand + " " + item.model_name + " " + item.model_number
967
    color = item.color
968
    if color is not None and color != 'NA':
969
        product_name = product_name + " (" + color + ")"
3201 rajveer 970
    product_name = product_name.replace("  "," ")
3086 rajveer 971
    return product_name
972
 
973
 
974
def __get_product_url(item):
975
    product_url = "http://www.saholic.com/mobile-phones/" + item.brand + "-" + item.model_name + "-" + item.model_number + "-" + str(item.catalog_item_id)
976
    product_url = product_url.replace("--","-")
977
    product_url = product_url.replace(" ","")
978
    return product_url
979
 
3348 varun.gupt 980
def get_all_brands_by_category(category_id):
981
    catm = CategoryManager()
982
    child_categories = catm.getCategory(category_id).children_category_ids
983
    brands = session.query(distinct(Item.brand)).filter(Item.category.in_(child_categories)).all()
984
 
985
    return [brand[0] for brand in brands]
3086 rajveer 986
 
4957 phani.kuma 987
def get_all_brands():
988
    brands = session.query(distinct(Item.brand)).order_by(Item.brand).all()
989
 
990
    return [brand[0] for brand in brands]
991
 
3086 rajveer 992
def __enque_product_notification_email(email, product, date, url, itemId):
993
 
994
    html = """
995
        <html>
996
        <body>
997
        <div>
998
        <p>
999
            Hi,<br /><br />
1000
            The product requested by you on $date is now available on saholic.com.
1001
        </p>
1002
 
1003
        <p>    
1004
        <strong>Product: $product </strong>
1005
        </p>
1006
 
1007
        <p>
1008
        Click the link below to visit the product: 
1009
        <br/>
1010
        $url
1011
        </p>
1012
        <p>
1013
        Regards,<br/>
1014
        Saholic Customer Support Team<br/>
1015
        www.saholic.com<br/>
1016
        Email: help@saholic.com<br/>
1017
        </p>
1018
        </div>
1019
        </body>
1020
        </html>
1021
        """
1022
 
1023
    html = Template(html).substitute(dict(product=product,date=date,url=url))
3079 rajveer 1024
 
3086 rajveer 1025
    try:
1026
        helper_client = HelperClient().get_client()
5866 rajveer 1027
        helper_client.saveUserEmailForSending([email], "", "Product requested by you is available now.", html, str(itemId), "ProductNotification", [], [])
3086 rajveer 1028
    except Exception as e:
1029
        print e
1030
 
3557 rajveer 1031
def get_all_sources():
1032
    sources = Source.query.all()
1033
    return [to_t_source(source) for source in sources]
3086 rajveer 1034
 
3557 rajveer 1035
def get_item_pricing_by_source(itemId, sourceId):
1036
    item = Item.query.filter_by(id=itemId).first()
1037
    if item is None:
1038
        raise InventoryServiceException(101, "Bad Item")
1039
 
1040
    source = Source.query.filter_by(id=sourceId).first()
1041
    if source is None:
1042
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1043
 
1044
    item_pricing = SourceItemPricing.query.filter_by(source=source, item=item).first()
1045
    if item_pricing is None:
1046
        raise InventoryServiceException(101, "Pricing information not found for sourceId " + str(sourceId))
1047
    return item_pricing
1048
 
1049
def add_source_item_pricing(sourceItemPricing):
1050
    if not sourceItemPricing:
1051
        raise InventoryServiceException(108, "Bad sourceItemPricing in request")
1052
 
1053
    if not sourceItemPricing.sellingPrice:
4326 mandeep.dh 1054
        raise InventoryServiceException(101, "Selling Price is not defined for sourceId " + str(sourceItemPricing.sourceId))
3557 rajveer 1055
 
1056
    sourceId = sourceItemPricing.sourceId
1057
    itemId = sourceItemPricing.itemId
1058
 
1059
    item = Item.query.filter_by(id=itemId).first()
1060
    if item is None:
1061
        raise InventoryServiceException(101, "Bad Item")
1062
 
1063
    source = Source.query.filter_by(id=sourceId).first()
1064
    if source is None:
1065
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1066
 
3564 rajveer 1067
    ds_sourceItemPricing = SourceItemPricing.get_by(source=source, item=item)
3557 rajveer 1068
    if ds_sourceItemPricing is None:
1069
        ds_sourceItemPricing = SourceItemPricing()
1070
        ds_sourceItemPricing.source = source
1071
        ds_sourceItemPricing.item = item
1072
 
1073
    if sourceItemPricing.mrp:
1074
        ds_sourceItemPricing.mrp = sourceItemPricing.mrp
1075
    ds_sourceItemPricing.sellingPrice = sourceItemPricing.sellingPrice
1076
 
1077
    session.commit()
1078
    return
1079
 
1080
def get_all_source_pricing(itemId):
1081
    item = Item.query.filter_by(id=itemId).first()
1082
    if item is None:
1083
        raise InventoryServiceException(101, "Bad Item")
1084
    source_pricing = SourceItemPricing.query.filter_by(item=item).all()
1085
    return source_pricing
1086
 
1087
 
1088
def get_item_for_source(item_id, sourceId):
1089
    item = get_item(item_id)
1090
    if sourceId == -1:
1091
        return item
1092
    try:
1093
        sip = get_item_pricing_by_source(item_id, sourceId)
1094
        item.sellingPrice = sip.sellingPrice
1095
        if sip.mrp:
1096
            item.mrp = sip.mrp
1097
    except:
1098
        print "No source pricing"
1099
    return item
1100
 
3872 chandransh 1101
def search_items(search_terms, offset, limit):
1102
    query = Item.query
1103
 
1104
    query_clause = []
1105
 
1106
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1107
 
1108
    for search_term in search_terms:
1109
        query_clause.append(Item.brand.like(search_term))
1110
        query_clause.append(Item.model_number.like(search_term))
1111
        query_clause.append(Item.model_name.like(search_term))
1112
 
1113
    query = query.filter(or_(*query_clause))
1114
 
1115
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
1116
    if limit:
1117
        query = query.limit(limit)
1118
    items = query.all()
1119
    return items
1120
 
1121
def get_search_result_count(search_terms):
1122
    query = Item.query
1123
 
1124
    query_clause = []
1125
 
1126
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1127
 
1128
    for search_term in search_terms:
1129
        query_clause.append(Item.brand.like(search_term))
1130
        query_clause.append(Item.model_number.like(search_term))
1131
        query_clause.append(Item.model_name.like(search_term))
1132
 
1133
    query = query.filter(or_(*query_clause))
1134
 
1135
    return query.count()
1136
 
3924 rajveer 1137
def __clear_homepage_cache():
1138
    try:
1139
        # create a password manager
1140
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
1141
        # Add the username and password.
1142
        configclient = ConfigClient()
4310 rajveer 1143
        ips = configclient.get_property("production_servers_private_ips");
3924 rajveer 1144
        ips = ips.split(" ")
1145
 
1146
        for ip in ips:
4310 rajveer 1147
            try:
1148
                top_level_url = "http://" + ip + ":8080/"
1149
                password_mgr.add_password(None, top_level_url, "saholic", "shop2020")
1150
                handler = urllib2.HTTPBasicAuthHandler(password_mgr)
3924 rajveer 1151
 
4310 rajveer 1152
                opener = urllib2.build_opener(handler)
3924 rajveer 1153
 
4310 rajveer 1154
                # use the opener to fetch a URL
1155
                res = opener.open(top_level_url + "cache-admin/HomePageSnippets?_method=delete")
1156
                print "Successfully cleared home page cache" + res.read()
1157
            except:
1158
                print "Unable to clear home page cache" + res.read()
3924 rajveer 1159
    except:
1160
        print "Unable to clear cache, still should continue with other operations"
4024 chandransh 1161
 
4295 varun.gupt 1162
def get_product_notifications(start_datetime):
1163
    '''
1164
    Returns a list of Product Notification objects each representing user requests for notification
1165
    '''
1166
    query = ProductNotification.query
3924 rajveer 1167
 
4295 varun.gupt 1168
    if start_datetime:
1169
        query = query.filter(ProductNotification.addedOn > start_datetime)
1170
 
1171
    notifications = query.order_by(desc('addedOn')).all()
1172
    return notifications
1173
 
1174
def get_product_notification_request_count(start_datetime):
1175
    '''
1176
    Returns list of items and the counts of product notification requests
1177
    '''
1178
    print start_datetime
1179
    query = session.query(ProductNotification, func.count(ProductNotification.email).label('count'))
1180
 
1181
    if start_datetime:
1182
        query = query.filter(ProductNotification.addedOn > start_datetime)
1183
 
1184
    counts = query.group_by(ProductNotification.item_id).order_by(desc('count')).all()
1185
    return counts
1186
 
766 rajveer 1187
def close_session():
1188
    if session.is_active:
1189
        print "session is active. closing it."
1399 rajveer 1190
        session.close()
3376 rajveer 1191
 
1192
def is_alive():
1193
    try:
1194
        session.query(Item.id).limit(1).one()
1195
        return True
1196
    except:
1197
        return False
4332 anupam.sin 1198
 
4649 phani.kuma 1199
def add_authorization_log_for_item(itemId, username, reason):
1200
    if not itemId or not username:
1201
        raise InventoryServiceException(101, "Bad itemId or Invalid username in request")
1202
    authorize_log = AuthorizationLog()
1203
    authorize_log.item_id = itemId
1204
    authorize_log.username = username
1205
    authorize_log.reason = reason
1206
    session.commit()
4797 rajveer 1207
    return True
1208
 
1209
def __send_mail_for_oos_item(item): 
1210
    try:
4930 rajveer 1211
        EmailAttachmentSender.mail('cnc.center@shop2020.in', '5h0p2o2o', ['abhishek.mathur@shop2020.in', 'chaitnaya.vats@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)
4797 rajveer 1212
    except Exception as e:
1213
        print e
4985 mandeep.dh 1214
 
5047 amit.gupta 1215
def __send_mail(subject, message):
5080 amit.gupta 1216
    try:
1217
        thread = threading.Thread(target=partial(mail, from_user, from_pwd, to_addresses, subject, message))
1218
        thread.start()
1219
    except Exception as ex:
1220
        print ex    
5185 mandeep.dh 1221
 
5460 phani.kuma 1222
def get_clearance_sale_catalog_ids():
1223
    all_status = [status.ACTIVE, status.PAUSED, status.PAUSED_BY_RISK]
1224
    query = Item.query.filter_by(clearance=True)
1225
    query = query.filter(Item.status.in_(all_status))
1226
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate)).order_by(Item.catalog_item_id)
1227
    clearance_sales = query.all()
1228
    return [item.catalog_item_id for item in clearance_sales]