Subversion Repositories SmartDukaan

Rev

Rev 2428 | Rev 2621 | 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 *
7
from shop2020.model.v1.catalog.impl import DataService
122 ashish 8
from shop2020.model.v1.catalog.impl.DataService import Item, \
103 ashish 9
    Warehouse, ItemInventoryHistory, CurrentInventorySnapshot, ItemInfo,\
1368 chandransh 10
    ItemChangeLog, Category, EntityIDGenerator, VendorItemPricing,\
1991 ankur.sing 11
    VendorItemMapping, Vendor
122 ashish 12
from shop2020.thriftpy.model.v1.catalog.ttypes import \
13
    InventoryServiceException, status
2065 ankur.sing 14
from shop2020.model.v1.catalog.impl.Convertors import to_t_item,\
15
    to_t_vendor_item_pricing
94 ashish 16
import datetime
871 chandransh 17
import sys
2286 ankur.sing 18
from shop2020.utils.Utils import log_entry, to_py_date, log_risky_flag
621 chandransh 19
from sqlalchemy import desc, asc
1970 rajveer 20
from shop2020.model.v1.catalog.impl.CategoryManager import CategoryManager
2404 chandransh 21
from sqlalchemy.sql.expression import and_, distinct, func
94 ashish 22
 
23
def initialize():
24
    DataService.initialize()
25
 
26
 
103 ashish 27
def get_all_items(is_active):
28
    if is_active:
766 rajveer 29
        items = Item.query.filter_by(status= status.ACTIVE).all()
103 ashish 30
    else:
766 rajveer 31
        items = Item.query.all()
32
    return items
33
 
103 ashish 34
def get_all_items_by_status(status):
2174 ankur.sing 35
    if status == None:
103 ashish 36
        #return all items
766 rajveer 37
        items = get_all_items(False)
103 ashish 38
    else:
766 rajveer 39
        items = Item.query.filter_by(status=status).all()
40
    return items
103 ashish 41
 
635 rajveer 42
def get_item(item_id):
766 rajveer 43
    item = Item.get_by(id=item_id)
44
    return item
94 ashish 45
 
635 rajveer 46
def get_items_by_catalog_id(catalog_id):
447 rajveer 47
    query = Item.query.filter_by(catalog_item_id=catalog_id)
437 rajveer 48
    try:
635 rajveer 49
        items = query.all()
50
        return get_thrift_item_list(items)
1399 rajveer 51
    except Exception as ex:
52
        print ex
437 rajveer 53
        raise InventoryServiceException(109, "Item not found")
54
 
576 chandransh 55
def is_active(item_id):
56
    try:
635 rajveer 57
        item = get_item(item_id)
576 chandransh 58
        return item.status == status.ACTIVE
59
    except InventoryServiceException:
60
        return False
2035 rajveer 61
 
62
def get_item_status_description(itemId):
63
    item = get_item(itemId)
64
    return item.status_description
563 chandransh 65
 
94 ashish 66
def get_Warehouse(warehouse_id):
67
    return Warehouse.get_by(id=warehouse_id)
68
 
122 ashish 69
def get_all_warehouses_by_status(status):
70
    if not status:
766 rajveer 71
        warehouses = Warehouse.query.all()
122 ashish 72
    else:
851 chandransh 73
        warehouses = Warehouse.query.filter_by(status=status).all()
74
    return warehouses
122 ashish 75
 
94 ashish 76
def get_all_warehouses_for_item(item_id):
635 rajveer 77
    item = get_item(item_id)
94 ashish 78
    if not item:
122 ashish 79
        raise InventoryServiceException(108, "Some unforeseen error while obtaining item")
80
    return item.get_all_warehouses
94 ashish 81
 
122 ashish 82
def get_all_items_for_warehouse(warehouse_id):
83
    warehouse = get_Warehouse(warehouse_id)
84
    if not warehouse:
85
        raise InventoryServiceException(108, "bad warehouse")
86
    return warehouse.all_items
87
 
94 ashish 88
def add_warehouse(warehouse):
103 ashish 89
    if not warehouse:
122 ashish 90
        raise InventoryServiceException(108, "Bad warehouse")
103 ashish 91
    if get_Warehouse(warehouse.id):
92
        #warehouse is already present.
122 ashish 93
        raise InventoryServiceException(101, "Warehouse already present")
103 ashish 94
 
94 ashish 95
    ds_warehouse = Warehouse()
96
    ds_warehouse.id = warehouse.id
97
    ds_warehouse.location = warehouse.location
122 ashish 98
    ds_warehouse.status = status.ACTIVE
103 ashish 99
    ds_warehouse.addedOn = datetime.datetime.now()
