Subversion Repositories SmartDukaan

Rev

Rev 6833 | Rev 7149 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5944 mandeep.dh 1
'''
2
Created on 27-Apr-2010
3
 
4
@author: ashish
5
'''
6
from shop2020.config.client.ConfigClient import ConfigClient
7
from shop2020.model.v1.inventory.impl import DataService
5957 mandeep.dh 8
from shop2020.model.v1.inventory.impl.Convertors import to_t_item_inventory, \
6821 amar.kumar 9
    to_t_warehouse, to_t_vendor_item_pricing, to_t_vendor, to_t_vendor_item_mapping, \
6832 amar.kumar 10
    to_t_item_stock_purchase_params, to_t_oos_status
5944 mandeep.dh 11
from shop2020.model.v1.inventory.impl.DataAcessors import add_warehouse, \
12
    update_inventory, retire_warehouse, get_item_availability_for_warehouse, \
13
    get_item_availability_for_location, get_all_warehouses_by_status, get_Warehouse, \
5957 mandeep.dh 14
    get_all_items_for_warehouse, close_session, add_vendor, \
15
    get_item_inventory_by_item_id, reserve_item_in_warehouse, \
16
    reduce_reservation_count, get_all_item_pricing, add_vendor_pricing, \
17
    get_item_pricing, get_all_vendors, get_item_mappings, add_vendor_item_mapping, \
18
    update_inventory_history, is_alive, add_inventory, add_bad_inventory, \
19
    mark_missed_inventory_updates_as_processed, update_vendor_string, \
20
    get_item_keys_to_be_processed, reset_availability, get_shipping_locations, \
5944 mandeep.dh 21
    initialize, get_inventory_snapshot, clear_item_availability_cache, \
5987 rajveer 22
    reset_availability_for_warehouse, get_vendor, get_pending_orders_inventory, \
6531 vikram.rag 23
    is_order_billable, get_our_warehouse_id_for_vendor, \
24
    get_item_availability_for_our_warehouses, get_monitored_warehouses_for_vendors, \
25
    get_ignored_warehouseids_and_itemids,insert_item_to_ignore_inventory_update_list, \
26
    delete_item_from_ignore_inventory_update_list,get_all_ignored_inventoryupdate_items_count, \
6821 amar.kumar 27
    get_ignored_inventoryupdate_itemids, update_item_stock_purchase_params, \
6857 amar.kumar 28
    get_item_stock_purchase_params, add_oos_status_for_item, \
29
    get_oos_statuses_for_x_days_for_item, get_non_zero_item_stock_purchase_params
5944 mandeep.dh 30
from shop2020.model.v1.inventory.impl.DataService import Warehouse, \
31
    MissedInventoryUpdate, VendorItemMapping
5957 mandeep.dh 32
from shop2020.thriftpy.model.v1.inventory.ttypes import \
33
    InventoryServiceException, WarehouseType, InventoryType, \
34
    AvailableAndReservedStock
5944 mandeep.dh 35
from shop2020.utils.Utils import log_entry, to_java_date
36
 
37
class InventoryServiceHandler:
38
    '''
39
    classdocs
40
    '''
41
 
42
    def __init__(self, dbname='catalog', db_hostname='localhost'):
43
        '''
44
        Constructor
6532 amit.gupta 45
u        '''
5944 mandeep.dh 46
        initialize(dbname, db_hostname)
47
        try:
48
            config_client = ConfigClient()
49
            self.latest_arrivals_limit = int(config_client.get_property("LATEST_ARRIVALS_LIMIT"));
50
            self.best_sellers_limit = int(config_client.get_property("BEST_SELLERS_LIMIT"))
51
        except:
52
            self.latest_arrivals_limit = 50
53
            self.best_sellers_limit = 50
54
 
55
    def addWarehouse(self, warehouse):
56
        """
57
        Parameters:
58
         - warehouse
59
        """
60
        log_entry(self, "addWarehouse called")
61
        try:
62
            return add_warehouse(warehouse)
63
        finally:
64
            close_session()
65
 
66
    def updateInventoryHistory(self, warehouse_id, timestamp, availability):
67
        """
68
        Stores the incremental warehouse updates of items.
69
 
70
        Parameters:
71
         - warehouse_id
72
         - timestamp
73
         - availability
74
        """
