Subversion Repositories SmartDukaan

Rev

Rev 4391 | Rev 4442 | 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:
3217 rajveer 82
        for value in serviceable_location_cache.itervalues():
3218 rajveer 83
            cod = cod or value[destination_pin][2]
3064 chandransh 84
    except Exception as ex:
85
        print "Unexpected error:", sys.exc_info()[0]
86
 
3217 rajveer 87
    return cod
3064 chandransh 88
 
89
def get_logistics_estimation(destination_pin, item_selling_price, warehouse_location=None, type=DeliveryType.PREPAID):
3355 chandransh 90
    logging.info("Getting logistics estimation for pincode:" + destination_pin + " and warehouse location: " + str(warehouse_location))
2341 chandransh 91
    if warehouse_location is None:
92
        try:
3217 rajveer 93
            warehouse_location = warehouse_allocation_cache[destination_pin]
2341 chandransh 94
        except:
95
            print "Unexpected error:", sys.exc_info()[0]
3064 chandransh 96
            raise LogisticsServiceException(101, "No Warehouse locations assigned to this pincode: " + destination_pin)
1504 ankur.sing 97
 
4439 rajveer 98
    provider_id = __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price)
3064 chandransh 99
 
3217 rajveer 100
    if not provider_id:
1504 ankur.sing 101
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin) + \
102
                                        ", and warehouse location: " + str(warehouse_location))
644 chandransh 103
    try:
3218 rajveer 104
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
105
        reliability = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
106
        delivery_estimate = _DeliveryEstimateObject(delivery_time, reliability, provider_id, warehouse_location)
107
        return delivery_estimate
1504 ankur.sing 108
    except Exception as ex:
109
        print ex
644 chandransh 110
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")
3150 rajveer 111
 
4439 rajveer 112
def __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price):
113
    ret_provider_list = []
3217 rajveer 114
    for provider_id, value in serviceable_location_cache.iteritems():
115
        try:
116
            dest_code, exp, cod, station_type = value[destination_pin]
117
        except:
118
            print "Unexpected error:", sys.exc_info()[0]
119
            continue
120
        if type == DeliveryType.PREPAID and exp:
4439 rajveer 121
            ret_provider_list.append(provider_id)
3217 rajveer 122
        if type == DeliveryType.COD and cod:
4439 rajveer 123
            ret_provider_list.append(provider_id)
124
    if len(ret_provider_list) == 1:
125
        return ret_provider_list[0]
126
    elif len(ret_provider_list) == 0:
127
        return None
128
    elif destination_provider_allocation_cache.has_key(destination_pin):
129
        if item_selling_price < 10000:
130
            return destination_provider_allocation_cache.get(destination_pin)[0]
131
        else:
132
            return destination_provider_allocation_cache.get(destination_pin)[1]
133
    else:
134
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin))
135
 
644 chandransh 136
def add_empty_AWBs(numbers, provider_id, type):
442 rajveer 137
    for number in numbers:
644 chandransh 138
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
444 rajveer 139
        try:
140
            query.one()
141
        except:    
644 chandransh 142
            awb = Awb()
444 rajveer 143
            awb.awb_number = number
644 chandransh 144
            awb.provider_id = provider_id
444 rajveer 145
            awb.is_available = True
644 chandransh 146
            awb.type = type
147
    session.commit()
442 rajveer 148
 
444 rajveer 149
def set_AWB_as_used(awb_number):
644 chandransh 150
    query = Awb.query.filter_by(awb_number = awb_number)
444 rajveer 151
    awb = query.one() 
152
    awb.is_available=False
153
    session.commit()
154
 
3044 chandransh 155
def get_empty_AWB(provider_id, type = DeliveryType.PREPAID):
2342 chandransh 156
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
3044 chandransh 157
    if type == DeliveryType.PREPAID:
158
        query = query.filter_by(type="Prepaid")
159
    if type == DeliveryType.COD:
160
        query = query.filter_by(type="COD")
161
 
442 rajveer 162
    try:
644 chandransh 163
        awb = query.first()
164
        awb.is_available = False
165
        session.commit()
444 rajveer 166
        return awb.awb_number
442 rajveer 167
    except:
644 chandransh 168
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
1137 chandransh 169
 
3103 chandransh 170
def get_free_awb_count(provider_id, type):
171
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
1137 chandransh 172
    if count == None:
173
        count = 0
174
    return count
442 rajveer 175
 
644 chandransh 176
def get_shipment_info(awb_number, provider_id):
177
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
178
    query = AwbUpdate.query.filter_by(awb = awb)
766 rajveer 179
    info = query.all()
180
    return info
181
 
1730 ankur.sing 182
def get_holidays(start_date, end_date):
183
    query = PublicHolidays.query
184
    if start_date != -1:
185
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
186
    if end_date != -1:
187
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
188
    holidays = query.all()
189
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
190
    return holiday_dates
191
 
766 rajveer 192
def close_session():
193
    if session.is_active:
194
        print "session is active. closing it."
2823 chandransh 195
        session.close()
3376 rajveer 196
 
197
def is_alive():
198
    try:
199
        session.query(Awb.id).limit(1).one()
200
        return True
201
    except:
202
        return False