Subversion Repositories SmartDukaan

Rev

Rev 2081 | Rev 2116 | 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
602 chandransh 18
from shop2020.utils.Utils import log_entry, to_py_date
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):
35
    if not status:
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
 
2065 ankur.sing 115
    validate_prices(item)
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
 
140
    if item.mrp:
141
        ds_item.mrp = item.mrp
142
    if item.mop:
143
        ds_item.mop = item.mop
144
    if item.sellingPrice:
145
        ds_item.sellingPrice = item.sellingPrice
609 chandransh 146
    if item.dealerPrice:
147
        ds_item.dealerPrice = item.dealerPrice
2065 ankur.sing 148
    if item.transferPrice:
149
        ds_item.transfer_price = item.transferPrice
122 ashish 150
    if item.weight:
151
        ds_item.weight = item.weight
511 rajveer 152
    if item.itemStatus:
153
        ds_item.status = item.itemStatus
2035 rajveer 154
    if item.status_description:
155
        ds_item.status_description = item.status_description
122 ashish 156
 
511 rajveer 157
    if item.startDate:
158
        ds_item.startDate = item.startDate
159
    if item.retireDate:
160
        ds_item.retireDate = item.retireDate
161
 
122 ashish 162
    if item.featureId:
163
        ds_item.feature_id = item.featureId
164
    if item.featureDescription:
165
        ds_item.feature_description = item.featureDescription
166
 
609 chandransh 167
    if item.bestDealText:
168
        ds_item.bestDealText = item.bestDealText
169
    if item.bestDealValue:
170
        ds_item.bestDealValue = item.bestDealValue
171
 
2065 ankur.sing 172
    ds_item.bestSellingRank = item.bestSellingRank
173
    ds_item.defaultForEntity = item.defaultForEntity
174
 
609 chandransh 175
    ds_item.updated_on = datetime.datetime.now()
2065 ankur.sing 176
 
122 ashish 177
    session.commit();
178
    return ds_item.id
94 ashish 179
 
103 ashish 180
def add_item(item):
181
    if not item:
122 ashish 182
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 183
    if get_item(item.id):
122 ashish 184
        raise InventoryServiceException(101, "Item already exists")
483 rajveer 185
 
103 ashish 186
    ds_item = Item()
122 ashish 187
    if item.id:
188
        ds_item.id = item.id
963 chandransh 189
    if item.productGroup:
190
        ds_item.product_group = item.productGroup
191
    if item.brand:
192
        ds_item.brand = item.brand
515 rajveer 193
    if item.modelName:
194
        ds_item.model_name = item.modelName
195
    if item.modelNumber:
196
        ds_item.model_number = item.modelNumber
609 chandransh 197
    if item.color:
198
        ds_item.color = item.color
483 rajveer 199
    if item.category:
200
        ds_item.category = item.category
201
    if item.comments:
202
        ds_item.comments = item.comments
203
 
122 ashish 204
    if item.catalogItemId:
205
        ds_item.catalog_item_id = item.catalogItemId
2035 rajveer 206
    if item.status_description:
207
        ds_item.status_description = item.status_description
122 ashish 208
    if item.itemStatus:
209
        ds_item.status = item.itemStatus
2035 rajveer 210
    else: #If new item is added without status it will have status as IN_PROCESS
122 ashish 211
        ds_item.status = status.IN_PROCESS
2035 rajveer 212
        ds_item.status_description = "This item is in process."
213
 
103 ashish 214
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 215
    ds_item.updatedOn = datetime.datetime.now()
216
 
483 rajveer 217
    if item.mrp:
218
        ds_item.mrp = item.mrp
219
    if item.mop:
220
        ds_item.mop = item.mop
221
    if item.sellingPrice:
222
        ds_item.sellingPrice = item.sellingPrice
609 chandransh 223
    if item.dealerPrice:
224
        ds_item.dealerPrice = item.dealerPrice
122 ashish 225
    if item.weight:
226
        ds_item.weight = item.weight
227
 
228
    if item.featureId:
229
        ds_item.feature_id = item.featureId
230
    if item.featureDescription:
231
        ds_item.feature_description = item.featureDescription
232
 
103 ashish 233
    if item.otherInfo:
234
        for k,v in item.otherInfo.iteritems():
235
            info = ItemInfo()
236
            info.key = k
237
            info.value = v
238
            ds_item.iteminfo.append(info)
239
    #check if categories present. If yes, add them to system
122 ashish 240
 
609 chandransh 241
    if item.bestDealValue:
242
        ds_item.bestDealValue = item.bestDealValue
