Subversion Repositories SmartDukaan

Rev

Rev 2286 | Rev 2343 | 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
1991 ankur.sing 21
from sqlalchemy.sql.expression import and_
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.modelName:
127
        ds_item.model_name = item.modelName
128
    if item.modelNumber:
129
        ds_item.model_number = item.modelNumber
609 chandransh 130
    if item.color:
131
        ds_item.color = item.color
483 rajveer 132
    if item.category:
133
        ds_item.category = item.category
134
    if item.comments:
135
        ds_item.comments = item.comments
511 rajveer 136
 
122 ashish 137
    if item.catalogItemId:
138
        ds_item.catalog_item_id = item.catalogItemId
483 rajveer 139
 
2129 ankur.sing 140
    ds_item.mrp = item.mrp
141
    ds_item.sellingPrice = item.sellingPrice
142
 
483 rajveer 143
    if item.mop:
144
        ds_item.mop = item.mop
609 chandransh 145
    if item.dealerPrice:
146
        ds_item.dealerPrice = item.dealerPrice
2065 ankur.sing 147
    if item.transferPrice:
148
        ds_item.transfer_price = item.transferPrice
2174 ankur.sing 149
    ds_item.weight = item.weight
2129 ankur.sing 150
 
2248 rajveer 151
    ds_item.status = item.itemStatus
2035 rajveer 152
    if item.status_description:
153
        ds_item.status_description = item.status_description
122 ashish 154
 
511 rajveer 155
    if item.startDate:
2116 ankur.sing 156
        ds_item.startDate = to_py_date(item.startDate)
511 rajveer 157
    if item.retireDate:
2116 ankur.sing 158
        ds_item.retireDate = to_py_date(item.retireDate)
511 rajveer 159
 
122 ashish 160
    if item.featureId:
161
        ds_item.feature_id = item.featureId
162
    if item.featureDescription:
163
        ds_item.feature_description = item.featureDescription
164
 
2129 ankur.sing 165
    ds_item.bestDealText = item.bestDealText
166
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 167
    ds_item.bestSellingRank = item.bestSellingRank
168
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 169
    ds_item.risky = item.risky
609 chandransh 170
    ds_item.updated_on = datetime.datetime.now()
2065 ankur.sing 171
 
122 ashish 172
    session.commit();
173
    return ds_item.id
94 ashish 174
 
2116 ankur.sing 175
def check_vendor_item_mapping(product_group, brand, model_number, color, vendor_id, vendor_category):
176
    key = product_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
177
    try:
178
        vim = VendorItemMapping.query.filter_by(vendor_id=vendor_id, item_key=key, vendor_category=vendor_category).one()
179
        return True
180
    except:
181
        return False
182
 
103 ashish 183
def add_item(item):
184
    if not item:
122 ashish 185
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 186
    if get_item(item.id):
122 ashish 187
        raise InventoryServiceException(101, "Item already exists")
2120 ankur.sing 188
 
189
    validate_item_prices(item)
190
 
103 ashish 191
    ds_item = Item()
963 chandransh 192
    if item.productGroup:
193
        ds_item.product_group = item.productGroup
194
    if item.brand:
195
        ds_item.brand = item.brand
515 rajveer 196
    if item.modelName:
197
        ds_item.model_name = item.modelName
198
    if item.modelNumber:
199
        ds_item.model_number = item.modelNumber
609 chandransh 200
    if item.color:
201
        ds_item.color = item.color
2116 ankur.sing 202
    if item.hotspotCategory:
203
        ds_item.hotspotCategory = item.hotspotCategory
204
        if item.hotspotCategory == 'Handsets':
205
            item.preferredWarehouse = 1
206
        else:
207
            item.preferredWarehouse = 2
208
 
483 rajveer 209
    if item.category:
210
        ds_item.category = item.category
211
    if item.comments:
212
        ds_item.comments = item.comments
213
 
103 ashish 214
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 215
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 216
    if item.startDate:
217
        ds_item.startDate = to_py_date(item.startDate)
218
    if item.retireDate:
219
        ds_item.retireDate = to_py_date(item.retireDate)
