Subversion Repositories SmartDukaan

Rev

Rev 4804 | Rev 4866 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
442 rajveer 1
'''
2
Created on 13-Sep-2010
3
 
4
@author: rajveer
5
'''
6
 
7
from shop2020.logistics.service.impl import DataService
644 chandransh 8
from shop2020.logistics.service.impl.DataService import Awb, AwbUpdate, Provider, \
3218 rajveer 9
     DeliveryEstimate, WarehouseAllocation, \
4439 rajveer 10
    PublicHolidays, ServiceableLocationDetails, DestinationProviderAllocation
3044 chandransh 11
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException,\
12
    DeliveryType
442 rajveer 13
from shop2020.utils.Utils import log_entry, to_py_date, to_java_date
14
from elixir import session
1730 ankur.sing 15
import datetime, time
1504 ankur.sing 16
import sys
3355 chandransh 17
import logging
18
logging.basicConfig(level=logging.DEBUG)
442 rajveer 19
 
3217 rajveer 20
warehouse_allocation_cache = {}
21
serviceable_location_cache = {}
22
delivery_estimate_cache = {}
4439 rajveer 23
destination_provider_allocation_cache = {}
3218 rajveer 24
'''
25
This class is for only data transfer. Never used outside this module.
26
'''
27
class _DeliveryEstimateObject:
28
    def __init__(self, delivery_time, reliability, provider_id, warehouse_location):
29
        self.delivery_time = delivery_time
30
        self.reliability = reliability
31
        self.provider_id = provider_id
32
        self.warehouse_location = warehouse_location 
33
 
3187 rajveer 34
def initialize(dbname="logistics", db_hostname="localhost"):
442 rajveer 35
    log_entry("initialize@DataAccessor", "Initializing data service")
3187 rajveer 36
    DataService.initialize(dbname, db_hostname)
3218 rajveer 37
    print "Starting cache population at: " + str(datetime.datetime.now())
3217 rajveer 38
    __cache_warehouse_allocation_table()
39
    __cache_serviceable_location_details_table()
40
    __cache_delivery_estimate_table()
4439 rajveer 41
    __cache_destination_provider_allocation_table()
3217 rajveer 42
    close_session()
3218 rajveer 43
    print "Done cache population at: " + str(datetime.datetime.now())
442 rajveer 44
 
3217 rajveer 45
def __cache_delivery_estimate_table():
46
    delivery_estimates = DeliveryEstimate.query.all()
47
    for delivery_estimate in delivery_estimates:
48
        delivery_estimate_cache[delivery_estimate.destination_pin, delivery_estimate.provider_id, delivery_estimate.warehouse_location]\
49
        =delivery_estimate.delivery_time, delivery_estimate.reliability
50
 
51
def __cache_serviceable_location_details_table():
52
    serviceable_locations = ServiceableLocationDetails.query.all()
53
    for serviceable_location in serviceable_locations:
54
        try:
55
            provider_pincodes = serviceable_location_cache[serviceable_location.provider_id]
56
        except:
57
            provider_pincodes = {}
58
            serviceable_location_cache[serviceable_location.provider_id] = provider_pincodes 
59
        provider_pincodes[serviceable_location.dest_pincode] = serviceable_location.dest_code, serviceable_location.exp, serviceable_location.cod, serviceable_location.station_type 
60
 
61
def __cache_warehouse_allocation_table():
62
    warehouse_allocations = WarehouseAllocation.query.all()
63
    for warehouse_allocation in warehouse_allocations:
64
        warehouse_allocation_cache[warehouse_allocation.pincode]=warehouse_allocation.primary_warehouse_location
65
 
4439 rajveer 66
def __cache_destination_provider_allocation_table():
67
    destiontion_providers = DestinationProviderAllocation.query.all()
68
    for destiontion_provider in destiontion_providers:
69
        destination_provider_allocation_cache[destiontion_provider.destination_pin] = destiontion_provider.provider_less_amount.id, destiontion_provider.provider_more_amount.id  
70
 
644 chandransh 71
def get_provider(provider_id):
766 rajveer 72
    provider =  Provider.get_by(id=provider_id)
73
    return provider
644 chandransh 74
 
75
def get_providers():
766 rajveer 76
    providers = Provider.query.all()
77
    return providers 
644 chandransh 78
 
3064 chandransh 79
def is_cod_allowed(destination_pin):
3217 rajveer 80
    cod = False
3064 chandransh 81
    try:
4848 anupam.sin 82
        #FIXME As per ticket location from where only Aramex is servicing, should not be given to Aramex.
83
        for provider_id, value in serviceable_location_cache.iteritems():
84
            dest_code, exp, iscod, station_type = value[destination_pin]
85
            if provider_id == 1:
86
                cod = cod or iscod
3064 chandransh 87
    except Exception as ex:
88
        print "Unexpected error:", sys.exc_info()[0]
3217 rajveer 89
    return cod
3064 chandransh 90
 
