Subversion Repositories SmartDukaan

Rev

Rev 5957 | Rev 5978 | 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
 
124
    def getItemAvailabilityAtLocation(self, itemId):
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
139
        """
140
        try:
141
            return get_item_availability_for_location(itemId)
142
        finally:
143
            close_session()
144
 
145
    def getItemAvailibilityAtWarehouse(self, warehouse_id, item_id):
146
        """
147
        Parameters:
148
         - warehouse_id
149
         - item_id
150
        """
151
        log_entry(self, "item availability at warehouse requested")
152
        try:
153
            return get_item_availability_for_warehouse(warehouse_id, item_id)
154
        finally:
155
            close_session()
156
 
157
    def getItemInventoryHistory(self, id, item_id, warehouse_id, from_date, to_date):
158
        """
159
        Parameters:
160
         - id
161
         - item_id
162
         - warehouse_id
163
         - from_date
164
         - to_date
165
        """
166
        pass
167
 
168
    def getAllWarehouses(self, isActive):
169
        """
170
        Parameters:
171
        - isActive
172
        """
173
        try:
174
            if isActive:
175
                warehouses = get_all_warehouses_by_status(3)
176
            else:
177
                warehouses = get_all_warehouses_by_status(None)
178
 
179
            ret_warehouses = []
180
 
181
            for warehouse in warehouses:
182
                ret_warehouses.append(to_t_warehouse(warehouse))
183
            return ret_warehouses
184
        finally:
185
            close_session()
186
 
187
    def getWarehouse(self, warehouse_id):
188
        """
189
        Parameters:
190
         - warehouse_id
191
        """
192
        log_entry(self, "get warehouse call")
193
        try:
194
            warehouse = get_Warehouse(warehouse_id)
195
            if warehouse:
196
                return to_t_warehouse(warehouse)
197
            else:
198
                raise InventoryServiceException(101, "no such warehouse: " + str(warehouse_id))
199
        finally:
200
            close_session()
201
 
202
    def getAllItemsForWarehouse(self, warehouse_id):
203
        """
204
        Parameters:
205
         - warehouse_id
206
        """
207
        log_entry(self, "getting all items for warehouse")
208
        try:
209
            all_items = get_all_items_for_warehouse(warehouse_id)
210
            t_items = []
211
            for item in all_items:
212
                t_items.append(item.id)
213
            return t_items
214
        finally:
215
            close_session()
216
 
5966 rajveer 217
    def isOrderBillable(self, itemId, warehouseId, sourceId, orderId):
5944 mandeep.dh 218
        """
5966 rajveer 219
        Depending on reservation in the table, verify if we can bill this order or not.
220
 
221
        Parameters:
222
         - itemId
223
         - warehouseId
224
         - sourceId
225
         - orderId
226
        """
227
        try:
228
            return is_order_billable(itemId, warehouseId, sourceId, orderId)
229
        finally:
230
            close_session()
231
 
232
    def reserveItemInWarehouse(self, itemId, warehouseId, sourceId, orderId, createdTimestamp, promisedShippingTimestamp, quantity):
233
        """
5944 mandeep.dh 234
        Increases the reservation count for an item in a warehouse. Should always succeed normally.
235
 
236
        Parameters:
237
         - itemId
238
         - warehouseId
239
        """
240
        log_entry(self, "reserveItemInWarehouse called")
241
        try:
5966 rajveer 242
            return reserve_item_in_warehouse(itemId, warehouseId, sourceId, orderId, createdTimestamp, promisedShippingTimestamp, quantity)
5944 mandeep.dh 243
        finally:
244
            close_session()
245
 
5966 rajveer 246
    def reduceReservationCount(self, itemId, warehouseId, sourceId, orderId, quantity):
5944 mandeep.dh 247
        """
248
        Decreases 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, "reduceReservationCount called")
255
        try:
5966 rajveer 256
            return reduce_reservation_count(itemId, warehouseId, sourceId, orderId, quantity)
5944 mandeep.dh 257
        finally:
258
            close_session()
259
 
260
    def getItemPricing(self, itemId, vendorId):
261
        """
262
        Returns the pricing information of an item associated with the vendor of the given warehouse.
263
        Raises an exception if either the item, vendor or the associated pricing information can't be found.
264
 
265
        Parameters:
266
         - itemId
267
         - warehouseId
268
        """
269
        try:
270
            return to_t_vendor_item_pricing(get_item_pricing(itemId, vendorId))
271
        finally:
272
            close_session()
273
 
274
 
275
    def getAllItemPricing(self, itemId):
276
        """
277
        Returns list of the pricing information of an item associated an item.
278
        Raises an exception if the item can't be found.
279
 
280
        Parameters:
281
         - itemId
282
        """
283
        try:
284
            return [to_t_vendor_item_pricing(vid) for vid in get_all_item_pricing(itemId)]
285
        finally:
286
            close_session()
287
 
288
    def addVendorItemPricing(self, vendorItemPricing):
289
        """
290
        Adds vendor prices corresponding to the item. If pricing already exists then updates the prices. 
291
        Raises an exception if either the item or vendor can't be found corresponding to their ids.
292
 
293
        Parameters:
294
         - vendorItemPricing
295
        """
296
        log_entry(self, "updateVendorItemPricing called")
297
        try:
298
            return add_vendor_pricing(vendorItemPricing)
299
        finally:
300
            close_session()
301
 
302
    def getVendor(self, vendorId):
303
        """
304
        Return a vendor for id
305
        """
306
        try:
307
            return to_t_vendor(get_vendor(vendorId))
308
        finally:
309
            close_session()
310
 
311
 
312
    def getAllVendors(self, ):
313
        """
314
        Return list of all vendors
315
        """
316
        try:
317
            return [to_t_vendor(v) for v in get_all_vendors()]
318
        finally:
319
            close_session()
320
 
321
    def addVendorItemMapping(self, key, vendorItemMapping):
322
        """
323
        Adds VendorItemMapping. Updates VendorItemMapping if exists corresponding to the item key.
324
 
325
        Parameters:
326
         - key
327
         - vendorItemMapping
328
        """
329
        log_entry(self, "addVendorItemMapping called")
330
        try:
331
            return add_vendor_item_mapping(key, vendorItemMapping)
332
        finally:
333
            close_session()
334
 
335
    def getVendorItemMappings(self, itemId):
336
        """
337
        Returns the list of vendor item mapping corresponding to itemId passed as parameter.
338
        Raises an exception if item not found corresponding to itemId
339
 
340
        Parameters:
341
         - itemId
342
        """
343
        try:
344
            item_mappings = get_item_mappings(itemId)
345
            return [to_t_vendor_item_mapping(vim) for vim in item_mappings]
346
        finally:
347
            close_session()
348
 
349
    def isAlive(self, ):
350
        """
351
        For checking weather service is active alive or not. It also checks connectivity with database
352
        """
353
        try:
354
            return is_alive()
355
        finally:
356
            close_session()
357
 
358
    def closeSession(self, ):
359
        """
360
        For closing the open session in sqlalchemy
361
        """
362
        close_session()
363
 
364
    def addVendor(self, vendor):
365
        """
366
        add a new vendor
367
        """
368
        try:
369
            return add_vendor(vendor)
370
        finally:
371
            close_session()
372
 
373
    def getWarehouses(self, warehouseType, inventoryType, vendorId, billingWarehouseId, shippingWarehouseId):
374
        """
375
        This method returns all warehouses for a given warehosueType, inventoryType, vendor, billingWarehouse and shippingWarehouse.
376
        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
377
        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
378
        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
379
        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
380
 
381
        Parameters:
382
         - warehouseType
383
         - inventoryType
384
         - vendorId
385
         - billingWarehouseId
386
         - shippingWarehouseId
387
        """
388
        try:
389
            query = Warehouse.query
390
            if warehouseType is not None:
391
                query = query.filter_by(warehouseType = WarehouseType._VALUES_TO_NAMES[warehouseType])
392
            if inventoryType is not None:
393
                query = query.filter_by(inventoryType = InventoryType._VALUES_TO_NAMES[inventoryType])
394
            if vendorId:
395
                query = query.filter_by(vendor_id = vendorId)
396
            if billingWarehouseId:
397
                query = query.filter_by(billingWarehouseId = billingWarehouseId)
398
            if shippingWarehouseId:
399
                query = query.filter_by(shippingWarehouseId = shippingWarehouseId)
400
 
401
            return [to_t_warehouse(w) for w in query.all()]
402
        finally:
403
            close_session()
404
 
405
    def getItemKeysToBeProcessed(self, warehouseId):
406
        """
407
        Returns the list of item keys which need to be processed for a given warehouse.
408
        This is currently used by Support application to send item keys whose inventory needs
409
        to be updated from PLB
410
 
411
        Parameters:
412
         - warehouseId
413
        """