75
        try:
76
            return update_inventory_history(warehouse_id, timestamp, availability)
77
        finally:
78
            close_session()
79
 
80
    def updateInventory(self, warehouse_id, timestamp, availability):
81
        """
82
        Parameters:
83
         - warehouse_id
84
         - timestamp
85
         - availability
86
        """
87
        log_entry(self, "update Inventory called")
88
        try:
89
            return update_inventory(warehouse_id, timestamp, availability)
90
        finally:
91
            close_session()
92
 
93
    def addInventory(self, itemId, warehouseId, quantity):
94
        """
95
        Add the inventory to existing stock.
96
 
97
        Parameters:
98
         - itemId
99
         - warehouseId
100
         - quantity
101
        """
102
        log_entry(self, "add Inventory called")
103
        try:
104
            return add_inventory(itemId, warehouseId, quantity)
105
        finally:
106
            close_session()
107
 
108
    def retireWarehouse(self, warehouse_id):
109
        """
110
        Parameters:
111
         - warehouse_id
112
        """
113
        log_entry(self, "retire warehouse called")
114
        try:
115
            return retire_warehouse(warehouse_id)
116
        finally:
117
            close_session()
118
 
119
 
120
    def getItemInventoryByItemId(self, item_id):
121
        """
122
        Parameters:
123
         - item_id
124
        """
125
        log_entry(self, "item inventory requested")
126
        try:
127
            inventory = get_item_inventory_by_item_id(item_id)
128
            return to_t_item_inventory(inventory, item_id)
129
        finally:
130
            close_session()
131
 
5978 rajveer 132
    def getItemAvailabilityAtLocation(self, itemId, sourceId):
5944 mandeep.dh 133
        """
134
        Determines the warehouse that should be used to fulfil an order for the given item.
135
        It first checks all the warehouses which are in the logistics location given by the
136
        warehouse_loc parameter. If none of the warehouses there have any inventory, then the
137
        preferred warehouse for the item is used.
138
 
139
        Returns an ordered list of size 4 with following elements in the given order:
140
        1. Logistics location of the warehouse which was finally picked up to ship the order.
141
        2. Id of the warehouse which was finally picked up.
142
        3. Inventory size in the selected warehouse.
143
        4. Expected delay added by the category manager.
144
 
145
        Parameters:
146
         - itemId
5978 rajveer 147
         - sourceId
5944 mandeep.dh 148
        """
149
        try:
5978 rajveer 150
            return get_item_availability_for_location(itemId, sourceId)
5944 mandeep.dh 151
        finally:
152
            close_session()
153
 
154
    def getItemAvailibilityAtWarehouse(self, warehouse_id, item_id):
155
        """
156
        Parameters:
157
         - warehouse_id
158
         - item_id
159
        """
160
        log_entry(self, "item availability at warehouse requested")
161
        try:
162
            return get_item_availability_for_warehouse(warehouse_id, item_id)
163
        finally:
164
            close_session()
6484 amar.kumar 165
 
166
    def getItemAvailabilitiesAtOurWarehouses(self, item_ids):
167
        try:   
168
            return get_item_availability_for_our_warehouses(item_ids)
169
        finally:
170
            close_session()
5944 mandeep.dh 171
 
172
    def getItemInventoryHistory(self, id, item_id, warehouse_id, from_date, to_date):
173
        """
174
        Parameters:
175
         - id
176
         - item_id
177
         - warehouse_id
178
         - from_date
179
         - to_date
180
        """
181
        pass
182
 
183
    def getAllWarehouses(self, isActive):
184
        """
185
        Parameters:
186
        - isActive
187
        """
188
        try:
189
            if isActive:
190
                warehouses = get_all_warehouses_by_status(3)
191
            else:
192
                warehouses = get_all_warehouses_by_status(None)
193
 
194
            ret_warehouses = []
195
 
196
            for warehouse in warehouses:
197
                ret_warehouses.append(to_t_warehouse(warehouse))
198
            return ret_warehouses
199
        finally:
200
            close_session()
201
 
202
    def getWarehouse(self, warehouse_id):
203
        """
204
        Parameters:
205
         - warehouse_id
206
        """
