Subversion Repositories SmartDukaan

Rev

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