243
    if item.bestDealText:
244
        ds_item.bestDealText = item.bestDealText
245
 
103 ashish 246
    session.commit();
609 chandransh 247
    return ds_item.id       
103 ashish 248
 
483 rajveer 249
def update_inventory(warehouse_id, timestamp, availability):
250
    warehouse = get_Warehouse(warehouse_id)
251
    if not warehouse:
252
        raise InventoryServiceException(107, "Warehouse? Where?")
253
 
254
    time = datetime.datetime.now()
255
    warehouse.lastCheckedOn = time
256
    warehouse.vendorString = timestamp
1368 chandransh 257
    vendor = warehouse.vendor
483 rajveer 258
 
1368 chandransh 259
    for item_key, quantity in availability.iteritems():
483 rajveer 260
        try:
1368 chandransh 261
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
262
            item = vendor_item_mapping.item
494 rajveer 263
        except:
264
            continue  
265
        try:
483 rajveer 266
            item_inventory_history = ItemInventoryHistory()
267
            item_inventory_history.warehouse = warehouse
268
            item_inventory_history.item = item
269
            item_inventory_history.timestamp = time
270
            item_inventory_history.availibility = quantity
271
 
272
            current_inventory_snapshot = CurrentInventorySnapshot.get_by(item=item, warehouse=warehouse)
273
            if not current_inventory_snapshot:
274
                current_inventory_snapshot = CurrentInventorySnapshot()
275
                current_inventory_snapshot.item = item
276
                current_inventory_snapshot.warehouse = warehouse
277
                current_inventory_snapshot.availibility = 0
871 chandransh 278
                current_inventory_snapshot.reserved = 0
483 rajveer 279
            # added the difference in the current inventory    
280
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
281
        except:
282
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
283
    session.commit() 
284
 
94 ashish 285
def get_item_inventoy(item_id):
286
 
287
    inventory = Item.get_by(id=item_id).currentInventory
288
    if not inventory:
122 ashish 289
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
94 ashish 290
    return inventory
291
 
635 rajveer 292
def get_item_inventory_by_item_id(item_id):
293
    inventory = Item.get_by(id=item_id).currentInventory
379 ashish 294
    if not inventory:
295
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
296
    return inventory
297
 
103 ashish 298
 
299
def retire_warehouse(warehouse_id):
300
    if not warehouse_id:
122 ashish 301
        raise InventoryServiceException(101, "Bad warehouse id")
103 ashish 302
    warehouse = get_Warehouse(warehouse_id)
303
    if not warehouse:
122 ashish 304
        raise InventoryServiceException(108, "warehouse id not present")
305
    warehouse.status = status.DELETED;
103 ashish 306
    session.commit()
307
 
308
def retire_item(item_id):
309
    if not item_id:
122 ashish 310
        raise InventoryServiceException(101, "bad item id")
635 rajveer 311
    item = get_item(item_id)
103 ashish 312
    if not item:
122 ashish 313
        raise InventoryServiceException(108, "item id not present")
314
    item.status = status.PHASED_OUT
315
    item.retireDate = datetime.datetime.now()
103 ashish 316
    session.commit()
122 ashish 317
 
318
#need to implement threads based solution here
103 ashish 319
def start_item_on(item_id, timestamp):
320
    if not item_id:
122 ashish 321
        raise InventoryServiceException(101, "bad item id")
635 rajveer 322
    item = get_item(item_id)
103 ashish 323
    if not item:
122 ashish 324
        raise InventoryServiceException(108, "item id not present")
103 ashish 325
 
122 ashish 326
    item.status = status.ACTIVE
327
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
328
    add_status_change_log(item, status.ACTIVE)
103 ashish 329
    session.commit()
330
 
122 ashish 331
#need to implement threads here
103 ashish 332
def retire_item_on(item_id, timestamp):
333
    if not item_id:
122 ashish 334
        raise InventoryServiceException(101, "bad item id")
635 rajveer 335
    item = get_item(item_id)
103 ashish 336
    if not item:
122 ashish 337
        raise InventoryServiceException(108, "item id not present")
103 ashish 338
 
122 ashish 339
    item.status = status.PHASED_OUT
340
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
341
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 342
    session.commit()
343
 
344
def add_status_change_log(item, new_status):
345
    item_change_log = ItemChangeLog()
346
    item_change_log.new_status = new_status
347
    item_change_log.old_status = item.status
348
    item_change_log.timestamp = datetime.datetime.now()
349
    item_change_log.item = item
350
    session.commit()
351
 