483 rajveer 100
    ds_warehouse.lastCheckedOn = datetime.datetime.now()
101
    ds_warehouse.tinNumber = warehouse.tinNumber
102
    ds_warehouse.pincode = warehouse.pincode
103
    if warehouse.vendorString:
104
        ds_warehouse.vendorString = warehouse.vendorString
94 ashish 105
    session.commit()
103 ashish 106
    return ds_warehouse.id
94 ashish 107
 
122 ashish 108
def update_item(item):
109
    if not item:
110
        raise InventoryServiceException(108, "Bad item in request")
111
 
112
    if not item.id:
609 chandransh 113
        raise InventoryServiceException(101, "Missing id for update")
122 ashish 114
 
2120 ankur.sing 115
    validate_item_prices(item)
2065 ankur.sing 116
 
635 rajveer 117
    ds_item = get_item(item.id)
122 ashish 118
 
119
    if not ds_item:
609 chandransh 120
        raise InventoryServiceException(101, "Item missing in our database")
122 ashish 121
 
963 chandransh 122
    if item.productGroup:
123
        ds_item.product_group = item.productGroup 
124
    if item.brand:
125
        ds_item.brand = item.brand
511 rajveer 126
    if item.modelNumber:
127
        ds_item.model_number = item.modelNumber
2497 ankur.sing 128
    ds_item.color = item.color
129
    ds_item.model_name = item.modelName
130
    ds_item.category = item.category
131
    ds_item.comments = item.comments
511 rajveer 132
 
2497 ankur.sing 133
    ds_item.catalog_item_id = item.catalogItemId
483 rajveer 134
 
2129 ankur.sing 135
    ds_item.mrp = item.mrp
136
    ds_item.sellingPrice = item.sellingPrice
137
 
2497 ankur.sing 138
    ds_item.mop = item.mop
139
    ds_item.dealerPrice = item.dealerPrice
140
    ds_item.transfer_price = item.transferPrice
141
 
2174 ankur.sing 142
    ds_item.weight = item.weight
2129 ankur.sing 143
 
2358 ankur.sing 144
    if ds_item.status != item.itemStatus:
2402 rajveer 145
        add_status_change_log(ds_item, item.itemStatus)
2358 ankur.sing 146
        ds_item.status = item.itemStatus
2035 rajveer 147
    if item.status_description:
148
        ds_item.status_description = item.status_description
122 ashish 149
 
511 rajveer 150
    if item.startDate:
2116 ankur.sing 151
        ds_item.startDate = to_py_date(item.startDate)
2497 ankur.sing 152
    else:
153
        ds_item.startDate = None
511 rajveer 154
    if item.retireDate:
2116 ankur.sing 155
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 156
    else:
157
        ds_item.retireDate = None
511 rajveer 158
 
2497 ankur.sing 159
    ds_item.feature_id = item.featureId
160
    ds_item.feature_description = item.featureDescription
122 ashish 161
 
2129 ankur.sing 162
    ds_item.bestDealText = item.bestDealText
163
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 164
    ds_item.bestSellingRank = item.bestSellingRank
2497 ankur.sing 165
 
2065 ankur.sing 166
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 167
    ds_item.risky = item.risky
2347 ankur.sing 168
    ds_item.updatedOn = datetime.datetime.now()
2065 ankur.sing 169
 
122 ashish 170
    session.commit();
171
    return ds_item.id
94 ashish 172
 
2116 ankur.sing 173
def check_vendor_item_mapping(product_group, brand, model_number, color, vendor_id, vendor_category):
174
    key = product_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
175
    try:
176
        vim = VendorItemMapping.query.filter_by(vendor_id=vendor_id, item_key=key, vendor_category=vendor_category).one()
177
        return True
178
    except:
179
        return False
180
 
103 ashish 181
def add_item(item):
182
    if not item:
122 ashish 183
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 184
    if get_item(item.id):
122 ashish 185
        raise InventoryServiceException(101, "Item already exists")
2120 ankur.sing 186
 
187
    validate_item_prices(item)
188
 
103 ashish 189
    ds_item = Item()
963 chandransh 190
    if item.productGroup:
191
        ds_item.product_group = item.productGroup
192
    if item.brand:
193
        ds_item.brand = item.brand
515 rajveer 194
    if item.modelName:
195
        ds_item.model_name = item.modelName
196
    if item.modelNumber:
197
        ds_item.model_number = item.modelNumber
609 chandransh 198
    if item.color:
199
        ds_item.color = item.color
2116 ankur.sing 200
    if item.hotspotCategory:
201
        ds_item.hotspotCategory = item.hotspotCategory
