Subversion Repositories SmartDukaan

Rev

Rev 4866 | Rev 4934 | 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, DeliveryType
from 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_alive
from shop2020.logistics.service.impl.Converters import to_t_awbupdate,\
    to_t_provider
from shop2020.clients.CatalogClient import CatalogClient
from shop2020.config.client.ConfigClient import ConfigClient
import datetime
import math
import sys
from shop2020.logistics.service.impl import DataAccessor

class 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 = 15
            self.cod_cutoff_time = 0
            self.stock_threshold = 2
            self.time_to_procure = 48
            self.default_pincode = "110001"
         
    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_info
        finally:
            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_updates
        finally:
            close_session()
    
    def getLogisticsEstimation(self, itemId, destination_pin, type):
        """
        Parameters:
         - itemId
         - destination_pin
         - type
        """
        try:
            return self.get_logistics_estimation_with_type(itemId, destination_pin, type)
        finally:
            close_session()
    
    def get_logistics_estimation_with_type(self, itemId, destination_pin, type):
        if not destination_pin:
            destination_pin = self.default_pincode
        try:
            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_location
        try:
            #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 estimates based on the actual warehouse that this order will be assigned to.
        # This warehouse may be located in a zone which is different from 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
        
        '''
        We're now calculating the expected shipping delay which is independent of
        the courier agency and is completely within our control (well, almost).
        '''
        #Always add the expected delay
        shipping_delay = 24 * expected_delay
        
        # Increase the estimate if the actual stock is less than the threshold 
        if items_in_inventory < self.stock_threshold :
            shipping_delay = shipping_delay + self.time_to_procure
        
        # Sometimes we set negative shipping delay just in case we know time to procure will be less than the default.
        # If we have received inventory and forgot to remove expected delay from item, it could lead to display negative shipping days. 
        if shipping_delay < 0:
            shipping_delay = 0
            
        #Further increase the estimate if it's late in the day
        current_hour = datetime.datetime.now().hour
        if type == DeliveryType.PREPAID and self.cutoff_time <= current_hour:
            shipping_delay = shipping_delay + 24
        elif type == DeliveryType.COD and self.cod_cutoff_time <= current_hour:
            shipping_delay = shipping_delay + 24
        
        #In case of COD,increase delay by one more day
        if type == DeliveryType.COD:
            shipping_delay = shipping_delay + 24
            
        delivery_time = delivery_time + shipping_delay
        
        shipping_delay = int(math.ceil(shipping_delay/24.0))
        delivery_time = int(math.ceil(delivery_time/24.0))
        
        logistics_info = LogisticsInfo()
        logistics_info.deliveryTime = delivery_time
        logistics_info.providerId = delivery_estimate.provider_id
        logistics_info.warehouseId = warehouse_id
        logistics_info.shippingTime = shipping_delay
        logistics_info.codAllowed = delivery_estimate.codAllowed 
        
        return logistics_info
        
    def 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_code
            except:
                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 type
        
        Parameters:
         - 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 filtering
        If toDate is passed as -1, toDate is not considered for filtering
        
        Parameters:
         - fromDate
         - toDate
        """
        try:
            return get_holidays(fromDate, toDate)
        finally:
            close_session()
    
    def closeSession(self, ):
        close_session()

    def isAlive(self, ):
        """
        For checking weather service is active alive or not. It also checks connectivity with database
        """
        try:
            return is_alive()
        finally:
            close_session()