Subversion Repositories SmartDukaan

Rev

Rev 23686 | Rev 23712 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 23686 Rev 23711
Line 29... Line 29...
29
import collections
29
import collections
30
import datetime
30
import datetime
31
import math
31
import math
32
import sys
32
import sys
33
from shop2020.utils.caching.SimpleCaching import memoized
33
from shop2020.utils.caching.SimpleCaching import memoized
34
#Start:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
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
35
# End:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
-
 
36
 
36
 
37
 
37
class LogisticsServiceHandler:
38
class LogisticsServiceHandler:
38
    
39
    
39
    def __init__(self, dbname='logistics', db_hostname='localhost'):
40
    def __init__(self, dbname='logistics', db_hostname='localhost'):
40
        initialize(dbname, db_hostname)
41
        initialize(dbname, db_hostname)
41
        try:
42
        try:
42
            config_client = ConfigClient()
43
            config_client = ConfigClient()
43
            self.sourceId = int(config_client.get_property("sourceid"))
44
            self.sourceId = int(config_client.get_property("sourceid"))
44
            self.cutoff_time = int(config_client.get_property('delivery_cutoff_time'))
45
            self.cutoff_time = int(config_client.get_property('delivery_cutoff_time'))
45
            self.cod_cutoff_time = 24 #int(config_client.get_property('delivery_cutoff_time'))
46
            self.cod_cutoff_time = 24  # int(config_client.get_property('delivery_cutoff_time'))
46
            self.default_pincode = int(config_client.get_property('default_pincode'))
47
            self.default_pincode = int(config_client.get_property('default_pincode'))
47
        except Exception as ex:
48
        except Exception as ex:
48
            print "[ERROR] Unexpected config error:", sys.exc_info()[0]
49
            print "[ERROR] Unexpected config error:", sys.exc_info()[0]
49
            self.sourceId = 1
50
            self.sourceId = 1
50
            self.cutoff_time = 15
51
            self.cutoff_time = 15
51
            self.cod_cutoff_time = 24
52
            self.cod_cutoff_time = 24
52
            self.default_pincode = "110001"
53
            self.default_pincode = "110001"
53
        
-
 
54
         
54
         
55
    def getProvider(self, providerId):
55
    def getProvider(self, providerId):
56
        """
56
        """
57
        Returns a provider for a given provider ID. Throws an exception if none found.
57
        Returns a provider for a given provider ID. Throws an exception if none found.
58
        
58
        
Line 66... Line 66...
66
            else:
66
            else:
67
                raise LogisticsServiceException(101, "No Provider found for the given id")
67
                raise LogisticsServiceException(101, "No Provider found for the given id")
68
        finally:
68
        finally:
69
            close_session()
69
            close_session()
70
            
70
            
71
    def getAllProviders(self, ):
71
    def getAllProviders(self,):
72
        """
72
        """
73
        Returns a list containing all the providers.
73
        Returns a list containing all the providers.
74
        """
74
        """
75
        try:
75
        try:
76
            return [to_t_provider(provider) for provider in get_providers()]
76
            return [to_t_provider(provider) for provider in get_providers()]
Line 84... Line 84...
84
         - item_id
84
         - item_id
85
         - type
85
         - type
86
        """
86
        """
87
        try:
87
        try:
88
            logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pincode, type, pickUp, stateId)
88
            logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pincode, type, pickUp, stateId)
89
            #logistics_info.airway_billno = get_empty_AWB(logistics_info.providerId, type)
89
            # logistics_info.airway_billno = get_empty_AWB(logistics_info.providerId, type)
90
            return logistics_info
90
            return logistics_info
91
        finally:
91
        finally:
92
            close_session()
92
            close_session()
93
            
93
            
94
    def getEmptyAWB(self, providerId, logisticsTransactionId):
94
    def getEmptyAWB(self, providerId, logisticsTransactionId):
Line 124... Line 124...
124
        """
124
        """
125
        try:
125
        try:
126
            store_shipment_info(update)
126
            store_shipment_info(update)