202
        if item.hotspotCategory == 'Handsets':
2403 ankur.sing 203
            ds_item.preferredWarehouse = 1
2116 ankur.sing 204
        else:
2403 ankur.sing 205
            ds_item.preferredWarehouse = 2
2116 ankur.sing 206
 
483 rajveer 207
    if item.category:
208
        ds_item.category = item.category
209
    if item.comments:
210
        ds_item.comments = item.comments
211
 
103 ashish 212
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 213
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 214
    if item.startDate:
215
        ds_item.startDate = to_py_date(item.startDate)
216
    if item.retireDate:
217
        ds_item.retireDate = to_py_date(item.retireDate)
609 chandransh 218
 
483 rajveer 219
    if item.mrp:
220
        ds_item.mrp = item.mrp
221
    if item.mop:
222
        ds_item.mop = item.mop
223
    if item.sellingPrice:
224
        ds_item.sellingPrice = item.sellingPrice
609 chandransh 225
    if item.dealerPrice:
226
        ds_item.dealerPrice = item.dealerPrice
2116 ankur.sing 227
    if item.transferPrice:
228
        ds_item.transfer_price = item.transferPrice
122 ashish 229
    if item.weight:
230
        ds_item.weight = item.weight
231
 
232
    if item.featureId:
233
        ds_item.feature_id = item.featureId
234
    if item.featureDescription:
235
        ds_item.feature_description = item.featureDescription
236
 
103 ashish 237
    if item.otherInfo:
238
        for k,v in item.otherInfo.iteritems():
239
            info = ItemInfo()
240
            info.key = k
241
            info.value = v
242
            ds_item.iteminfo.append(info)
2116 ankur.sing 243
 
103 ashish 244
    #check if categories present. If yes, add them to system
122 ashish 245
 
609 chandransh 246
    if item.bestDealValue:
247
        ds_item.bestDealValue = item.bestDealValue
248
    if item.bestDealText:
249
        ds_item.bestDealText = item.bestDealText
2116 ankur.sing 250
    if item.bestSellingRank:
251
        ds_item.bestSellingRank = item.bestSellingRank
252
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 253
    ds_item.risky = item.risky
609 chandransh 254
 
2116 ankur.sing 255
    # Check if a similar item already exists in our database
256
    similar_item = Item.query.filter_by(product_group=item.productGroup, brand = item.brand, model_number=item.modelNumber, hotspotCategory=item.hotspotCategory).first()
257
    print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2} {3} {4}".format(item.productGroup, item.brand, item.modelNumber, item.hotspotCategory, item.color)
258
 
259
    if similar_item is None or similar_item.catalog_item_id is None:
260
        # If there is no similar item in the database from before,
261
        # use the entity_id_generator
262
        entity_id = EntityIDGenerator.query.first()
263
        ds_item.catalog_item_id = entity_id.id + 1
264
        ds_item.status = status.IN_PROCESS
265
        ds_item.status_description = "This item is in process."
266
        entity_id.id = entity_id.id  + 1
267
    else:
268
        #If a similar item already exists for a product group, brand and model_number, set it as same.
269
        ds_item.catalog_item_id = similar_item.catalog_item_id
270
        ds_item.category = similar_item.category
271
        ds_item.status = similar_item.status
272
        ds_item.status_description = similar_item.status_description
273
 
103 ashish 274
    session.commit();
609 chandransh 275
    return ds_item.id       
103 ashish 276
 
483 rajveer 277
def update_inventory(warehouse_id, timestamp, availability):
278
    warehouse = get_Warehouse(warehouse_id)
279
    if not warehouse:
280
        raise InventoryServiceException(107, "Warehouse? Where?")
281
 
282
    time = datetime.datetime.now()
283
    warehouse.lastCheckedOn = time
284
    warehouse.vendorString = timestamp
1368 chandransh 285
    vendor = warehouse.vendor
2368 ankur.sing 286
    session.commit()
1368 chandransh 287
    for item_key, quantity in availability.iteritems():
483 rajveer 288
        try:
1368 chandransh 289
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
290
            item = vendor_item_mapping.item
494 rajveer 291
        except:
292
            continue  
293
        try:
483 rajveer 294
            item_inventory_history = ItemInventoryHistory()
295
            item_inventory_history.warehouse = warehouse
296
            item_inventory_history.item = item
297
            item_inventory_history.timestamp = time
298
            item_inventory_history.availibility = quantity
299
 
300
            current_inventory_snapshot = CurrentInventorySnapshot.get_by(item=item, warehouse=warehouse)
301
            if not current_inventory_snapshot:
302
                current_inventory_snapshot = CurrentInventorySnapshot()
