Subversion Repositories SmartDukaan

Rev

Rev 4881 | Rev 4897 | 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
633
        session.commit()
2368 ankur.sing 634
        check_risky_item(item)
4822 mandeep.dh 635
        if current_inventory_snapshot.reserved < 0:
636
            __send_alert_for_negative_reserved(get_item(item_id), current_inventory_snapshot.reserved, get_Warehouse(warehouse_id))
871 chandransh 637
        return True
638
    except:
639
        print "Unexpected error:", sys.exc_info()[0]
640
        return False
641
 
2075 rajveer 642
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
2828 rajveer 643
    '''
644
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
645
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
646
    '''
723 chandransh 647
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 648
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 649
    current_timestamp = datetime.datetime.now()
650
    for item in items:
2828 rajveer 651
        if item.status == status.IN_PROCESS:
652
            item.status = content_complete_status
653
            item_change_log = ItemChangeLog()
654
            item_change_log.old_status = item.status
655
            item_change_log.new_status = content_complete_status
656
            item_change_log.timestamp = current_timestamp
657
            item_change_log.item = item
723 chandransh 658
 
4762 phani.kuma 659
        category_object = get_category(category)
660
        if category_object is not None:
661
            item.category = category
662
            item.product_group = category_object.display_name
2075 rajveer 663
        item.brand = brand
2081 rajveer 664
        item.model_name = modelName
665
        item.model_number = modelNumber
723 chandransh 666
        item.updatedOn = current_timestamp
667
    session.commit()
668
    return True
1294 chandransh 669
 
643 chandransh 670
def get_item_availability_for_location(warehouse_loc, item_id):
3355 chandransh 671
    """
672
    Determines the warehouse that should be used to fulfil an order for the given item.
4406 anupam.sin 673
    It first checks whether the preferred warehouse for that item is set or not. If set 
674
    and preference is sticky then that warehouse is used for fulfilment.
675
    If preference is not sticky then we see if item is available in the preferred WH,
676
    in which case that warehouse is used otherwise we use that warehouse which has the max
677
    availability. And if there is no inventory for that item in any warehouses then we use
678
    default warehouse.
679
    If preference is not set in that case we just find the warehouse with max availability
680
    and in case of zero inventory we use default warehouse
3355 chandransh 681
 
682
    Returns an ordered list of size 4 with following elements in the given order:
683
    1. Logistics location of the warehouse which was finally picked up to ship the order.
684
    2. Id of the warehouse which was finally picked up.
685
    3. Inventory size in the selected warehouse.
686
    4. Expected delay added by the category manager.
687
 
688
    Parameters:
689
     - warehouse_loc
690
     - item_id
691
    """
643 chandransh 692
    if warehouse_loc is None:
693
        raise InventoryServiceException(101, "Bad Warehouse Location")
694
    if not item_id:
1416 chandransh 695
        raise InventoryServiceException(101, "Bad Item id")
643 chandransh 696
 
1416 chandransh 697
    item = Item.get_by(id=item_id)
4406 anupam.sin 698
    logisticsLocation = warehouse_loc
699
    warehouses = Warehouse.query.filter_by(logisticsLocation=logisticsLocation).all()
643 chandransh 700
    warehouse_ids = [warehouse.id for warehouse in warehouses]
701
    warehouse_retid = -1
4406 anupam.sin 702
 
3503 chandransh 703
    total_availability = 0
4406 anupam.sin 704
    '''
705
    If warehouse preference is set and it is sticky then we should fulfil this order from this warehouse only.
706
    But we still need to calculate total availability across warehouses.
707
    '''
708
    if (item.isWarehousePreferenceSticky and item.preferredWarehouse is not None) :
709
        warehouse_retid = item.preferredWarehouse
710
        warehouse = Warehouse.get_by(id=warehouse_retid)
711
        logisticsLocation = warehouse.logisticsLocation
4476 anupam.sin 712
        total_availability = __get_item_availability(item, [warehouse_retid])
4406 anupam.sin 713
 
714
    #If preference is not sticky then this order should be fulfilled from preferred WH if inventory available
715
    #otherwise we should check for its availability elsewhere and fulfil this order from there, but if it is not available anywhere
716
    #then we should fulfil this order from its default warehouse.
717
 
718
    elif (not item.isWarehousePreferenceSticky and item.preferredWarehouse is not None) :
785 rajveer 719
        try:
4406 anupam.sin 720
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = item.preferredWarehouse, item_id = item_id).one()
871 chandransh 721
            availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
4317 varun.gupt 722
        except Exception as e:
723
            print e
785 rajveer 724
            availability = 0    
4406 anupam.sin 725
        if availability > 0:
726
            warehouse_retid = item.preferredWarehouse
4476 anupam.sin 727
            total_availability = availability
4406 anupam.sin 728
        else :
729
            [logisticsLocation, warehouse_retid, total_availability] = \