352
def change_item_status(item_id, new_status):
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 = new_status
360
    add_status_change_log(item, new_status)
103 ashish 361
    session.commit()
362
 
363
def get_item_availability_for_warehouse(warehouse_id, item_id):
364
    if not warehouse_id:
122 ashish 365
        raise InventoryServiceException(101, "bad warehouse_id")
103 ashish 366
    if not item_id:
122 ashish 367
        raise InventoryServiceException(101, "bad item_id")
103 ashish 368
 
369
    warehouse = get_Warehouse(warehouse_id)
370
    if not warehouse:
122 ashish 371
        raise InventoryServiceException(108, "warehouse does not exist")
635 rajveer 372
    item = get_item(item_id)
504 rajveer 373
 
103 ashish 374
    if not item:
766 rajveer 375
        raise InventoryServiceException(108, "item does not exist")
122 ashish 376
 
494 rajveer 377
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id)
504 rajveer 378
    query = query.filter_by(item_id = item.id)
494 rajveer 379
    try:
380
        current_inventory_snapshot = query.one()
871 chandransh 381
        return current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
494 rajveer 382
    except:
383
        return 0
384
    """
385
    current_inventory_snapshot = CurrentInventorySnapshot.query.filter(CurrentInventorySnapshot.warehouse_id == warehouse_id, CurrentInventorySnapshot.item_id == item_id).one()
103 ashish 386
    if not current_inventory_snapshot:
387
        return 0
388
    else:
389
        return current_inventory_snapshot.availibility
494 rajveer 390
    """
643 chandransh 391
 
871 chandransh 392
def reserve_item_in_warehouse(item_id, warehouse_id, quantity):    
393
    if not warehouse_id:
394
        raise InventoryServiceException(101, "bad warehouse_id")
395
    if not item_id:
396
        raise InventoryServiceException(101, "bad item_id")
397
 
398
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
399
    try:
400
        current_inventory_snapshot = query.one()
401
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved + quantity
402
        session.commit()
403
        return True
404
    except:
405
        print "Unexpected error:", sys.exc_info()[0]
406
        return False
407
 
408
def reduce_reservation_count(item_id, warehouse_id, quantity):
409
    if not warehouse_id:
410
        raise InventoryServiceException(101, "bad warehouse_id")
411
    if not item_id:
412
        raise InventoryServiceException(101, "bad item_id")
413
 
414
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
415
    try:
416
        current_inventory_snapshot = query.one()
417
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved - quantity
418
        session.commit()
419
        return True
420
    except:
421
        print "Unexpected error:", sys.exc_info()[0]
422
        return False
423
 
2075 rajveer 424
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
723 chandransh 425
    content_complete_status = status.CONTENT_COMPLETE
1294 chandransh 426
    items = Item.query.filter_by(catalog_item_id=entity_id, status=status.IN_PROCESS).all()
723 chandransh 427
    current_timestamp = datetime.datetime.now()
428
    for item in items:
429
        item_change_log = ItemChangeLog()
430
        item_change_log.old_status = item.status
431
        item_change_log.new_status = content_complete_status
432
        item_change_log.timestamp = current_timestamp
433
        item_change_log.item = item
434
 
435
        item.status = content_complete_status
2075 rajveer 436
        item.category = category
437
        item.brand = brand
2081 rajveer 438
        item.model_name = modelName
439
        item.model_number = modelNumber
723 chandransh 440
        item.updatedOn = current_timestamp
441
    session.commit()
442
    return True
1294 chandransh 443
 
643 chandransh 444
def get_item_availability_for_location(warehouse_loc, item_id):
445
    if warehouse_loc is None:
446
        raise InventoryServiceException(101, "Bad Warehouse Location")
447
    if not item_id:
1416 chandransh 448
        raise InventoryServiceException(101, "Bad Item id")
643 chandransh 449
 
1416 chandransh 450
    item = Item.get_by(id=item_id)
643 chandransh 451
    warehouses = Warehouse.query.filter_by(logisticsLocation=warehouse_loc).all()
452
    warehouse_ids = [warehouse.id for warehouse in warehouses]
453
    warehouse_retid = -1
454
    global_availability = 0
455
    for warehouse_id in warehouse_ids:
785 rajveer 456
        try:
871 chandransh 457
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id).one()
458
            availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
785 rajveer 459
        except:
460
            availability = 0    
643 chandransh 461
        if availability > global_availability:
462
            warehouse_retid = warehouse_id
463
            global_availability = availability
464
    if warehouse_retid == -1:
759 chandransh 465
        # This is the case when all warehouses have exhausted their