303
                current_inventory_snapshot.item = item
304
                current_inventory_snapshot.warehouse = warehouse
305
                current_inventory_snapshot.availibility = 0
871 chandransh 306
                current_inventory_snapshot.reserved = 0
483 rajveer 307
            # added the difference in the current inventory    
308
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
309
        except:
310
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
2368 ankur.sing 311
        session.commit() 
312
        check_risky_item(item)
483 rajveer 313
 
94 ashish 314
def get_item_inventoy(item_id):
315
 
316
    inventory = Item.get_by(id=item_id).currentInventory
317
    if not inventory:
122 ashish 318
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
94 ashish 319
    return inventory
320
 
635 rajveer 321
def get_item_inventory_by_item_id(item_id):
322
    inventory = Item.get_by(id=item_id).currentInventory
379 ashish 323
    if not inventory:
324
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
325
    return inventory
326
 
103 ashish 327
 
328
def retire_warehouse(warehouse_id):
329
    if not warehouse_id:
122 ashish 330
        raise InventoryServiceException(101, "Bad warehouse id")
103 ashish 331
    warehouse = get_Warehouse(warehouse_id)
332
    if not warehouse:
122 ashish 333
        raise InventoryServiceException(108, "warehouse id not present")
334
    warehouse.status = status.DELETED;
103 ashish 335
    session.commit()
336
 
337
def retire_item(item_id):
338
    if not item_id:
122 ashish 339
        raise InventoryServiceException(101, "bad item id")
635 rajveer 340
    item = get_item(item_id)
103 ashish 341
    if not item:
122 ashish 342
        raise InventoryServiceException(108, "item id not present")
343
    item.status = status.PHASED_OUT
344
    item.retireDate = datetime.datetime.now()
103 ashish 345
    session.commit()
122 ashish 346
 
347
#need to implement threads based solution here
103 ashish 348
def start_item_on(item_id, timestamp):
349
    if not item_id:
122 ashish 350
        raise InventoryServiceException(101, "bad item id")
635 rajveer 351
    item = get_item(item_id)
103 ashish 352
    if not item:
122 ashish 353
        raise InventoryServiceException(108, "item id not present")
103 ashish 354
 
122 ashish 355
    item.status = status.ACTIVE
356
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
357
    add_status_change_log(item, status.ACTIVE)
103 ashish 358
    session.commit()
359
 
122 ashish 360
#need to implement threads here
103 ashish 361
def retire_item_on(item_id, timestamp):
362
    if not item_id:
122 ashish 363
        raise InventoryServiceException(101, "bad item id")
635 rajveer 364
    item = get_item(item_id)
103 ashish 365
    if not item:
122 ashish 366
        raise InventoryServiceException(108, "item id not present")
103 ashish 367
 
122 ashish 368
    item.status = status.PHASED_OUT
369
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
370
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 371
    session.commit()
372
 
373
def add_status_change_log(item, new_status):
374
    item_change_log = ItemChangeLog()
375
    item_change_log.new_status = new_status
376
    item_change_log.old_status = item.status
377
    item_change_log.timestamp = datetime.datetime.now()
378
    item_change_log.item = item
379
    session.commit()
380
 
381
def change_item_status(item_id, new_status):
382
    if not item_id:
122 ashish 383
        raise InventoryServiceException(101, "bad item id")
635 rajveer 384
    item = get_item(item_id)
103 ashish 385
    if not item:
122 ashish 386
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 387
    add_status_change_log(item, new_status)
122 ashish 388
    item.status = new_status
2251 ankur.sing 389
    if item.status == status.PHASED_OUT:
390
        item.status_description = "This item has been phased out"
391
    elif item.status == status.DELETED:
392
        item.status_description = "This item has been deleted"
393
    elif item.status == status.PAUSED:
394
        item.status_description = "This item is currently out of stock"        
395
    elif item.status == status.ACTIVE:
396
        item.status_description = "This item is active"
397
    elif item.status == status.IN_PROCESS:
398
        item.status_description = "This item is in process"
399
    elif item.status == status.CONTENT_COMPLETE:
400
        item.status_description = "This item is in process"
103 ashish 401
    session.commit()
402
 
403
def get_item_availability_for_warehouse(warehouse_id, item_id):
404
    if not warehouse_id:
122 ashish 405
        raise InventoryServiceException(101, "bad warehouse_id")
103 ashish 406
    if not item_id:
122 ashish 407
        raise InventoryServiceException(101, "bad item_id")
103 ashish 408
 
409
    warehouse = get_Warehouse(warehouse_id)
410
    if not warehouse:
122 ashish 411
        raise InventoryServiceException(108, "warehouse does not exist")
635 rajveer 412
    item = get_item(item_id)
504 rajveer 413
 
103 ashish 414
    if not item:
766 rajveer 415
        raise InventoryServiceException(108, "item does not exist")
122 ashish 416
 
494 rajveer 417
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id)
504 rajveer 418
    query = query.filter_by(item_id = item.id)
494 rajveer 419
    try:
420
        current_inventory_snapshot = query.one()
871 chandransh 421
        return current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
494 rajveer 422
    except:
423
        return 0
424
    """
425
    current_inventory_snapshot = CurrentInventorySnapshot.query.filter(CurrentInventorySnapshot.warehouse_id == warehouse_id, CurrentInventorySnapshot.item_id == item_id).one()
103 ashish 426
    if not current_inventory_snapshot:
427
        return 0
428
    else:
429
        return current_inventory_snapshot.availibility
494 rajveer 430
    """
643 chandransh 431
 
2368 ankur.sing 432
def check_risky_item(item):
2251 ankur.sing 433
    if not item.risky:
434
        return
2368 ankur.sing 435
    all_inventory = CurrentInventorySnapshot.query.filter_by(item = item).all()
436
    availibility = 0
437
    reserved = 0
438
    for currInv in all_inventory:
439
        availibility = availibility + currInv.availibility
440
        reserved = reserved + currInv.reserved 
441
    if availibility - reserved <= 0:
2251 ankur.sing 442
        if item.status == status.ACTIVE:
443
            change_item_status(item.id, status.PAUSED)
444
    else:
445
        if item.status == status.PAUSED:
446
            change_item_status(item.id, status.ACTIVE)
2368 ankur.sing 447
    session.commit()
2251 ankur.sing 448
 
871 chandransh 449
def reserve_item_in_warehouse(item_id, warehouse_id, quantity):    
450
    if not warehouse_id:
451
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 452
    item = get_item(item_id)
453
    if not item:
871 chandransh 454
        raise InventoryServiceException(101, "bad item_id")
455
 
456
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
457
    try:
458
        current_inventory_snapshot = query.one()
459
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved + quantity
460
        session.commit()
2368 ankur.sing 461
        check_risky_item(item)
871 chandransh 462
        return True
463
    except:
464
        print "Unexpected error:", sys.exc_info()[0]
465
        return False
466
 
467
def reduce_reservation_count(item_id, warehouse_id, quantity):
468
    if not warehouse_id:
469
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 470
    item = get_item(item_id)
471
    if not item:
871 chandransh 472
        raise InventoryServiceException(101, "bad item_id")
473
 
474
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
475
    try:
476
        current_inventory_snapshot = query.one()
477
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved - quantity
478
        session.commit()
2368 ankur.sing 479
        check_risky_item(item)
871 chandransh 480
        return True
481
    except:
482
        print "Unexpected error:", sys.exc_info()[0]
483
        return False
484
 
2075 rajveer 485
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
723 chandransh 486
    content_complete_status = status.CONTENT_COMPLETE
1294 chandransh 487
    items = Item.query.filter_by(catalog_item_id=entity_id, status=status.IN_PROCESS).all()
723 chandransh 488
    current_timestamp = datetime.datetime.now()
489
    for item in items:
490
        item_change_log = ItemChangeLog()
491
        item_change_log.old_status = item.status
492
        item_change_log.new_status = content_complete_status
493
        item_change_log.timestamp = current_timestamp
494
        item_change_log.item = item
495
 
496
        item.status = content_complete_status
2075 rajveer 497
        item.category = category
498
        item.brand = brand
2081 rajveer 499
        item.model_name = modelName
500
        item.model_number = modelNumber
723 chandransh 501
        item.updatedOn = current_timestamp
502
    session.commit()
503
    return True
1294 chandransh 504
 
643 chandransh 505
def get_item_availability_for_location(warehouse_loc, item_id):
506
    if warehouse_loc is None:
507
        raise InventoryServiceException(101, "Bad Warehouse Location")
508
    if not item_id:
1416 chandransh 509
        raise InventoryServiceException(101, "Bad Item id")
643 chandransh 510
 
1416 chandransh 511
    item = Item.get_by(id=item_id)
643 chandransh 512
    warehouses = Warehouse.query.filter_by(logisticsLocation=warehouse_loc).all()
513
    warehouse_ids = [warehouse.id for warehouse in warehouses]
514
    warehouse_retid = -1
515
    global_availability = 0
516
    for warehouse_id in warehouse_ids:
785 rajveer 517
        try:
871 chandransh 518
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id).one()
519
            availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
