Subversion Repositories SmartDukaan

Rev

Rev 7946 | Rev 9840 | 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:
8182 amar.kumar 240
                    if providerId >7:
241
                        return ""
6017 amar.kumar 242
                    raise LogisticsServiceException(101, "The pincode " + pinCode + " is not serviced by this provider: " + str(providerId))
796 rajveer 243
        finally:
244
            close_session()
1137 chandransh 245
 
3103 chandransh 246
    def getFreeAwbCount(self, providerId, type):
1137 chandransh 247
        """
3103 chandransh 248
        Returns the number of unused AWB numbers for the given provider of the given type
796 rajveer 249
 
1137 chandransh 250
        Parameters:
251
         - providerId
3103 chandransh 252
         - type
1137 chandransh 253
        """
254
        try:
3103 chandransh 255
            return get_free_awb_count(providerId, type)
1137 chandransh 256
        finally:
257
            close_session()
1730 ankur.sing 258
 
259
    def getHolidays(self, fromDate, toDate):
260
        """
261
        Returns list of Holiday dates between fromDate and toDate (both inclusive)
262
        fromDate should be passed as milliseconds corresponding to the start of the day.
263
        If fromDate is passed as -1, fromDate is not considered for filtering
264
        If toDate is passed as -1, toDate is not considered for filtering
1137 chandransh 265
 
1730 ankur.sing 266
        Parameters:
267
         - fromDate
268
         - toDate
269
        """
270
        try:
271
            return get_holidays(fromDate, toDate)
272
        finally:
273
            close_session()
5527 anupam.sin 274
 
275
    def getProviderForPickupType(self, pickUp):
276
        try:
277
            return get_provider_for_pickup_type(pickUp)
278
        finally:
279
            close_session()
3064 chandransh 280
 
766 rajveer 281
    def closeSession(self, ):
282
        close_session()
3376 rajveer 283
 
284
    def isAlive(self, ):
285
        """
286
        For checking weather service is active alive or not. It also checks connectivity with database
287
        """
288
        try:
289
            return is_alive()
290
        finally:
291
            close_session()
4934 amit.gupta 292
 
293
    def getEntityLogisticsEstimation(self, catalogItemId, destination_pin, type):
294
        """
295
        Returns a LogisticsInfo structure w/o an airway bill number. Use this method during the estimation phase.
296
        Raises an exception if this pincode is not allocated to any warehouse zone or provider. Also, if the pincode
297
        is allocated to a warehouse zone but there are no actual warehouses in that zone, an exception is raised.
298
 
299
        Parameters:
300
         - catalogItemId
301
         - destination_pin
302
         - type
303
        """
304
        try:
305
            return self.get_entity_logistics_estimation_with_type(catalogItemId, destination_pin, type)
306
        finally:
307
            close_session()
308
 
309
    def get_entity_logistics_estimation_with_type(self, catalog_item_id, destination_pin, type):
310
        try:
311
            client = CatalogClient().get_client()
312
            items = client.getValidItemsByCatalogId(catalog_item_id)
313
        except Exception as ex:
314
            raise LogisticsServiceException(103, "Unable to fetch inventory information about this entity.")
315
 
316
        estimateList = []
317
 
318
        for item in items:
319
            estimationInfo = self.get_logistics_estimation_with_type(item.id, destination_pin, type)
320
            if item.itemStatus == status.ACTIVE:
321
                estimateList.append((0, estimationInfo.deliveryTime, item.id))
322
            elif item.itemStatus == status.PAUSED:
323
                estimateList.append((1, estimationInfo.deliveryTime, item.id))
324
            elif item.itemStatus == status.PAUSED_BY_RISK:
325
                estimateList.append((2, estimationInfo.deliveryTime, item.id))
6074 amit.gupta 326
            elif item.itemStatus == status.COMING_SOON:
327
                estimateList.append((3, estimationInfo.deliveryTime, item.id))
4934 amit.gupta 328
 
329
        estimateList.sort()
5595 anupam.sin 330
        try:
331
            return [estimate[-1] for estimate in estimateList]
332
        finally:
333
            close_session()
5555 rajveer 334
 
5595 anupam.sin 335
    def getAllPickupStores(self):
336
        try:
337
            return [to_t_pickup_store(pickup_store) for pickup_store in get_all_pickup_stores()]
338
        finally:
339
            close_session()
5555 rajveer 340
 
341
    def getPickupStore(self, storeId):
342
        """
343
        Parameters:
344
         - storeId
345
        """
5595 anupam.sin 346
        try:
347
            storeToReturn = to_t_pickup_store(get_pickup_store(storeId))
348
            return storeToReturn
349
        finally:
5719 rajveer 350
            close_session()
351
 
352
    def getPickupStoreByHotspotId(self, hotspotId):
353
        """
354
        Parameters:
355
         - hotspotId
356
        """
357
        try:
358
            storeToReturn = to_t_pickup_store(get_pickup_store_by_hotspot_id(hotspotId))
359
            return storeToReturn
360
        finally:
6322 amar.kumar 361
            close_session()
6524 rajveer 362
    def addPincode(self, providerId, pincode, destCode, exp, cod, stationType, otgAvailable):
6322 amar.kumar 363
        try:
6524 rajveer 364
            add_pincode(providerId, pincode, destCode, exp, cod, stationType, otgAvailable)
6322 amar.kumar 365
        finally:
366
            close_session()
6524 rajveer 367
    def updatePincode(self, providerId, pincode, exp, cod, otgAvailable):
6322 amar.kumar 368
        try:
6524 rajveer 369
            update_pincode(providerId, pincode, exp, cod, otgAvailable)
6322 amar.kumar 370
        finally:
7567 rajveer 371
            close_session()
372
 
373
    def addNewAwbs(self, providerId, isCod, awbs):
374
        try:
7608 rajveer 375
            return add_new_awbs(providerId, isCod, awbs)
7567 rajveer 376
        finally:
7733 manish.sha 377
            close_session()
7786 manish.sha 378
 
379
 
380
    def runLogisticsLocationInfoUpdate(self, logisticsLocationInfoList, runCompleteUpdate):
7733 manish.sha 381
        try:
7786 manish.sha 382
            run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate)
7733 manish.sha 383
        finally:
384
            close_session()
7888 rajveer 385
 
386
    def adjustDeliveryDays(self, startDate, days):
387
        try:
388
            return adjust_delivery_time(to_py_date(startDate), days)
389
        finally:
390
            close_session()