207
        log_entry(self, "get warehouse call")
208
        try:
209
            warehouse = get_Warehouse(warehouse_id)
210
            if warehouse:
211
                return to_t_warehouse(warehouse)
212
            else:
213
                raise InventoryServiceException(101, "no such warehouse: " + str(warehouse_id))
214
        finally:
215
            close_session()
216
 
217
    def getAllItemsForWarehouse(self, warehouse_id):
218
        """
219
        Parameters:
220
         - warehouse_id
221
        """
222
        log_entry(self, "getting all items for warehouse")
223
        try:
224
            all_items = get_all_items_for_warehouse(warehouse_id)
225
            t_items = []
226
            for item in all_items:
227
                t_items.append(item.id)
228
            return t_items
229
        finally:
230
            close_session()
231
 
5966 rajveer 232
    def isOrderBillable(self, itemId, warehouseId, sourceId, orderId):
5944 mandeep.dh 233
        """
5966 rajveer 234
        Depending on reservation in the table, verify if we can bill this order or not.
235
 
236
        Parameters:
237
         - itemId
238
         - warehouseId
239
         - sourceId
240
         - orderId
241
        """
242
        try:
243
            return is_order_billable(itemId, warehouseId, sourceId, orderId)
244
        finally:
245
            close_session()
246
 
247
    def reserveItemInWarehouse(self, itemId, warehouseId, sourceId, orderId, createdTimestamp, promisedShippingTimestamp, quantity):
248
        """
5944 mandeep.dh 249
        Increases the reservation count for an item in a warehouse. Should always succeed normally.
250
 
251
        Parameters:
252
         - itemId
253
         - warehouseId
254
        """
255
        log_entry(self, "reserveItemInWarehouse called")
256
        try:
5966 rajveer 257
            return reserve_item_in_warehouse(itemId, warehouseId, sourceId, orderId, createdTimestamp, promisedShippingTimestamp, quantity)
5944 mandeep.dh 258
        finally:
259
            close_session()
260
 
5966 rajveer 261
    def reduceReservationCount(self, itemId, warehouseId, sourceId, orderId, quantity):
5944 mandeep.dh 262
        """
263
        Decreases the reservation count for an item in a warehouse. Should always succeed normally.
264
 
265
        Parameters:
266
         - itemId
267
         - warehouseId
268
        """
269
        log_entry(self, "reduceReservationCount called")
270
        try:
5966 rajveer 271
            return reduce_reservation_count(itemId, warehouseId, sourceId, orderId, quantity)
5944 mandeep.dh 272
        finally:
273
            close_session()
274
 
275
    def getItemPricing(self, itemId, vendorId):
276
        """
277
        Returns the pricing information of an item associated with the vendor of the given warehouse.
278
        Raises an exception if either the item, vendor or the associated pricing information can't be found.
279
 
280
        Parameters:
281
         - itemId
282
         - warehouseId
283
        """
284
        try:
285
            return to_t_vendor_item_pricing(get_item_pricing(itemId, vendorId))
286
        finally:
287
            close_session()
288
 
289
 
290
    def getAllItemPricing(self, itemId):
291
        """
292
        Returns list of the pricing information of an item associated an item.
293
        Raises an exception if the item can't be found.
294
 
295
        Parameters:
296
         - itemId
297
        """
298
        try:
299
            return [to_t_vendor_item_pricing(vid) for vid in get_all_item_pricing(itemId)]
300
        finally:
301
            close_session()
302
 
303
    def addVendorItemPricing(self, vendorItemPricing):
304
        """
305
        Adds vendor prices corresponding to the item. If pricing already exists then updates the prices. 
306
        Raises an exception if either the item or vendor can't be found corresponding to their ids.
307
 
308
        Parameters:
309
         - vendorItemPricing
310
        """
311
        log_entry(self, "updateVendorItemPricing called")
312
        try:
313
            return add_vendor_pricing(vendorItemPricing)
314
        finally:
315
            close_session()
316
 
317
    def getVendor(self, vendorId):
318
        """
319
        Return a vendor for id
320
        """
321
        try:
322
            return to_t_vendor(get_vendor(vendorId))
323
        finally:
324
            close_session()
325
 
326
 