785 rajveer 520
        except:
521
            availability = 0    
643 chandransh 522
        if availability > global_availability:
523
            warehouse_retid = warehouse_id
524
            global_availability = availability
2341 chandransh 525
 
643 chandransh 526
    if warehouse_retid == -1:
759 chandransh 527
        # This is the case when all warehouses have exhausted their
528
        # inventory of this item or no warehouse is available in this
529
        # location.
1416 chandransh 530
        warehouse_retid = int(item.preferredWarehouse)
2344 chandransh 531
        warehouse = Warehouse.get_by(id=warehouse_retid)
2341 chandransh 532
        try:
533
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_retid, item_id = item_id).one()
534
            global_availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
535
        except:
536
            global_availability = 0
643 chandransh 537
 
2341 chandransh 538
    return [warehouse.logisticsLocation, warehouse_retid, global_availability]
539
 
122 ashish 540
def get_warehouses_for_item(item_id):
643 chandransh 541
 
122 ashish 542
    if not item_id:
543
        raise InventoryServiceException(101, "bad item_id")
635 rajveer 544
    item = get_item(item_id)
122 ashish 545
 
546
    if not item:
547
        raise InventoryServiceException(101, "bad item")
548
 
483 rajveer 549
    warehouses = item.currentInventory.warehouse
501 rajveer 550
    return warehouses
551
 
2404 chandransh 552
def get_child_categories(category):
553
    cm = CategoryManager()
554
    return cm.getCategory(category).children_category_ids
555
 
626 chandransh 556
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 557
    '''
558
    Returns the Best Sellers between the start and the stop index in the given category
559
    '''
1926 rajveer 560
    query = get_best_sellers_query(category, None)
1098 chandransh 561
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 562
    return get_thrift_item_list(best_sellers)
563
 
2093 chandransh 564
def get_best_sellers_count(category=-1):
2404 chandransh 565
    '''
566
    Returns the number of best sellers in the given category
567
    '''
1926 rajveer 568
    count = get_best_sellers_query(category, None).count()
1120 rajveer 569
    if count is None:
570
        count = 0
766 rajveer 571
    return count
621 chandransh 572
 
1926 rajveer 573
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 574
    '''
575
    Returns the Best sellers for the given brand and category between the start and the stop index.
576
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
577
    '''
1926 rajveer 578
    query = get_best_sellers_query(category, brand)
1098 chandransh 579
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 580
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 581
 
1926 rajveer 582
def get_best_sellers_query(category, brand):
2404 chandransh 583
    '''
584
    Returns the query to be used for getting Best Sellers.
585
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
586
    '''
1098 chandransh 587
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 588
    if category != -1:
1970 rajveer 589
        all_categories = [category]
590
        child_categories = get_child_categories(category)
591
        if child_categories is not None:
592
            all_categories = all_categories + child_categories 
593
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 594
    if brand is not None:
595
        query = query.filter_by(brand=brand)
1098 chandransh 596
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 597
    return query
609 chandransh 598
 
1098 chandransh 599
def get_best_deals(category=-1):
2404 chandransh 600
    '''
601
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
602
    '''
603
    query = get_best_deals_query(Item, category, None)
1098 chandransh 604
    items = query.all()
609 chandransh 605
    return get_thrift_item_list(items)
606
 
1098 chandransh 607
def get_best_deals_count(category=-1):
2404 chandransh 608
    '''
609
    Returns the count of best deals in the given category.
610
    Ignores the category if it's -1.
611
    '''
612
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 613
    if count is None:
614
        count = 0
766 rajveer 615
    return count
501 rajveer 616
 
1926 rajveer 617
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 618
    '''
619
    Returns the catalog_item_ids of best deal items for the given brand and category.
620
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
621
    '''
622
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 623
    best_deal_items = query.all()[start_index:stop_index]
624
    return [item.catalog_item_id for item in best_deal_items]
625
 
2404 chandransh 626
def get_best_deals_counting_query(obj, category, brand):
627
    '''
628
    Returns the query to be used to select the best deals in the given brand and category.
629
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
630
    '''
631
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 632
    if category != -1:
1970 rajveer 633
        all_categories = [category]
634
        child_categories = get_child_categories(category)
635
        if child_categories is not None:
636
            all_categories = all_categories + child_categories 
637
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 638
    if brand is not None:
639
        query = query.filter_by(brand=brand)
2404 chandransh 640
    return query
641
 
642
def get_best_deals_query(obj, category, brand):
643
    '''
644
    Returns the query to be used to get the best deals in the given category and brand.
645
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
646
    '''
647
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 648
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
649
    return query
609 chandransh 650
 