609 chandransh 220
 
483 rajveer 221
    if item.mrp:
222
        ds_item.mrp = item.mrp
223
    if item.mop:
224
        ds_item.mop = item.mop
225
    if item.sellingPrice:
226
        ds_item.sellingPrice = item.sellingPrice
609 chandransh 227
    if item.dealerPrice:
228
        ds_item.dealerPrice = item.dealerPrice
2116 ankur.sing 229
    if item.transferPrice:
230
        ds_item.transfer_price = item.transferPrice
122 ashish 231
    if item.weight:
232
        ds_item.weight = item.weight
233
 
234
    if item.featureId:
235
        ds_item.feature_id = item.featureId
236
    if item.featureDescription:
237
        ds_item.feature_description = item.featureDescription
238
 
103 ashish 239
    if item.otherInfo:
240
        for k,v in item.otherInfo.iteritems():
241
            info = ItemInfo()
242
            info.key = k
243
            info.value = v
244
            ds_item.iteminfo.append(info)
2116 ankur.sing 245
 
103 ashish 246
    #check if categories present. If yes, add them to system
122 ashish 247
 
609 chandransh 248
    if item.bestDealValue:
249
        ds_item.bestDealValue = item.bestDealValue
250
    if item.bestDealText:
251
        ds_item.bestDealText = item.bestDealText
2116 ankur.sing 252
    if item.bestSellingRank:
253
        ds_item.bestSellingRank = item.bestSellingRank
254
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 255
    ds_item.risky = item.risky
609 chandransh 256
 
2116 ankur.sing 257
    # Check if a similar item already exists in our database
258
    similar_item = Item.query.filter_by(product_group=item.productGroup, brand = item.brand, model_number=item.modelNumber, hotspotCategory=item.hotspotCategory).first()
259
    print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2} {3} {4}".format(item.productGroup, item.brand, item.modelNumber, item.hotspotCategory, item.color)
260
 
261
    if similar_item is None or similar_item.catalog_item_id is None:
262
        # If there is no similar item in the database from before,
263
        # use the entity_id_generator
264
        entity_id = EntityIDGenerator.query.first()
265
        ds_item.catalog_item_id = entity_id.id + 1
266
        ds_item.status = status.IN_PROCESS
267
        ds_item.status_description = "This item is in process."
268
        entity_id.id = entity_id.id  + 1
269
    else:
270
        #If a similar item already exists for a product group, brand and model_number, set it as same.
271
        ds_item.catalog_item_id = similar_item.catalog_item_id
272
        ds_item.category = similar_item.category
273
        ds_item.status = similar_item.status
274
        ds_item.status_description = similar_item.status_description
275
 
103 ashish 276
    session.commit();
609 chandransh 277
    return ds_item.id       
103 ashish 278
 
483 rajveer 279
def update_inventory(warehouse_id, timestamp, availability):
280
    warehouse = get_Warehouse(warehouse_id)
281
    if not warehouse:
282
        raise InventoryServiceException(107, "Warehouse? Where?")
283
 
284
    time = datetime.datetime.now()
285
    warehouse.lastCheckedOn = time
286
    warehouse.vendorString = timestamp
1368 chandransh 287
    vendor = warehouse.vendor
483 rajveer 288
 
1368 chandransh 289
    for item_key, quantity in availability.iteritems():
483 rajveer 290
        try:
1368 chandransh 291
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
292
            item = vendor_item_mapping.item
494 rajveer 293
        except:
294
            continue  
295
        try:
483 rajveer 296
            item_inventory_history = ItemInventoryHistory()
297
            item_inventory_history.warehouse = warehouse
298
            item_inventory_history.item = item
299
            item_inventory_history.timestamp = time
300
            item_inventory_history.availibility = quantity
301
 
302
            current_inventory_snapshot = CurrentInventorySnapshot.get_by(item=item, warehouse=warehouse)
303
            if not current_inventory_snapshot:
304
                current_inventory_snapshot = CurrentInventorySnapshot()
305
                current_inventory_snapshot.item = item
306
                current_inventory_snapshot.warehouse = warehouse
