Subversion Repositories SmartDukaan

Rev

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