Rev 3218 | Rev 3376 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
'''Created on 05-Aug-2010@author: ashish'''from shop2020.thriftpy.logistics.ttypes import LogisticsInfo,\LogisticsServiceException, DeliveryTypefrom shop2020.logistics.service.impl.DataAccessor import get_empty_AWB,\get_shipment_info, initialize, get_logistics_estimation, get_provider,\get_providers, close_session, get_free_awb_count, get_holidays,\is_cod_allowedfrom shop2020.logistics.service.impl.Converters import to_t_awbupdate,\to_t_providerfrom shop2020.clients.CatalogClient import CatalogClientfrom shop2020.config.client.ConfigClient import ConfigClientimport datetimeimport mathimport sysfrom shop2020.logistics.service.impl import DataAccessorclass LogisticsServiceHandler:def __init__(self, dbname='logistics', db_hostname='localhost'):initialize(dbname, db_hostname)try:config_client = ConfigClient()self.cutoff_time = int(config_client.get_property('delivery_cutoff_time'))self.cod_cutoff_time = 0 #int(config_client.get_property('delivery_cutoff_time'))self.stock_threshold = int(config_client.get_property('inventory_stock_threshold'))self.time_to_procure = int(config_client.get_property('inventory_time_to_procure'))self.default_pincode = int(config_client.get_property('default_pincode'))except Exception as ex:print "[ERROR] Unexpected config error:", sys.exc_info()[0]self.cutoff_time = 15self.cod_cutoff_time = 0self.stock_threshold = 2self.time_to_procure = 48self.default_pincode = "110001"##FIXME'''self.kanwaar_effected_pins_by_two_days = ['244713', '247667', '248001', '248002', '248003', '248005', '248006','248008', '248009', '248110', '248146', '248171', '248179', '249201','249401', '249403', '249404', '249407', '249408', '249409', '249410','249411', '262405', '263139', '263153']self.kanwaar_effected_pins_by_one_day = ['201001', '201002', '201003', '201004', '201005', '201007', '201009','201010', '201011', '201012', '201014', '201204', '202001', '202002','203001', '203131', '204101']'''def getProvider(self, providerId):"""Returns a provider for a given provider ID. Throws an exception if none found.Parameters:- providerId"""try:provider = get_provider(providerId)if provider:return to_t_provider(provider)else:raise LogisticsServiceException(101, "No Provider found for the given id")finally:close_session()def getAllProviders(self, ):"""Returns a list containing all the providers."""try:return [to_t_provider(provider) for provider in get_providers()]finally:close_session()def getLogisticsInfo(self, destination_pincode, itemId, type):"""Parameters:- destination_pincode- item_id- type"""try:logistics_info = self.get_logistics_estimation_with_type(itemId, destination_pincode, type)logistics_info.airway_billno = get_empty_AWB(logistics_info.providerId, type)return logistics_infofinally:close_session()def getEmptyAWB(self, provider_id):"""Parameters:- provider_id"""try:return get_empty_AWB(provider_id)finally:close_session()def getShipmentInfo(self, awb, providerId):"""Parameters:- awb- providerId"""try:awb_updates = get_shipment_info(awb, providerId)t_updates = []for update in awb_updates:t_updates.append(to_t_awbupdate(update))return t_updatesfinally:close_session()def getLogisticsEstimation(self, itemId, destination_pin):"""Parameters:- itemId- destination_pin"""try:return self.get_logistics_estimation_with_type(itemId, destination_pin)finally:close_session()def get_logistics_estimation_with_type(self, itemId, destination_pin, type = DeliveryType.PREPAID):if not destination_pin:destination_pin = self.default_pincodetry:client = CatalogClient().get_client()item = client.getItem(itemId)except Exception as ex:raise LogisticsServiceException(103, "Unable to fetch inventory information about this item.")delivery_estimate = get_logistics_estimation(destination_pin, item.sellingPrice, None, type)if delivery_estimate is None:raise LogisticsServiceException(104, "Unable to fetch delivery estimate for this pincode.")warehouse_loc = delivery_estimate.warehouse_locationtry:#Get the id and location of actual warehouse that'll be used to fulfil this order.warehouse_loc, warehouse_id, items_in_inventory, expected_delay = client.getItemAvailabilityAtLocation(warehouse_loc, itemId)except Exception as ex:raise LogisticsServiceException(103, "Unable to fetch inventory information about this item.")# We are revising the estimated based on the actual warehouse that will be assigned to this order.# This warehouse may be located in a different zone that the one we allocated for this pincode.delivery_estimate = get_logistics_estimation(destination_pin, item.sellingPrice, warehouse_loc, type)if delivery_estimate is None:raise LogisticsServiceException(105, "Unable to fetch delivery estimate for pincode: " + destination_pin + " and revised location: " + str(warehouse_loc))delivery_time = 24*delivery_estimate.delivery_time#Always add the expected delaydelivery_time = delivery_time + 24*expected_delay# Increase the estimate if the actual stock is less than the thresholdif items_in_inventory < self.stock_threshold :delivery_time = delivery_time + self.time_to_procure#Further increase the estimate if it's late in the daycurrent_hour = datetime.datetime.now().hourif type == DeliveryType.PREPAID and self.cutoff_time <= current_hour:delivery_time = delivery_time + 24elif type == DeliveryType.COD and self.cod_cutoff_time <= current_hour:delivery_time = delivery_time + 24delivery_time = int(math.ceil(delivery_time/24.0))'''## FIXME Due to Kanwaar on the delhi Dehradun route deliveries on following pin codes will be effected.## Changing as per ticket number #462if destination_pin in self.kanwaar_effected_pins_by_two_days:delivery_time += 2elif destination_pin in self.kanwaar_effected_pins_by_one_day:delivery_time += 1## FIXME Remove the above code once Kanwaar season is over'''logistics_info = LogisticsInfo()logistics_info.deliveryTime = delivery_timelogistics_info.providerId = delivery_estimate.provider_idlogistics_info.warehouseId = warehouse_idreturn logistics_infodef getDestinationCode(self, providerId, pinCode):"""Returns the short three letter code of a pincode for the given provider.Raises an exception if the pin code is not serviced by the given provider.Parameters:- providerId- pinCode"""try:try:dest_code = DataAccessor.serviceable_location_cache[providerId][pinCode][0]return dest_codeexcept:raise LogisticsServiceException(101, "The pincode " + pinCode + " is not serviced by this provider: " + str(providerId))finally:close_session()def getFreeAwbCount(self, providerId, type):"""Returns the number of unused AWB numbers for the given provider of the given typeParameters:- providerId- type"""try:return get_free_awb_count(providerId, type)finally:close_session()def getHolidays(self, fromDate, toDate):"""Returns list of Holiday dates between fromDate and toDate (both inclusive)fromDate should be passed as milliseconds corresponding to the start of the day.If fromDate is passed as -1, fromDate is not considered for filteringIf toDate is passed as -1, toDate is not considered for filteringParameters:- fromDate- toDate"""try:return get_holidays(fromDate, toDate)finally:close_session()def isCodAllowed(self, destination_pincode):"""Returns true if COD is allowed for this destination pincodeParameters:- destination_pincode"""try:return is_cod_allowed(destination_pincode)finally:close_session()def closeSession(self, ):close_session()