Subversion Repositories SmartDukaan

Rev

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