Subversion Repositories SmartDukaan

Rev

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