Subversion Repositories SmartDukaan

Rev

Rev 4876 | Rev 4887 | 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 *
4748 mandeep.dh 7
from pydoc import Helper
8
from shop2020.clients.HelperClient import HelperClient
9
from shop2020.clients.TransactionClient import TransactionClient
10
from shop2020.config.client.ConfigClient import ConfigClient
94 ashish 11
from shop2020.model.v1.catalog.impl import DataService
4748 mandeep.dh 12
from shop2020.model.v1.catalog.impl.CategoryManager import CategoryManager
13
from shop2020.model.v1.catalog.impl.Convertors import to_t_item, \
3557 rajveer 14
    to_t_vendor_item_pricing, to_t_source
4748 mandeep.dh 15
from shop2020.model.v1.catalog.impl.DataService import Item, Warehouse, \
16
    ItemInventoryHistory, CurrentInventorySnapshot, ItemInfo, ItemChangeLog, \
17
    Category, EntityIDGenerator, VendorItemPricing, VendorItemMapping, Vendor, \
18
    SimilarItems, ProductNotification, Source, SourceItemPricing, AuthorizationLog, \
4873 mandeep.dh 19
    MissedInventoryUpdate
4748 mandeep.dh 20
from shop2020.thriftpy.model.v1.catalog.ttypes import InventoryServiceException, \
21
    status, ItemShippingInfo
22
from shop2020.thriftpy.model.v1.order.ttypes import AlertType
4873 mandeep.dh 23
from shop2020.utils import EmailAttachmentSender
4748 mandeep.dh 24
from shop2020.utils.EmailAttachmentSender import mail
2286 ankur.sing 25
from shop2020.utils.Utils import log_entry, to_py_date, log_risky_flag
621 chandransh 26
from sqlalchemy import desc, asc
3244 chandransh 27
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
3872 chandransh 28
from sqlalchemy.sql.expression import and_, or_, distinct, func
3086 rajveer 29
from string import Template
4748 mandeep.dh 30
from urllib2 import HTTPBasicAuthHandler
31
import datetime
32
import sys
3924 rajveer 33
import urllib2
94 ashish 34
 
35
def initialize():
36
    DataService.initialize()
37
 
3849 chandransh 38
def get_all_items_by_status(status, offset=0, limit=None):
39
    query = Item.query
4539 rajveer 40
    if status is not None:
3849 chandransh 41
        query = query.filter_by(status=status)
42
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
43
    if limit:
44
        query = query.limit(limit)
45
    items = query.all()
46
    return items
47
 
48
def get_all_items(is_active, offset=0, limit=None):
103 ashish 49
    if is_active:
3849 chandransh 50
        items = get_all_items_by_status(status.ACTIVE, offset, limit)
103 ashish 51
    else:
3849 chandransh 52
        items = get_all_items_by_status(None, offset, limit)
766 rajveer 53
    return items
54
 
3849 chandransh 55
def get_item_count_by_status(use_status, status):
56
    if use_status:
57
        return Item.query.filter_by(status=status).count()
103 ashish 58
    else:
3849 chandransh 59
        return Item.query.count()
103 ashish 60
 
635 rajveer 61
def get_item(item_id):
766 rajveer 62
    item = Item.get_by(id=item_id)
63
    return item
94 ashish 64
 
635 rajveer 65
def get_items_by_catalog_id(catalog_id):
447 rajveer 66
    query = Item.query.filter_by(catalog_item_id=catalog_id)
437 rajveer 67
    try:
635 rajveer 68
        items = query.all()
69
        return get_thrift_item_list(items)
1399 rajveer 70
    except Exception as ex:
71
        print ex
437 rajveer 72
        raise InventoryServiceException(109, "Item not found")
73
 
576 chandransh 74
def is_active(item_id):
2983 chandransh 75
    t_item_shipping_info = ItemShippingInfo()
576 chandransh 76
    try:
635 rajveer 77
        item = get_item(item_id)
3281 chandransh 78
        t_item_shipping_info.isRisky = item.risky
4708 anupam.sin 79
        warehouse_ids = None
80
        if item.isWarehousePreferenceSticky :
81
            warehouse_ids = [item.preferredWarehouse]
82
        availability = __get_item_availability(item, warehouse_ids)
3281 chandransh 83
        if item.risky and availability <= 0 and item.status == status.ACTIVE:
84
            add_status_change_log(item, status.PAUSED_BY_RISK)
85
            item.status = status.PAUSED_BY_RISK
86
            item.status_description = "This item is currently out of stock"
87
            session.commit()
4797 rajveer 88
            __send_mail_for_oos_item(item)
3924 rajveer 89
            #This will clear cache from tomcat
90
            __clear_homepage_cache()
2983 chandransh 91
        t_item_shipping_info.isActive = (item.status == status.ACTIVE)
3281 chandransh 92
        t_item_shipping_info.quantity = availability
576 chandransh 93
    except InventoryServiceException:
2983 chandransh 94
        print "[ERROR] Unexpected error:", sys.exc_info()[0]
95
    return t_item_shipping_info
96
 
2035 rajveer 97
def get_item_status_description(itemId):
98
    item = get_item(itemId)
99
    return item.status_description
563 chandransh 100
 
94 ashish 101
def get_Warehouse(warehouse_id):
102
    return Warehouse.get_by(id=warehouse_id)
103
 
4332 anupam.sin 104
def get_Vendor(vendorId):
105
    return Vendor.get_by(id=vendorId)
106
 
122 ashish 107
def get_all_warehouses_by_status(status):
108
    if not status:
766 rajveer 109
        warehouses = Warehouse.query.all()
122 ashish 110
    else:
851 chandransh 111
        warehouses = Warehouse.query.filter_by(status=status).all()
112
    return warehouses
122 ashish 113
 
94 ashish 114
def get_all_warehouses_for_item(item_id):
635 rajveer 115
    item = get_item(item_id)
94 ashish 116
    if not item:
122 ashish 117
        raise InventoryServiceException(108, "Some unforeseen error while obtaining item")
118
    return item.get_all_warehouses
94 ashish 119
 
122 ashish 120
def get_all_items_for_warehouse(warehouse_id):
121
    warehouse = get_Warehouse(warehouse_id)
122
    if not warehouse:
123
        raise InventoryServiceException(108, "bad warehouse")
124
    return warehouse.all_items
125
 
94 ashish 126
def add_warehouse(warehouse):
103 ashish 127
    if not warehouse:
122 ashish 128
        raise InventoryServiceException(108, "Bad warehouse")
103 ashish 129
    if get_Warehouse(warehouse.id):
130
        #warehouse is already present.
122 ashish 131
        raise InventoryServiceException(101, "Warehouse already present")
103 ashish 132
 
94 ashish 133
    ds_warehouse = Warehouse()
134
    ds_warehouse.id = warehouse.id
135
    ds_warehouse.location = warehouse.location
122 ashish 136
    ds_warehouse.status = status.ACTIVE
103 ashish 137
    ds_warehouse.addedOn = datetime.datetime.now()
483 rajveer 138
    ds_warehouse.lastCheckedOn = datetime.datetime.now()
139
    ds_warehouse.tinNumber = warehouse.tinNumber
140
    ds_warehouse.pincode = warehouse.pincode
141
    if warehouse.vendorString:
142
        ds_warehouse.vendorString = warehouse.vendorString
94 ashish 143
    session.commit()
103 ashish 144
    return ds_warehouse.id
94 ashish 145
 
122 ashish 146
def update_item(item):
147
    if not item:
148
        raise InventoryServiceException(108, "Bad item in request")
149
 
150
    if not item.id:
609 chandransh 151
        raise InventoryServiceException(101, "Missing id for update")
122 ashish 152
 
2120 ankur.sing 153
    validate_item_prices(item)
2065 ankur.sing 154
 
635 rajveer 155
    ds_item = get_item(item.id)
122 ashish 156
 
157
    if not ds_item:
609 chandransh 158
        raise InventoryServiceException(101, "Item missing in our database")
122 ashish 159
 
963 chandransh 160
    if item.productGroup:
161
        ds_item.product_group = item.productGroup 
162
    if item.brand:
163
        ds_item.brand = item.brand
511 rajveer 164
    if item.modelNumber:
165
        ds_item.model_number = item.modelNumber
2497 ankur.sing 166
    ds_item.color = item.color
167
    ds_item.model_name = item.modelName
168
    ds_item.category = item.category
169
    ds_item.comments = item.comments
511 rajveer 170
 
2497 ankur.sing 171
    ds_item.catalog_item_id = item.catalogItemId
483 rajveer 172
 
2129 ankur.sing 173
    ds_item.mrp = item.mrp
174
    ds_item.sellingPrice = item.sellingPrice
2497 ankur.sing 175
 
