Subversion Repositories SmartDukaan

Rev

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