414
        try:
415
            return get_item_keys_to_be_processed(warehouseId)
416
        finally:
417
            close_session()
418
 
419
    def markMissedInventoryUpdatesAsProcessed(self, itemKey, warehouseId):
420
        """
421
        Marks/Deletes missed inventory updates for a given key and warehouse.
422
        This generally happens when updates from PLB are applied on the currentinventorysnapshot for an item
423
 
424
        Parameters:
425
         - itemKey
426
         - warehouseId
427
        """
428
        try:
429
            mark_missed_inventory_updates_as_processed(itemKey, warehouseId)
430
        finally:
431
            close_session()
432
 
433
    def resetAvailability(self, itemKey, vendorId, quantity, warehouseId):
434
        """
435
        Resets availability of an item to the quantity mentioned in a warehouse.
436
 
437
        Parameters:
438
         - itemKey
439
         - vendorId
440
         - quantity
441
         - warehouseId
442
        """
443
        try:
444
            reset_availability(itemKey, vendorId, quantity, warehouseId)
445
        finally:
446
            close_session()
447
 
448
    def resetAvailabilityForWarehouse(self, warehouseId):
449
        """
450
        Resets availability of a warehouse to zero.
451
 
452
        Parameters:
453
         - warehouseId
454
        """
455
        try:
456
            reset_availability_for_warehouse(warehouseId)
457
        finally:
458
            close_session()
459
 
460
    def getIgnoredItemKeys(self, ):
461
        """
462
        Returns all the item key mappings that have been ignored until date. Value of map has the warehouse id
463
        and the timestamp from where alert was raised.
464
        """
465
        try:
466
            itemKeysMap = {}
467
            for key in MissedInventoryUpdate.query.filter_by(isIgnored = 1).all():
468
                itemKeysMap[key.itemKey] = { key.warehouseId : to_java_date(key.timestamp) }
469
 
470
            return itemKeysMap
471
        finally:
472
            close_session()
473
 
474
    def addBadInventory(self, itemId, warehouseId, quantity):
475
        """
476
        Add the BAD type inventory to existing stock.
477
 
478
        Parameters:
479
         - itemId
480
         - warehouseId
481
         - quantity
482
        """
483
        try:
484
            add_bad_inventory(itemId, warehouseId, quantity)
485
        finally:
486
            close_session()
487
 
488
    def getShippingLocations(self, ):
489
        """
490
        Returns all shipping locations
491
        """
492
        try:
493
            return [to_t_warehouse(w) for w in get_shipping_locations()]
494
        finally:
495
            close_session()
496
 
497
    def getAllVendorItemMappings(self, ):
498
        """
499
        Fetches all the vendor item mappings present.
500
        """
501
        try:
502
            return [to_t_vendor_item_mapping(m) for m in VendorItemMapping.query.all()]
503
        finally:
504
            close_session()
505
 
506
    def getInventorySnapshot(self, warehouseId):
507
        """
508
        Gets items' inventory for a warehouse
509
        If warehouse is passed as zero, items' inventory across all warehouses is sent
510
 
511
        Parameters:
512
         - warehouseId
513
        """
514
        try:
515
            resultMap = {}
516
            itemInventoryMap = get_inventory_snapshot(warehouseId)
517
            for key, value in itemInventoryMap.items():
518
                resultMap[key] = to_t_item_inventory(value, key)
519
 
520
            return resultMap
521
        finally:
522
            close_session()
523
 
524
    def clearItemAvailabilityCache(self, ):
525
        """
526
        Clear item availability cache.
527
        """
528
        try:
529
            clear_item_availability_cache()
530
        finally:
531
            close_session()
5957 mandeep.dh 532
 
533
    def getPendingOrdersInventory(self, vendorId):
534
        """
535
        Returns a list of inventory stock for items for which there are pending orders for the given vendor.
536
        """
537
        try:
538
            pending_items_inventory = get_pending_orders_inventory(vendorId)
539
            return [AvailableAndReservedStock(itemId = i[0], available=i[1], reserved=i[2], minimumStock=0) for i in pending_items_inventory]
540
        finally:
541
            close_session()
542
 
5944 mandeep.dh 543
    def updateVendorString(self, warehouseId, vendorString):
544
        """
545
        Parameters:
546
         - warehouseId
547
         - vendorString
548
        """
549
        try:
550
            update_vendor_string(warehouseId, vendorString)
551
        finally:
552
            close_session()
553