1098 chandransh 651
def get_latest_arrivals(limit, category=-1):
2404 chandransh 652
    '''
653
    Returns up to limit number of Latest Arrivals in the given category.
654
    '''
655
    query = get_latest_arrivals_query(Item, category, None)
1098 chandransh 656
    items = query.all()[0:limit]
609 chandransh 657
    return get_thrift_item_list(items)
598 chandransh 658
 
1098 chandransh 659
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 660
    '''
661
    Returns the number of latest arrivals which will be displayed on the website.
662
    Ignores the category if it's passed as -1.
663
    '''
664
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 665
    if count is None:
666
        count = 0
667
    count = min(count, limit)
766 rajveer 668
    return count
602 chandransh 669
 
1926 rajveer 670
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 671
    '''
672
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
673
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
674
    '''
675
    query = get_latest_arrivals_query(Item, category, brand)
1098 chandransh 676
    latest_arrivals = query.all()[start_index:stop_index]
677
    return [item.catalog_item_id for item in latest_arrivals]
678
 
2404 chandransh 679
def get_latest_arrivals_counting_query(obj, category, brand):
680
    '''
681
    Returns the query to be used to count Latest arrivals.
682
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
683
    '''
684
    query = session.query(obj).filter_by(status=status.ACTIVE)
626 chandransh 685
    if category != -1:
1970 rajveer 686
        all_categories = [category]
687
        child_categories = get_child_categories(category)
688
        if child_categories is not None:
689
            all_categories = all_categories + child_categories 
690
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 691
    if brand is not None:
692
        query = query.filter_by(brand=brand)
2404 chandransh 693
    return query
694
 
695
def get_latest_arrivals_query(obj, category, brand):
696
    '''
697
    Returns the query to be used to retrieve Latest Arrivals.
698
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
699
    '''
700
    query = get_latest_arrivals_counting_query(obj, category, brand)
1098 chandransh 701
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
702
    return query
609 chandransh 703
 
704
def get_thrift_item_list(items):
1098 chandransh 705
    return [to_t_item(item) for item in items if item != None]
635 rajveer 706
 
1155 rajveer 707
def generate_new_entity_id():
708
    generator =  EntityIDGenerator.query.one()
709
    id = generator.id + 1
710
    generator.id = id
711
    session.commit()
712
    return id
713
 
635 rajveer 714
def put_category_object(object):
715
    category = Category.get_by(id=1)
716
    if category is None:
717
        category = Category()
718
    category.object = object    
719
    session.commit()
720
    return True
721
 
722
def get_category_object():
766 rajveer 723
    object = Category.get_by(id=1).object
724
    return object
725
 
1341 chandransh 726
def get_item_pricing(item_id, warehouse_id):
727
    item = Item.query.filter_by(id=item_id).first()
728
    if item is None:
729
        raise InventoryServiceException(101, "Bad Item")
730
 
731
    warehouse = get_Warehouse(warehouse_id)
732
    if not warehouse:
733
        raise InventoryServiceException(108, "Bad Warehouse")
734
    vendor = warehouse.vendor
735
 
736
    try:
737
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 738
        return item_pricing
1341 chandransh 739
    except sqlalchemy.orm.exc.MultipleResultsFound:
740
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
741
    except sqlalchemy.orm.exc.NoResultFound:
742
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
743
 
1970 rajveer 744
def add_category(t_category):
745
    category = Category.get_by(id=t_category.id)
746
    if category is None:
747
        category = Category()
748
    category.id = t_category.id 
749
    category.label = t_category.label
750
    category.description = t_category.description
751
    category.parent_category_id = t_category.parent_category_id 
752
    session.commit()
753
    return True
754
 
755
def get_category(id):
756
    return Category.query.filter_by(id=id).first()
757
 
758
def get_all_categories():
759
    return Category.query.all()
760
 
1991 ankur.sing 761
 
762
def get_all_item_pricing(item_id):
763
    item = Item.query.filter_by(id=item_id).first()
764
    if item is None:
765
        raise InventoryServiceException(101, "Bad Item")
766
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
767
    return item_pricing
768
 
2116 ankur.sing 769
def get_item_mappings(item_id):
770
    item = Item.query.filter_by(id=item_id).first()
771
    if item is None:
772
        raise InventoryServiceException(101, "Bad Item")
773
    item_mappings = VendorItemMapping.query.filter_by(item=item).all()
774
    return item_mappings
775
 
776
def add_vendor_pricing(vendorItemPricing):
1991 ankur.sing 777
    if not vendorItemPricing:
778
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
779
    vendorId = vendorItemPricing.vendorId
780
    itemId = vendorItemPricing.itemId