307
                current_inventory_snapshot.availibility = 0
871 chandransh 308
                current_inventory_snapshot.reserved = 0
483 rajveer 309
            # added the difference in the current inventory    
310
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
2251 ankur.sing 311
 
2269 ankur.sing 312
            check_risky_item(item, current_inventory_snapshot.availibility, current_inventory_snapshot.reserved)
2251 ankur.sing 313
 
483 rajveer 314
        except:
315
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
316
    session.commit() 
317
 
94 ashish 318
def get_item_inventoy(item_id):
319
 
320
    inventory = Item.get_by(id=item_id).currentInventory
321
    if not inventory:
122 ashish 322
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
94 ashish 323
    return inventory
324
 
635 rajveer 325
def get_item_inventory_by_item_id(item_id):
326
    inventory = Item.get_by(id=item_id).currentInventory
379 ashish 327
    if not inventory:
328
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
329
    return inventory
330
 
103 ashish 331
 
332
def retire_warehouse(warehouse_id):
333
    if not warehouse_id:
122 ashish 334
        raise InventoryServiceException(101, "Bad warehouse id")
103 ashish 335
    warehouse = get_Warehouse(warehouse_id)
336
    if not warehouse:
122 ashish 337
        raise InventoryServiceException(108, "warehouse id not present")
338
    warehouse.status = status.DELETED;
103 ashish 339
    session.commit()
340
 
341
def retire_item(item_id):
342
    if not item_id:
122 ashish 343
        raise InventoryServiceException(101, "bad item id")
635 rajveer 344
    item = get_item(item_id)
103 ashish 345
    if not item:
122 ashish 346
        raise InventoryServiceException(108, "item id not present")
347
    item.status = status.PHASED_OUT
348
    item.retireDate = datetime.datetime.now()
103 ashish 349
    session.commit()
122 ashish 350
 
351
#need to implement threads based solution here
103 ashish 352
def start_item_on(item_id, timestamp):
353
    if not item_id:
122 ashish 354
        raise InventoryServiceException(101, "bad item id")
635 rajveer 355
    item = get_item(item_id)
103 ashish 356
    if not item:
122 ashish 357
        raise InventoryServiceException(108, "item id not present")
103 ashish 358
 
122 ashish 359
    item.status = status.ACTIVE
360
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
361
    add_status_change_log(item, status.ACTIVE)
103 ashish 362
    session.commit()
363
 
122 ashish 364
#need to implement threads here
103 ashish 365
def retire_item_on(item_id, timestamp):
366
    if not item_id:
122 ashish 367
        raise InventoryServiceException(101, "bad item id")
635 rajveer 368
    item = get_item(item_id)
103 ashish 369
    if not item:
122 ashish 370
        raise InventoryServiceException(108, "item id not present")
103 ashish 371
 
122 ashish 372
    item.status = status.PHASED_OUT
373
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
374
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 375
    session.commit()
376
 
377
def add_status_change_log(item, new_status):
378
    item_change_log = ItemChangeLog()
379
    item_change_log.new_status = new_status
380
    item_change_log.old_status = item.status
381
    item_change_log.timestamp = datetime.datetime.now()
382
    item_change_log.item = item
383
    session.commit()
384
 
385
def change_item_status(item_id, new_status):
386
    if not item_id:
122 ashish 387
        raise InventoryServiceException(101, "bad item id")
635 rajveer 388
    item = get_item(item_id)
103 ashish 389
    if not item:
122 ashish 390
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 391
    add_status_change_log(item, new_status)
122 ashish 392
    item.status = new_status
2251 ankur.sing 393
    if item.status == status.PHASED_OUT:
394
        item.status_description = "This item has been phased out"
395
    elif item.status == status.DELETED:
396
        item.status_description = "This item has been deleted"
397
    elif item.status == status.PAUSED:
398
        item.status_description = "This item is currently out of stock"        
399
    elif item.status == status.ACTIVE:
400
        item.status_description = "This item is active"
401
    elif item.status == status.IN_PROCESS:
402
        item.status_description = "This item is in process"
403
    elif item.status == status.CONTENT_COMPLETE:
404
        item.status_description = "This item is in process"
103 ashish 405
    session.commit()
406
 
407
def get_item_availability_for_warehouse(warehouse_id, item_id):
408
    if not warehouse_id:
122 ashish 409
        raise InventoryServiceException(101, "bad warehouse_id")
103 ashish 410
    if not item_id:
122 ashish 411
        raise InventoryServiceException(101, "bad item_id")
103 ashish 412
 
413
    warehouse = get_Warehouse(warehouse_id)
414
    if not warehouse:
122 ashish 415
        raise InventoryServiceException(108, "warehouse does not exist")
635 rajveer 416
    item = get_item(item_id)
504 rajveer 417
 
103 ashish 418
    if not item:
766 rajveer 419
        raise InventoryServiceException(108, "item does not exist")
122 ashish 420
 
494 rajveer 421
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id)
504 rajveer 422
    query = query.filter_by(item_id = item.id)
494 rajveer 423
    try:
424
        current_inventory_snapshot = query.one()
871 chandransh 425
        return current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
494 rajveer 426
    except:
427
        return 0
428
    """
429
    current_inventory_snapshot = CurrentInventorySnapshot.query.filter(CurrentInventorySnapshot.warehouse_id == warehouse_id, CurrentInventorySnapshot.item_id == item_id).one()
103 ashish 430
    if not current_inventory_snapshot:
431
        return 0
432
    else:
433
        return current_inventory_snapshot.availibility
494 rajveer 434
    """
643 chandransh 435
 
2269 ankur.sing 436
def check_risky_item(item, availability, reserved):
2251 ankur.sing 437
    if not item.risky:
438
        return
439
    if availability - reserved <= 0:
440
        if item.status == status.ACTIVE:
441
            change_item_status(item.id, status.PAUSED)
442
    else:
443
        if item.status == status.PAUSED:
444
            change_item_status(item.id, status.ACTIVE)
445
 
446
 
871 chandransh 447
def reserve_item_in_warehouse(item_id, warehouse_id, quantity):    
448
    if not warehouse_id:
449
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 450
    item = get_item(item_id)
451
    if not item:
871 chandransh 452
        raise InventoryServiceException(101, "bad item_id")
453
 
454
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
455
    try:
456
        current_inventory_snapshot = query.one()
457
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved + quantity
2251 ankur.sing 458
 
2269 ankur.sing 459
        check_risky_item(item, current_inventory_snapshot.availibility, current_inventory_snapshot.reserved)
2251 ankur.sing 460
 
871 chandransh 461
        session.commit()
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
2251 ankur.sing 478
 
2269 ankur.sing 479
        check_risky_item(item, current_inventory_snapshot.availibility, current_inventory_snapshot.reserved)
2251 ankur.sing 480
 
871 chandransh 481
        session.commit()
482
        return True
483
    except:
484
        print "Unexpected error:", sys.exc_info()[0]
485
        return False
486
 
2075 rajveer 487
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
723 chandransh 488
    content_complete_status = status.CONTENT_COMPLETE
1294 chandransh 489
    items = Item.query.filter_by(catalog_item_id=entity_id, status=status.IN_PROCESS).all()
723 chandransh 490
    current_timestamp = datetime.datetime.now()
491
    for item in items:
492
        item_change_log = ItemChangeLog()
493
        item_change_log.old_status = item.status
494
        item_change_log.new_status = content_complete_status
495
        item_change_log.timestamp = current_timestamp
496
        item_change_log.item = item
497
 
498
        item.status = content_complete_status
2075 rajveer 499
        item.category = category
500
        item.brand = brand
2081 rajveer 501
        item.model_name = modelName
502
        item.model_number = modelNumber
723 chandransh 503
        item.updatedOn = current_timestamp
504
    session.commit()
505
    return True
1294 chandransh 506
 
643 chandransh 507
def get_item_availability_for_location(warehouse_loc, item_id):
508
    if warehouse_loc is None:
509
        raise InventoryServiceException(101, "Bad Warehouse Location")
510
    if not item_id:
1416 chandransh 511
        raise InventoryServiceException(101, "Bad Item id")
