Subversion Repositories SmartDukaan

Rev

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