Subversion Repositories SmartDukaan

Rev

Rev 22724 | Rev 23183 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
412 ashish 1
'''
2
Created on 05-Aug-2010
3
 
4
@author: ashish
5
'''
3133 rajveer 6
from shop2020.clients.CatalogClient import CatalogClient
5944 mandeep.dh 7
from shop2020.clients.InventoryClient import InventoryClient
494 rajveer 8
from shop2020.config.client.ConfigClient import ConfigClient
5944 mandeep.dh 9
from shop2020.logistics.service.impl import DataAccessor
10
from shop2020.logistics.service.impl.Converters import to_t_awbupdate, \
20745 kshitij.so 11
    to_t_provider, to_t_pickup_store, to_t_bluedart_attribute
5944 mandeep.dh 12
from shop2020.logistics.service.impl.DataAccessor import get_empty_AWB, \
13
    get_shipment_info, initialize, get_logistics_estimation, get_provider, \
14
    get_providers, close_session, get_free_awb_count, get_holidays, is_alive, \
15
    get_provider_for_pickup_type, get_pickup_store, get_all_pickup_stores, \
6322 amar.kumar 16
    get_pickup_store_by_hotspot_id, get_destination_code, update_pincode, \
9840 amit.gupta 17
    add_pincode, store_shipment_info, adjust_delivery_time, get_min_advance_amount, \
19413 amit.gupta 18
    add_new_awbs, run_Logistics_Location_Info_Update, \
19
    get_first_delivery_estimate_for_wh_location, \
20
    get_provider_limit_details_for_pincode, get_new_empty_awb, \
20745 kshitij.so 21
    get_logistics_locations, get_costing_and_delivery_estimate_for_pincode, \
22634 amit.gupta 22
    get_bluedart_attributes_for_logistics_txn_id, _DeliveryEstimateObject
9840 amit.gupta 23
from shop2020.logistics.service.impl.DataService import \
24
    ServiceableLocationDetails
19413 amit.gupta 25
from shop2020.thriftpy.logistics.ttypes import ItemText, LogisticsInfo, \
5944 mandeep.dh 26
    LogisticsServiceException, DeliveryType, PickUpType
27
from shop2020.thriftpy.model.v1.catalog.ttypes import status
9840 amit.gupta 28
from shop2020.utils.Utils import to_java_date, to_py_date
29
import collections
494 rajveer 30
import datetime
644 chandransh 31
import math
1687 vikas 32
import sys
23121 amit.gupta 33
from shop2020.utils.caching.SimpleCaching import memoized
9840 amit.gupta 34
#Start:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
35
#End:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
472 rajveer 36
 
412 ashish 37
class LogisticsServiceHandler:
38
 
3187 rajveer 39
    def __init__(self, dbname='logistics', db_hostname='localhost'):
40
        initialize(dbname, db_hostname)
746 rajveer 41
        try:
42
            config_client = ConfigClient()
5978 rajveer 43
            self.sourceId = int(config_client.get_property("sourceid"))
746 rajveer 44
            self.cutoff_time = int(config_client.get_property('delivery_cutoff_time'))
5843 mandeep.dh 45
            self.cod_cutoff_time = 24 #int(config_client.get_property('delivery_cutoff_time'))
776 rajveer 46
            self.default_pincode = int(config_client.get_property('default_pincode'))
1687 vikas 47
        except Exception as ex:
48
            print "[ERROR] Unexpected config error:", sys.exc_info()[0]
5978 rajveer 49
            self.sourceId = 1
746 rajveer 50
            self.cutoff_time = 15
5843 mandeep.dh 51
            self.cod_cutoff_time = 24
4866 rajveer 52
            self.default_pincode = "110001"
5978 rajveer 53
 
3064 chandransh 54
 
669 chandransh 55
    def getProvider(self, providerId):
675 chandransh 56
        """
57
        Returns a provider for a given provider ID. Throws an exception if none found.
58
 
59
        Parameters:
60
         - providerId
61
        """