643 chandransh 512
 
1416 chandransh 513
    item = Item.get_by(id=item_id)
643 chandransh 514
    warehouses = Warehouse.query.filter_by(logisticsLocation=warehouse_loc).all()
515
    warehouse_ids = [warehouse.id for warehouse in warehouses]
516
    warehouse_retid = -1
517
    global_availability = 0
518
    for warehouse_id in warehouse_ids:
785 rajveer 519
        try:
871 chandransh 520
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id).one()
521
            availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
785 rajveer 522
        except:
523
            availability = 0    
643 chandransh 524
        if availability > global_availability:
525
            warehouse_retid = warehouse_id
526
            global_availability = availability
2341 chandransh 527
 
643 chandransh 528
    if warehouse_retid == -1:
759 chandransh 529
        # This is the case when all warehouses have exhausted their
530
        # inventory of this item or no warehouse is available in this
531
        # location.
1416 chandransh 532
        warehouse_retid = int(item.preferredWarehouse)
2341 chandransh 533
        warehouse = Warehouse.get_by(warehouse_retid)
534
        try:
535
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_retid, item_id = item_id).one()
536
            global_availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
537
        except:
538
            global_availability = 0
643 chandransh 539
 
2341 chandransh 540
    return [warehouse.logisticsLocation, warehouse_retid, global_availability]
541
 
122 ashish 542
def get_warehouses_for_item(item_id):
643 chandransh 543
 
122 ashish 544
    if not item_id:
545
        raise InventoryServiceException(101, "bad item_id")
635 rajveer 546
    item = get_item(item_id)
122 ashish 547
 
548
    if not item:
549
        raise InventoryServiceException(101, "bad item")
550
 
483 rajveer 551
    warehouses = item.currentInventory.warehouse
501 rajveer 552
    return warehouses
553
 
626 chandransh 554
def get_best_sellers(start_index, stop_index, category=-1):
1926 rajveer 555
    query = get_best_sellers_query(category, None)
1098 chandransh 556
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 557
    return get_thrift_item_list(best_sellers)
558
 
2093 chandransh 559
def get_best_sellers_count(category=-1):
1926 rajveer 560
    count = get_best_sellers_query(category, None).count()
1120 rajveer 561
    if count is None:
562
        count = 0
766 rajveer 563
    return count
621 chandransh 564
 
1926 rajveer 565
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
566
    query = get_best_sellers_query(category, brand)
1098 chandransh 567
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 568
    return [item.catalog_item_id for item in best_sellers]
1926 rajveer 569
 
1970 rajveer 570
def get_child_categories(category):
571
    cm = CategoryManager()
572
    return cm.getCategory(category).children_category_ids
573
 
1926 rajveer 574
def get_best_sellers_query(category, brand):
1098 chandransh 575
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 576
    if category != -1:
1970 rajveer 577
        all_categories = [category]
578
        child_categories = get_child_categories(category)
579
        if child_categories is not None:
580
            all_categories = all_categories + child_categories 
581
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 582
    if brand is not None:
583
        query = query.filter_by(brand=brand)
1098 chandransh 584
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 585
    return query
609 chandransh 586
 
1098 chandransh 587
def get_best_deals(category=-1):
1926 rajveer 588
    query = get_best_deals_query(category, None)
1098 chandransh 589
    items = query.all()
609 chandransh 590
    return get_thrift_item_list(items)
591
 
1098 chandransh 592
def get_best_deals_count(category=-1):
1926 rajveer 593
    count = get_best_deals_query(category, None).count()
1120 rajveer 594
    if count is None:
595
        count = 0
766 rajveer 596
    return count
501 rajveer 597
 
1926 rajveer 598
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
599
    query = get_best_deals_query(category, brand)
1098 chandransh 600
    best_deal_items = query.all()[start_index:stop_index]
601
    return [item.catalog_item_id for item in best_deal_items]
602
 
1926 rajveer 603
def get_best_deals_query(category, brand):
1098 chandransh 604
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 605
    if category != -1:
1970 rajveer 606
        all_categories = [category]
