Subversion Repositories SmartDukaan

Rev

Rev 7733 | Rev 7831 | 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
7273 rajveer 28
from shop2020.utils.Utils import to_java_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)
3044 chandransh 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
 
7187 rajveer 207
        if itemId in (7943,8195):
6987 rajveer 208
            delivery_estimate.codAllowed = False
7490 rajveer 209
        if itemId in (7974, 7558):
210
            delivery_estimate.otgAvailable = False
3044 chandransh 211
        logistics_info = LogisticsInfo()
212
        logistics_info.deliveryTime = delivery_time
3218 rajveer 213
        logistics_info.providerId = delivery_estimate.provider_id
5110 mandeep.dh 214
        logistics_info.warehouseId = billingWarehouseId
215
        logistics_info.fulfilmentWarehouseId = fulfilmentWarehouseId
4009 chandransh 216
        logistics_info.shippingTime = shipping_delay
4870 rajveer 217
        logistics_info.codAllowed = delivery_estimate.codAllowed 
6524 rajveer 218
        logistics_info.otgAvailable = delivery_estimate.otgAvailable
6726 rajveer 219
        logistics_info.deliveryDelay = delivery_estimate.delivery_delay
3044 chandransh 220
 
5595 anupam.sin 221
        try:
222
            return logistics_info
223
        finally:
224
            close_session()
3044 chandransh 225
 
731 chandransh 226
    def getDestinationCode(self, providerId, pinCode):
227
        """
228
        Returns the short three letter code of a pincode for the given provider.
229
        Raises an exception if the pin code is not serviced by the given provider.
230
 
231
        Parameters:
232
         - providerId
233
         - pinCode
234
        """
796 rajveer 235
        try:
3217 rajveer 236
            try:
3218 rajveer 237
                dest_code = DataAccessor.serviceable_location_cache[providerId][pinCode][0]
3217 rajveer 238
                return dest_code
239
            except:
6017 amar.kumar 240
                try:
241
                    dest_code = get_destination_code(providerId, pinCode) 
242
                    return dest_code
243
                except:
244
                    raise LogisticsServiceException(101, "The pincode " + pinCode + " is not serviced by this provider: " + str(providerId))
796 rajveer 245
        finally:
246
            close_session()
1137 chandransh 247
 
3103 chandransh 248
    def getFreeAwbCount(self, providerId, type):
1137 chandransh 249
        """
3103 chandransh 250
        Returns the number of unused AWB numbers for the given provider of the given type
796 rajveer 251
 
1137 chandransh 252
        Parameters:
253
         - providerId
3103 chandransh 254
         - type
1137 chandransh 255
        """
256
        try:
3103 chandransh 257
            return get_free_awb_count(providerId, type)
1137 chandransh 258
        finally:
259
            close_session()
1730 ankur.sing 260
 
261
    def getHolidays(self, fromDate, toDate):
262
        """
263
        Returns list of Holiday dates between fromDate and toDate (both inclusive)
264
        fromDate should be passed as milliseconds corresponding to the start of the day.
265
        If fromDate is passed as -1, fromDate is not considered for filtering
266
        If toDate is passed as -1, toDate is not considered for filtering
1137 chandransh 267
 
1730 ankur.sing 268
        Parameters:
269
         - fromDate
270
         - toDate
271
        """
272
        try:
273
            return get_holidays(fromDate, toDate)
274
        finally:
275
            close_session()
5527 anupam.sin 276
 
277
    def getProviderForPickupType(self, pickUp):
278
        try:
279
            return get_provider_for_pickup_type(pickUp)
280
        finally:
281
            close_session()
3064 chandransh 282
 
766 rajveer 283
    def closeSession(self, ):
284
        close_session()
3376 rajveer 285
 
286
    def isAlive(self, ):
287
        """
288
        For checking weather service is active alive or not. It also checks connectivity with database
289
        """
290
        try:
291
            return is_alive()
292
        finally:
293
            close_session()
4934 amit.gupta 294
 
295
    def getEntityLogisticsEstimation(self, catalogItemId, destination_pin, type):