2174 ankur.sing 176
    ds_item.weight = item.weight
2129 ankur.sing 177
 
2358 ankur.sing 178
    if ds_item.status != item.itemStatus:
2402 rajveer 179
        add_status_change_log(ds_item, item.itemStatus)
2358 ankur.sing 180
        ds_item.status = item.itemStatus
2035 rajveer 181
    if item.status_description:
182
        ds_item.status_description = item.status_description
122 ashish 183
 
511 rajveer 184
    if item.startDate:
2116 ankur.sing 185
        ds_item.startDate = to_py_date(item.startDate)
2497 ankur.sing 186
    else:
187
        ds_item.startDate = None
511 rajveer 188
    if item.retireDate:
2116 ankur.sing 189
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 190
    else:
191
        ds_item.retireDate = None
511 rajveer 192
 
2497 ankur.sing 193
    ds_item.feature_id = item.featureId
194
    ds_item.feature_description = item.featureDescription
122 ashish 195
 
2129 ankur.sing 196
    ds_item.bestDealText = item.bestDealText
197
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 198
    ds_item.bestSellingRank = item.bestSellingRank
2497 ankur.sing 199
 
2065 ankur.sing 200
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 201
    ds_item.risky = item.risky
3359 chandransh 202
 
3459 chandransh 203
    if item.expectedDelay is not None:
3359 chandransh 204
        ds_item.expectedDelay = item.expectedDelay
205
 
206
    if item.preferredWarehouse:
207
        ds_item.preferredWarehouse = item.preferredWarehouse
4413 anupam.sin 208
 
209
    if item.defaultWarehouse:
210
        ds_item.defaultWarehouse = item.defaultWarehouse
4506 phani.kuma 211
 
212
    if item.preferredVendor:
213
        ds_item.preferredVendor = item.preferredVendor
4413 anupam.sin 214
 
215
    ds_item.isWarehousePreferenceSticky = item.isWarehousePreferenceSticky
3359 chandransh 216
 
2347 ankur.sing 217
    ds_item.updatedOn = datetime.datetime.now()
2065 ankur.sing 218
 
122 ashish 219
    session.commit();
220
    return ds_item.id
94 ashish 221
 
103 ashish 222
def add_item(item):
223
    if not item:
122 ashish 224
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 225
    if get_item(item.id):
122 ashish 226
        raise InventoryServiceException(101, "Item already exists")
2120 ankur.sing 227
 
228
    validate_item_prices(item)
229
 
103 ashish 230
    ds_item = Item()
963 chandransh 231
    if item.productGroup:
232
        ds_item.product_group = item.productGroup
233
    if item.brand:
234
        ds_item.brand = item.brand
515 rajveer 235
    if item.modelName:
236
        ds_item.model_name = item.modelName
237
    if item.modelNumber:
238
        ds_item.model_number = item.modelNumber
609 chandransh 239
    if item.color:
240
        ds_item.color = item.color
483 rajveer 241
    if item.category:
242
        ds_item.category = item.category
243
    if item.comments:
244
        ds_item.comments = item.comments
245
 
103 ashish 246
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 247
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 248
    if item.startDate:
249
        ds_item.startDate = to_py_date(item.startDate)
250
    if item.retireDate:
251
        ds_item.retireDate = to_py_date(item.retireDate)
609 chandransh 252
 
483 rajveer 253
    if item.mrp:
254
        ds_item.mrp = item.mrp
255
    if item.sellingPrice:
256
        ds_item.sellingPrice = item.sellingPrice
122 ashish 257
    if item.weight:
258
        ds_item.weight = item.weight
259
 
260
    if item.featureId:
261
        ds_item.feature_id = item.featureId
262
    if item.featureDescription:
263
        ds_item.feature_description = item.featureDescription
264
 
103 ashish 265
    if item.otherInfo:
266
        for k,v in item.otherInfo.iteritems():
267
            info = ItemInfo()
268
            info.key = k
269
            info.value = v
270
            ds_item.iteminfo.append(info)
2116 ankur.sing 271
 
103 ashish 272
    #check if categories present. If yes, add them to system
122 ashish 273
 
609 chandransh 274
    if item.bestDealValue:
275
        ds_item.bestDealValue = item.bestDealValue
276
    if item.bestDealText:
277
        ds_item.bestDealText = item.bestDealText
2116 ankur.sing 278
    if item.bestSellingRank:
279
        ds_item.bestSellingRank = item.bestSellingRank
280
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 281
    ds_item.risky = item.risky
609 chandransh 282
 
3467 chandransh 283
    if item.expectedDelay is not None:
3359 chandransh 284
        ds_item.expectedDelay = item.expectedDelay
3467 chandransh 285
    else:
286
        ds_item.expectedDelay = 0
3359 chandransh 287
 
288
    if item.preferredWarehouse:
289
        ds_item.preferredWarehouse = item.preferredWarehouse
290
 
4881 phani.kuma 291
    if item.defaultWarehouse:
292
        ds_item.defaultWarehouse = item.defaultWarehouse
293
 
294
    if item.preferredVendor:
295
        ds_item.preferredVendor = item.preferredVendor
296
 
2116 ankur.sing 297
    # Check if a similar item already exists in our database
4725 phani.kuma 298
    similar_item = Item.query.filter_by(brand=item.brand, model_number=item.modelNumber, model_name=item.modelName).first()
299
    print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2}".format(item.brand, item.modelNumber, item.modelName)
2116 ankur.sing 300
 
301
    if similar_item is None or similar_item.catalog_item_id is None:
302
        # If there is no similar item in the database from before,
303
        # use the entity_id_generator
304
        entity_id = EntityIDGenerator.query.first()
305
        ds_item.catalog_item_id = entity_id.id + 1
306
        ds_item.status = status.IN_PROCESS
307
        ds_item.status_description = "This item is in process."
308
        entity_id.id = entity_id.id  + 1
4725 phani.kuma 309
        if similar_item is not None and similar_item.catalog_item_id is None:
310
            similar_item.catalog_item_id = entity_id.id
2116 ankur.sing 311
    else:
312
        #If a similar item already exists for a product group, brand and model_number, set it as same.
313
        ds_item.catalog_item_id = similar_item.catalog_item_id
314
        ds_item.category = similar_item.category
4762 phani.kuma 315
        ds_item.product_group = similar_item.product_group
2116 ankur.sing 316
        ds_item.status = similar_item.status
317
        ds_item.status_description = similar_item.status_description
318
 
103 ashish 319
    session.commit();
3325 chandransh 320
    return ds_item.id
321
 
322
def update_inventory_history(warehouse_id, timestamp, availability):
323
    warehouse = get_Warehouse(warehouse_id)
324
    if not warehouse:
325
        raise InventoryServiceException(107, "Warehouse? Where?")
4368 rajveer 326
    vendors = get_vendors_for_warehouse(warehouse_id)
327
    if len(vendors) > 1:
328
        raise InventoryServiceException(110, "Multiple vendors found for warehouse !")
329
    vendor = vendors[0]
3325 chandransh 330
    time = datetime.datetime.now()
331
    for item_key, quantity in availability.iteritems():
332
        try:
333
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
334
            item = vendor_item_mapping.item
335
        except:
336
            continue  
337
        try:
338
            item_inventory_history = ItemInventoryHistory()
339
            item_inventory_history.warehouse = warehouse
340
            item_inventory_history.item = item
341
            item_inventory_history.timestamp = time
342
            item_inventory_history.availibility = quantity
343
        except:
344
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
345
    session.commit()
103 ashish 346
 
483 rajveer 347
def update_inventory(warehouse_id, timestamp, availability):
348
    warehouse = get_Warehouse(warehouse_id)
349
    if not warehouse:
350
        raise InventoryServiceException(107, "Warehouse? Where?")
351
 
352
    time = datetime.datetime.now()
353
    warehouse.lastCheckedOn = time
354
    warehouse.vendorString = timestamp
4368 rajveer 355
    vendors = get_vendors_for_warehouse(warehouse_id)
356
    if len(vendors) > 1:
357
        raise InventoryServiceException(110, "Multiple vendors found for warehouse !")
358
    vendor = vendors[0]
2368 ankur.sing 359
    session.commit()
1368 chandransh 360
    for item_key, quantity in availability.iteritems():
483 rajveer 361
        try:
1368 chandransh 362
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
363
            item = vendor_item_mapping.item
494 rajveer 364
        except:
4873 mandeep.dh 365
            print 'Skipping update for ' + item_key + ' quantity ' + str(quantity) + ' warehouse id: ' + str(warehouse_id)
366
            __send_mail_for_missing_key(item_key, quantity, warehouse_id)
4748 mandeep.dh 367
            continue
494 rajveer 368
        try:
483 rajveer 369
            current_inventory_snapshot = CurrentInventorySnapshot.get_by(item=item, warehouse=warehouse)
370
            if not current_inventory_snapshot:
371
                current_inventory_snapshot = CurrentInventorySnapshot()
372
                current_inventory_snapshot.item = item
373
                current_inventory_snapshot.warehouse = warehouse
374
                current_inventory_snapshot.availibility = 0
871 chandransh 375
                current_inventory_snapshot.reserved = 0
483 rajveer 376
            # added the difference in the current inventory    
377
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
4400 rajveer 378
            try:
379
                if quantity > 0 and __get_item_reserved(item) > 0:
380
                    cl = TransactionClient().get_client()
4448 rajveer 381
                    #FIXME hardcoding for warehouse id 
382
                    cl.addAlert(AlertType.NEW_INVENTORY_ALERT, 5, "Inventory received for item " + item.brand + " " + item.model_name + " " + item.model_number + " " +  item.color)
4400 rajveer 383
            except:
384
                print "Not able to raise alert for incoming inventory" 
4822 mandeep.dh 385
            if current_inventory_snapshot.availibility < 0:
386
                __send_alert_for_negative_availability(item, current_inventory_snapshot.availibility, warehouse)
483 rajveer 387
        except:
388
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
2368 ankur.sing 389
        session.commit() 
390
        check_risky_item(item)
483 rajveer 391
 
4822 mandeep.dh 392
def __send_alert_for_negative_reserved(item, reserved, warehouse):
4873 mandeep.dh 393
    itemName = " ".join([str(item.id), str(item.brand), str(item.model_name), str(item.model_number), str(item.color)])
394
    EmailAttachmentSender.mail('cnc.center@shop2020.in', '5h0p2o2o', 'mandeep.dhir@shop2020.in', 'Negative reserved: ' + str(reserved) + ' for Item Id: ' + itemName + ' warehouse id: ' + str(warehouse.id), None)
4822 mandeep.dh 395
 
396
def __send_alert_for_negative_availability(item, availability, warehouse):
4873 mandeep.dh 397
    itemName = " ".join([str(item.id), str(item.brand), str(item.model_name), str(item.model_number), str(item.color)])
398
    EmailAttachmentSender.mail('cnc.center@shop2020.in', '5h0p2o2o', 'mandeep.dhir@shop2020.in', 'Negative availability ' + str(availability) + ' for Item id: ' + itemName + ' warehouse id: ' + str(warehouse.id), None)
4822 mandeep.dh 399
 
4873 mandeep.dh 400
def __send_mail_for_missing_key(item_key, quantity, warehouse_id):
401
    if not MissedInventoryUpdate.get_by(itemKey = item_key, isIgnored = 1):
402
        # One email per product key mismatch
403
        if not MissedInventoryUpdate.get_by(itemKey = item_key):
404
            EmailAttachmentSender.mail('cnc.center@shop2020.in', '5h0p2o2o', ['mandeep.dhir@shop2020.in', 'chaitnaya.vats@shop2020.in'], 'Skipped inventory update for ' + item_key + ' quantity ' + str(quantity) + ' warehouse id: ' + str(warehouse_id), None)
405
        missedInventoryUpdate = MissedInventoryUpdate()
406
        missedInventoryUpdate.itemKey = item_key
407
        missedInventoryUpdate.quantity = quantity
408
        missedInventoryUpdate.isIgnored = 0
409
        missedInventoryUpdate.timestamp = datetime.datetime.now()
410
        missedInventoryUpdate.warehouseId = warehouse_id
4748 mandeep.dh 411
        session.commit()
412
 
4320 rajveer 413
def add_inventory(itemId, warehouseId, quantity):
414
    current_inventory_snapshot = CurrentInventorySnapshot.get_by(item_id=itemId, warehouse_id=warehouseId)
415
    if not current_inventory_snapshot:
416
        current_inventory_snapshot = CurrentInventorySnapshot()
417
        current_inventory_snapshot.item_id = itemId
418
        current_inventory_snapshot.warehouse_id = warehouseId
419
        current_inventory_snapshot.availibility = 0
420
        current_inventory_snapshot.reserved = 0
421
    # added the difference in the current inventory    
422
    current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
4813 rajveer 423
    session.commit()
4822 mandeep.dh 424
    if current_inventory_snapshot.availibility < 0:
425
        __send_alert_for_negative_availability(get_item(itemId), current_inventory_snapshot.availibility, get_Warehouse(warehouseId))
4813 rajveer 426
    check_risky_item(get_item(itemId)) 
4320 rajveer 427
 
4431 phani.kuma 428
'''
94 ashish 429
def get_item_inventoy(item_id):
430
 
431
    inventory = Item.get_by(id=item_id).currentInventory
432
    if not inventory:
122 ashish 433
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
94 ashish 434
    return inventory
4431 phani.kuma 435
'''
94 ashish 436
 
635 rajveer 437
def get_item_inventory_by_item_id(item_id):
438
    inventory = Item.get_by(id=item_id).currentInventory
379 ashish 439
    if not inventory:
440
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
441
    return inventory
442
 
103 ashish 443
 
444
def retire_warehouse(warehouse_id):
445
    if not warehouse_id:
122 ashish 446
        raise InventoryServiceException(101, "Bad warehouse id")
103 ashish 447
    warehouse = get_Warehouse(warehouse_id)
448
    if not warehouse:
122 ashish 449
        raise InventoryServiceException(108, "warehouse id not present")
450
    warehouse.status = status.DELETED;
103 ashish 451
    session.commit()
452
 
453
def retire_item(item_id):
454
    if not item_id:
122 ashish 455
        raise InventoryServiceException(101, "bad item id")
635 rajveer 456
    item = get_item(item_id)
103 ashish 457
    if not item:
122 ashish 458
        raise InventoryServiceException(108, "item id not present")
459
    item.status = status.PHASED_OUT
460
    item.retireDate = datetime.datetime.now()
103 ashish 461
    session.commit()
122 ashish 462
 
463
#need to implement threads based solution here
103 ashish 464
def start_item_on(item_id, timestamp):
465
    if not item_id:
122 ashish 466
        raise InventoryServiceException(101, "bad item id")
635 rajveer 467
    item = get_item(item_id)
103 ashish 468
    if not item:
122 ashish 469
        raise InventoryServiceException(108, "item id not present")
103 ashish 470
 
122 ashish 471
    item.status = status.ACTIVE
472
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
473
    add_status_change_log(item, status.ACTIVE)
103 ashish 474
    session.commit()
475
 
122 ashish 476
#need to implement threads here
103 ashish 477
def retire_item_on(item_id, timestamp):
478
    if not item_id:
122 ashish 479
        raise InventoryServiceException(101, "bad item id")
635 rajveer 480
    item = get_item(item_id)
103 ashish 481
    if not item:
122 ashish 482
        raise InventoryServiceException(108, "item id not present")
103 ashish 483
 
122 ashish 484
    item.status = status.PHASED_OUT
485
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
486
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 487
    session.commit()
488
 
489
def add_status_change_log(item, new_status):
490
    item_change_log = ItemChangeLog()
491
    item_change_log.new_status = new_status
492
    item_change_log.old_status = item.status
493
    item_change_log.timestamp = datetime.datetime.now()
494
    item_change_log.item = item
495
    session.commit()
496
 
497
def change_item_status(item_id, new_status):
498
    if not item_id:
122 ashish 499
        raise InventoryServiceException(101, "bad item id")
635 rajveer 500
    item = get_item(item_id)
103 ashish 501
    if not item:
122 ashish 502
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 503
    add_status_change_log(item, new_status)
122 ashish 504
    item.status = new_status
2251 ankur.sing 505
    if item.status == status.PHASED_OUT:
506
        item.status_description = "This item has been phased out"
507
    elif item.status == status.DELETED:
508
        item.status_description = "This item has been deleted"
3924 rajveer 509
    elif item.status == status.PAUSED:
510
        item.status_description = "This item is currently out of stock"      
511
    elif item.status == status.PAUSED_BY_RISK:
512
        item.status_description = "This item is currently out of stock"
513
        #This will clear cache from tomcat
514
        __clear_homepage_cache()  
2251 ankur.sing 515
    elif item.status == status.ACTIVE:
516
        item.status_description = "This item is active"
517
    elif item.status == status.IN_PROCESS:
518
        item.status_description = "This item is in process"
519
    elif item.status == status.CONTENT_COMPLETE:
520
        item.status_description = "This item is in process"
103 ashish 521
    session.commit()
522
 
523
def get_item_availability_for_warehouse(warehouse_id, item_id):
524
    if not warehouse_id:
122 ashish 525
        raise InventoryServiceException(101, "bad warehouse_id")
103 ashish 526
    if not item_id:
122 ashish 527
        raise InventoryServiceException(101, "bad item_id")
103 ashish 528
 
529
    warehouse = get_Warehouse(warehouse_id)
530
    if not warehouse:
122 ashish 531
        raise InventoryServiceException(108, "warehouse does not exist")
635 rajveer 532
    item = get_item(item_id)
504 rajveer 533
 
103 ashish 534
    if not item:
766 rajveer 535
        raise InventoryServiceException(108, "item does not exist")
122 ashish 536
 
494 rajveer 537
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id)
504 rajveer 538
    query = query.filter_by(item_id = item.id)
494 rajveer 539
    try:
540
        current_inventory_snapshot = query.one()
871 chandransh 541
        return current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
494 rajveer 542
    except:
543
        return 0
544
    """
545
    current_inventory_snapshot = CurrentInventorySnapshot.query.filter(CurrentInventorySnapshot.warehouse_id == warehouse_id, CurrentInventorySnapshot.item_id == item_id).one()
103 ashish 546
    if not current_inventory_snapshot:
547
        return 0
548
    else:
549
        return current_inventory_snapshot.availibility
494 rajveer 550
    """
643 chandransh 551
 
2368 ankur.sing 552
def check_risky_item(item):
2251 ankur.sing 553
    if not item.risky:
554
        return
4813 rajveer 555
    warehouse_ids = None
556
    if item.isWarehousePreferenceSticky :
557
        warehouse_ids = [item.preferredWarehouse]
558
    availability = __get_item_availability(item, warehouse_ids)
2983 chandransh 559
    if availability <= 0:
2251 ankur.sing 560
        if item.status == status.ACTIVE:
2984 rajveer 561
            change_item_status(item.id, status.PAUSED_BY_RISK)
4797 rajveer 562
            __send_mail_for_oos_item(item)
2251 ankur.sing 563
    else:
2984 rajveer 564
        if item.status == status.PAUSED_BY_RISK:
2251 ankur.sing 565
            change_item_status(item.id, status.ACTIVE)
2368 ankur.sing 566
    session.commit()
2251 ankur.sing 567
 
4406 anupam.sin 568
'''
569
This method returns quantity of a particular item across all warehouses whose ids is provided
570
if warehouse_ids is null it checks for inventory in all warehouses.
571
'''
572
def __get_item_availability(item, warehouse_ids):
573
    if warehouse_ids is None:
574
        all_inventory = CurrentInventorySnapshot.query.filter_by(item = item).all()
575
        availability = 0
576
        reserved = 0
577
        for currInv in all_inventory:
578
            availability = availability + currInv.availibility
579
            reserved = reserved + currInv.reserved
580
        return availability - reserved
581
    else:
582
        total_availability = 0
583
        for warehouse_id in warehouse_ids:
584
            try:
585
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item.id).one()
586
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
587
            except Exception as e:
588
                print e
589
                availability = 0    
590
            total_availability = total_availability + availability
591
        return total_availability 
4400 rajveer 592
 
593
def __get_item_reserved(item):
594
    all_inventory = CurrentInventorySnapshot.query.filter_by(item = item).all()
595
    reserved = 0
596
    for currInv in all_inventory:
597
        reserved = reserved + currInv.reserved
598
    return reserved
2983 chandransh 599
 
871 chandransh 600
def reserve_item_in_warehouse(item_id, warehouse_id, quantity):    
601
    if not warehouse_id:
602
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 603
    item = get_item(item_id)
604
    if not item:
871 chandransh 605
        raise InventoryServiceException(101, "bad item_id")
606
 
607
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
608
    try:
609
        current_inventory_snapshot = query.one()
610
    except:
4103 chandransh 611
        current_inventory_snapshot = CurrentInventorySnapshot()
612
        current_inventory_snapshot.warehouse_id = warehouse_id
613
        current_inventory_snapshot.item_id = item_id
614
        current_inventory_snapshot.availibility = 0
615
        current_inventory_snapshot.reserved = 0
616
 
617
    current_inventory_snapshot.reserved = current_inventory_snapshot.reserved + quantity
618
    session.commit()
619
    check_risky_item(item)
620
    return True
871 chandransh 621
 
622
def reduce_reservation_count(item_id, warehouse_id, quantity):
623
    if not warehouse_id:
624
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 625
    item = get_item(item_id)
626
    if not item:
871 chandransh 627
        raise InventoryServiceException(101, "bad item_id")
628
 
629
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
630
    try:
631
        current_inventory_snapshot = query.one()
632
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved - quantity
4318 rajveer 633
        ##FIXME In case of our own warehouse reduce availability also
634
        if warehouse_id == 7:
4335 rajveer 635
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility - quantity
871 chandransh 636
        session.commit()
2368 ankur.sing 637
        check_risky_item(item)
4822 mandeep.dh 638
        if current_inventory_snapshot.reserved < 0:
639
            __send_alert_for_negative_reserved(get_item(item_id), current_inventory_snapshot.reserved, get_Warehouse(warehouse_id))
871 chandransh 640
        return True
641
    except:
642
        print "Unexpected error:", sys.exc_info()[0]
643
        return False
644
 
2075 rajveer 645
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
2828 rajveer 646
    '''
647
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
648
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
649
    '''
723 chandransh 650
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 651
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 652
    current_timestamp = datetime.datetime.now()
653
    for item in items:
2828 rajveer 654
        if item.status == status.IN_PROCESS:
655
            item.status = content_complete_status
656
            item_change_log = ItemChangeLog()
657
            item_change_log.old_status = item.status
658
            item_change_log.new_status = content_complete_status
659
            item_change_log.timestamp = current_timestamp
660
            item_change_log.item = item
723 chandransh 661
 
4762 phani.kuma 662
        category_object = get_category(category)
663
        if category_object is not None:
664
            item.category = category
665
            item.product_group = category_object.display_name
2075 rajveer 666
        item.brand = brand
2081 rajveer 667
        item.model_name = modelName
668
        item.model_number = modelNumber
723 chandransh 669
        item.updatedOn = current_timestamp
670
    session.commit()
671
    return True
1294 chandransh 672
 
643 chandransh 673
def get_item_availability_for_location(warehouse_loc, item_id):
3355 chandransh 674
    """
675
    Determines the warehouse that should be used to fulfil an order for the given item.
4406 anupam.sin 676
    It first checks whether the preferred warehouse for that item is set or not. If set 
677
    and preference is sticky then that warehouse is used for fulfilment.
678
    If preference is not sticky then we see if item is available in the preferred WH,
679
    in which case that warehouse is used otherwise we use that warehouse which has the max
680
    availability. And if there is no inventory for that item in any warehouses then we use
681
    default warehouse.
682
    If preference is not set in that case we just find the warehouse with max availability
683
    and in case of zero inventory we use default warehouse
3355 chandransh 684
 
685
    Returns an ordered list of size 4 with following elements in the given order:
686
    1. Logistics location of the warehouse which was finally picked up to ship the order.
687
    2. Id of the warehouse which was finally picked up.
688
    3. Inventory size in the selected warehouse.
689
    4. Expected delay added by the category manager.
690
 
691
    Parameters:
692
     - warehouse_loc
693
     - item_id
694
    """
643 chandransh 695
    if warehouse_loc is None:
696
        raise InventoryServiceException(101, "Bad Warehouse Location")
697
    if not item_id:
1416 chandransh 698
        raise InventoryServiceException(101, "Bad Item id")
643 chandransh 699
 
1416 chandransh 700
    item = Item.get_by(id=item_id)
4406 anupam.sin 701
    logisticsLocation = warehouse_loc
702
    warehouses = Warehouse.query.filter_by(logisticsLocation=logisticsLocation).all()
643 chandransh 703
    warehouse_ids = [warehouse.id for warehouse in warehouses]
704
    warehouse_retid = -1
4406 anupam.sin 705
 
3503 chandransh 706
    total_availability = 0
4406 anupam.sin 707
    '''
708
    If warehouse preference is set and it is sticky then we should fulfil this order from this warehouse only.
709
    But we still need to calculate total availability across warehouses.
710
    '''
711
    if (item.isWarehousePreferenceSticky and item.preferredWarehouse is not None) :
712
        warehouse_retid = item.preferredWarehouse
713
        warehouse = Warehouse.get_by(id=warehouse_retid)
714
        logisticsLocation = warehouse.logisticsLocation
4476 anupam.sin 715
        total_availability = __get_item_availability(item, [warehouse_retid])
4406 anupam.sin 716
 
717
    #If preference is not sticky then this order should be fulfilled from preferred WH if inventory available
718
    #otherwise we should check for its availability elsewhere and fulfil this order from there, but if it is not available anywhere
719
    #then we should fulfil this order from its default warehouse.
720
 
721
    elif (not item.isWarehousePreferenceSticky and item.preferredWarehouse is not None) :