127
        finally:
127
        finally:
128
            close_session()
128
            close_session()
129
 
-
 
130
    
129
    
131
    def getLogisticsEstimation(self, itemId, destination_pin, type):
130
    def getLogisticsEstimation(self, itemId, destination_pin, type):
132
        """
131
        """
133
        Parameters:
132
        Parameters:
134
         - itemId
133
         - itemId
Line 137... Line 136...
137
        """
136
        """
138
        try:
137
        try:
139
            return self.get_logistics_estimation_with_type(itemId, destination_pin, type)
138
            return self.get_logistics_estimation_with_type(itemId, destination_pin, type)
140
        finally:
139
        finally:
141
            close_session()
140
            close_session()
142
    
-
 
143
 
141
 
144
    def getLogisticsEstimationForStore(self, itemId, destination_pin, type):
142
    def getLogisticsEstimationForStore(self, itemId, destination_pin, type):
145
        """
143
        """
146
        Parameters:
144
        Parameters:
147
         - itemId
145
         - itemId
Line 149... Line 147...
149
         - type
147
         - type
150
        """
148
        """
151
        try:
149
        try:
152
            todate = datetime.datetime.now()
150
            todate = datetime.datetime.now()
153
            logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pin, type, -1)
151
            logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pin, type, -1)
154
            logistics_info.deliveryTime = to_java_date(todate +  datetime.timedelta(days = adjust_delivery_time(todate, logistics_info.deliveryTime)))
152
            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)))
153
            logistics_info.shippingTime = to_java_date(todate + datetime.timedelta(days=adjust_delivery_time(todate, logistics_info.shippingTime)))
156
            minAdvanceAmount, logistics_info.codAllowed = get_min_advance_amount(itemId, destination_pin, logistics_info.providerId, logistics_info.codAllowed)
154
            minAdvanceAmount, logistics_info.codAllowed = get_min_advance_amount(itemId, destination_pin, logistics_info.providerId, logistics_info.codAllowed)
157
            ## Send minadvanceamount in providerId field 
155
            # # Send minadvanceamount in providerId field 
158
            logistics_info.providerId = int(minAdvanceAmount)
156
            logistics_info.providerId = int(minAdvanceAmount)
159
            return logistics_info
157
            return logistics_info
160
        finally:
158
        finally:
161
            close_session()
159
            close_session()
162
            
160
            
163
    def get_logistics_estimation_with_type(self, itemId, destination_pin, type, pickUp=PickUpType.COURIER, stateId=-1):
161
    def get_logistics_estimation_with_type(self, itemId, destination_pin, type, pickUp=PickUpType.COURIER, stateId=-1):
164
        try:
162
        try:
165
            #Get the id and location of actual warehouse that'll be used to fulfil this order.
163
            # Get the id and location of actual warehouse that'll be used to fulfil this order.
166
            client = InventoryClient().get_client()
164
            client = InventoryClient().get_client()
167
            fulfilmentWarehouseId, expected_delay, billingWarehouseId, sellingPrice, totalAvailability, weight = client.getItemAvailabilityAtLocation(itemId, self.sourceId, stateId)
165
            fulfilmentWarehouseId, expected_delay, billingWarehouseId, sellingPrice, totalAvailability, weight = client.getItemAvailabilityAtLocation(itemId, self.sourceId, stateId)
168
            if totalAvailability <= 0:
166
            if totalAvailability <= 0:
169
                expected_delay = 0
167
                expected_delay = 0
170
                
168
                
Line 176... Line 174...
176
        else:
174
        else:
177
            delivery_estimate = _DeliveryEstimateObject(0, 0, get_provider_for_pickup_type(pickUp), False, False)
175
            delivery_estimate = _DeliveryEstimateObject(0, 0, get_provider_for_pickup_type(pickUp), False, False)
178
        if delivery_estimate is None:
176
        if delivery_estimate is None:
179
            raise LogisticsServiceException(104, "Unable to fetch delivery estimate for this pincode.")
177
            raise LogisticsServiceException(104, "Unable to fetch delivery estimate for this pincode.")