730
                        __get_warehouse_with_max_availability(warehouse_loc = warehouse_loc, \
731
                                                            warehouse_ids = warehouse_ids, item = item)
732
 
733
    else :
734
        [logisticsLocation, warehouse_retid, total_availability] = \
735
                        __get_warehouse_with_max_availability(warehouse_loc = warehouse_loc, \
736
                                                            warehouse_ids = warehouse_ids, item = item)
2341 chandransh 737
 
4406 anupam.sin 738
    if item.expectedDelay is None:
739
        print 'expectedDelay field for this item was Null. Resetting it to 0'
740
        item.expectedDelay = 0
741
 
742
    ## FIXME Assign warehouse 5 (9D2) for all the hotspot products.
743
    #if warehouse_retid in [warehouse.id for warehouse in get_warehouses_for_vendor(1)]:
4433 anupam.sin 744
    if int(warehouse_retid) in [1,2,3,4,5]:
4406 anupam.sin 745
        warehouse_retid = 5
746
        warehouse = Warehouse.get_by(id=warehouse_retid)
747
        logisticsLocation = warehouse.logisticsLocation  
748
 
749
    return [logisticsLocation, int(warehouse_retid), total_availability, int(item.expectedDelay)]
750
 
751
def __get_warehouse_with_max_availability(warehouse_loc, warehouse_ids, item):
752
 
753
    warehouse_retid = -1
754
    max_availability = 0
755
    total_availability = 0
756
 
757
    for warehouse_id in warehouse_ids:
758
            try:
759
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item.id).one()
760
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
761
            except Exception as e:
762
                print e
763
                availability = 0    
764
            if availability > max_availability:
765
                warehouse_retid = warehouse_id
766
                max_availability = availability
767
            total_availability = total_availability + availability
768
 
769
    #If no warehouse could be found, use the default warehouse for this item
643 chandransh 770
    if warehouse_retid == -1:
759 chandransh 771
        # This is the case when all warehouses have exhausted their
772
        # inventory of this item or no warehouse is available in this
773
        # location.
4406 anupam.sin 774
        warehouse_retid = int(item.defaultWarehouse)
2344 chandransh 775
        warehouse = Warehouse.get_by(id=warehouse_retid)
4406 anupam.sin 776
        warehouse_loc = warehouse.logisticsLocation
2341 chandransh 777
        try:
4406 anupam.sin 778
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_retid, item_id = item.id).one()
3503 chandransh 779
            max_availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
4317 varun.gupt 780
        except Exception as e:
781
            print e
3503 chandransh 782
            max_availability = 0
783
        total_availability = max_availability
643 chandransh 784
 
4406 anupam.sin 785
    return [warehouse_loc, warehouse_retid, total_availability]
786
'''    
787
def calculate_total_availability(warehouse_ids, item_id):
788
    total_availability = 0
789
    for warehouse_id in warehouse_ids:
790
            try:
791
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id).one()
792
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
793
            except Exception as e:
794
                print e
795
                availability = 0    
796
            total_availability = total_availability + availability
797
    return total_availability
798
'''
2341 chandransh 799
 
122 ashish 800
def get_warehouses_for_item(item_id):
643 chandransh 801
 
122 ashish 802
    if not item_id:
803
        raise InventoryServiceException(101, "bad item_id")
635 rajveer 804
    item = get_item(item_id)
122 ashish 805
 
806
    if not item:
807
        raise InventoryServiceException(101, "bad item")
808
 
483 rajveer 809
    warehouses = item.currentInventory.warehouse
501 rajveer 810
    return warehouses
811
 
2404 chandransh 812
def get_child_categories(category):
813
    cm = CategoryManager()
2621 varun.gupt 814
    cat = cm.getCategory(category)
815
    return cat.children_category_ids if cat else None
2404 chandransh 816
 
626 chandransh 817
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 818
    '''
819
    Returns the Best Sellers between the start and the stop index in the given category
820
    '''
1926 rajveer 821
    query = get_best_sellers_query(category, None)
1098 chandransh 822
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 823
    return get_thrift_item_list(best_sellers)
824
 
2093 chandransh 825
def get_best_sellers_count(category=-1):
2404 chandransh 826
    '''
827
    Returns the number of best sellers in the given category
828
    '''
1926 rajveer 829
    count = get_best_sellers_query(category, None).count()
1120 rajveer 830
    if count is None:
831
        count = 0
766 rajveer 832
    return count
621 chandransh 833
 
1926 rajveer 834
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 835
    '''
836
    Returns the Best sellers for the given brand and category between the start and the stop index.
837
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
838
    '''
1926 rajveer 839
    query = get_best_sellers_query(category, brand)
1098 chandransh 840
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 841
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 842
 
1926 rajveer 843
def get_best_sellers_query(category, brand):
2404 chandransh 844
    '''
845
    Returns the query to be used for getting Best Sellers.
846
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
847
    '''
1098 chandransh 848
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 849
    if category != -1:
1970 rajveer 850
        all_categories = [category]
851
        child_categories = get_child_categories(category)
852
        if child_categories is not None:
853
            all_categories = all_categories + child_categories 
854
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 855
    if brand is not None:
856
        query = query.filter_by(brand=brand)
1098 chandransh 857
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 858
    return query
609 chandransh 859
 
1098 chandransh 860
def get_best_deals(category=-1):
2404 chandransh 861
    '''
862
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
863
    '''
864
    query = get_best_deals_query(Item, category, None)
1098 chandransh 865
    items = query.all()
609 chandransh 866
    return get_thrift_item_list(items)
867
 
1098 chandransh 868
def get_best_deals_count(category=-1):
2404 chandransh 869
    '''
870
    Returns the count of best deals in the given category.
871
    Ignores the category if it's -1.
872
    '''
873
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 874
    if count is None:
875
        count = 0
766 rajveer 876
    return count
501 rajveer 877
 
1926 rajveer 878
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 879
    '''
880
    Returns the catalog_item_ids of best deal items for the given brand and category.
881
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
882
    '''
883
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 884
    best_deal_items = query.all()[start_index:stop_index]
885
    return [item.catalog_item_id for item in best_deal_items]
886
 
2404 chandransh 887
def get_best_deals_counting_query(obj, category, brand):
888
    '''
889
    Returns the query to be used to select the best deals in the given brand and category.
890
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
891
    '''
892
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 893
    if category != -1:
1970 rajveer 894
        all_categories = [category]
895
        child_categories = get_child_categories(category)
896
        if child_categories is not None:
897
            all_categories = all_categories + child_categories 
898
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 899
    if brand is not None:
900
        query = query.filter_by(brand=brand)
2404 chandransh 901
    return query
902
 
903
def get_best_deals_query(obj, category, brand):
904
    '''
905
    Returns the query to be used to get the best deals in the given category and brand.
906
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
907
    '''
908
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 909
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
910
    return query
609 chandransh 911
 
1098 chandransh 912
def get_latest_arrivals(limit, category=-1):
2404 chandransh 913
    '''
914
    Returns up to limit number of Latest Arrivals in the given category.
915
    '''
2975 chandransh 916
    categories = []
917
    if category != -1:
918
        categories = [category]
919
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 920
    items = query.all()[0:limit]
609 chandransh 921
    return get_thrift_item_list(items)
598 chandransh 922
 
1098 chandransh 923
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 924
    '''
925
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 926
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 927
    '''
2975 chandransh 928
    categories = []
929
    if category != -1:
930
        categories = [category]
931
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 932
    if count is None:
933
        count = 0
934
    count = min(count, limit)
766 rajveer 935
    return count
602 chandransh 936
 
2975 chandransh 937
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 938
    '''
939
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 940
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 941
    '''
2975 chandransh 942
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 943
    latest_arrivals = query.all()[start_index:stop_index]
944
    return [item.catalog_item_id for item in latest_arrivals]
945
 
2975 chandransh 946
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 947
    '''
948
    Returns the query to be used to count Latest arrivals.
3016 chandransh 949
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 950
    '''
951
    query = session.query(obj).filter_by(status=status.ACTIVE)
2975 chandransh 952
 
953
    all_categories = []
954
    for category in categories:
955
        all_categories.append(category)
1970 rajveer 956
        child_categories = get_child_categories(category)
2975 chandransh 957
        if child_categories:
958
            all_categories = all_categories + child_categories
959
    if all_categories: 
1970 rajveer 960
        query = query.filter(Item.category.in_(all_categories))
2975 chandransh 961
 
1926 rajveer 962
    if brand is not None:
963
        query = query.filter_by(brand=brand)
2404 chandransh 964
    return query
965
 
2975 chandransh 966
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 967
    '''
968
    Returns the query to be used to retrieve Latest Arrivals.
969
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
970
    '''
2975 chandransh 971
    query = get_latest_arrivals_counting_query(obj, categories, brand)
1098 chandransh 972
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
973
    return query
609 chandransh 974
 
975
def get_thrift_item_list(items):
1098 chandransh 976
    return [to_t_item(item) for item in items if item != None]
635 rajveer 977
 
1155 rajveer 978
def generate_new_entity_id():
979
    generator =  EntityIDGenerator.query.one()
980
    id = generator.id + 1
981
    generator.id = id
982
    session.commit()
983
    return id
984
 
635 rajveer 985
def put_category_object(object):
986
    category = Category.get_by(id=1)
987
    if category is None:
988
        category = Category()
989
    category.object = object    
990
    session.commit()
991
    return True
992
 
993
def get_category_object():
766 rajveer 994
    object = Category.get_by(id=1).object
995
    return object
996
 
4283 anupam.sin 997
def get_item_pricing(item_id, vendorId):
1341 chandransh 998
    item = Item.query.filter_by(id=item_id).first()
999
    if item is None:
1000
        raise InventoryServiceException(101, "Bad Item")
4307 anupam.sin 1001
    '''
1002
    if vendor id is -1 then we calculate an average transfer price to be populated
1003
    at the time of order creation. This will be later updated with actual transfer price
1004
    at the time of billing.
1005
    '''
1006
    if(vendorId == -1):
4543 anupam.sin 1007
        total = 0
4307 anupam.sin 1008
        try:
4858 anupam.sin 1009
            if item.preferredWarehouse is not None:
1010
                warehouse = Warehouse.query.filter_by(id=item.preferredWarehouse).first()
1011
                vendors = warehouse.vendors
1012
                item_pricings = []
1013
                for vendor in vendors :
1014
                    item_pricing = VendorItemPricing.query.filter_by(item=item, vendor=vendor).first()
1015
                    if item_pricing :
1016
                        item_pricings.append(item_pricing)
1017
            else :
1018
                item_pricings = VendorItemPricing.query.filter_by(item=item).all()
4315 anupam.sin 1019
            if item_pricings:
4307 anupam.sin 1020
                for item_pricing in item_pricings:
4543 anupam.sin 1021
                    total += item_pricing.transfer_price
4315 anupam.sin 1022
                avg = total / len(item_pricings)
1023
                item_pricing.transfer_price = avg
4543 anupam.sin 1024
            else:
1025
                item_pricing = VendorItemPricing()
1026
                item_pricing.transfer_price = item.sellingPrice
1027
                vendor = Vendor()
1028
                vendor.id = vendorId
1029
                item_pricing.vendor = vendor
1030
                item_pricing.item = item
1031
 
1032
            return item_pricing
4307 anupam.sin 1033
        except:
1034
            raise InventoryServiceException(101, "Item pricing not found ")
4283 anupam.sin 1035
    vendor = Vendor.get_by(id=vendorId)    
1341 chandransh 1036
    try:
1037
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 1038
        return item_pricing
3244 chandransh 1039
    except MultipleResultsFound:
1341 chandransh 1040
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
3244 chandransh 1041
    except NoResultFound:
1341 chandransh 1042
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
1043
 
1970 rajveer 1044
def add_category(t_category):
1045
    category = Category.get_by(id=t_category.id)
1046
    if category is None:
1047
        category = Category()
1048
    category.id = t_category.id 
1049
    category.label = t_category.label
1050
    category.description = t_category.description
4762 phani.kuma 1051
    category.display_name = t_category.display_name
1970 rajveer 1052
    category.parent_category_id = t_category.parent_category_id 
1053
    session.commit()
1054
    return True
1055
 
1056
def get_category(id):
1057
    return Category.query.filter_by(id=id).first()
1058
 
1059
def get_all_categories():
1060
    return Category.query.all()
1061
 
1991 ankur.sing 1062
 
1063
def get_all_item_pricing(item_id):
1064
    item = Item.query.filter_by(id=item_id).first()
1065
    if item is None:
1066
        raise InventoryServiceException(101, "Bad Item")
1067
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
1068
    return item_pricing
1069
 
2116 ankur.sing 1070
def get_item_mappings(item_id):
1071
    item = Item.query.filter_by(id=item_id).first()
1072
    if item is None:
1073
        raise InventoryServiceException(101, "Bad Item")
1074
    item_mappings = VendorItemMapping.query.filter_by(item=item).all()
1075
    return item_mappings
1076
 
1077
def add_vendor_pricing(vendorItemPricing):
1991 ankur.sing 1078
    if not vendorItemPricing:
1079
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
1080
    vendorId = vendorItemPricing.vendorId
1081
    itemId = vendorItemPricing.itemId
1082
 
1083
    try:
1084
        vendor = Vendor.query.filter_by(id=vendorId).one()
1085
    except:
1086
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
1087
 
1088
    try:
1089
        item = Item.query.filter_by(id=itemId).one()
1090
    except:
1091
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
1092
 
2120 ankur.sing 1093
    validate_vendor_prices(to_t_item(item), vendorItemPricing)
2065 ankur.sing 1094
 
1991 ankur.sing 1095
    try:
1096
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
1097
    except:
2116 ankur.sing 1098
        ds_vendorItemPricing = VendorItemPricing()
1099
        ds_vendorItemPricing.vendor = vendor
1100
        ds_vendorItemPricing.item = item
1991 ankur.sing 1101
 
1102
    if vendorItemPricing.mop:
1103
        ds_vendorItemPricing.mop = vendorItemPricing.mop
1104
    if vendorItemPricing.dealerPrice:
1105
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
1106
    if vendorItemPricing.transferPrice:
2065 ankur.sing 1107
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 1108
 
1109
    session.commit()
1110
    return
1111
 
2358 ankur.sing 1112
def add_vendor_item_mapping(key, vendorItemMapping):
2116 ankur.sing 1113
    if not vendorItemMapping:
1114
        raise InventoryServiceException(108, "Bad vendorItemMapping in request")
1115
    vendorId = vendorItemMapping.vendorId
1116
    itemId = vendorItemMapping.itemId
1117
 
1118
    try:
1119
        vendor = Vendor.query.filter_by(id=vendorId).one()
1120
    except:
1121
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
1122
 
1123
    try:
1124
        item = Item.query.filter_by(id=itemId).one()
1125
    except:
1126
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
1127
 
1128
    try:
2358 ankur.sing 1129
        ds_vendorItemMapping = VendorItemMapping.query.filter(and_(VendorItemMapping.vendor==vendor, VendorItemMapping.item==item, VendorItemMapping.item_key==key)).one()
2116 ankur.sing 1130
    except:
1131
        ds_vendorItemMapping = VendorItemMapping()
1132
        ds_vendorItemMapping.vendor = vendor
1133
        ds_vendorItemMapping.item = item
1134
    ds_vendorItemMapping.item_key = vendorItemMapping.itemKey
1135
 
1136
    session.commit()
1137
    return
1138
 
2120 ankur.sing 1139
def validate_item_prices(item):
2129 ankur.sing 1140
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
1141
        return
1142
    if item.mrp < item.sellingPrice:
2120 ankur.sing 1143
        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))
1144
        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 1145
    return
2120 ankur.sing 1146
 
1147
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 1148
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 1149
        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))
1150
        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)))
1151
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
1152
        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))
1153
        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)))
1154
    return
2065 ankur.sing 1155
 
1156
def get_all_vendors():
1157
    return Vendor.query.all()
1158
 
4725 phani.kuma 1159
def check_color_valid(color):
1160
    if color is not None:
1161
        color = color.strip().lower()
1162
        if color != '' and color != 'na' and color != 'blank' and color != '(blank)':
1163
            return True
1164
    return False
1165
 
1166
def check_similar_item(brand, model_number, model_name, color):
2129 ankur.sing 1167
    query = Item.query
2428 ankur.sing 1168
    query = query.filter_by(brand=brand)
1169
    query = query.filter_by(model_number=model_number)
4725 phani.kuma 1170
    query = query.filter_by(model_name=model_name)
1171
    similar_items = query.all()
1172
    item = None
1173
    # Check if a similar item already exists in our database
1174
    for old_item in similar_items:
1175
        if old_item.color != None and old_item.color.strip().lower() == color.strip().lower():
1176
            item = old_item
1177
            break
1178
 
1179
    # 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 1180
    if item is None:
4725 phani.kuma 1181
        for old_item in similar_items:
1182
            if not check_color_valid(old_item.color):
1183
                item = old_item
1184
                break
1185
    i = 0
1186
    color_of_similar_item = None
1187
    # Check if a similar item already exists in our database to be used to get catalog_item_id
1188
    for old_item in similar_items:
1189
        # get a similar item already existing in our database with valid color
1190
        if check_color_valid(old_item.color):
1191
            similar_item = old_item
1192
            color_of_similar_item = similar_item.color
1193
            break
1194
        i = i + 1
1195
        # get a similar item already existing in our database if similar item with valid color is not found
1196
        if i == len(similar_items):
1197
            similar_item = old_item
1198
            color_of_similar_item = similar_item.color
1199
 
1200
    # Check if a similar item that is obtained above is having a valid color
1201
    if check_color_valid(color_of_similar_item):
1202
        # 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.
1203
        # 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.
1204
        if item is None and not check_color_valid(color):
1205
            return similar_item.id
1206
 
1207
    if item is None:
2116 ankur.sing 1208
        return 0
1209
    else:
1210
        return item.id
2286 ankur.sing 1211
 
1212
def change_risky_flag(item_id, risky):
1213
    item = get_item(item_id)
1214
    if not item:
1215
        raise InventoryServiceException(101, "Item missing in our database")
1216
    try:
1217
        log_risky_flag(item_id, risky)
1218
    except:
1219
        print "Not able to log risky flag change"
1220
    item.risky = risky
4295 varun.gupt 1221
    if not risky and item.status == status.PAUSED_BY_RISK:
2368 ankur.sing 1222
        change_item_status(item.id, status.ACTIVE)
2286 ankur.sing 1223
    session.commit()
1224
 
4762 phani.kuma 1225
def get_items_by_category(categoryName):
1226
    if not categoryName:
1227
        raise InventoryServiceException(101, "Invalid category in request")
1228
    categories = ["Handsets", "Tablets", "Laptops"]
1229
    if categoryName == "Accessories":
4843 phani.kuma 1230
        query = Item.query.filter(Item.status != status.PHASED_OUT).filter(~Item.product_group.in_(categories))
4762 phani.kuma 1231
    elif categoryName == "Handsets":
4843 phani.kuma 1232
        query = Item.query.filter(Item.status != status.PHASED_OUT).filter(Item.product_group.in_(categories))
2358 ankur.sing 1233
    items = query.all()