785 rajveer 722
        try:
4406 anupam.sin 723
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = item.preferredWarehouse, item_id = item_id).one()
871 chandransh 724
            availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
4317 varun.gupt 725
        except Exception as e:
726
            print e
785 rajveer 727
            availability = 0    
4406 anupam.sin 728
        if availability > 0:
729
            warehouse_retid = item.preferredWarehouse
4476 anupam.sin 730
            total_availability = availability
4406 anupam.sin 731
        else :
732
            [logisticsLocation, warehouse_retid, total_availability] = \
733
                        __get_warehouse_with_max_availability(warehouse_loc = warehouse_loc, \
734
                                                            warehouse_ids = warehouse_ids, item = item)
735
 
736
    else :
737
        [logisticsLocation, warehouse_retid, total_availability] = \
738
                        __get_warehouse_with_max_availability(warehouse_loc = warehouse_loc, \
739
                                                            warehouse_ids = warehouse_ids, item = item)
2341 chandransh 740
 
4406 anupam.sin 741
    if item.expectedDelay is None:
742
        print 'expectedDelay field for this item was Null. Resetting it to 0'
743
        item.expectedDelay = 0
744
 
745
    ## FIXME Assign warehouse 5 (9D2) for all the hotspot products.
746
    #if warehouse_retid in [warehouse.id for warehouse in get_warehouses_for_vendor(1)]:
4433 anupam.sin 747
    if int(warehouse_retid) in [1,2,3,4,5]:
4406 anupam.sin 748
        warehouse_retid = 5
749
        warehouse = Warehouse.get_by(id=warehouse_retid)
750
        logisticsLocation = warehouse.logisticsLocation  
751
 
752
    return [logisticsLocation, int(warehouse_retid), total_availability, int(item.expectedDelay)]
753
 
754
def __get_warehouse_with_max_availability(warehouse_loc, warehouse_ids, item):
755
 
756
    warehouse_retid = -1
757
    max_availability = 0
758
    total_availability = 0
759
 
760
    for warehouse_id in warehouse_ids:
761
            try:
762
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item.id).one()
763
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
764
            except Exception as e:
765
                print e
766
                availability = 0    
767
            if availability > max_availability:
768
                warehouse_retid = warehouse_id
769
                max_availability = availability
770
            total_availability = total_availability + availability
771
 
772
    #If no warehouse could be found, use the default warehouse for this item
643 chandransh 773
    if warehouse_retid == -1:
759 chandransh 774
        # This is the case when all warehouses have exhausted their
775
        # inventory of this item or no warehouse is available in this
776
        # location.
4406 anupam.sin 777
        warehouse_retid = int(item.defaultWarehouse)
2344 chandransh 778
        warehouse = Warehouse.get_by(id=warehouse_retid)
4406 anupam.sin 779
        warehouse_loc = warehouse.logisticsLocation
2341 chandransh 780
        try:
4406 anupam.sin 781
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_retid, item_id = item.id).one()
3503 chandransh 782
            max_availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
4317 varun.gupt 783
        except Exception as e:
784
            print e
3503 chandransh 785
            max_availability = 0
786
        total_availability = max_availability
643 chandransh 787
 
4406 anupam.sin 788
    return [warehouse_loc, warehouse_retid, total_availability]
789
'''    
790
def calculate_total_availability(warehouse_ids, item_id):
791
    total_availability = 0
792
    for warehouse_id in warehouse_ids:
793
            try:
794
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id).one()
795
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
796
            except Exception as e:
797
                print e
798
                availability = 0    
799
            total_availability = total_availability + availability
800
    return total_availability
801
'''
2341 chandransh 802
 
122 ashish 803
def get_warehouses_for_item(item_id):
643 chandransh 804
 
122 ashish 805
    if not item_id:
806
        raise InventoryServiceException(101, "bad item_id")
635 rajveer 807
    item = get_item(item_id)
122 ashish 808
 
809
    if not item:
810
        raise InventoryServiceException(101, "bad item")
811
 
483 rajveer 812
    warehouses = item.currentInventory.warehouse
501 rajveer 813
    return warehouses
814
 
2404 chandransh 815
def get_child_categories(category):
816
    cm = CategoryManager()
2621 varun.gupt 817
    cat = cm.getCategory(category)
818
    return cat.children_category_ids if cat else None
2404 chandransh 819
 
626 chandransh 820
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 821
    '''
822
    Returns the Best Sellers between the start and the stop index in the given category
823
    '''
1926 rajveer 824
    query = get_best_sellers_query(category, None)
1098 chandransh 825
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 826
    return get_thrift_item_list(best_sellers)
827
 
2093 chandransh 828
def get_best_sellers_count(category=-1):
2404 chandransh 829
    '''
830
    Returns the number of best sellers in the given category
831
    '''
1926 rajveer 832
    count = get_best_sellers_query(category, None).count()
1120 rajveer 833
    if count is None:
834
        count = 0
766 rajveer 835
    return count
621 chandransh 836
 
1926 rajveer 837
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 838
    '''
839
    Returns the Best sellers for the given brand and category between the start and the stop index.
840
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
841
    '''
1926 rajveer 842
    query = get_best_sellers_query(category, brand)
1098 chandransh 843
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 844
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 845
 
1926 rajveer 846
def get_best_sellers_query(category, brand):
2404 chandransh 847
    '''
848
    Returns the query to be used for getting Best Sellers.
849
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
850
    '''
1098 chandransh 851
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 852
    if category != -1:
1970 rajveer 853
        all_categories = [category]
854
        child_categories = get_child_categories(category)
855
        if child_categories is not None:
856
            all_categories = all_categories + child_categories 
857
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 858
    if brand is not None:
859
        query = query.filter_by(brand=brand)
1098 chandransh 860
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 861
    return query
609 chandransh 862
 
1098 chandransh 863
def get_best_deals(category=-1):
2404 chandransh 864
    '''
865
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
866
    '''
867
    query = get_best_deals_query(Item, category, None)
1098 chandransh 868
    items = query.all()
609 chandransh 869
    return get_thrift_item_list(items)
870
 
1098 chandransh 871
def get_best_deals_count(category=-1):
2404 chandransh 872
    '''
873
    Returns the count of best deals in the given category.
874
    Ignores the category if it's -1.
875
    '''
876
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 877
    if count is None:
878
        count = 0
766 rajveer 879
    return count
501 rajveer 880
 
1926 rajveer 881
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 882
    '''
883
    Returns the catalog_item_ids of best deal items for the given brand and category.
884
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
885
    '''
886
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 887
    best_deal_items = query.all()[start_index:stop_index]
888
    return [item.catalog_item_id for item in best_deal_items]
889
 
2404 chandransh 890
def get_best_deals_counting_query(obj, category, brand):
891
    '''
892
    Returns the query to be used to select the best deals in the given brand and category.
893
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
894
    '''
895
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 896
    if category != -1:
1970 rajveer 897
        all_categories = [category]
898
        child_categories = get_child_categories(category)
899
        if child_categories is not None:
900
            all_categories = all_categories + child_categories 
901
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 902
    if brand is not None:
903
        query = query.filter_by(brand=brand)
2404 chandransh 904
    return query
905
 
906
def get_best_deals_query(obj, category, brand):
907
    '''
908
    Returns the query to be used to get the best deals in the given category and brand.
909
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
910
    '''
911
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 912
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
913
    return query
609 chandransh 914
 
1098 chandransh 915
def get_latest_arrivals(limit, category=-1):
2404 chandransh 916
    '''
917
    Returns up to limit number of Latest Arrivals in the given category.
918
    '''
2975 chandransh 919
    categories = []
920
    if category != -1:
921
        categories = [category]
922
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 923
    items = query.all()[0:limit]
609 chandransh 924
    return get_thrift_item_list(items)
598 chandransh 925
 
1098 chandransh 926
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 927
    '''
928
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 929
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 930
    '''
2975 chandransh 931
    categories = []
932
    if category != -1:
933
        categories = [category]
934
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 935
    if count is None:
936
        count = 0
937
    count = min(count, limit)
766 rajveer 938
    return count
602 chandransh 939
 
2975 chandransh 940
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 941
    '''
942
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 943
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 944
    '''
2975 chandransh 945
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 946
    latest_arrivals = query.all()[start_index:stop_index]
947
    return [item.catalog_item_id for item in latest_arrivals]
948
 
2975 chandransh 949
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 950
    '''
951
    Returns the query to be used to count Latest arrivals.
3016 chandransh 952
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 953
    '''
954
    query = session.query(obj).filter_by(status=status.ACTIVE)
2975 chandransh 955
 
956
    all_categories = []
957
    for category in categories:
958
        all_categories.append(category)
