Subversion Repositories SmartDukaan

Rev

Rev 2497 | Rev 2809 | 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()
2621 varun.gupt 554
    cat = cm.getCategory(category)
555
    return cat.children_category_ids if cat else None
2404 chandransh 556
 
626 chandransh 557
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 558
    '''
559
    Returns the Best Sellers between the start and the stop index in the given category
560
    '''
1926 rajveer 561
    query = get_best_sellers_query(category, None)
1098 chandransh 562
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 563
    return get_thrift_item_list(best_sellers)
564
 
2093 chandransh 565
def get_best_sellers_count(category=-1):
2404 chandransh 566
    '''
567
    Returns the number of best sellers in the given category
568
    '''
1926 rajveer 569
    count = get_best_sellers_query(category, None).count()
1120 rajveer 570
    if count is None:
571
        count = 0
766 rajveer 572
    return count
621 chandransh 573
 
1926 rajveer 574
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 575
    '''
576
    Returns the Best sellers for the given brand and category between the start and the stop index.
577
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
578
    '''
1926 rajveer 579
    query = get_best_sellers_query(category, brand)
1098 chandransh 580
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 581
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 582
 
1926 rajveer 583
def get_best_sellers_query(category, brand):
2404 chandransh 584
    '''
585
    Returns the query to be used for getting Best Sellers.
586
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
587
    '''
1098 chandransh 588
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 589
    if category != -1:
1970 rajveer 590
        all_categories = [category]
591
        child_categories = get_child_categories(category)
592
        if child_categories is not None:
593
            all_categories = all_categories + child_categories 
594
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 595
    if brand is not None:
596
        query = query.filter_by(brand=brand)
1098 chandransh 597
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 598
    return query
609 chandransh 599
 
1098 chandransh 600
def get_best_deals(category=-1):
2404 chandransh 601
    '''
602
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
603
    '''
604
    query = get_best_deals_query(Item, category, None)
1098 chandransh 605
    items = query.all()
609 chandransh 606
    return get_thrift_item_list(items)
607
 
1098 chandransh 608
def get_best_deals_count(category=-1):
2404 chandransh 609
    '''
610
    Returns the count of best deals in the given category.
611
    Ignores the category if it's -1.
612
    '''
613
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 614
    if count is None:
615
        count = 0
766 rajveer 616
    return count
501 rajveer 617
 
1926 rajveer 618
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 619
    '''
620
    Returns the catalog_item_ids of best deal items for the given brand and category.
621
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
622
    '''
623
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 624
    best_deal_items = query.all()[start_index:stop_index]
625
    return [item.catalog_item_id for item in best_deal_items]
626
 
2404 chandransh 627
def get_best_deals_counting_query(obj, category, brand):
628
    '''
629
    Returns the query to be used to select the best deals in the given brand and category.
630
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
631
    '''
632
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 633
    if category != -1:
1970 rajveer 634
        all_categories = [category]
635
        child_categories = get_child_categories(category)
636
        if child_categories is not None:
637
            all_categories = all_categories + child_categories 
638
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 639
    if brand is not None:
640
        query = query.filter_by(brand=brand)
2404 chandransh 641
    return query
642
 
643
def get_best_deals_query(obj, category, brand):
644
    '''
645
    Returns the query to be used to get the best deals in the given category and brand.
646
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
647
    '''
648
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 649
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
650
    return query
609 chandransh 651
 
1098 chandransh 652
def get_latest_arrivals(limit, category=-1):
2404 chandransh 653
    '''
654
    Returns up to limit number of Latest Arrivals in the given category.
655
    '''
656
    query = get_latest_arrivals_query(Item, category, None)
1098 chandransh 657
    items = query.all()[0:limit]
609 chandransh 658
    return get_thrift_item_list(items)
598 chandransh 659
 
1098 chandransh 660
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 661
    '''
662
    Returns the number of latest arrivals which will be displayed on the website.
663
    Ignores the category if it's passed as -1.
664
    '''
665
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 666
    if count is None:
667
        count = 0
668
    count = min(count, limit)
766 rajveer 669
    return count
602 chandransh 670
 
1926 rajveer 671
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 672
    '''
673
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
674
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
675
    '''
