Subversion Repositories SmartDukaan

Rev

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