327
    def getAllVendors(self, ):
328
        """
329
        Return list of all vendors
330
        """
331
        try:
332
            return [to_t_vendor(v) for v in get_all_vendors()]
333
        finally:
334
            close_session()
335
 
336
    def addVendorItemMapping(self, key, vendorItemMapping):
337
        """
338
        Adds VendorItemMapping. Updates VendorItemMapping if exists corresponding to the item key.
339
 
340
        Parameters:
341
         - key
342
         - vendorItemMapping
343
        """
344
        log_entry(self, "addVendorItemMapping called")
345
        try:
346
            return add_vendor_item_mapping(key, vendorItemMapping)
347
        finally:
348
            close_session()
349
 
350
    def getVendorItemMappings(self, itemId):
351
        """
352
        Returns the list of vendor item mapping corresponding to itemId passed as parameter.
353
        Raises an exception if item not found corresponding to itemId
354
 
355
        Parameters:
356
         - itemId
357
        """
358
        try:
359
            item_mappings = get_item_mappings(itemId)
360
            return [to_t_vendor_item_mapping(vim) for vim in item_mappings]
361
        finally:
362
            close_session()
363
 
364
    def isAlive(self, ):
365
        """
366
        For checking weather service is active alive or not. It also checks connectivity with database
367
        """
368
        try:
369
            return is_alive()
370
        finally:
371
            close_session()
372
 
373
    def closeSession(self, ):
374
        """
375
        For closing the open session in sqlalchemy
376
        """
377
        close_session()
378
 
379
    def addVendor(self, vendor):
380
        """
381
        add a new vendor
382
        """
383
        try:
384
            return add_vendor(vendor)
385
        finally:
386
            close_session()
387
 
388
    def getWarehouses(self, warehouseType, inventoryType, vendorId, billingWarehouseId, shippingWarehouseId):
389
        """
390
        This method returns all warehouses for a given warehosueType, inventoryType, vendor, billingWarehouse and shippingWarehouse.
391
        getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 3, 7, 7) would return ours warehouse with GOOD type inventory for vendor 1 for billing warehouse 7 and shipping warehouse 7
392
        getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 3, 7, 7) would return ours warehouse with GOOD type inventory for vendor 3 for billing warehouse 7 and shipping warehouse 7
393
        getWarehouses(null, null, 3, 7, 7) would return all type warehouses with all type inventory for vendor 3 for billing warehouse 7 and shipping warehouse 7
394
        getWarehouses(null, null, 0, 0, 7) would return all type warehouses with all type inventory for all vendors for all billing warehouses at shipping warehouse 7
395
 
396
        Parameters:
397
         - warehouseType
398
         - inventoryType
399
         - vendorId
400
         - billingWarehouseId
401
         - shippingWarehouseId
402
        """
403
        try:
404
            query = Warehouse.query
405
            if warehouseType is not None:
406
                query = query.filter_by(warehouseType = WarehouseType._VALUES_TO_NAMES[warehouseType])
407
            if inventoryType is not None:
408
                query = query.filter_by(inventoryType = InventoryType._VALUES_TO_NAMES[inventoryType])
409
            if vendorId:
410
                query = query.filter_by(vendor_id = vendorId)
411
            if billingWarehouseId:
412
                query = query.filter_by(billingWarehouseId = billingWarehouseId)
413
            if shippingWarehouseId:
414
                query = query.filter_by(shippingWarehouseId = shippingWarehouseId)
415
 
416
            return [to_t_warehouse(w) for w in query.all()]
417
        finally:
418
            close_session()
419
 
420
    def getItemKeysToBeProcessed(self, warehouseId):
421
        """
422
        Returns the list of item keys which need to be processed for a given warehouse.
423
        This is currently used by Support application to send item keys whose inventory needs
424
        to be updated from PLB
425
 
426
        Parameters:
427
         - warehouseId
428
        """
429
        try:
430
            return get_item_keys_to_be_processed(warehouseId)
431
        finally:
432
            close_session()
433
 
434
    def markMissedInventoryUpdatesAsProcessed(self, itemKey, warehouseId):
435
        """
436
        Marks/Deletes missed inventory updates for a given key and warehouse.
437
        This generally happens when updates from PLB are applied on the currentinventorysnapshot for an item
438
 
439
        Parameters:
440
         - itemKey
441
         - warehouseId
442
        """