296
        """
297
        Returns a LogisticsInfo structure w/o an airway bill number. Use this method during the estimation phase.
298
        Raises an exception if this pincode is not allocated to any warehouse zone or provider. Also, if the pincode
299
        is allocated to a warehouse zone but there are no actual warehouses in that zone, an exception is raised.
300
 
301
        Parameters:
302
         - catalogItemId
303
         - destination_pin
304
         - type
305
        """
306
        try:
307
            return self.get_entity_logistics_estimation_with_type(catalogItemId, destination_pin, type)
308
        finally:
309
            close_session()
310
 
311
    def get_entity_logistics_estimation_with_type(self, catalog_item_id, destination_pin, type):
312
        try:
313
            client = CatalogClient().get_client()
314
            items = client.getValidItemsByCatalogId(catalog_item_id)
315
        except Exception as ex:
316
            raise LogisticsServiceException(103, "Unable to fetch inventory information about this entity.")
317
 
318
        estimateList = []
319
 
320
        for item in items:
321
            estimationInfo = self.get_logistics_estimation_with_type(item.id, destination_pin, type)
322
            if item.itemStatus == status.ACTIVE:
323
                estimateList.append((0, estimationInfo.deliveryTime, item.id))
324
            elif item.itemStatus == status.PAUSED:
325
                estimateList.append((1, estimationInfo.deliveryTime, item.id))
326
            elif item.itemStatus == status.PAUSED_BY_RISK:
327
                estimateList.append((2, estimationInfo.deliveryTime, item.id))
6074 amit.gupta 328
            elif item.itemStatus == status.COMING_SOON:
329
                estimateList.append((3, estimationInfo.deliveryTime, item.id))
4934 amit.gupta 330
 
331
        estimateList.sort()
5595 anupam.sin 332
        try:
333
            return [estimate[-1] for estimate in estimateList]
334
        finally:
335
            close_session()
5555 rajveer 336
 
5595 anupam.sin 337
    def getAllPickupStores(self):
338
        try:
339
            return [to_t_pickup_store(pickup_store) for pickup_store in get_all_pickup_stores()]
340
        finally:
341
            close_session()
5555 rajveer 342
 
343
    def getPickupStore(self, storeId):
344
        """
345
        Parameters:
346
         - storeId
347
        """
5595 anupam.sin 348
        try:
349
            storeToReturn = to_t_pickup_store(get_pickup_store(storeId))
350
            return storeToReturn
351
        finally:
5719 rajveer 352
            close_session()
353
 
354
    def getPickupStoreByHotspotId(self, hotspotId):
355
        """
356
        Parameters:
357
         - hotspotId
358
        """
359
        try:
360
            storeToReturn = to_t_pickup_store(get_pickup_store_by_hotspot_id(hotspotId))
361
            return storeToReturn
362
        finally:
6322 amar.kumar 363
            close_session()
6524 rajveer 364
    def addPincode(self, providerId, pincode, destCode, exp, cod, stationType, otgAvailable):
6322 amar.kumar 365
        try:
6524 rajveer 366
            add_pincode(providerId, pincode, destCode, exp, cod, stationType, otgAvailable)
6322 amar.kumar 367
        finally:
368
            close_session()
6524 rajveer 369
    def updatePincode(self, providerId, pincode, exp, cod, otgAvailable):
6322 amar.kumar 370
        try:
6524 rajveer 371
            update_pincode(providerId, pincode, exp, cod, otgAvailable)
6322 amar.kumar 372
        finally:
7567 rajveer 373
            close_session()
374
 
375
    def addNewAwbs(self, providerId, isCod, awbs):
376
        try:
7608 rajveer 377
            return add_new_awbs(providerId, isCod, awbs)
7567 rajveer 378
        finally:
7733 manish.sha 379
            close_session()
7786 manish.sha 380
 
381
 
382
    def runLogisticsLocationInfoUpdate(self, logisticsLocationInfoList, runCompleteUpdate):
7733 manish.sha 383
        try:
7786 manish.sha 384
            run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate)
7733 manish.sha 385
        finally:
386
            close_session()