Subversion Repositories SmartDukaan

Rev

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