796 rajveer 62
        try:
1137 chandransh 63
            provider = get_provider(providerId)
64
            if provider:
65
                return to_t_provider(provider)
66
            else:
67
                raise LogisticsServiceException(101, "No Provider found for the given id")
796 rajveer 68
        finally:
69
            close_session()
70
 
675 chandransh 71
    def getAllProviders(self, ):
72
        """
73
        Returns a list containing all the providers.
74
        """
796 rajveer 75
        try:
76
            return [to_t_provider(provider) for provider in get_providers()]
77
        finally:
78
            close_session()
79
 
5767 rajveer 80
    def getLogisticsInfo(self, destination_pincode, itemId, type, pickUp):
483 rajveer 81
        """
82
        Parameters:
83
         - destination_pincode
716 rajveer 84
         - item_id
3044 chandransh 85
         - type
483 rajveer 86
        """
796 rajveer 87
        try:
22634 amit.gupta 88
            logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pincode, type, pickUp)
7946 manish.sha 89
            #logistics_info.airway_billno = get_empty_AWB(logistics_info.providerId, type)
796 rajveer 90
            return logistics_info
91
        finally:
92
            close_session()
93
 
20724 kshitij.so 94
    def getEmptyAWB(self, providerId, logisticsTransactionId):
412 ashish 95
        """
96
        Parameters:
97
         - provider_id
5247 rajveer 98
         - type
412 ashish 99
        """
796 rajveer 100
        try:
20724 kshitij.so 101
            return get_empty_AWB(providerId, logisticsTransactionId)
796 rajveer 102
        finally:
103
            close_session()
104
 
6643 rajveer 105
    def getShipmentInfo(self, awbNumber, providerId):
412 ashish 106
        """
107
        Parameters:
6643 rajveer 108
         - awbNumber
766 rajveer 109
         - providerId
412 ashish 110
        """
796 rajveer 111
        try:
6643 rajveer 112
            awb_updates = get_shipment_info(awbNumber, providerId)
796 rajveer 113
            t_updates = []
114
            for update in awb_updates:
115
                t_updates.append(to_t_awbupdate(update))
116
            return t_updates
117
        finally:
118
            close_session()
3044 chandransh 119
 
6643 rajveer 120
    def storeShipmentInfo(self, update):
121
        """
122
        Parameters:
123
         - update
124
        """
125
        try:
126
            store_shipment_info(update)
127
        finally:
128
            close_session()
129
 
130
 
4630 mandeep.dh 131
    def getLogisticsEstimation(self, itemId, destination_pin, type):
472 rajveer 132
        """
133
        Parameters:
134
         - itemId
135
         - destination_pin
4630 mandeep.dh 136
         - type
472 rajveer 137
        """
644 chandransh 138
        try:
4630 mandeep.dh 139
            return self.get_logistics_estimation_with_type(itemId, destination_pin, type)
796 rajveer 140
        finally:
141
            close_session()
3044 chandransh 142
 
7256 rajveer 143
 
144
    def getLogisticsEstimationForStore(self, itemId, destination_pin, type):
145
        """
146
        Parameters:
147
         - itemId
148
         - destination_pin
149
         - type
150
        """
151
        try:
152
            todate = datetime.datetime.now()
153
            logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pin, type)
7273 rajveer 154
            logistics_info.deliveryTime = to_java_date(todate +  datetime.timedelta(days = adjust_delivery_time(todate, logistics_info.deliveryTime)))
155
            logistics_info.shippingTime = to_java_date(todate +  datetime.timedelta(days = adjust_delivery_time(todate, logistics_info.shippingTime)))
7275 rajveer 156
            minAdvanceAmount, logistics_info.codAllowed = get_min_advance_amount(itemId, destination_pin, logistics_info.providerId, logistics_info.codAllowed)
157
            ## Send minadvanceamount in providerId field 
158
            logistics_info.providerId = int(minAdvanceAmount)
