Subversion Repositories SmartDukaan

Rev

Rev 4848 | Rev 5278 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on 13-Sep-2010

@author: rajveer
'''

from shop2020.logistics.service.impl import DataService
from shop2020.logistics.service.impl.DataService import Awb, AwbUpdate, Provider, \
     DeliveryEstimate, WarehouseAllocation, \
    PublicHolidays, ServiceableLocationDetails, DestinationProviderAllocation
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException,\
    DeliveryType
from shop2020.utils.Utils import log_entry, to_py_date, to_java_date
from elixir import session
import datetime, time
import sys
import logging
logging.basicConfig(level=logging.DEBUG)

warehouse_allocation_cache = {}
serviceable_location_cache = {}
delivery_estimate_cache = {}
destination_provider_allocation_cache = {}
ncr_pincodes = ['110001','110002','110003','110004','110005','110006','110007','110008','110009','110010','110011','110012','110013','110014','110015', \
                '110016','110017','110018','110019','110020','110021','110022','110023','110024','110025','110026','110027','110028','110029','110030', \
                '110031','110032','110033','110034','110035','110036','110037','110038','110039','110040','110041','110042','110043','110044','110045', \
                '110046','110047','110048','110049','110050','110051','110052','110053','110054','110055','110056','110057','110058','110059','110060', \
                '110061','110062','110063','110064','110065','110066','110067','110068','110069','110070','110071','110072','110073','110074','110075', \
                '110076','110077','110078','110081','110082','110083','110084','110085','110086','110087','110088','110089','110091','110092','110093', \
                '110094','110095','110096','121001','121002','121003','121004','121005','121006','121007','121008','121009','122001','122002','122003', \
                '122004','122005','122006','122007','122008','122009','122010','122011','122012','122015','122016','122017','122018','122050','122051', \
                '201001','201002','201003','201004','201005','201006','201007','201008','201009','201010','201011','201012','201301','201303','201304', \
                '201305','201306','201307']
ludhiyana_pincodes  = ['141001','141002','141003','141004','141005','141006','141007','141008','141009','141010','141011','141012','141013','141014']

'''
This class is for only data transfer. Never used outside this module.
'''
class _DeliveryEstimateObject:
    def __init__(self, delivery_time, reliability, provider_id, warehouse_location, codAllowed):
        self.delivery_time = delivery_time
        self.reliability = reliability
        self.provider_id = provider_id
        self.warehouse_location = warehouse_location
        self.codAllowed = codAllowed
    
def initialize(dbname="logistics", db_hostname="localhost"):
    log_entry("initialize@DataAccessor", "Initializing data service")
    DataService.initialize(dbname, db_hostname)
    print "Starting cache population at: " + str(datetime.datetime.now())
    __cache_warehouse_allocation_table()
    __cache_serviceable_location_details_table()
    __cache_delivery_estimate_table()
    __cache_destination_provider_allocation_table()
    close_session()
    print "Done cache population at: " + str(datetime.datetime.now())

def __cache_delivery_estimate_table():
    delivery_estimates = DeliveryEstimate.query.all()
    for delivery_estimate in delivery_estimates:
        delivery_estimate_cache[delivery_estimate.destination_pin, delivery_estimate.provider_id, delivery_estimate.warehouse_location]\
        =delivery_estimate.delivery_time, delivery_estimate.reliability

def __cache_serviceable_location_details_table():
    serviceable_locations = ServiceableLocationDetails.query.all()
    for serviceable_location in serviceable_locations:
        try:
            provider_pincodes = serviceable_location_cache[serviceable_location.provider_id]
        except:
            provider_pincodes = {}
            serviceable_location_cache[serviceable_location.provider_id] = provider_pincodes 
        provider_pincodes[serviceable_location.dest_pincode] = serviceable_location.dest_code, serviceable_location.exp, serviceable_location.cod, serviceable_location.station_type 

def __cache_warehouse_allocation_table():
    warehouse_allocations = WarehouseAllocation.query.all()
    for warehouse_allocation in warehouse_allocations:
        warehouse_allocation_cache[warehouse_allocation.pincode]=warehouse_allocation.primary_warehouse_location

def __cache_destination_provider_allocation_table():
    destiontion_providers = DestinationProviderAllocation.query.all()
    for destiontion_provider in destiontion_providers:
        destination_provider_allocation_cache[destiontion_provider.destination_pin] = destiontion_provider.provider_less_amount.id, destiontion_provider.provider_more_amount.id  
        
def get_provider(provider_id):
    provider =  Provider.get_by(id=provider_id)
    return provider

def get_providers():
    providers = Provider.query.all()
    return providers 

def get_logistics_estimation(destination_pin, item_selling_price, warehouse_location=None, type=DeliveryType.PREPAID):
    logging.info("Getting logistics estimation for pincode:" + destination_pin + " and warehouse location: " + str(warehouse_location))
    if warehouse_location is None:
        try:
            warehouse_location = warehouse_allocation_cache[destination_pin]
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise LogisticsServiceException(101, "No Warehouse locations assigned to this pincode: " + destination_pin)
    
    provider_id, codAllowed = __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price)
    
    if not provider_id:
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin) + \
                                        ", and warehouse location: " + str(warehouse_location))
    try:
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
        reliability = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
        delivery_estimate = _DeliveryEstimateObject(delivery_time, reliability, provider_id, warehouse_location, codAllowed)
        return delivery_estimate
    except Exception as ex:
        print ex
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")

def __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price):
    if ncr_pincodes.__contains__(destination_pin):
        if item_selling_price <= 20000:
            return 2, True
    if ludhiyana_pincodes.__contains__(destination_pin):
        if item_selling_price <= 10000:
            return 2, True
    if serviceable_location_cache.get(1).has_key(destination_pin):
        dest_code, exp, iscod, station_type = serviceable_location_cache.get(1).get(destination_pin)
        iscod = iscod and item_selling_price <= 10000
        return 1, iscod
    else:
        return None, False    
    '''
    for provider_id, value in serviceable_location_cache.iteritems():
        try:
            dest_code, exp, cod, station_type = value[destination_pin]
        except:
            print "Unexpected error:", sys.exc_info()[0]
            continue
        if type == DeliveryType.PREPAID and exp:
            ret_provider_list.append(provider_id)
        if type == DeliveryType.COD and cod:
            ret_provider_list.append(provider_id)
    #FIXME As per ticket location from where only Aramex is servicing, should not be given to Aramex.
    if len(ret_provider_list) == 1:
        if ret_provider_list.__contains__(1):
            return ret_provider_list[0]
        else:
            return None
    elif len(ret_provider_list) == 0:
        return None
    elif destination_provider_allocation_cache.has_key(destination_pin):
        if item_selling_price < 10000:
            return destination_provider_allocation_cache.get(destination_pin)[0]
        else:
            return destination_provider_allocation_cache.get(destination_pin)[1]
    else:
        return ret_provider_list[0]
    '''
        
def add_empty_AWBs(numbers, provider_id, type):
    for number in numbers:
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
        try:
            query.one()
        except:    
            awb = Awb()
            awb.awb_number = number
            awb.provider_id = provider_id
            awb.is_available = True
            awb.type = type
    session.commit()

def set_AWB_as_used(awb_number):
    query = Awb.query.filter_by(awb_number = awb_number)
    awb = query.one() 
    awb.is_available=False
    session.commit()
    
def get_empty_AWB(provider_id, type = DeliveryType.PREPAID):
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
    if type == DeliveryType.PREPAID:
        query = query.filter_by(type="Prepaid")
    if type == DeliveryType.COD:
        query = query.filter_by(type="COD")
    
    try:
        awb = query.first()
        awb.is_available = False
        session.commit()
        return awb.awb_number
    except:
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))

def get_free_awb_count(provider_id, type):
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
    if count == None:
        count = 0
    return count
   
def get_shipment_info(awb_number, provider_id):
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
    query = AwbUpdate.query.filter_by(awb = awb)
    info = query.all()
    return info

def get_holidays(start_date, end_date):
    query = PublicHolidays.query
    if start_date != -1:
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
    if end_date != -1:
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
    holidays = query.all()
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
    return holiday_dates

def close_session():
    if session.is_active:
        print "session is active. closing it."
        session.close()

def is_alive():
    try:
        session.query(Awb.id).limit(1).one()
        return True
    except:
        return False