443
        try:
444
            mark_missed_inventory_updates_as_processed(itemKey, warehouseId)
445
        finally:
446
            close_session()
447
 
448
    def resetAvailability(self, itemKey, vendorId, quantity, warehouseId):
449
        """
450
        Resets availability of an item to the quantity mentioned in a warehouse.
451
 
452
        Parameters:
453
         - itemKey
454
         - vendorId
455
         - quantity
456
         - warehouseId
457
        """
458
        try:
459
            reset_availability(itemKey, vendorId, quantity, warehouseId)
460
        finally:
461
            close_session()
462
 
463
    def resetAvailabilityForWarehouse(self, warehouseId):
464
        """
465
        Resets availability of a warehouse to zero.
466
 
467
        Parameters:
468
         - warehouseId
469
        """
470
        try:
471
            reset_availability_for_warehouse(warehouseId)
472
        finally:
473
            close_session()
474
 
475
    def getIgnoredItemKeys(self, ):
476
        """
477
        Returns all the item key mappings that have been ignored until date. Value of map has the warehouse id
478
        and the timestamp from where alert was raised.
479
        """
480
        try:
481
            itemKeysMap = {}
482
            for key in MissedInventoryUpdate.query.filter_by(isIgnored = 1).all():
483
                itemKeysMap[key.itemKey] = { key.warehouseId : to_java_date(key.timestamp) }
484
 
485
            return itemKeysMap
486
        finally:
487
            close_session()
488
 
489
    def addBadInventory(self, itemId, warehouseId, quantity):
490
        """
491
        Add the BAD type inventory to existing stock.
492
 
493
        Parameters:
494
         - itemId
495
         - warehouseId
496
         - quantity
497
        """
498
        try:
499
            add_bad_inventory(itemId, warehouseId, quantity)
500
        finally:
501
            close_session()
502
 
503
    def getShippingLocations(self, ):
504
        """
505
        Returns all shipping locations
506
        """
507
        try:
508
            return [to_t_warehouse(w) for w in get_shipping_locations()]
509
        finally:
510
            close_session()
511
 
512
    def getAllVendorItemMappings(self, ):
513
        """
514
        Fetches all the vendor item mappings present.
515
        """
516
        try:
517
            return [to_t_vendor_item_mapping(m) for m in VendorItemMapping.query.all()]
518
        finally:
519
            close_session()
520
 
521
    def getInventorySnapshot(self, warehouseId):
522
        """
523
        Gets items' inventory for a warehouse
524
        If warehouse is passed as zero, items' inventory across all warehouses is sent
525
 
526
        Parameters:
527
         - warehouseId
528
        """
529
        try:
530
            resultMap = {}
531
            itemInventoryMap = get_inventory_snapshot(warehouseId)
532
            for key, value in itemInventoryMap.items():
533
                resultMap[key] = to_t_item_inventory(value, key)
534
 
535
            return resultMap
536
        finally:
537
            close_session()
538
 
539
    def clearItemAvailabilityCache(self, ):
540
        """
541
        Clear item availability cache.
542
        """
543
        try:
544
            clear_item_availability_cache()
545
        finally:
546
            close_session()
5957 mandeep.dh 547
 
6096 amit.gupta 548
    def clearItemAvailabilityCacheForItem(self, item_id):
549
        """
550
        Clear item availability cache.
551
        """
552
        try:
553
            clear_item_availability_cache(item_id)
554
        finally:
555
            close_session()
556
 
5957 mandeep.dh 557
    def getPendingOrdersInventory(self, vendorId):
558
        """
559
        Returns a list of inventory stock for items for which there are pending orders for the given vendor.
560
        """
561
        try:
562
            pending_items_inventory = get_pending_orders_inventory(vendorId)
563
            return [AvailableAndReservedStock(itemId = i[0], available=i[1], reserved=i[2], minimumStock=0) for i in pending_items_inventory]
564
        finally:
565
            close_session()
566
 
5944 mandeep.dh 567
    def updateVendorString(self, warehouseId, vendorString):
568
        """
569
        Parameters:
570
         - warehouseId
571
         - vendorString
572
        """