7256 rajveer 159
            return logistics_info
160
        finally:
161
            close_session()
162
 
22634 amit.gupta 163
    def get_logistics_estimation_with_type(self, itemId, destination_pin, type, pickUp=PickUpType.COURIER):
3044 chandransh 164
        try:
5295 rajveer 165
            #Get the id and location of actual warehouse that'll be used to fulfil this order.
5944 mandeep.dh 166
            client = InventoryClient().get_client()
7589 rajveer 167
            fulfilmentWarehouseId, expected_delay, billingWarehouseId, sellingPrice, totalAvailability, weight = client.getItemAvailabilityAtLocation(itemId, self.sourceId)
22724 amit.gupta 168
            #We assume that if totalAvailability 0 then its the case of hotspot billing where itemAvailabilityCache is sort of bypassed
169
            if totalAvailability <= 0:
170
                expected_delay = 0
171
 
3044 chandransh 172
        except Exception as ex:
173
            raise LogisticsServiceException(103, "Unable to fetch inventory information about this item.")
5295 rajveer 174
 
22634 amit.gupta 175
        if pickUp == PickUpType.COURIER:
176
            delivery_estimate = get_logistics_estimation(destination_pin, sellingPrice, weight, type, billingWarehouseId)
177
        else:
178
            #if pickUp == PickUpType.RUNNER or pickUp == PickUpType.SELF:
22637 amit.gupta 179
            delivery_estimate = _DeliveryEstimateObject(0, 0, get_provider_for_pickup_type(pickUp), False, False)
3218 rajveer 180
        if delivery_estimate is None:
3044 chandransh 181
            raise LogisticsServiceException(104, "Unable to fetch delivery estimate for this pincode.")
5295 rajveer 182
 
3044 chandransh 183
 
5270 rajveer 184
        ## Commented below part as we have only Delhi as warehouse city. If we will add some more warehouses in different cities, this could be  useful. 
4009 chandransh 185
        # We are revising the estimates based on the actual warehouse that this order will be assigned to.
186
        # This warehouse may be located in a zone which is different from the one we allocated for this pincode.
5270 rajveer 187
        #delivery_estimate = get_logistics_estimation(destination_pin, item.sellingPrice, warehouse_loc, type)
188
        #if delivery_estimate is None:
189
        #    raise LogisticsServiceException(105, "Unable to fetch delivery estimate for pincode: " + destination_pin + " and revised location: " + str(warehouse_loc))
3044 chandransh 190
 
6537 rajveer 191
        delivery_time = 24 * (delivery_estimate.delivery_time + delivery_estimate.delivery_delay)
3044 chandransh 192
 
4009 chandransh 193
        '''
194
        We're now calculating the expected shipping delay which is independent of
195
        the courier agency and is completely within our control (well, almost).
196
        '''
3355 chandransh 197
        #Always add the expected delay
22634 amit.gupta 198
        #As per Deenanath This should be removed
4009 chandransh 199
        shipping_delay = 24 * expected_delay
3355 chandransh 200
 
4829 rajveer 201
        # Sometimes we set negative shipping delay just in case we know time to procure will be less than the default.
202
        # If we have received inventory and forgot to remove expected delay from item, it could lead to display negative shipping days. 
203
        if shipping_delay < 0:
204
            shipping_delay = 0
205
 
3044 chandransh 206
        #Further increase the estimate if it's late in the day
3064 chandransh 207
        current_hour = datetime.datetime.now().hour
208
        if type == DeliveryType.PREPAID and self.cutoff_time <= current_hour:
4009 chandransh 209
            shipping_delay = shipping_delay + 24
3044 chandransh 210
 
4426 rajveer 211
        #In case of COD,increase delay by one more day
22634 amit.gupta 212
        #As per deenanath why are doing this?
4426 rajveer 213
        if type == DeliveryType.COD:
214
            shipping_delay = shipping_delay + 24
6524 rajveer 215
            delivery_estimate.otgAvailable = False