1234
    return items
2116 ankur.sing 1235
 
2358 ankur.sing 1236
def get_risky_items():
1237
    items = Item.query.filter_by(risky=True).all()
1238
    return items
3008 rajveer 1239
 
2809 rajveer 1240
def get_similar_items_catalog_ids(start_index, stop_index, itemId):
3008 rajveer 1241
    query = SimilarItems.query.filter_by(item_id=itemId).limit(stop_index-start_index)
1242
    similar_items = query.all()
3289 rajveer 1243
    return_list = []
1244
    for similar_item in similar_items:
1245
        isActive = False
1246
        try:
1247
            all_items = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).all()
1248
        except:
1249
            continue
1250
        for item in all_items:
1251
            isActive = isActive or item.status == status.ACTIVE
1252
        if isActive:
1253
            return_list.append(similar_item.catalog_item_id)
1254
    return return_list
4423 phani.kuma 1255
 
1256
def get_all_similar_items_catalog_ids(itemId):
1257
    query = SimilarItems.query.filter_by(item_id=itemId)
1258
    similar_items = query.all()
1259
    return_list = []
1260
    for similar_item in similar_items:
1261
        item_query = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).limit(1)
1262
        item = item_query.one()
1263
        return_list.append(item)
2809 rajveer 1264
 
4423 phani.kuma 1265
    return get_thrift_item_list(return_list)
1266
 
1267
def add_similar_item_catalog_id(itemId, catalog_item_id):
1268
    if not itemId or not catalog_item_id:
1269
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
1270
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1271
    if not len(items_for_entity):
1272
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
1273
 
1274
    s_items = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1275
    if not len(s_items):
1276
        s_item = SimilarItems()
1277
        s_item.item_id=itemId
1278
        s_item.catalog_item_id=catalog_item_id
1279
        session.commit()
1280
        return items_for_entity[0]
1281
    else:
1282
        raise InventoryServiceException(101, "Already exists")
1283
 
1284
def delete_similar_item_catalog_id(itemId, catalog_item_id):
1285
    if not itemId or not catalog_item_id:
1286
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
1287
 
1288
    similar_item = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1289
    if len(similar_item):
1290
        similar_item[0].delete()
1291
    session.commit()
1292
    return True
1293
 
3079 rajveer 1294
def add_product_notification(itemId, email):
1295
    try:
3470 rajveer 1296
        try:
1297
            product_notification = ProductNotification.query.filter_by(item_id=itemId, email=email).one()
1298
        except:
1299
            product_notification = ProductNotification()
1300
            product_notification.email = email
1301
            product_notification.item_id = itemId
3079 rajveer 1302
        product_notification.addedOn = datetime.datetime.now()
1303
        session.commit()
1304
        return True
1305
    except:
1306
        return False
3086 rajveer 1307
 
1308
 
1309
def send_product_notifications():
1310
    product_notifications = ProductNotification.query.all()
1311
    for product_notification in product_notifications:
1312
        item = product_notification.item
4406 anupam.sin 1313
        availability = __get_item_availability(item, None)
3309 rajveer 1314
        if availability > 0 and item.status == status.ACTIVE:
3086 rajveer 1315
            __enque_product_notification_email(product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id)
1316
            product_notification.delete()
1317
    session.commit()
1318
    return True
1319
 
1320
def __get_product_name(item):
1321
    product_name = item.brand + " " + item.model_name + " " + item.model_number
1322
    color = item.color
1323
    if color is not None and color != 'NA':
1324
        product_name = product_name + " (" + color + ")"
3201 rajveer 1325
    product_name = product_name.replace("  "," ")
3086 rajveer 1326
    return product_name
1327
 
1328
 
1329
def __get_product_url(item):
1330
    product_url = "http://www.saholic.com/mobile-phones/" + item.brand + "-" + item.model_name + "-" + item.model_number + "-" + str(item.catalog_item_id)
1331
    product_url = product_url.replace("--","-")
1332
    product_url = product_url.replace(" ","")
1333
    return product_url
1334
 
3348 varun.gupt 1335
def get_all_brands_by_category(category_id):
1336
    catm = CategoryManager()
1337
    child_categories = catm.getCategory(category_id).children_category_ids
1338
    brands = session.query(distinct(Item.brand)).filter(Item.category.in_(child_categories)).all()
1339
 
1340
    return [brand[0] for brand in brands]
3086 rajveer 1341
 
1342
def __enque_product_notification_email(email, product, date, url, itemId):
1343
 
1344
    html = """
1345
        <html>
1346
        <body>
1347
        <div>
1348
        <p>
1349
            Hi,<br /><br />
1350
            The product requested by you on $date is now available on saholic.com.
1351
        </p>
1352
 
1353
        <p>    
1354
        <strong>Product: $product </strong>
1355
        </p>
1356
 
1357
        <p>
1358
        Click the link below to visit the product: 
1359
        <br/>
1360
        $url
1361
        </p>
1362
        <p>
1363
        Regards,<br/>
1364
        Saholic Customer Support Team<br/>
1365
        www.saholic.com<br/>
1366
        Email: help@saholic.com<br/>
1367
        </p>
1368
        </div>
1369
        </body>
1370
        </html>
1371
        """