91
def get_logistics_estimation(destination_pin, item_selling_price, warehouse_location=None, type=DeliveryType.PREPAID):
3355 chandransh 92
    logging.info("Getting logistics estimation for pincode:" + destination_pin + " and warehouse location: " + str(warehouse_location))
2341 chandransh 93
    if warehouse_location is None:
94
        try:
3217 rajveer 95
            warehouse_location = warehouse_allocation_cache[destination_pin]
2341 chandransh 96
        except:
97
            print "Unexpected error:", sys.exc_info()[0]
3064 chandransh 98
            raise LogisticsServiceException(101, "No Warehouse locations assigned to this pincode: " + destination_pin)
1504 ankur.sing 99
 
4439 rajveer 100
    provider_id = __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price)
3064 chandransh 101
 
3217 rajveer 102
    if not provider_id:
1504 ankur.sing 103
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin) + \
104
                                        ", and warehouse location: " + str(warehouse_location))
644 chandransh 105
    try:
3218 rajveer 106
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
107
        reliability = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
108
        delivery_estimate = _DeliveryEstimateObject(delivery_time, reliability, provider_id, warehouse_location)
109
        return delivery_estimate
1504 ankur.sing 110
    except Exception as ex:
111
        print ex
644 chandransh 112
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")
3150 rajveer 113
 
4439 rajveer 114
def __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price):
115
    ret_provider_list = []
3217 rajveer 116
    for provider_id, value in serviceable_location_cache.iteritems():
117
        try:
118
            dest_code, exp, cod, station_type = value[destination_pin]
119
        except:
120
            print "Unexpected error:", sys.exc_info()[0]
121
            continue
122
        if type == DeliveryType.PREPAID and exp:
4439 rajveer 123
            ret_provider_list.append(provider_id)
3217 rajveer 124
        if type == DeliveryType.COD and cod:
4439 rajveer 125
            ret_provider_list.append(provider_id)
4803 rajveer 126
    #FIXME As per ticket location from where only Aramex is servicing, should not be given to Aramex.
4439 rajveer 127
    if len(ret_provider_list) == 1:
4803 rajveer 128
        if ret_provider_list.__contains__(1):
129
            return ret_provider_list[0]
4804 rajveer 130
        else:
4803 rajveer 131
            return None
4439 rajveer 132
    elif len(ret_provider_list) == 0:
133
        return None
134
    elif destination_provider_allocation_cache.has_key(destination_pin):
4711 rajveer 135
        if item_selling_price < 10000:
4439 rajveer 136
            return destination_provider_allocation_cache.get(destination_pin)[0]
137
        else:
138
            return destination_provider_allocation_cache.get(destination_pin)[1]
139
    else:
4450 rajveer 140
        return ret_provider_list[0]
4439 rajveer 141
 
644 chandransh 142
def add_empty_AWBs(numbers, provider_id, type):
442 rajveer 143
    for number in numbers:
644 chandransh 144
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
444 rajveer 145
        try:
146
            query.one()
147
        except:    
644 chandransh 148
            awb = Awb()
444 rajveer 149
            awb.awb_number = number
644 chandransh 150
            awb.provider_id = provider_id
444 rajveer 151
            awb.is_available = True
644 chandransh 152
            awb.type = type
153
    session.commit()
442 rajveer 154
 
444 rajveer 155
def set_AWB_as_used(awb_number):
644 chandransh 156
    query = Awb.query.filter_by(awb_number = awb_number)
444 rajveer 157
    awb = query.one() 
158
    awb.is_available=False
159
    session.commit()
160
 
3044 chandransh 161
def get_empty_AWB(provider_id, type = DeliveryType.PREPAID):
2342 chandransh 162
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
3044 chandransh 163
    if type == DeliveryType.PREPAID:
164
        query = query.filter_by(type="Prepaid")
165
    if type == DeliveryType.COD:
166
        query = query.filter_by(type="COD")
167
 
442 rajveer 168
    try:
644 chandransh 169
        awb = query.first()
170
        awb.is_available = False
171
        session.commit()
444 rajveer 172
        return awb.awb_number
442 rajveer 173
    except:
644 chandransh 174
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
1137 chandransh 175
 
3103 chandransh 176
def get_free_awb_count(provider_id, type):
177
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
1137 chandransh 178
    if count == None:
179
        count = 0
180
    return count
442 rajveer 181
 
644 chandransh 182
def get_shipment_info(awb_number, provider_id):
183
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
184
    query = AwbUpdate.query.filter_by(awb = awb)
766 rajveer 185
    info = query.all()
186
    return info
187
 
1730 ankur.sing 188
def get_holidays(start_date, end_date):
189
    query = PublicHolidays.query
190
    if start_date != -1:
191
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
192
    if end_date != -1:
193
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
194
    holidays = query.all()
195
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
196
    return holiday_dates
197
 
766 rajveer 198
def close_session():
199
    if session.is_active:
200
        print "session is active. closing it."
2823 chandransh 201
        session.close()
3376 rajveer 202
 
203
def is_alive():
204
    try:
205
        session.query(Awb.id).limit(1).one()
206
        return True
207
    except:
208
        return False