781
 
782
    try:
783
        vendor = Vendor.query.filter_by(id=vendorId).one()
784
    except:
785
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
786
 
787
    try:
788
        item = Item.query.filter_by(id=itemId).one()
789
    except:
790
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
791
 
2120 ankur.sing 792
    validate_vendor_prices(to_t_item(item), vendorItemPricing)
2065 ankur.sing 793
 
1991 ankur.sing 794
    try:
795
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
796
    except:
2116 ankur.sing 797
        ds_vendorItemPricing = VendorItemPricing()
798
        ds_vendorItemPricing.vendor = vendor
799
        ds_vendorItemPricing.item = item
1991 ankur.sing 800
 
801
    if vendorItemPricing.mop:
802
        ds_vendorItemPricing.mop = vendorItemPricing.mop
803
    if vendorItemPricing.dealerPrice:
804
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
805
    if vendorItemPricing.transferPrice:
2065 ankur.sing 806
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 807
 
808
    session.commit()
809
    return
810
 
2358 ankur.sing 811
def add_vendor_item_mapping(key, vendorItemMapping):
2116 ankur.sing 812
    if not vendorItemMapping:
813
        raise InventoryServiceException(108, "Bad vendorItemMapping in request")
814
    vendorId = vendorItemMapping.vendorId
815
    itemId = vendorItemMapping.itemId
816
 
817
    try:
818
        vendor = Vendor.query.filter_by(id=vendorId).one()
819
    except:
820
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
821
 
822
    try:
823
        item = Item.query.filter_by(id=itemId).one()
824
    except:
825
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
826
 
827
    try:
2358 ankur.sing 828
        ds_vendorItemMapping = VendorItemMapping.query.filter(and_(VendorItemMapping.vendor==vendor, VendorItemMapping.item==item, VendorItemMapping.item_key==key)).one()
2116 ankur.sing 829
    except:
830
        ds_vendorItemMapping = VendorItemMapping()
831
        ds_vendorItemMapping.vendor = vendor
832
        ds_vendorItemMapping.item = item
2497 ankur.sing 833
    ds_vendorItemMapping.vendor_category = vendorItemMapping.vendorCategory
2116 ankur.sing 834
    ds_vendorItemMapping.item_key = vendorItemMapping.itemKey
835
 
836
    session.commit()
837
    return
838
 
2120 ankur.sing 839
def validate_item_prices(item):
2129 ankur.sing 840
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
841
        return
842
    if item.mrp < item.sellingPrice:
2120 ankur.sing 843
        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))
844
        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 845
    return
2120 ankur.sing 846
 
847
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 848
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 849
        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))
850
        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)))
851
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
852
        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))
853
        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)))
854
    return
2065 ankur.sing 855
 
856
def get_all_vendors():
857
    return Vendor.query.all()
858
 
2116 ankur.sing 859
def check_similar_item(product_group, brand, model_number, color):
2129 ankur.sing 860
    query = Item.query
2428 ankur.sing 861
    query = query.filter_by(product_group=product_group)
862
    query = query.filter_by(brand=brand)
863
    query = query.filter_by(model_number=model_number)
2129 ankur.sing 864
    if color:
865
        query = query.filter_by(color=color)
866
    item = query.first()
2116 ankur.sing 867
    if item is None:
868
        return 0
869
    else:
870
        return item.id
2286 ankur.sing 871
 
872
def change_risky_flag(item_id, risky):
873
    item = get_item(item_id)
874
    if not item:
875
        raise InventoryServiceException(101, "Item missing in our database")
876
    try:
877
        log_risky_flag(item_id, risky)
878
    except:
879
        print "Not able to log risky flag change"
880
    item.risky = risky
2368 ankur.sing 881
    if not risky and item.status == status.PAUSED:
882
        change_item_status(item.id, status.ACTIVE)
2286 ankur.sing 883
    session.commit()
2368 ankur.sing 884
    check_risky_item(item)
2286 ankur.sing 885
 
2358 ankur.sing 886
def get_items_by_vendor_category(vendor_category):
887
    if not vendor_category:
888
        raise InventoryServiceException(101, "Invalid vendor category in request")
889
    query = Item.query.filter(and_(Item.hotspotCategory==vendor_category, Item.status != status.PHASED_OUT))
890
    items = query.all()
891
    return items
2116 ankur.sing 892
 
2358 ankur.sing 893
def get_risky_items():
894
    items = Item.query.filter_by(risky=True).all()
895
    return items
896
 
766 rajveer 897
def close_session():
898
    if session.is_active:
899
        print "session is active. closing it."
1399 rajveer 900
        session.close()