1372
 
1373
    html = Template(html).substitute(dict(product=product,date=date,url=url))
3079 rajveer 1374
 
3086 rajveer 1375
    try:
1376
        helper_client = HelperClient().get_client()
1377
        helper_client.saveUserEmailForSending(email, "", "Product requested by you is available now.", html, str(itemId), "ProductNotification")
1378
    except Exception as e:
1379
        print e
1380
 
3557 rajveer 1381
def get_all_sources():
1382
    sources = Source.query.all()
1383
    return [to_t_source(source) for source in sources]
3086 rajveer 1384
 
3557 rajveer 1385
def get_item_pricing_by_source(itemId, sourceId):
1386
    item = Item.query.filter_by(id=itemId).first()
1387
    if item is None:
1388
        raise InventoryServiceException(101, "Bad Item")
1389
 
1390
    source = Source.query.filter_by(id=sourceId).first()
1391
    if source is None:
1392
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1393
 
1394
    item_pricing = SourceItemPricing.query.filter_by(source=source, item=item).first()
1395
    if item_pricing is None:
1396
        raise InventoryServiceException(101, "Pricing information not found for sourceId " + str(sourceId))
1397
    return item_pricing
1398
 
1399
def add_source_item_pricing(sourceItemPricing):
1400
    if not sourceItemPricing:
1401
        raise InventoryServiceException(108, "Bad sourceItemPricing in request")
1402
 
1403
    if not sourceItemPricing.sellingPrice:
4326 mandeep.dh 1404
        raise InventoryServiceException(101, "Selling Price is not defined for sourceId " + str(sourceItemPricing.sourceId))
3557 rajveer 1405
 
1406
    sourceId = sourceItemPricing.sourceId
1407
    itemId = sourceItemPricing.itemId
1408
 
1409
    item = Item.query.filter_by(id=itemId).first()
1410
    if item is None:
1411
        raise InventoryServiceException(101, "Bad Item")
1412
 
1413
    source = Source.query.filter_by(id=sourceId).first()
1414
    if source is None:
1415
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1416
 
3564 rajveer 1417
    ds_sourceItemPricing = SourceItemPricing.get_by(source=source, item=item)
3557 rajveer 1418
    if ds_sourceItemPricing is None:
1419
        ds_sourceItemPricing = SourceItemPricing()
1420
        ds_sourceItemPricing.source = source
1421
        ds_sourceItemPricing.item = item
1422
 
1423
    if sourceItemPricing.mrp:
1424
        ds_sourceItemPricing.mrp = sourceItemPricing.mrp
1425
    ds_sourceItemPricing.sellingPrice = sourceItemPricing.sellingPrice
1426
 
1427
    session.commit()
1428
    return
1429
 
1430
def get_all_source_pricing(itemId):
1431
    item = Item.query.filter_by(id=itemId).first()
1432
    if item is None:
1433
        raise InventoryServiceException(101, "Bad Item")
1434
    source_pricing = SourceItemPricing.query.filter_by(item=item).all()
1435
    return source_pricing
1436
 
1437
 
1438
def get_item_for_source(item_id, sourceId):
1439
    item = get_item(item_id)
1440
    if sourceId == -1:
1441
        return item
1442
    try:
1443
        sip = get_item_pricing_by_source(item_id, sourceId)
1444
        item.sellingPrice = sip.sellingPrice
1445
        if sip.mrp:
1446
            item.mrp = sip.mrp
1447
    except:
1448
        print "No source pricing"
1449
    return item
1450
 
3872 chandransh 1451
def search_items(search_terms, offset, limit):
1452
    query = Item.query
1453
 
1454
    query_clause = []
1455
 
1456
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1457
 
1458
    for search_term in search_terms:
1459
        query_clause.append(Item.brand.like(search_term))
1460
        query_clause.append(Item.model_number.like(search_term))
1461
        query_clause.append(Item.model_name.like(search_term))
1462
 
1463
    query = query.filter(or_(*query_clause))
1464
 
1465
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
1466
    if limit:
1467
        query = query.limit(limit)
1468
    items = query.all()
1469
    return items
1470
 
1471
def get_search_result_count(search_terms):
1472
    query = Item.query
1473
 
1474
    query_clause = []
1475
 
1476
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1477
 
1478
    for search_term in search_terms:
1479
        query_clause.append(Item.brand.like(search_term))
1480
        query_clause.append(Item.model_number.like(search_term))
1481
        query_clause.append(Item.model_name.like(search_term))
1482
 
1483
    query = query.filter(or_(*query_clause))
1484
 
1485
    return query.count()
1486
 