1970 rajveer 959
        child_categories = get_child_categories(category)
2975 chandransh 960
        if child_categories:
961
            all_categories = all_categories + child_categories
962
    if all_categories: 
1970 rajveer 963
        query = query.filter(Item.category.in_(all_categories))
2975 chandransh 964
 
1926 rajveer 965
    if brand is not None:
966
        query = query.filter_by(brand=brand)
2404 chandransh 967
    return query
968
 
2975 chandransh 969
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 970
    '''
971
    Returns the query to be used to retrieve Latest Arrivals.
972
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
973
    '''
2975 chandransh 974
    query = get_latest_arrivals_counting_query(obj, categories, brand)
1098 chandransh 975
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
976
    return query
609 chandransh 977
 
978
def get_thrift_item_list(items):
1098 chandransh 979
    return [to_t_item(item) for item in items if item != None]
635 rajveer 980
 
1155 rajveer 981
def generate_new_entity_id():
982
    generator =  EntityIDGenerator.query.one()
983
    id = generator.id + 1
984
    generator.id = id
985
    session.commit()
986
    return id
987
 
635 rajveer 988
def put_category_object(object):
989
    category = Category.get_by(id=1)
990
    if category is None:
991
        category = Category()
992
    category.object = object    
993
    session.commit()
994
    return True
995
 
996
def get_category_object():
766 rajveer 997
    object = Category.get_by(id=1).object
998
    return object
999
 
4283 anupam.sin 1000
def get_item_pricing(item_id, vendorId):
1341 chandransh 1001
    item = Item.query.filter_by(id=item_id).first()
1002
    if item is None:
1003
        raise InventoryServiceException(101, "Bad Item")
4307 anupam.sin 1004
    '''
1005
    if vendor id is -1 then we calculate an average transfer price to be populated
1006
    at the time of order creation. This will be later updated with actual transfer price
1007
    at the time of billing.
1008
    '''
1009
    if(vendorId == -1):
4543 anupam.sin 1010
        total = 0
4307 anupam.sin 1011
        try:
4858 anupam.sin 1012
            if item.preferredWarehouse is not None:
1013
                warehouse = Warehouse.query.filter_by(id=item.preferredWarehouse).first()
1014
                vendors = warehouse.vendors
1015
                item_pricings = []
1016
                for vendor in vendors :
1017
                    item_pricing = VendorItemPricing.query.filter_by(item=item, vendor=vendor).first()
1018
                    if item_pricing :
1019
                        item_pricings.append(item_pricing)
1020
            else :
1021
                item_pricings = VendorItemPricing.query.filter_by(item=item).all()
4315 anupam.sin 1022
            if item_pricings:
4307 anupam.sin 1023
                for item_pricing in item_pricings:
4543 anupam.sin 1024
                    total += item_pricing.transfer_price
4315 anupam.sin 1025
                avg = total / len(item_pricings)
1026
                item_pricing.transfer_price = avg
4543 anupam.sin 1027
            else:
1028
                item_pricing = VendorItemPricing()
1029
                item_pricing.transfer_price = item.sellingPrice
1030
                vendor = Vendor()
1031
                vendor.id = vendorId
1032
                item_pricing.vendor = vendor
1033
                item_pricing.item = item
1034
 
1035
            return item_pricing
4307 anupam.sin 1036
        except:
1037
            raise InventoryServiceException(101, "Item pricing not found ")
4283 anupam.sin 1038
    vendor = Vendor.get_by(id=vendorId)    
1341 chandransh 1039
    try:
1040
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 1041
        return item_pricing
3244 chandransh 1042
    except MultipleResultsFound:
1341 chandransh 1043
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
3244 chandransh 1044
    except NoResultFound:
1341 chandransh 1045
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
1046
 
1970 rajveer 1047
def add_category(t_category):
1048
    category = Category.get_by(id=t_category.id)
1049
    if category is None:
1050
        category = Category()
1051
    category.id = t_category.id 
1052
    category.label = t_category.label
1053
    category.description = t_category.description
4762 phani.kuma 1054
    category.display_name = t_category.display_name
1970 rajveer 1055
    category.parent_category_id = t_category.parent_category_id 
1056
    session.commit()
1057
    return True
1058
 
1059
def get_category(id):
1060
    return Category.query.filter_by(id=id).first()
1061
 
1062
def get_all_categories():
1063
    return Category.query.all()
1064
 
1991 ankur.sing 1065
 
1066
def get_all_item_pricing(item_id):
1067
    item = Item.query.filter_by(id=item_id).first()
1068
    if item is None:
1069
        raise InventoryServiceException(101, "Bad Item")
1070
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
1071
    return item_pricing
1072
 
2116 ankur.sing 1073
def get_item_mappings(item_id):
1074
    item = Item.query.filter_by(id=item_id).first()
1075
    if item is None:
1076
        raise InventoryServiceException(101, "Bad Item")
1077
    item_mappings = VendorItemMapping.query.filter_by(item=item).all()
1078
    return item_mappings
1079
 
1080
def add_vendor_pricing(vendorItemPricing):
1991 ankur.sing 1081
    if not vendorItemPricing:
1082
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
1083
    vendorId = vendorItemPricing.vendorId
1084
    itemId = vendorItemPricing.itemId
1085
 
1086
    try:
1087
        vendor = Vendor.query.filter_by(id=vendorId).one()
1088
    except:
1089
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
1090
 
1091
    try:
1092
        item = Item.query.filter_by(id=itemId).one()
1093
    except:
1094
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
1095
 
2120 ankur.sing 1096
    validate_vendor_prices(to_t_item(item), vendorItemPricing)
2065 ankur.sing 1097
 
1991 ankur.sing 1098
    try:
1099
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
1100
    except:
2116 ankur.sing 1101
        ds_vendorItemPricing = VendorItemPricing()
1102
        ds_vendorItemPricing.vendor = vendor
1103
        ds_vendorItemPricing.item = item
1991 ankur.sing 1104
 
1105
    if vendorItemPricing.mop:
1106
        ds_vendorItemPricing.mop = vendorItemPricing.mop
1107
    if vendorItemPricing.dealerPrice:
1108
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
1109
    if vendorItemPricing.transferPrice:
2065 ankur.sing 1110
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 1111
 
1112
    session.commit()
1113
    return
1114
 
2358 ankur.sing 1115
def add_vendor_item_mapping(key, vendorItemMapping):
2116 ankur.sing 1116
    if not vendorItemMapping:
1117
        raise InventoryServiceException(108, "Bad vendorItemMapping in request")
1118
    vendorId = vendorItemMapping.vendorId
1119
    itemId = vendorItemMapping.itemId
1120
 
1121
    try:
1122
        vendor = Vendor.query.filter_by(id=vendorId).one()
1123
    except:
1124
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
1125
 
1126
    try:
1127
        item = Item.query.filter_by(id=itemId).one()
1128
    except:
1129
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
1130
 
1131
    try:
2358 ankur.sing 1132
        ds_vendorItemMapping = VendorItemMapping.query.filter(and_(VendorItemMapping.vendor==vendor, VendorItemMapping.item==item, VendorItemMapping.item_key==key)).one()
2116 ankur.sing 1133
    except:
1134
        ds_vendorItemMapping = VendorItemMapping()
1135
        ds_vendorItemMapping.vendor = vendor
1136
        ds_vendorItemMapping.item = item
1137
    ds_vendorItemMapping.item_key = vendorItemMapping.itemKey
1138
 
1139
    session.commit()
1140
    return
1141
 
2120 ankur.sing 1142
def validate_item_prices(item):
2129 ankur.sing 1143
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
1144
        return
1145
    if item.mrp < item.sellingPrice:
2120 ankur.sing 1146
        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))
1147
        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 1148
    return
2120 ankur.sing 1149
 
1150
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 1151
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 1152
        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))
1153
        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)))
1154
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
1155
        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))
1156
        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)))
1157
    return
2065 ankur.sing 1158
 
1159
def get_all_vendors():
1160
    return Vendor.query.all()
1161
 
4725 phani.kuma 1162
def check_color_valid(color):
1163
    if color is not None:
1164
        color = color.strip().lower()
1165
        if color != '' and color != 'na' and color != 'blank' and color != '(blank)':
1166
            return True
1167
    return False
1168
 
1169
def check_similar_item(brand, model_number, model_name, color):
2129 ankur.sing 1170
    query = Item.query
2428 ankur.sing 1171
    query = query.filter_by(brand=brand)
1172
    query = query.filter_by(model_number=model_number)
4725 phani.kuma 1173
    query = query.filter_by(model_name=model_name)
1174
    similar_items = query.all()
1175
    item = None
1176
    # Check if a similar item already exists in our database
1177
    for old_item in similar_items:
1178
        if old_item.color != None and old_item.color.strip().lower() == color.strip().lower():