466
        # inventory of this item or no warehouse is available in this
467
        # location.
1416 chandransh 468
        warehouse_retid = int(item.preferredWarehouse)
643 chandransh 469
    return [warehouse_retid, global_availability]
470
 
122 ashish 471
def get_warehouses_for_item(item_id):
643 chandransh 472
 
122 ashish 473
    if not item_id:
474
        raise InventoryServiceException(101, "bad item_id")
635 rajveer 475
    item = get_item(item_id)
122 ashish 476
 
477
    if not item:
478
        raise InventoryServiceException(101, "bad item")
479
 
483 rajveer 480
    warehouses = item.currentInventory.warehouse
501 rajveer 481
    return warehouses
482
 
626 chandransh 483
def get_best_sellers(start_index, stop_index, category=-1):
1926 rajveer 484
    query = get_best_sellers_query(category, None)
1098 chandransh 485
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 486
    return get_thrift_item_list(best_sellers)
487
 
2093 chandransh 488
def get_best_sellers_count(category=-1):
1926 rajveer 489
    count = get_best_sellers_query(category, None).count()
1120 rajveer 490
    if count is None:
491
        count = 0
766 rajveer 492
    return count
621 chandransh 493
 
1926 rajveer 494
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
495
    query = get_best_sellers_query(category, brand)
1098 chandransh 496
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 497
    return [item.catalog_item_id for item in best_sellers]
1926 rajveer 498
 
1970 rajveer 499
def get_child_categories(category):
500
    cm = CategoryManager()
501
    return cm.getCategory(category).children_category_ids
502
 
1926 rajveer 503
def get_best_sellers_query(category, brand):
1098 chandransh 504
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 505
    if category != -1:
1970 rajveer 506
        all_categories = [category]
507
        child_categories = get_child_categories(category)
508
        if child_categories is not None:
509
            all_categories = all_categories + child_categories 
510
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 511
    if brand is not None:
512
        query = query.filter_by(brand=brand)
1098 chandransh 513
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 514
    return query
609 chandransh 515
 
1098 chandransh 516
def get_best_deals(category=-1):
1926 rajveer 517
    query = get_best_deals_query(category, None)
1098 chandransh 518
    items = query.all()
609 chandransh 519
    return get_thrift_item_list(items)
520
 
1098 chandransh 521
def get_best_deals_count(category=-1):
1926 rajveer 522
    count = get_best_deals_query(category, None).count()
1120 rajveer 523
    if count is None:
524
        count = 0
766 rajveer 525
    return count
501 rajveer 526
 
1926 rajveer 527
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
528
    query = get_best_deals_query(category, brand)
1098 chandransh 529
    best_deal_items = query.all()[start_index:stop_index]
530
    return [item.catalog_item_id for item in best_deal_items]
531
 
1926 rajveer 532
def get_best_deals_query(category, brand):
1098 chandransh 533
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 534
    if category != -1:
1970 rajveer 535
        all_categories = [category]
536
        child_categories = get_child_categories(category)
537
        if child_categories is not None:
538
            all_categories = all_categories + child_categories 
539
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 540
    if brand is not None:
541
        query = query.filter_by(brand=brand)
1098 chandransh 542
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
543
    return query
609 chandransh 544
 
1098 chandransh 545
def get_latest_arrivals(limit, category=-1):
1926 rajveer 546
    query = get_latest_arrivals_query(category, None)
1098 chandransh 547
    items = query.all()[0:limit]
609 chandransh 548
    return get_thrift_item_list(items)
598 chandransh 549
 
1098 chandransh 550
def get_latest_arrivals_count(limit, category=-1):
1926 rajveer 551
    count = get_latest_arrivals_query(category, None).count()
1120 rajveer 552
    if count is None:
553
        count = 0
554
    count = min(count, limit)
766 rajveer 555
    return count
602 chandransh 556
 
1926 rajveer 557
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, category=-1):
558
    query = get_latest_arrivals_query(category, brand)
1098 chandransh 559
    latest_arrivals = query.all()[start_index:stop_index]
560
    return [item.catalog_item_id for item in latest_arrivals]
561
 
1926 rajveer 562
def get_latest_arrivals_query(category, brand):
1098 chandransh 563
    query = Item.query.filter_by(status=status.ACTIVE)
626 chandransh 564
    if category != -1:
1970 rajveer 565
        all_categories = [category]
566
        child_categories = get_child_categories(category)
567
        if child_categories is not None:
568
            all_categories = all_categories + child_categories 
569
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 570
    if brand is not None:
571
        query = query.filter_by(brand=brand)
1098 chandransh 572
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
573
    return query
609 chandransh 574
 
575
def get_thrift_item_list(items):
1098 chandransh 576
    return [to_t_item(item) for item in items if item != None]
635 rajveer 577
 
1155 rajveer 578
def generate_new_entity_id():
579
    generator =  EntityIDGenerator.query.one()
580
    id = generator.id + 1
581
    generator.id = id
582
    session.commit()
583
    return id
584
 
635 rajveer 585
def put_category_object(object):
586
    category = Category.get_by(id=1)
587
    if category is None:
588
        category = Category()
589
    category.object = object    
590
    session.commit()
591
    return True
592
 
593
def get_category_object():
766 rajveer 594
    object = Category.get_by(id=1).object
595
    return object
596
 
1341 chandransh 597
def get_item_pricing(item_id, warehouse_id):
598
    item = Item.query.filter_by(id=item_id).first()
599
    if item is None:
600
        raise InventoryServiceException(101, "Bad Item")
601
 
602
    warehouse = get_Warehouse(warehouse_id)
603
    if not warehouse:
604
        raise InventoryServiceException(108, "Bad Warehouse")
605
    vendor = warehouse.vendor
606
 
607
    try:
608
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 609
        return item_pricing
1341 chandransh 610
    except sqlalchemy.orm.exc.MultipleResultsFound:
611
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
612
    except sqlalchemy.orm.exc.NoResultFound:
613
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
614
 
1970 rajveer 615
def add_category(t_category):
616
    category = Category.get_by(id=t_category.id)
617
    if category is None:
618
        category = Category()
619
    category.id = t_category.id 
620
    category.label = t_category.label
621
    category.description = t_category.description
622
    category.parent_category_id = t_category.parent_category_id 
623
    session.commit()
624
    return True
625
 
626
def get_category(id):
627
    return Category.query.filter_by(id=id).first()
628
 
629
def get_all_categories():
630
    return Category.query.all()
631
 
1991 ankur.sing 632
 
633
def get_all_item_pricing(item_id):
634
    item = Item.query.filter_by(id=item_id).first()
635
    if item is None:
636
        raise InventoryServiceException(101, "Bad Item")
637
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
638
    return item_pricing
639
 
640
def update_vendor_pricing(vendorItemPricing):
641
    if not vendorItemPricing:
642
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
643
    vendorId = vendorItemPricing.vendorId
644
    itemId = vendorItemPricing.itemId
645
 
646
    try:
647
        vendor = Vendor.query.filter_by(id=vendorId).one()
648
    except:
649
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
650
 
651
    try:
652
        item = Item.query.filter_by(id=itemId).one()
653
    except:
654
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
655
 
2065 ankur.sing 656
    validate_prices(to_t_item(item), vendorItemPricing)
657
 
1991 ankur.sing 658
    try:
659
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
660
    except:
661
        raise InventoryServiceException(101, "VendorItemPricing not found for vendorId " + str(vendorId) + " and itemId " + str(itemId))
662
 
663
    if vendorItemPricing.mop:
664
        ds_vendorItemPricing.mop = vendorItemPricing.mop
665
    if vendorItemPricing.dealerPrice:
666
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
667
    if vendorItemPricing.transferPrice:
2065 ankur.sing 668
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 669
 
670
    session.commit()
671
    return
672
 
2065 ankur.sing 673
def validate_prices(item, vendorPrices = None):
674
    if item.mrp != "" and item.sellingPrice != "" and item.mrp < item.sellingPrice:
675
        raise InventoryServiceException("[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}, SP={5}".format(item.productGroup, item.brand, item.modelNumber, item.color, item.mrp, item.sellingPrice))
676
    if not vendorPrices:
677
        vendorPricesList = [to_t_vendor_item_pricing(vip) for vip in get_all_item_pricing(item.id)]
678
    else:
679
        vendorPricesList = [vendorPrices]
680
    for vp in vendorPricesList:
681
        if item.mrp != "" and vp.mop != "" and item.mrp <  vp.mop:
682
            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, item.mrp, vp.mop, vp.vendorId))
683
        if vp.mop != "" and vp.transferPrice != "" and vp.transferPrice > vp.mop:
684
            raise InventoryServiceException("[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, vp.transferPrice, vp.mop, vp.vendorId))
685
    return
686
 
687
def get_all_vendors():
688
    return Vendor.query.all()
689
 
766 rajveer 690
def close_session():
691
    if session.is_active:
692
        print "session is active. closing it."
1399 rajveer 693
        session.close()