180
                
178
                
-
 
179
        print "destination", destination_pin, "stateId"
181
        if stateId != -1:
180
        if stateId != -1:
182
            if destination_pin in [132001,136027,132114,131001,132103]:
181
            if destination_pin in [132001, 136027, 132114, 131001, 132103]:
183
               delivery_estimate.provider_id = 48
182
                delivery_estimate.provider_id = 48
184
        
183
        
185
        ## 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. 
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. 
186
        # We are revising the estimates based on the actual warehouse that this order will be assigned to.
185
        # We are revising the estimates based on the actual warehouse that this order will be assigned to.
187
        # This warehouse may be located in a zone which is different from the one we allocated for this pincode.
186
        # This warehouse may be located in a zone which is different from the one we allocated for this pincode.
188
        #delivery_estimate = get_logistics_estimation(destination_pin, item.sellingPrice, warehouse_loc, type)
187
        # delivery_estimate = get_logistics_estimation(destination_pin, item.sellingPrice, warehouse_loc, type)
189
        #if delivery_estimate is None:
188
        # if delivery_estimate is None:
190
        #    raise LogisticsServiceException(105, "Unable to fetch delivery estimate for pincode: " + destination_pin + " and revised location: " + str(warehouse_loc))
189
        #    raise LogisticsServiceException(105, "Unable to fetch delivery estimate for pincode: " + destination_pin + " and revised location: " + str(warehouse_loc))
191
        
190
        
192
        delivery_time = 24 * (delivery_estimate.delivery_time + delivery_estimate.delivery_delay)
191
        delivery_time = 24 * (delivery_estimate.delivery_time + delivery_estimate.delivery_delay)
193
        
192
        
194
        '''
193
        '''
195
        We're now calculating the expected shipping delay which is independent of
194
        We're now calculating the expected shipping delay which is independent of
196
        the courier agency and is completely within our control (well, almost).
195
        the courier agency and is completely within our control (well, almost).
197
        '''
196
        '''
198
        #Always add the expected delay
197
        # Always add the expected delay
199
        #this is due to virtual inventory
198
        # this is due to virtual inventory
200
        shipping_delay = 24 * expected_delay
199
        shipping_delay = 24 * expected_delay
201
        
200
        
202
        # Sometimes we set negative shipping delay just in case we know time to procure will be less than the default.
201
        # Sometimes we set negative shipping delay just in case we know time to procure will be less than the default.
203
        # If we have received inventory and forgot to remove expected delay from item, it could lead to display negative shipping days. 
202
        # If we have received inventory and forgot to remove expected delay from item, it could lead to display negative shipping days. 
204
        if shipping_delay < 0:
203
        if shipping_delay < 0:
205
            shipping_delay = 0
204
            shipping_delay = 0
206
            
205
            
207
        #Further increase the estimate if it's late in the day
206
        # Further increase the estimate if it's late in the day
208
        current_hour = datetime.datetime.now().hour
207
        current_hour = datetime.datetime.now().hour
209
        if type == DeliveryType.PREPAID and self.cutoff_time <= current_hour:
208
        if type == DeliveryType.PREPAID and self.cutoff_time <= current_hour:
210
            shipping_delay = shipping_delay + 24
209
            shipping_delay = shipping_delay + 24
211
        
210
        
212
        #In case of COD,increase delay by one more day
211
        # In case of COD,increase delay by one more day
213
        #As per deenanath why are doing this?
212
        # As per deenanath why are doing this?
214
        if type == DeliveryType.COD:
213
        if type == DeliveryType.COD:
215
            shipping_delay = shipping_delay + 24
214
            shipping_delay = shipping_delay + 24
216
            delivery_estimate.otgAvailable = False
215
            delivery_estimate.otgAvailable = False
217
            
216
            
218
        delivery_time = delivery_time + shipping_delay
217
        delivery_time = delivery_time + shipping_delay
219
        
218
        
220
        shipping_delay = int(math.ceil(shipping_delay/24.0))