607
        child_categories = get_child_categories(category)
608
        if child_categories is not None:
609
            all_categories = all_categories + child_categories 
610
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 611
    if brand is not None:
612
        query = query.filter_by(brand=brand)
1098 chandransh 613
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
614
    return query
609 chandransh 615
 
1098 chandransh 616
def get_latest_arrivals(limit, category=-1):
1926 rajveer 617
    query = get_latest_arrivals_query(category, None)
1098 chandransh 618
    items = query.all()[0:limit]
609 chandransh 619
    return get_thrift_item_list(items)
598 chandransh 620
 
1098 chandransh 621
def get_latest_arrivals_count(limit, category=-1):
1926 rajveer 622
    count = get_latest_arrivals_query(category, None).count()
1120 rajveer 623
    if count is None:
624
        count = 0
625
    count = min(count, limit)
766 rajveer 626
    return count
602 chandransh 627
 
1926 rajveer 628
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, category=-1):
629
    query = get_latest_arrivals_query(category, brand)
1098 chandransh 630
    latest_arrivals = query.all()[start_index:stop_index]
631
    return [item.catalog_item_id for item in latest_arrivals]
632
 
1926 rajveer 633
def get_latest_arrivals_query(category, brand):
1098 chandransh 634
    query = Item.query.filter_by(status=status.ACTIVE)
626 chandransh 635
    if category != -1:
1970 rajveer 636
        all_categories = [category]
637
        child_categories = get_child_categories(category)
638
        if child_categories is not None:
639
            all_categories = all_categories + child_categories 
640
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 641
    if brand is not None:
642
        query = query.filter_by(brand=brand)
1098 chandransh 643
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
644
    return query
609 chandransh 645
 
646
def get_thrift_item_list(items):
1098 chandransh 647
    return [to_t_item(item) for item in items if item != None]
635 rajveer 648
 
1155 rajveer 649
def generate_new_entity_id():
650
    generator =  EntityIDGenerator.query.one()
651
    id = generator.id + 1
652
    generator.id = id
653
    session.commit()
654
    return id
655
 
635 rajveer 656
def put_category_object(object):
657
    category = Category.get_by(id=1)
658
    if category is None:
659
        category = Category()
660
    category.object = object    
661
    session.commit()
662
    return True
663
 
664
def get_category_object():
766 rajveer 665
    object = Category.get_by(id=1).object
666
    return object
667
 
1341 chandransh 668
def get_item_pricing(item_id, warehouse_id):
669
    item = Item.query.filter_by(id=item_id).first()
670
    if item is None:
671
        raise InventoryServiceException(101, "Bad Item")
672
 
673
    warehouse = get_Warehouse(warehouse_id)
674
    if not warehouse:
675
        raise InventoryServiceException(108, "Bad Warehouse")
676
    vendor = warehouse.vendor
677
 
678
    try:
679
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 680
        return item_pricing
1341 chandransh 681
    except sqlalchemy.orm.exc.MultipleResultsFound:
682
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
683
    except sqlalchemy.orm.exc.NoResultFound:
684
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
685
 
1970 rajveer 686
def add_category(t_category):
687
    category = Category.get_by(id=t_category.id)
688
    if category is None:
689
        category = Category()
690
    category.id = t_category.id 
691
    category.label = t_category.label
692
    category.description = t_category.description
693
    category.parent_category_id = t_category.parent_category_id 
694
    session.commit()
695
    return True
696
 
697
def get_category(id):
698
    return Category.query.filter_by(id=id).first()
699
 
700
def get_all_categories():
701
    return Category.query.all()
702
 
1991 ankur.sing 703
 
704
def get_all_item_pricing(item_id):
705
    item = Item.query.filter_by(id=item_id).first()
706
    if item is None:
707
        raise InventoryServiceException(101, "Bad Item")
708
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
709
    return item_pricing
710
 
2116 ankur.sing 711
def get_item_mappings(item_id):
712
    item = Item.query.filter_by(id=item_id).first()
713
    if item is None:
714
        raise InventoryServiceException(101, "Bad Item")
715
    item_mappings = VendorItemMapping.query.filter_by(item=item).all()