3924 rajveer 1487
def __clear_homepage_cache():
1488
    try:
1489
        # create a password manager
1490
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
1491
        # Add the username and password.
1492
        configclient = ConfigClient()
4310 rajveer 1493
        ips = configclient.get_property("production_servers_private_ips");
3924 rajveer 1494
        ips = ips.split(" ")
1495
 
1496
        for ip in ips:
4310 rajveer 1497
            try:
1498
                top_level_url = "http://" + ip + ":8080/"
1499
                password_mgr.add_password(None, top_level_url, "saholic", "shop2020")
1500
                handler = urllib2.HTTPBasicAuthHandler(password_mgr)
3924 rajveer 1501
 
4310 rajveer 1502
                opener = urllib2.build_opener(handler)
3924 rajveer 1503
 
4310 rajveer 1504
                # use the opener to fetch a URL
1505
                res = opener.open(top_level_url + "cache-admin/HomePageSnippets?_method=delete")
1506
                print "Successfully cleared home page cache" + res.read()
1507
            except:
1508
                print "Unable to clear home page cache" + res.read()
3924 rajveer 1509
    except:
1510
        print "Unable to clear cache, still should continue with other operations"
4024 chandransh 1511
 
4062 chandransh 1512
def get_pending_orders_inventory(vendor_id=1):
4024 chandransh 1513
    """
1514
    Returns a list of inventory stock for items for which there are pending orders.
1515
    """
4341 rajveer 1516
 
4368 rajveer 1517
    warehouse_ids = [warehouse.id for warehouse in get_warehouses_for_vendor(vendor_id)]
4064 chandransh 1518
    pending_items_inventory = []
1519
    if warehouse_ids:
1520
        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 1521
    return pending_items_inventory
4295 varun.gupt 1522
 
1523
def get_product_notifications(start_datetime):
1524
    '''
1525
    Returns a list of Product Notification objects each representing user requests for notification
1526
    '''
1527
    query = ProductNotification.query
3924 rajveer 1528
 
4295 varun.gupt 1529
    if start_datetime:
1530
        query = query.filter(ProductNotification.addedOn > start_datetime)
1531
 
1532
    notifications = query.order_by(desc('addedOn')).all()
1533
    return notifications
1534
 
1535
def get_product_notification_request_count(start_datetime):
1536
    '''
1537
    Returns list of items and the counts of product notification requests
1538
    '''
1539
    print start_datetime
1540
    query = session.query(ProductNotification, func.count(ProductNotification.email).label('count'))
1541
 
1542
    if start_datetime:
1543
        query = query.filter(ProductNotification.addedOn > start_datetime)
1544
 
1545
    counts = query.group_by(ProductNotification.item_id).order_by(desc('count')).all()
1546
    return counts
1547
 
766 rajveer 1548
def close_session():
1549
    if session.is_active:
1550
        print "session is active. closing it."
1399 rajveer 1551
        session.close()
3376 rajveer 1552
 
1553
def is_alive():
1554
    try:
1555
        session.query(Item.id).limit(1).one()
1556
        return True
1557
    except:
1558
        return False
4332 anupam.sin 1559
 
1560
def add_vendor(vendor):
1561
    if not vendor:
1562
        raise InventoryServiceException(108, "Bad vendor")
1563
    if get_Vendor(vendor.id):
1564
        #vendor is already present.
1565
        raise InventoryServiceException(101, "Vendor already present")
1566
 
1567
    ds_vendor = Vendor()
1568
    ds_vendor.id = vendor.id
1569
    ds_vendor.name = vendor.name
1570
    session.commit()
1571
    return ds_vendor.id
1572
 
1573
def add_warehouse_vendor_mapping(warehouse_id, VendorId):
1574
    return True
1575
 
1576
def get_vendors_for_warehouse(warehouse_id):
1577
    try:
1578
        warehouse = Warehouse.get_by(id=warehouse_id)
1579
        return warehouse.vendors
1580
    except:
1581
        raise InventoryServiceException(108, "Bad Warehouse Id")
1582
 
1583
def get_warehouses_for_vendor(vendorId):
1584
    try:
1585
        vendor = get_Vendor(vendorId)
1586
        return vendor.warehouses
1587
    except:
4649 phani.kuma 1588
        raise InventoryServiceException(108, "Bad Vendor Id")
1589
 
1590
def add_authorization_log_for_item(itemId, username, reason):
1591
    if not itemId or not username:
1592
        raise InventoryServiceException(101, "Bad itemId or Invalid username in request")
1593
    authorize_log = AuthorizationLog()
1594
    authorize_log.item_id = itemId
1595
    authorize_log.username = username
1596
    authorize_log.reason = reason
1597
    session.commit()
4797 rajveer 1598
    return True
1599
 
1600
def __send_mail_for_oos_item(item): 
1601
    try:
4876 mandeep.dh 1602
        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 1603
    except Exception as e:
1604
        print e