4426 rajveer 216
 
4010 chandransh 217
        delivery_time = delivery_time + shipping_delay
218
 
4009 chandransh 219
        shipping_delay = int(math.ceil(shipping_delay/24.0))
4010 chandransh 220
        delivery_time = int(math.ceil(delivery_time/24.0))
3044 chandransh 221
 
222
        logistics_info = LogisticsInfo()
223
        logistics_info.deliveryTime = delivery_time
3218 rajveer 224
        logistics_info.providerId = delivery_estimate.provider_id
5110 mandeep.dh 225
        logistics_info.warehouseId = billingWarehouseId
226
        logistics_info.fulfilmentWarehouseId = fulfilmentWarehouseId
4009 chandransh 227
        logistics_info.shippingTime = shipping_delay
4870 rajveer 228
        logistics_info.codAllowed = delivery_estimate.codAllowed 
6524 rajveer 229
        logistics_info.otgAvailable = delivery_estimate.otgAvailable
6726 rajveer 230
        logistics_info.deliveryDelay = delivery_estimate.delivery_delay
3044 chandransh 231
 
5595 anupam.sin 232
        try:
233
            return logistics_info
234
        finally:
235
            close_session()
3044 chandransh 236
 
731 chandransh 237
    def getDestinationCode(self, providerId, pinCode):
238
        """
239
        Returns the short three letter code of a pincode for the given provider.
240
        Raises an exception if the pin code is not serviced by the given provider.
241
 
242
        Parameters:
243
         - providerId
244
         - pinCode
245
        """
796 rajveer 246
        try:
3217 rajveer 247
            try:
3218 rajveer 248
                dest_code = DataAccessor.serviceable_location_cache[providerId][pinCode][0]
3217 rajveer 249
                return dest_code
250
            except:
6017 amar.kumar 251
                try:
252
                    dest_code = get_destination_code(providerId, pinCode) 
253
                    return dest_code
254
                except:
8182 amar.kumar 255
                    if providerId >7:
256
                        return ""
6017 amar.kumar 257
                    raise LogisticsServiceException(101, "The pincode " + pinCode + " is not serviced by this provider: " + str(providerId))
796 rajveer 258
        finally:
259
            close_session()
1137 chandransh 260
 
3103 chandransh 261
    def getFreeAwbCount(self, providerId, type):
1137 chandransh 262
        """
3103 chandransh 263
        Returns the number of unused AWB numbers for the given provider of the given type
796 rajveer 264
 
1137 chandransh 265
        Parameters:
266
         - providerId
3103 chandransh 267
         - type
1137 chandransh 268
        """
269
        try:
3103 chandransh 270
            return get_free_awb_count(providerId, type)
1137 chandransh 271
        finally:
272
            close_session()
1730 ankur.sing 273
 
274
    def getHolidays(self, fromDate, toDate):
275
        """
276
        Returns list of Holiday dates between fromDate and toDate (both inclusive)
277
        fromDate should be passed as milliseconds corresponding to the start of the day.
278
        If fromDate is passed as -1, fromDate is not considered for filtering
279
        If toDate is passed as -1, toDate is not considered for filtering
1137 chandransh 280
 
1730 ankur.sing 281
        Parameters:
282
         - fromDate
283
         - toDate
284
        """
285
        try:
286
            return get_holidays(fromDate, toDate)
287
        finally:
288
            close_session()
5527 anupam.sin 289
 
290
    def getProviderForPickupType(self, pickUp):
291
        try:
292
            return get_provider_for_pickup_type(pickUp)
293
        finally:
294
            close_session()
3064 chandransh 295
 
766 rajveer 296
    def closeSession(self, ):
297
        close_session()
3376 rajveer 298
 
299
    def isAlive(self, ):
300
        """
301
        For checking weather service is active alive or not. It also checks connectivity with database
302
        """
303
        try:
304
            return is_alive()
305
        finally:
306
            close_session()
4934 amit.gupta 307
 