573
        try:
574
            update_vendor_string(warehouseId, vendorString)
575
        finally:
576
            close_session()
6467 amar.kumar 577
    def getOurWarehouseIdForVendor(self, vendorId):
578
        """
579
        Returns warehouseId for our warehouse for a vendor
580
        """    
581
        try:
582
            return get_our_warehouse_id_for_vendor(vendorId)
583
        finally:
6531 vikram.rag 584
            close_session()
585
    def getMonitoredWarehouseForVendors(self, vendorIds):
586
        """
587
        Returns monitored warehouse ids for vendors
588
        """    
589
        try:
590
            return get_monitored_warehouses_for_vendors(vendorIds)
591
        finally:
592
            close_session()
593
    def getIgnoredWarehouseidsAndItemids(self):
594
        """
595
        Returns list of itemid and warehouseId for ignored inventory update
596
        """    
597
        try:
598
            return get_ignored_warehouseids_and_itemids()
599
        finally:
600
            close_session()
601
 
602
    def insertItemtoIgnoreInventoryUpdatelist(self,item_id,warehouse_id):
603
        """
604
        Returns list of itemid and warehouseId for ignored inventory update
605
        """
606
        try:
6532 amit.gupta 607
            return insert_item_to_ignore_inventory_update_list(item_id,warehouse_id)
6531 vikram.rag 608
        finally:
609
            close_session()     
610
    def deleteItemFromIgnoredInventoryUpdateList(self,item_id,warehouse_id):
611
        """
612
        Deletes warehouse and item entry from inventory update ignore list
613
        """
614
        try:
615
            return delete_item_from_ignore_inventory_update_list(item_id,warehouse_id)
616
        finally:
617
            close_session()
618
    def getAllIgnoredInventoryupdateItemsCount(self):
619
        """
620
        Returns all ignored inventory update item count
621
        """
6833 amar.kumar 622
        try:
623
            return get_all_ignored_inventoryupdate_items_count()
624
        finally:
625
            close_session()
6531 vikram.rag 626
 
627
 
628
    def getIgnoredInventoryUpdateItemids(self,offset,limit):
629
        """
630
        Returns all ignored inventory update items
631
        """
6833 amar.kumar 632
        try:
633
            return get_ignored_inventoryupdate_itemids(offset,limit)
634
        finally:
635
            close_session()
6821 amar.kumar 636
    def updateItemStockPurchaseParams(self, item_id, numOfDaysStock, minStockLevel):
637
        """
638
        Update/Add parameters required for heuristic purchase of Items 
6833 amar.kumar 639
        """ 
640
        try:               
641
            update_item_stock_purchase_params(item_id, numOfDaysStock, minStockLevel)
642
        finally:
643
            close_session()
644
 
6821 amar.kumar 645
    def getItemStockPurchaseParams(self, item_id):
646
        """
647
        Get parameters required for heuristic purchase of Items 
6833 amar.kumar 648
        """ 
649
        try:               
650
            return to_t_item_stock_purchase_params(get_item_stock_purchase_params(item_id))
651
        finally:
652
            close_session()
653
 
6821 amar.kumar 654
    def addOosStatusForItem(self, oosStatusMap, date):
655
        """
656
        Add OOS status for Item 
657
        """
6833 amar.kumar 658
        try:
659
            add_oos_status_for_item(oosStatusMap, date)
660
        finally:
661
            close_session()
662
 
6832 amar.kumar 663
    def getOosStatusesForXDaysForItem(self, itemId, days):
664
        """
665
        Get OOSStatus Objects for "days" number of days 
666
        """
6833 amar.kumar 667
        try:
668
            return [to_t_oos_status(oos) for oos in get_oos_statuses_for_x_days_for_item(itemId, days)]
669
        finally:
6857 amar.kumar 670
            close_session()
671
 
672
    def getNonZeroItemStockPurchaseParams(self):
673
        """
674
        Get All ItemStockPurchaseParam objects where either minStockLevel or minNumOfDaysOfStock is zero 
675
        """
676
        try:
677
            return [to_t_item_stock_purchase_params(ispp) for ispp in get_non_zero_item_stock_purchase_params()]
678
        finally:
6833 amar.kumar 679
            close_session()