1179
            item = old_item
1180
            break
1181
 
1182
    # 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 1183
    if item is None:
4725 phani.kuma 1184
        for old_item in similar_items:
1185
            if not check_color_valid(old_item.color):
1186
                item = old_item
1187
                break
1188
    i = 0
1189
    color_of_similar_item = None
1190
    # Check if a similar item already exists in our database to be used to get catalog_item_id
1191
    for old_item in similar_items:
1192
        # get a similar item already existing in our database with valid color
1193
        if check_color_valid(old_item.color):
1194
            similar_item = old_item
1195
            color_of_similar_item = similar_item.color
1196
            break
1197
        i = i + 1
1198
        # get a similar item already existing in our database if similar item with valid color is not found
1199
        if i == len(similar_items):
1200
            similar_item = old_item
1201
            color_of_similar_item = similar_item.color
1202
 
1203
    # Check if a similar item that is obtained above is having a valid color
1204
    if check_color_valid(color_of_similar_item):
1205
        # 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.
1206
        # 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.
1207
        if item is None and not check_color_valid(color):
1208
            return similar_item.id
1209
 
1210
    if item is None:
2116 ankur.sing 1211
        return 0
1212
    else:
1213
        return item.id
2286 ankur.sing 1214
 
1215
def change_risky_flag(item_id, risky):
1216
    item = get_item(item_id)
1217
    if not item:
1218
        raise InventoryServiceException(101, "Item missing in our database")
1219
    try:
1220
        log_risky_flag(item_id, risky)
1221
    except:
1222
        print "Not able to log risky flag change"
1223
    item.risky = risky
4295 varun.gupt 1224
    if not risky and item.status == status.PAUSED_BY_RISK:
2368 ankur.sing 1225
        change_item_status(item.id, status.ACTIVE)
2286 ankur.sing 1226
    session.commit()
1227
 
4762 phani.kuma 1228
def get_items_by_category(categoryName):
1229
    if not categoryName:
1230
        raise InventoryServiceException(101, "Invalid category in request")
1231
    categories = ["Handsets", "Tablets", "Laptops"]
1232
    if categoryName == "Accessories":
4843 phani.kuma 1233
        query = Item.query.filter(Item.status != status.PHASED_OUT).filter(~Item.product_group.in_(categories))
4762 phani.kuma 1234
    elif categoryName == "Handsets":
4843 phani.kuma 1235
        query = Item.query.filter(Item.status != status.PHASED_OUT).filter(Item.product_group.in_(categories))
2358 ankur.sing 1236
    items = query.all()
1237
    return items
2116 ankur.sing 1238
 
2358 ankur.sing 1239
def get_risky_items():
1240
    items = Item.query.filter_by(risky=True).all()
1241
    return items
3008 rajveer 1242
 
2809 rajveer 1243
def get_similar_items_catalog_ids(start_index, stop_index, itemId):
3008 rajveer 1244
    query = SimilarItems.query.filter_by(item_id=itemId).limit(stop_index-start_index)
1245
    similar_items = query.all()
3289 rajveer 1246
    return_list = []
1247
    for similar_item in similar_items:
1248
        isActive = False
1249
        try:
1250
            all_items = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).all()
1251
        except:
1252
            continue
1253
        for item in all_items:
1254
            isActive = isActive or item.status == status.ACTIVE
1255
        if isActive:
1256
            return_list.append(similar_item.catalog_item_id)
1257
    return return_list
4423 phani.kuma 1258
 
1259
def get_all_similar_items_catalog_ids(itemId):
1260
    query = SimilarItems.query.filter_by(item_id=itemId)
1261
    similar_items = query.all()
1262
    return_list = []
1263
    for similar_item in similar_items:
1264
        item_query = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).limit(1)
1265
        item = item_query.one()
1266
        return_list.append(item)
2809 rajveer 1267
 
4423 phani.kuma 1268
    return get_thrift_item_list(return_list)
1269
 
1270
def add_similar_item_catalog_id(itemId, catalog_item_id):
1271
    if not itemId or not catalog_item_id:
1272
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
1273
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1274
    if not len(items_for_entity):
1275
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
1276
 
1277
    s_items = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1278
    if not len(s_items):
1279
        s_item = SimilarItems()
1280
        s_item.item_id=itemId
1281
        s_item.catalog_item_id=catalog_item_id
1282
        session.commit()
1283
        return items_for_entity[0]
1284
    else:
1285
        raise InventoryServiceException(101, "Already exists")
1286
 
1287
def delete_similar_item_catalog_id(itemId, catalog_item_id):
1288
    if not itemId or not catalog_item_id:
1289
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
1290
 
1291
    similar_item = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1292
    if len(similar_item):
1293
        similar_item[0].delete()
1294
    session.commit()
1295
    return True
1296
 
3079 rajveer 1297
def add_product_notification(itemId, email):
1298
    try:
3470 rajveer 1299
        try:
1300
            product_notification = ProductNotification.query.filter_by(item_id=itemId, email=email).one()
1301
        except:
1302
            product_notification = ProductNotification()
1303
            product_notification.email = email
1304
            product_notification.item_id = itemId
3079 rajveer 1305
        product_notification.addedOn = datetime.datetime.now()
1306
        session.commit()
1307
        return True
1308
    except:
1309
        return False
3086 rajveer 1310
 
1311
 
1312
def send_product_notifications():
1313
    product_notifications = ProductNotification.query.all()
1314
    for product_notification in product_notifications:
1315
        item = product_notification.item
4406 anupam.sin 1316
        availability = __get_item_availability(item, None)
3309 rajveer 1317
        if availability > 0 and item.status == status.ACTIVE:
3086 rajveer 1318
            __enque_product_notification_email(product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id)
1319
            product_notification.delete()
1320
    session.commit()
1321
    return True
1322
 
1323
def __get_product_name(item):
1324
    product_name = item.brand + " " + item.model_name + " " + item.model_number
1325
    color = item.color
1326
    if color is not None and color != 'NA':
1327
        product_name = product_name + " (" + color + ")"
3201 rajveer 1328
    product_name = product_name.replace("  "," ")
3086 rajveer 1329
    return product_name
1330
 
1331
 
1332
def __get_product_url(item):
1333
    product_url = "http://www.saholic.com/mobile-phones/" + item.brand + "-" + item.model_name + "-" + item.model_number + "-" + str(item.catalog_item_id)
1334
    product_url = product_url.replace("--","-")
1335
    product_url = product_url.replace(" ","")
1336
    return product_url
1337
 
3348 varun.gupt 1338
def get_all_brands_by_category(category_id):
1339
    catm = CategoryManager()
1340
    child_categories = catm.getCategory(category_id).children_category_ids
1341
    brands = session.query(distinct(Item.brand)).filter(Item.category.in_(child_categories)).all()
1342
 
1343
    return [brand[0] for brand in brands]
3086 rajveer 1344
 
1345
def __enque_product_notification_email(email, product, date, url, itemId):
1346
 
1347
    html = """
1348
        <html>
1349
        <body>
1350
        <div>
1351
        <p>
1352
            Hi,<br /><br />
1353
            The product requested by you on $date is now available on saholic.com.
1354
        </p>
1355
 
1356
        <p>    
1357
        <strong>Product: $product </strong>
1358
        </p>
1359
 
1360
        <p>
1361
        Click the link below to visit the product: 
1362
        <br/>
1363
        $url
1364
        </p>
1365
        <p>
1366
        Regards,<br/>
1367
        Saholic Customer Support Team<br/>
1368
        www.saholic.com<br/>
1369
        Email: help@saholic.com<br/>
1370
        </p>
1371
        </div>
1372
        </body>
1373
        </html>
1374
        """
1375
 
1376
    html = Template(html).substitute(dict(product=product,date=date,url=url))
3079 rajveer 1377
 
3086 rajveer 1378
    try:
1379
        helper_client = HelperClient().get_client()
1380
        helper_client.saveUserEmailForSending(email, "", "Product requested by you is available now.", html, str(itemId), "ProductNotification")
1381
    except Exception as e:
1382
        print e
1383
 
3557 rajveer 1384
def get_all_sources():
1385
    sources = Source.query.all()
1386
    return [to_t_source(source) for source in sources]
3086 rajveer 1387
 
3557 rajveer 1388
def get_item_pricing_by_source(itemId, sourceId):
1389
    item = Item.query.filter_by(id=itemId).first()
1390
    if item is None:
1391
        raise InventoryServiceException(101, "Bad Item")
1392
 
1393
    source = Source.query.filter_by(id=sourceId).first()
1394
    if source is None:
1395
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1396
 
1397
    item_pricing = SourceItemPricing.query.filter_by(source=source, item=item).first()
1398
    if item_pricing is None:
1399
        raise InventoryServiceException(101, "Pricing information not found for sourceId " + str(sourceId))
1400
    return item_pricing
1401
 
1402
def add_source_item_pricing(sourceItemPricing):
1403
    if not sourceItemPricing:
1404
        raise InventoryServiceException(108, "Bad sourceItemPricing in request")
1405
 
1406
    if not sourceItemPricing.sellingPrice:
4326 mandeep.dh 1407
        raise InventoryServiceException(101, "Selling Price is not defined for sourceId " + str(sourceItemPricing.sourceId))
3557 rajveer 1408
 
1409
    sourceId = sourceItemPricing.sourceId
1410
    itemId = sourceItemPricing.itemId
1411
 
1412
    item = Item.query.filter_by(id=itemId).first()
1413
    if item is None:
1414
        raise InventoryServiceException(101, "Bad Item")
1415
 
1416
    source = Source.query.filter_by(id=sourceId).first()
1417
    if source is None:
1418
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1419
 
3564 rajveer 1420
    ds_sourceItemPricing = SourceItemPricing.get_by(source=source, item=item)
3557 rajveer 1421
    if ds_sourceItemPricing is None:
1422
        ds_sourceItemPricing = SourceItemPricing()
1423
        ds_sourceItemPricing.source = source
1424
        ds_sourceItemPricing.item = item
1425
 
1426
    if sourceItemPricing.mrp:
1427
        ds_sourceItemPricing.mrp = sourceItemPricing.mrp
1428
    ds_sourceItemPricing.sellingPrice = sourceItemPricing.sellingPrice
1429
 
1430
    session.commit()
1431
    return
1432
 
1433
def get_all_source_pricing(itemId):
1434
    item = Item.query.filter_by(id=itemId).first()
1435
    if item is None:
1436
        raise InventoryServiceException(101, "Bad Item")
1437
    source_pricing = SourceItemPricing.query.filter_by(item=item).all()
1438
    return source_pricing
1439
 
1440
 
1441
def get_item_for_source(item_id, sourceId):
1442
    item = get_item(item_id)
1443
    if sourceId == -1:
1444
        return item
1445
    try:
1446
        sip = get_item_pricing_by_source(item_id, sourceId)
1447
        item.sellingPrice = sip.sellingPrice
1448
        if sip.mrp:
1449
            item.mrp = sip.mrp
1450
    except:
1451
        print "No source pricing"
1452
    return item
1453
 
3872 chandransh 1454
def search_items(search_terms, offset, limit):
1455
    query = Item.query
1456
 
1457
    query_clause = []
1458
 
1459
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1460
 
1461
    for search_term in search_terms:
1462
        query_clause.append(Item.brand.like(search_term))
1463
        query_clause.append(Item.model_number.like(search_term))
1464
        query_clause.append(Item.model_name.like(search_term))
1465
 
1466
    query = query.filter(or_(*query_clause))
1467
 
1468
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
1469
    if limit:
1470
        query = query.limit(limit)
1471
    items = query.all()
1472
    return items
1473
 
1474
def get_search_result_count(search_terms):
1475
    query = Item.query
1476
 
1477
    query_clause = []
1478
 
1479
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1480
 
1481
    for search_term in search_terms:
1482
        query_clause.append(Item.brand.like(search_term))
1483
        query_clause.append(Item.model_number.like(search_term))
1484
        query_clause.append(Item.model_name.like(search_term))
1485
 
1486
    query = query.filter(or_(*query_clause))
1487
 
1488
    return query.count()
1489
 
3924 rajveer 1490
def __clear_homepage_cache():
1491
    try:
1492
        # create a password manager
1493
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
1494
        # Add the username and password.
1495
        configclient = ConfigClient()
4310 rajveer 1496
        ips = configclient.get_property("production_servers_private_ips");
3924 rajveer 1497
        ips = ips.split(" ")
1498
 
1499
        for ip in ips:
4310 rajveer 1500
            try:
1501
                top_level_url = "http://" + ip + ":8080/"
1502
                password_mgr.add_password(None, top_level_url, "saholic", "shop2020")
1503
                handler = urllib2.HTTPBasicAuthHandler(password_mgr)
3924 rajveer 1504
 
4310 rajveer 1505
                opener = urllib2.build_opener(handler)
3924 rajveer 1506
 
4310 rajveer 1507
                # use the opener to fetch a URL
1508
                res = opener.open(top_level_url + "cache-admin/HomePageSnippets?_method=delete")
1509
                print "Successfully cleared home page cache" + res.read()
1510
            except:
1511
                print "Unable to clear home page cache" + res.read()
3924 rajveer 1512
    except:
1513
        print "Unable to clear cache, still should continue with other operations"
4024 chandransh 1514
 
4062 chandransh 1515
def get_pending_orders_inventory(vendor_id=1):
4024 chandransh 1516
    """
1517
    Returns a list of inventory stock for items for which there are pending orders.
1518
    """
4341 rajveer 1519
 
4368 rajveer 1520
    warehouse_ids = [warehouse.id for warehouse in get_warehouses_for_vendor(vendor_id)]
4064 chandransh 1521
    pending_items_inventory = []
1522
    if warehouse_ids:
1523
        pending_items_inventory = session.query(CurrentInventorySnapshot.item_id, func.sum(CurrentInventorySnapshot.availibility), func.sum(CurrentInventorySnapshot.reserved)).filter(CurrentInventorySnapshot.warehouse_id.in_(warehouse_ids)).group_by(CurrentInventorySnapshot.item_id).having(func.sum(CurrentInventorySnapshot.reserved) > 0).all()
4024 chandransh 1524
    return pending_items_inventory
4295 varun.gupt 1525
 
1526
def get_product_notifications(start_datetime):
1527
    '''
1528
    Returns a list of Product Notification objects each representing user requests for notification
1529
    '''
1530
    query = ProductNotification.query
3924 rajveer 1531
 
4295 varun.gupt 1532
    if start_datetime:
1533
        query = query.filter(ProductNotification.addedOn > start_datetime)
1534
 
1535
    notifications = query.order_by(desc('addedOn')).all()
1536
    return notifications
1537
 
1538
def get_product_notification_request_count(start_datetime):
1539
    '''
1540
    Returns list of items and the counts of product notification requests
1541
    '''
1542
    print start_datetime
1543
    query = session.query(ProductNotification, func.count(ProductNotification.email).label('count'))
1544
 
1545
    if start_datetime:
1546
        query = query.filter(ProductNotification.addedOn > start_datetime)
1547
 
1548
    counts = query.group_by(ProductNotification.item_id).order_by(desc('count')).all()
1549
    return counts
1550
 
766 rajveer 1551
def close_session():
1552
    if session.is_active:
1553
        print "session is active. closing it."
1399 rajveer 1554
        session.close()
3376 rajveer 1555
 
1556
def is_alive():
1557
    try:
1558
        session.query(Item.id).limit(1).one()
1559
        return True
1560
    except:
1561
        return False
4332 anupam.sin 1562
 
1563
def add_vendor(vendor):
1564
    if not vendor:
1565
        raise InventoryServiceException(108, "Bad vendor")
1566
    if get_Vendor(vendor.id):
1567
        #vendor is already present.
1568
        raise InventoryServiceException(101, "Vendor already present")
1569
 
1570
    ds_vendor = Vendor()
1571
    ds_vendor.id = vendor.id
1572
    ds_vendor.name = vendor.name
1573
    session.commit()
1574
    return ds_vendor.id
1575
 
1576
def add_warehouse_vendor_mapping(warehouse_id, VendorId):
1577
    return True
1578
 
1579
def get_vendors_for_warehouse(warehouse_id):
1580
    try:
1581
        warehouse = Warehouse.get_by(id=warehouse_id)
1582
        return warehouse.vendors
1583
    except:
1584
        raise InventoryServiceException(108, "Bad Warehouse Id")
1585
 
1586
def get_warehouses_for_vendor(vendorId):
1587
    try:
1588
        vendor = get_Vendor(vendorId)
1589
        return vendor.warehouses
1590
    except:
4649 phani.kuma 1591
        raise InventoryServiceException(108, "Bad Vendor Id")
1592
 
1593
def add_authorization_log_for_item(itemId, username, reason):
1594
    if not itemId or not username:
1595
        raise InventoryServiceException(101, "Bad itemId or Invalid username in request")
1596
    authorize_log = AuthorizationLog()
1597
    authorize_log.item_id = itemId
1598
    authorize_log.username = username
1599
    authorize_log.reason = reason
1600
    session.commit()
4797 rajveer 1601
    return True
1602
 
1603
def __send_mail_for_oos_item(item): 
1604
    try:
4876 mandeep.dh 1605
        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), None)
4797 rajveer 1606
    except Exception as e:
1607
        print e