676
    query = get_latest_arrivals_query(Item, category, brand)
1098 chandransh 677
    latest_arrivals = query.all()[start_index:stop_index]
678
    return [item.catalog_item_id for item in latest_arrivals]
679
 
2404 chandransh 680
def get_latest_arrivals_counting_query(obj, category, brand):
681
    '''
682
    Returns the query to be used to count Latest arrivals.
683
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
684
    '''
685
    query = session.query(obj).filter_by(status=status.ACTIVE)
626 chandransh 686
    if category != -1:
1970 rajveer 687
        all_categories = [category]
688
        child_categories = get_child_categories(category)
689
        if child_categories is not None:
690
            all_categories = all_categories + child_categories 
691
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 692
    if brand is not None:
693
        query = query.filter_by(brand=brand)
2404 chandransh 694
    return query
695
 
696
def get_latest_arrivals_query(obj, category, brand):
697
    '''
698
    Returns the query to be used to retrieve Latest Arrivals.
699
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
700
    '''
701
    query = get_latest_arrivals_counting_query(obj, category, brand)
1098 chandransh 702
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
703
    return query
609 chandransh 704
 
705
def get_thrift_item_list(items):
1098 chandransh 706
    return [to_t_item(item) for item in items if item != None]
635 rajveer 707
 
1155 rajveer 708
def generate_new_entity_id():
709
    generator =  EntityIDGenerator.query.one()
710
    id = generator.id + 1
711
    generator.id = id
712
    session.commit()
713
    return id
714
 
635 rajveer 715
def put_category_object(object):
716
    category = Category.get_by(id=1)
717
    if category is None:
718
        category = Category()
719
    category.object = object    
720
    session.commit()
721
    return True
722
 
723
def get_category_object():
766 rajveer 724
    object = Category.get_by(id=1).object
725
    return object
726
 
1341 chandransh 727
def get_item_pricing(item_id, warehouse_id):
728
    item = Item.query.filter_by(id=item_id).first()
729
    if item is None:
730
        raise InventoryServiceException(101, "Bad Item")
731
 
732
    warehouse = get_Warehouse(warehouse_id)
733
    if not warehouse:
734
        raise InventoryServiceException(108, "Bad Warehouse")
735
    vendor = warehouse.vendor
736
 
737
    try:
738
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 739
        return item_pricing
1341 chandransh 740
    except sqlalchemy.orm.exc.MultipleResultsFound:
741
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
742
    except sqlalchemy.orm.exc.NoResultFound:
743
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
744
 
1970 rajveer 745
def add_category(t_category):
746
    category = Category.get_by(id=t_category.id)
747
    if category is None:
748
        category = Category()
749
    category.id = t_category.id 
750
    category.label = t_category.label
751
    category.description = t_category.description
752
    category.parent_category_id = t_category.parent_category_id 
753
    session.commit()
754
    return True
755
 
756
def get_category(id):
757
    return Category.query.filter_by(id=id).first()
758
 
759
def get_all_categories():
760
    return Category.query.all()
761
 
1991 ankur.sing 762
 
763
def get_all_item_pricing(item_id):
764
    item = Item.query.filter_by(id=item_id).first()
765
    if item is None:
766
        raise InventoryServiceException(101, "Bad Item")
767
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
768
    return item_pricing
769
 
2116 ankur.sing 770
def get_item_mappings(item_id):
771
    item = Item.query.filter_by(id=item_id).first()
772
    if item is None:
773
        raise InventoryServiceException(101, "Bad Item")
774
    item_mappings = VendorItemMapping.query.filter_by(item=item).all()
775
    return item_mappings
776
 
777
def add_vendor_pricing(vendorItemPricing):
1991 ankur.sing 778
    if not vendorItemPricing:
779
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
780
    vendorId = vendorItemPricing.vendorId
781
    itemId = vendorItemPricing.itemId
782
 
783
    try:
784
        vendor = Vendor.query.filter_by(id=vendorId).one()
785
    except:
786
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
787
 
788
    try:
789
        item = Item.query.filter_by(id=itemId).one()
790
    except:
791
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
792
 
2120 ankur.sing 793
    validate_vendor_prices(to_t_item(item), vendorItemPricing)
2065 ankur.sing 794
 