219
        shipping_delay = int(math.ceil(shipping_delay / 24.0))
221
        delivery_time = int(math.ceil(delivery_time/24.0))
220
        delivery_time = int(math.ceil(delivery_time / 24.0))
222
        
221
        
223
        logistics_info = LogisticsInfo()
222
        logistics_info = LogisticsInfo()
224
        logistics_info.deliveryTime = delivery_time
223
        logistics_info.deliveryTime = delivery_time
225
        logistics_info.providerId = delivery_estimate.provider_id
224
        logistics_info.providerId = delivery_estimate.provider_id
226
        logistics_info.warehouseId = billingWarehouseId
225
        logistics_info.warehouseId = billingWarehouseId
Line 251... Line 250...
251
            except:
250
            except:
252
                try:
251
                try:
253
                    dest_code = get_destination_code(providerId, pinCode) 
252
                    dest_code = get_destination_code(providerId, pinCode) 
254
                    return dest_code
253
                    return dest_code
255
                except:
254
                except:
256
                    if providerId >7:
255
                    if providerId > 7:
257
                        return ""
256
                        return ""
258
                    raise LogisticsServiceException(101, "The pincode " + pinCode + " is not serviced by this provider: " + str(providerId))
257
                    raise LogisticsServiceException(101, "The pincode " + pinCode + " is not serviced by this provider: " + str(providerId))
259
        finally:
258
        finally:
260
            close_session()
259
            close_session()
261
 
260
 
Line 292... Line 291...
292
        try:
291
        try:
293
            return get_provider_for_pickup_type(pickUp)
292
            return get_provider_for_pickup_type(pickUp)
294
        finally:
293
        finally:
295
            close_session()
294
            close_session()
296
    
295
    
297
    def closeSession(self, ):
296
    def closeSession(self,):
298
        close_session()
297
        close_session()
299
 
298
 
300
    def isAlive(self, ):
299
    def isAlive(self,):
301
        """
300
        """
302
        For checking weather service is active alive or not. It also checks connectivity with database
301
        For checking weather service is active alive or not. It also checks connectivity with database
303
        """
302
        """
304
        try:
303
        try:
305
            return is_alive()
304
            return is_alive()
Line 377... Line 376...
377
        try:
376
        try:
378
            storeToReturn = to_t_pickup_store(get_pickup_store_by_hotspot_id(hotspotId))
377
            storeToReturn = to_t_pickup_store(get_pickup_store_by_hotspot_id(hotspotId))
379
            return storeToReturn
378
            return storeToReturn
380
        finally:
379
        finally:
381
            close_session()
380
            close_session()
-
 
381
 
382
    def addPincode(self, providerId, pincode, destCode, exp, cod, stationType, otgAvailable):
382
    def addPincode(self, providerId, pincode, destCode, exp, cod, stationType, otgAvailable):
383
        try:
383
        try:
384
            add_pincode(providerId, pincode, destCode, exp, cod, stationType, otgAvailable)
384
            add_pincode(providerId, pincode, destCode, exp, cod, stationType, otgAvailable)
385
        finally:
385
        finally:
386
            close_session()
386
            close_session()
-
 
387
 
387
    def updatePincode(self, providerId, pincode, exp, cod, otgAvailable):
388
    def updatePincode(self, providerId, pincode, exp, cod, otgAvailable):
388
        try:
389
        try:
389
            update_pincode(providerId, pincode, exp, cod, otgAvailable)
390
            update_pincode(providerId, pincode, exp, cod, otgAvailable)
390
        finally:
391
        finally:
391
            close_session()
392
            close_session()
Line 394... Line 395...
394
        try:
395
        try:
395
            return add_new_awbs(providerId, isCod, awbs, awbUsedFor)
396
            return add_new_awbs(providerId, isCod, awbs, awbUsedFor)
396
        finally:
397
        finally:
397
            close_session()
398
            close_session()
398
            
399
            
399
            
-
 
400
    def runLogisticsLocationInfoUpdate(self, logisticsLocationInfoList, runCompleteUpdate, providerId):
