Subversion Repositories SmartDukaan

Rev

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