1991 ankur.sing 795
    try:
796
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
797
    except:
2116 ankur.sing 798
        ds_vendorItemPricing = VendorItemPricing()
799
        ds_vendorItemPricing.vendor = vendor
800
        ds_vendorItemPricing.item = item
1991 ankur.sing 801
 
802
    if vendorItemPricing.mop:
803
        ds_vendorItemPricing.mop = vendorItemPricing.mop
804
    if vendorItemPricing.dealerPrice:
805
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
806
    if vendorItemPricing.transferPrice:
2065 ankur.sing 807
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 808
 
809
    session.commit()
810
    return
811
 
2358 ankur.sing 812
def add_vendor_item_mapping(key, vendorItemMapping):
2116 ankur.sing 813
    if not vendorItemMapping:
814
        raise InventoryServiceException(108, "Bad vendorItemMapping in request")
815
    vendorId = vendorItemMapping.vendorId
816
    itemId = vendorItemMapping.itemId
817
 
818
    try:
819
        vendor = Vendor.query.filter_by(id=vendorId).one()
820
    except:
821
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
822
 
823
    try:
824
        item = Item.query.filter_by(id=itemId).one()
825
    except:
826
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
827
 
828
    try:
2358 ankur.sing 829
        ds_vendorItemMapping = VendorItemMapping.query.filter(and_(VendorItemMapping.vendor==vendor, VendorItemMapping.item==item, VendorItemMapping.item_key==key)).one()
2116 ankur.sing 830
    except:
831
        ds_vendorItemMapping = VendorItemMapping()
832
        ds_vendorItemMapping.vendor = vendor
833
        ds_vendorItemMapping.item = item
2497 ankur.sing 834
    ds_vendorItemMapping.vendor_category = vendorItemMapping.vendorCategory
2116 ankur.sing 835
    ds_vendorItemMapping.item_key = vendorItemMapping.itemKey
836
 
837
    session.commit()
838
    return
839
 
2120 ankur.sing 840
def validate_item_prices(item):
2129 ankur.sing 841
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
842
        return
843
    if item.mrp < item.sellingPrice:
2120 ankur.sing 844
        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))
845
        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 846
    return
2120 ankur.sing 847
 
848
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 849
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 850
        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))
851
        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)))
852
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
853
        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))
854
        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)))
855
    return
2065 ankur.sing 856
 
857
def get_all_vendors():
858
    return Vendor.query.all()
859
 
2116 ankur.sing 860
def check_similar_item(product_group, brand, model_number, color):
2129 ankur.sing 861
    query = Item.query
2428 ankur.sing 862
    query = query.filter_by(product_group=product_group)
863
    query = query.filter_by(brand=brand)
864
    query = query.filter_by(model_number=model_number)
2129 ankur.sing 865
    if color:
866
        query = query.filter_by(color=color)
867
    item = query.first()
2116 ankur.sing 868
    if item is None:
869
        return 0
870
    else:
871
        return item.id
2286 ankur.sing 872
 
873
def change_risky_flag(item_id, risky):
874
    item = get_item(item_id)
875
    if not item:
876
        raise InventoryServiceException(101, "Item missing in our database")
877
    try:
878
        log_risky_flag(item_id, risky)
879
    except:
880
        print "Not able to log risky flag change"
881
    item.risky = risky
2368 ankur.sing 882
    if not risky and item.status == status.PAUSED:
883
        change_item_status(item.id, status.ACTIVE)
2286 ankur.sing 884
    session.commit()
2368 ankur.sing 885
    check_risky_item(item)
2286 ankur.sing 886
 
2358 ankur.sing 887
def get_items_by_vendor_category(vendor_category):
888
    if not vendor_category:
889
        raise InventoryServiceException(101, "Invalid vendor category in request")
890
    query = Item.query.filter(and_(Item.hotspotCategory==vendor_category, Item.status != status.PHASED_OUT))
891
    items = query.all()
892
    return items
2116 ankur.sing 893
 
2358 ankur.sing 894
def get_risky_items():
895
    items = Item.query.filter_by(risky=True).all()
896
    return items
897
 
766 rajveer 898
def close_session():
899
    if session.is_active:
900
        print "session is active. closing it."
1399 rajveer 901
        session.close()