400
    def runLogisticsLocationInfoUpdate(self, logisticsLocationInfoList, runCompleteUpdate, providerId):
401
        try:
401
        try:
402
            run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate, providerId)
402
            run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate, providerId)
403
        finally:
403
        finally:
404
            close_session()
404
            close_session()
Line 437... Line 437...
437
        try:
437
        try:
438
            costingAndDeliveryEstimateObj = get_costing_and_delivery_estimate_for_pincode(pincode, transactionAmount, isCod, weight, billingWarehouseId, isCompleteTxn)
438
            costingAndDeliveryEstimateObj = get_costing_and_delivery_estimate_for_pincode(pincode, transactionAmount, isCod, weight, billingWarehouseId, isCompleteTxn)
439
            delivery_time = 24 * (costingAndDeliveryEstimateObj.deliveryTime + costingAndDeliveryEstimateObj.delivery_delay)
439
            delivery_time = 24 * (costingAndDeliveryEstimateObj.deliveryTime + costingAndDeliveryEstimateObj.delivery_delay)
440
            shipping_delay = 0
440
            shipping_delay = 0
441
            
441
            
442
            #Further increase the estimate if it's late in the day
442
            # Further increase the estimate if it's late in the day
443
            current_hour = datetime.datetime.now().hour
443
            current_hour = datetime.datetime.now().hour
444
            if not isCod and self.cutoff_time <= current_hour:
444
            if not isCod and self.cutoff_time <= current_hour:
445
                shipping_delay = shipping_delay + 24
445
                shipping_delay = shipping_delay + 24
446
            
446
            
447
            #In case of COD,increase delay by one more day
447
            # In case of COD,increase delay by one more day
448
            if isCod:
448
            if isCod:
449
                shipping_delay = shipping_delay + 24
449
                shipping_delay = shipping_delay + 24
450
                costingAndDeliveryEstimateObj.otgAvailable = False
450
                costingAndDeliveryEstimateObj.otgAvailable = False
451
                
451
                
452
            delivery_time = delivery_time + shipping_delay
452
            delivery_time = delivery_time + shipping_delay
453
        
453
        
454
            shipping_delay = int(math.ceil(shipping_delay/24.0))
454
            shipping_delay = int(math.ceil(shipping_delay / 24.0))
455
            delivery_time = int(math.ceil(delivery_time/24.0))
455
            delivery_time = int(math.ceil(delivery_time / 24.0))
456
            
456
            
457
            costingAndDeliveryEstimateObj.deliveryTime = delivery_time
457
            costingAndDeliveryEstimateObj.deliveryTime = delivery_time
458
            costingAndDeliveryEstimateObj.shippingTime = shipping_delay
458
            costingAndDeliveryEstimateObj.shippingTime = shipping_delay
459
            return costingAndDeliveryEstimateObj
459
            return costingAndDeliveryEstimateObj
460
        finally:
460
        finally:
Line 464... Line 464...
464
        try:
464
        try:
465
            return to_t_bluedart_attribute(get_bluedart_attributes_for_logistics_txn_id(logisticsTxnId, name))
465
            return to_t_bluedart_attribute(get_bluedart_attributes_for_logistics_txn_id(logisticsTxnId, name))
466
        finally:
466
        finally:
467
            close_session()
467
            close_session()
468
            
468
            
469
            
-
 
470
    def pushCourierDetailsForEcomExpress(self, logisticsTransactionIds):
469
    def pushCourierDetailsForEcomExpress(self, logisticsTransactionIds):
471
        try:
470
        try:
472
            for logisticsTransactionId in logisticsTransactionIds:
471
            for logisticsTransactionId in logisticsTransactionIds:
473
                EcomExpressService.forward_request(logisticsTransactionId)
472
                EcomExpressService.forward_request(logisticsTransactionId)
474
            return True
473
            return True
475
        finally:
474
        finally:
476
            close_session()
475
            close_session()
477
            
476
            
478
        return False
-
 
479
477
        return False
-
 
478