308
    def getEntityLogisticsEstimation(self, catalogItemId, destination_pin, type):
309
        """
310
        Returns a LogisticsInfo structure w/o an airway bill number. Use this method during the estimation phase.
311
        Raises an exception if this pincode is not allocated to any warehouse zone or provider. Also, if the pincode
312
        is allocated to a warehouse zone but there are no actual warehouses in that zone, an exception is raised.
313
 
314
        Parameters:
315
         - catalogItemId
316
         - destination_pin
317
         - type
318
        """
319
        try:
320
            return self.get_entity_logistics_estimation_with_type(catalogItemId, destination_pin, type)
321
        finally:
322
            close_session()
323
 
324
    def get_entity_logistics_estimation_with_type(self, catalog_item_id, destination_pin, type):
325
        try:
326
            client = CatalogClient().get_client()
327
            items = client.getValidItemsByCatalogId(catalog_item_id)
328
        except Exception as ex:
329
            raise LogisticsServiceException(103, "Unable to fetch inventory information about this entity.")
330
 
331
        estimateList = []
332
 
333
        for item in items:
11254 amit.gupta 334
            try:
335
                estimationInfo = self.get_logistics_estimation_with_type(item.id, destination_pin, type)
336
            except Exception as ex:
337
                estimationInfo = LogisticsInfo()
338
                estimationInfo.deliveryTime = 0
4934 amit.gupta 339
            if item.itemStatus == status.ACTIVE:
9840 amit.gupta 340
                estimateList.append((0, estimationInfo.deliveryTime, "BUY NOW", item.id))
4934 amit.gupta 341
            elif item.itemStatus == status.PAUSED:
9840 amit.gupta 342
                estimateList.append((1, estimationInfo.deliveryTime, "NOTIFY ME", item.id))
4934 amit.gupta 343
            elif item.itemStatus == status.PAUSED_BY_RISK:
9840 amit.gupta 344
                estimateList.append((2, estimationInfo.deliveryTime, "NOTIFY ME", item.id))
6074 amit.gupta 345
            elif item.itemStatus == status.COMING_SOON:
10688 amit.gupta 346
                estimateList.append((3, estimationInfo.deliveryTime, "NOTIFY ME", item.id))
4934 amit.gupta 347
 
348
        estimateList.sort()
5595 anupam.sin 349
        try:
9840 amit.gupta 350
            return [ ItemText(estimate[-1], estimate[-2]) for estimate in estimateList]
5595 anupam.sin 351
        finally:
352
            close_session()
5555 rajveer 353
 
5595 anupam.sin 354
    def getAllPickupStores(self):
355
        try:
356
            return [to_t_pickup_store(pickup_store) for pickup_store in get_all_pickup_stores()]
357
        finally:
358
            close_session()
5555 rajveer 359
 
360
    def getPickupStore(self, storeId):
361
        """
362
        Parameters:
363
         - storeId
364
        """
5595 anupam.sin 365
        try:
366
            storeToReturn = to_t_pickup_store(get_pickup_store(storeId))
367
            return storeToReturn
368
        finally:
5719 rajveer 369
            close_session()
370
 
371
    def getPickupStoreByHotspotId(self, hotspotId):
372
        """
373
        Parameters:
374
         - hotspotId
375
        """
376
        try:
377
            storeToReturn = to_t_pickup_store(get_pickup_store_by_hotspot_id(hotspotId))
378
            return storeToReturn
379
        finally:
6322 amar.kumar 380
            close_session()
6524 rajveer 381
    def addPincode(self, providerId, pincode, destCode, exp, cod, stationType, otgAvailable):
6322 amar.kumar 382
        try:
6524 rajveer 383
            add_pincode(providerId, pincode, destCode, exp, cod, stationType, otgAvailable)
6322 amar.kumar 384
        finally:
385
            close_session()
6524 rajveer 386
    def updatePincode(self, providerId, pincode, exp, cod, otgAvailable):
6322 amar.kumar 387
        try:
6524 rajveer 388
            update_pincode(providerId, pincode, exp, cod, otgAvailable)
6322 amar.kumar 389
        finally:
7567 rajveer 390
            close_session()
391
 
13146 manish.sha 392
    def addNewAwbs(self, providerId, isCod, awbs, awbUsedFor):
7567 rajveer 393
        try:
13146 manish.sha 394
            return add_new_awbs(providerId, isCod, awbs, awbUsedFor)
7567 rajveer 395
        finally:
7733 manish.sha 396
            close_session()
7786 manish.sha 397
 
398
 
23121 amit.gupta 399
    def runLogisticsLocationInfoUpdate(self, logisticsLocationInfoList, runCompleteUpdate, providerId):
7733 manish.sha 400
        try:
23121 amit.gupta 401
            run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate, providerId)
7733 manish.sha 402
        finally:
403
            close_session()
7888 rajveer 404
 
405
    def adjustDeliveryDays(self, startDate, days):
406
        try:
407
            return adjust_delivery_time(to_py_date(startDate), days)
408
        finally:
12895 manish.sha 409
            close_session()
410
 
411
    def getFirstDeliveryEstimateForWhLocation(self, pincode, whLocation):
412
        try:
413
            return get_first_delivery_estimate_for_wh_location(pincode, whLocation)
414
        finally:
13146 manish.sha 415
            close_session()
416
 
417
    def getProviderLimitDetailsForPincode(self, providerId, pincode):
418
        try:
419
            return get_provider_limit_details_for_pincode(providerId, pincode)
420
        finally:
421
            close_session()
422
 
423
    def getNewEmptyAwb(self, providerId, type, orderQuantity):
424
        try:
425
            return get_new_empty_awb(providerId, type, orderQuantity)
426
        finally:
427
            close_session()
19421 manish.sha 428
 
19413 amit.gupta 429
    def getLocationInfoMap(self, destinationPin, sellingPriceList):
430
        try:
431
            return get_logistics_locations(destinationPin, sellingPriceList)
432
        finally:
19421 manish.sha 433
            close_session()
434
 
19474 manish.sha 435
    def getCostingAndDeliveryEstimateForPincode(self, pincode, transactionAmount, isCod, weight, billingWarehouseId, isCompleteTxn):
19421 manish.sha 436
        try:
19474 manish.sha 437
            costingAndDeliveryEstimateObj = get_costing_and_delivery_estimate_for_pincode(pincode, transactionAmount, isCod, weight, billingWarehouseId, isCompleteTxn)
19421 manish.sha 438
            delivery_time = 24 * (costingAndDeliveryEstimateObj.deliveryTime + costingAndDeliveryEstimateObj.delivery_delay)
439
            shipping_delay = 0
440
 
441
            #Further increase the estimate if it's late in the day
442
            current_hour = datetime.datetime.now().hour
443
            if not isCod and self.cutoff_time <= current_hour:
444
                shipping_delay = shipping_delay + 24
445
 
446
            #In case of COD,increase delay by one more day
447
            if isCod:
448
                shipping_delay = shipping_delay + 24
449
                costingAndDeliveryEstimateObj.otgAvailable = False
450
 
451
            delivery_time = delivery_time + shipping_delay
452
 
453
            shipping_delay = int(math.ceil(shipping_delay/24.0))
454
            delivery_time = int(math.ceil(delivery_time/24.0))
455
 
456
            costingAndDeliveryEstimateObj.deliveryTime = delivery_time
457
            costingAndDeliveryEstimateObj.shippingTime = shipping_delay
458
            return costingAndDeliveryEstimateObj
459
        finally:
460
            close_session()
20745 kshitij.so 461
 
462
    def getBluedartAttributesForLogisticsTxnId(self, logisticsTxnId, name):
463
        try:
464
            return to_t_bluedart_attribute(get_bluedart_attributes_for_logistics_txn_id(logisticsTxnId, name))
465
        finally:
466
            close_session()