716
    return item_mappings
717
 
718
def add_vendor_pricing(vendorItemPricing):
1991 ankur.sing 719
    if not vendorItemPricing:
720
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
721
    vendorId = vendorItemPricing.vendorId
722
    itemId = vendorItemPricing.itemId
723
 
724
    try:
725
        vendor = Vendor.query.filter_by(id=vendorId).one()
726
    except:
727
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
728
 
729
    try:
730
        item = Item.query.filter_by(id=itemId).one()
731
    except:
732
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
733
 
2120 ankur.sing 734
    validate_vendor_prices(to_t_item(item), vendorItemPricing)
2065 ankur.sing 735
 
1991 ankur.sing 736
    try:
737
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
738
    except:
2116 ankur.sing 739
        ds_vendorItemPricing = VendorItemPricing()
740
        ds_vendorItemPricing.vendor = vendor
741
        ds_vendorItemPricing.item = item
1991 ankur.sing 742
 
743
    if vendorItemPricing.mop:
744
        ds_vendorItemPricing.mop = vendorItemPricing.mop
745
    if vendorItemPricing.dealerPrice:
746
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
747
    if vendorItemPricing.transferPrice:
2065 ankur.sing 748
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 749
 
750
    session.commit()
751
    return
752
 
2116 ankur.sing 753
def add_vendor_item_mapping(vendorItemMapping):
754
    if not vendorItemMapping:
755
        raise InventoryServiceException(108, "Bad vendorItemMapping in request")
756
    vendorId = vendorItemMapping.vendorId
757
    itemId = vendorItemMapping.itemId
758
 
759
    try:
760
        vendor = Vendor.query.filter_by(id=vendorId).one()
761
    except:
762
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
763
 
764
    try:
765
        item = Item.query.filter_by(id=itemId).one()
766
    except:
767
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
768
 
769
    try:
770
        ds_vendorItemMapping = VendorItemMapping.query.filter(and_(VendorItemMapping.vendor==vendor, VendorItemMapping.item==item, VendorItemMapping.item_key==vendorItemMapping.itemKey)).one()
771
    except:
772
        ds_vendorItemMapping = VendorItemMapping()
773
        ds_vendorItemMapping.vendor = vendor
774
        ds_vendorItemMapping.item = item
775
        ds_vendorItemMapping.vendor_category = vendorItemMapping.vendorCategory
776
    ds_vendorItemMapping.item_key = vendorItemMapping.itemKey
777
 
778
    session.commit()
779
    return
780
 
2120 ankur.sing 781
def validate_item_prices(item):
2129 ankur.sing 782
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
783
        return
784
    if item.mrp < item.sellingPrice:
2120 ankur.sing 785
        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))
786
        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 787
    return
2120 ankur.sing 788
 
789
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 790
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 791
        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))
792
        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)))
793
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
794
        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))
795
        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)))
796
    return
2065 ankur.sing 797
 
798
def get_all_vendors():
799
    return Vendor.query.all()
800
 
2116 ankur.sing 801
def check_similar_item(product_group, brand, model_number, color):
2129 ankur.sing 802
    query = Item.query
803
    if product_group:
804
        query = query.filter_by(product_group=product_group)
805
    if brand:
806
        query = query.filter_by(brand=brand)
807
    if model_number:
808
        query = query.filter_by(model_number=model_number)
809
    if color:
810
        query = query.filter_by(color=color)
811
    item = query.first()
2116 ankur.sing 812
    if item is None:
813
        return 0
814
    else:
815
        return item.id
2286 ankur.sing 816
 
817
def change_risky_flag(item_id, risky):
818
    item = get_item(item_id)
819
    if not item:
820
        raise InventoryServiceException(101, "Item missing in our database")
821
    try:
822
        log_risky_flag(item_id, risky)
823
    except:
824
        print "Not able to log risky flag change"
825
    item.risky = risky
826
    session.commit()
827
 
2116 ankur.sing 828
 
766 rajveer 829
def close_session():
830
    if session.is_active:
831
        print "session is active. closing it."
1399 rajveer 832
        session.close()