Subversion Repositories SmartDukaan

Rev

Rev 4848 | Rev 5243 | 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 = {}
4866 rajveer 24
ncr_pincodes = ['110001','110002','110003','110004','110005','110006','110007','110008','110009','110010','110011','110012','110013','110014','110015', \
25
                '110016','110017','110018','110019','110020','110021','110022','110023','110024','110025','110026','110027','110028','110029','110030', \
26
                '110031','110032','110033','110034','110035','110036','110037','110038','110039','110040','110041','110042','110043','110044','110045', \
27
                '110046','110047','110048','110049','110050','110051','110052','110053','110054','110055','110056','110057','110058','110059','110060', \
28
                '110061','110062','110063','110064','110065','110066','110067','110068','110069','110070','110071','110072','110073','110074','110075', \
29
                '110076','110077','110078','110081','110082','110083','110084','110085','110086','110087','110088','110089','110091','110092','110093', \
30
                '110094','110095','110096','121001','121002','121003','121004','121005','121006','121007','121008','121009','122001','122002','122003', \
31
                '122004','122005','122006','122007','122008','122009','122010','122011','122012','122015','122016','122017','122018','122050','122051', \
32
                '201001','201002','201003','201004','201005','201006','201007','201008','201009','201010','201011','201012','201301','201303','201304', \
33
                '201305','201306','201307']
34
ludhiyana_pincodes  = ['141001','141002','141003','141004','141005','141006','141007','141008','141009','141010','141011','141012','141013','141014']
35
 
3218 rajveer 36
'''
37
This class is for only data transfer. Never used outside this module.
38
'''
39
class _DeliveryEstimateObject:
4866 rajveer 40
    def __init__(self, delivery_time, reliability, provider_id, warehouse_location, codAllowed):
3218 rajveer 41
        self.delivery_time = delivery_time
42
        self.reliability = reliability
43
        self.provider_id = provider_id
4866 rajveer 44
        self.warehouse_location = warehouse_location
45
        self.codAllowed = codAllowed
3218 rajveer 46
 
3187 rajveer 47
def initialize(dbname="logistics", db_hostname="localhost"):
442 rajveer 48
    log_entry("initialize@DataAccessor", "Initializing data service")
3187 rajveer 49
    DataService.initialize(dbname, db_hostname)
3218 rajveer 50
    print "Starting cache population at: " + str(datetime.datetime.now())
3217 rajveer 51
    __cache_warehouse_allocation_table()
52
    __cache_serviceable_location_details_table()
53
    __cache_delivery_estimate_table()
4439 rajveer 54
    __cache_destination_provider_allocation_table()
3217 rajveer 55
    close_session()
3218 rajveer 56
    print "Done cache population at: " + str(datetime.datetime.now())
442 rajveer 57
 
3217 rajveer 58
def __cache_delivery_estimate_table():
59
    delivery_estimates = DeliveryEstimate.query.all()
60
    for delivery_estimate in delivery_estimates:
61
        delivery_estimate_cache[delivery_estimate.destination_pin, delivery_estimate.provider_id, delivery_estimate.warehouse_location]\
62
        =delivery_estimate.delivery_time, delivery_estimate.reliability
63
 
64
def __cache_serviceable_location_details_table():
65
    serviceable_locations = ServiceableLocationDetails.query.all()
66
    for serviceable_location in serviceable_locations:
67
        try:
68
            provider_pincodes = serviceable_location_cache[serviceable_location.provider_id]
69
        except:
70
            provider_pincodes = {}
71
            serviceable_location_cache[serviceable_location.provider_id] = provider_pincodes 
72
        provider_pincodes[serviceable_location.dest_pincode] = serviceable_location.dest_code, serviceable_location.exp, serviceable_location.cod, serviceable_location.station_type 
73
 
74
def __cache_warehouse_allocation_table():
75
    warehouse_allocations = WarehouseAllocation.query.all()
76
    for warehouse_allocation in warehouse_allocations:
77
        warehouse_allocation_cache[warehouse_allocation.pincode]=warehouse_allocation.primary_warehouse_location
78
 
4439 rajveer 79
def __cache_destination_provider_allocation_table():
80
    destiontion_providers = DestinationProviderAllocation.query.all()
81
    for destiontion_provider in destiontion_providers:
82
        destination_provider_allocation_cache[destiontion_provider.destination_pin] = destiontion_provider.provider_less_amount.id, destiontion_provider.provider_more_amount.id  
83
 
644 chandransh 84
def get_provider(provider_id):
766 rajveer 85
    provider =  Provider.get_by(id=provider_id)
86
    return provider
644 chandransh 87
 
88
def get_providers():
766 rajveer 89
    providers = Provider.query.all()
90
    return providers 
644 chandransh 91
 
3064 chandransh 92
def get_logistics_estimation(destination_pin, item_selling_price, warehouse_location=None, type=DeliveryType.PREPAID):
3355 chandransh 93
    logging.info("Getting logistics estimation for pincode:" + destination_pin + " and warehouse location: " + str(warehouse_location))
2341 chandransh 94
    if warehouse_location is None:
95
        try:
3217 rajveer 96
            warehouse_location = warehouse_allocation_cache[destination_pin]
2341 chandransh 97
        except:
98
            print "Unexpected error:", sys.exc_info()[0]
3064 chandransh 99
            raise LogisticsServiceException(101, "No Warehouse locations assigned to this pincode: " + destination_pin)
1504 ankur.sing 100
 
4866 rajveer 101
    provider_id, codAllowed = __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price)
3064 chandransh 102
 
3217 rajveer 103
    if not provider_id:
1504 ankur.sing 104
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin) + \
105
                                        ", and warehouse location: " + str(warehouse_location))
644 chandransh 106
    try:
3218 rajveer 107
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
108
        reliability = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
4866 rajveer 109
        delivery_estimate = _DeliveryEstimateObject(delivery_time, reliability, provider_id, warehouse_location, codAllowed)
3218 rajveer 110
        return delivery_estimate
1504 ankur.sing 111
    except Exception as ex:
112
        print ex
644 chandransh 113
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")
3150 rajveer 114
 
4439 rajveer 115
def __get_logistics_provider_for_destination_pincode(type, destination_pin, item_selling_price):
4866 rajveer 116
    if ncr_pincodes.__contains__(destination_pin):
117
        if item_selling_price <= 20000:
118
            return 2, True
119
    if ludhiyana_pincodes.__contains__(destination_pin):
120
        if item_selling_price <= 10000:
121
            return 2, True
122
    if serviceable_location_cache.get(1).has_key(destination_pin):
123
        dest_code, exp, iscod, station_type = serviceable_location_cache.get(1).get(destination_pin)
124
        iscod = iscod and item_selling_price <= 10000
125
        return 1, iscod
126
    else:
127
        return None, False    
128
    '''
3217 rajveer 129
    for provider_id, value in serviceable_location_cache.iteritems():
130
        try:
131
            dest_code, exp, cod, station_type = value[destination_pin]
132
        except:
133
            print "Unexpected error:", sys.exc_info()[0]
134
            continue
135
        if type == DeliveryType.PREPAID and exp:
4439 rajveer 136
            ret_provider_list.append(provider_id)
3217 rajveer 137
        if type == DeliveryType.COD and cod:
4439 rajveer 138
            ret_provider_list.append(provider_id)
4803 rajveer 139
    #FIXME As per ticket location from where only Aramex is servicing, should not be given to Aramex.
4439 rajveer 140
    if len(ret_provider_list) == 1:
4803 rajveer 141
        if ret_provider_list.__contains__(1):
142
            return ret_provider_list[0]
4804 rajveer 143
        else:
4803 rajveer 144
            return None
4439 rajveer 145
    elif len(ret_provider_list) == 0:
146
        return None
147
    elif destination_provider_allocation_cache.has_key(destination_pin):
4711 rajveer 148
        if item_selling_price < 10000:
4439 rajveer 149
            return destination_provider_allocation_cache.get(destination_pin)[0]
150
        else:
151
            return destination_provider_allocation_cache.get(destination_pin)[1]
152
    else:
4450 rajveer 153
        return ret_provider_list[0]
4866 rajveer 154
    '''
155
 
644 chandransh 156
def add_empty_AWBs(numbers, provider_id, type):
442 rajveer 157
    for number in numbers:
644 chandransh 158
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
444 rajveer 159
        try:
160
            query.one()
161
        except:    
644 chandransh 162
            awb = Awb()
444 rajveer 163
            awb.awb_number = number
644 chandransh 164
            awb.provider_id = provider_id
444 rajveer 165
            awb.is_available = True
644 chandransh 166
            awb.type = type
167
    session.commit()
442 rajveer 168
 
444 rajveer 169
def set_AWB_as_used(awb_number):
644 chandransh 170
    query = Awb.query.filter_by(awb_number = awb_number)
444 rajveer 171
    awb = query.one() 
172
    awb.is_available=False
173
    session.commit()
174
 
3044 chandransh 175
def get_empty_AWB(provider_id, type = DeliveryType.PREPAID):
2342 chandransh 176
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
3044 chandransh 177
    if type == DeliveryType.PREPAID:
178
        query = query.filter_by(type="Prepaid")
179
    if type == DeliveryType.COD:
180
        query = query.filter_by(type="COD")
181
 
442 rajveer 182
    try:
644 chandransh 183
        awb = query.first()
184
        awb.is_available = False
185
        session.commit()
444 rajveer 186
        return awb.awb_number
442 rajveer 187
    except:
644 chandransh 188
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
1137 chandransh 189
 
3103 chandransh 190
def get_free_awb_count(provider_id, type):
191
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
1137 chandransh 192
    if count == None:
193
        count = 0
194
    return count
442 rajveer 195
 
644 chandransh 196
def get_shipment_info(awb_number, provider_id):
197
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
198
    query = AwbUpdate.query.filter_by(awb = awb)
766 rajveer 199
    info = query.all()
200
    return info
201
 
1730 ankur.sing 202
def get_holidays(start_date, end_date):
203
    query = PublicHolidays.query
204
    if start_date != -1:
205
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
206
    if end_date != -1:
207
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
208
    holidays = query.all()
209
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
210
    return holiday_dates
211
 
766 rajveer 212
def close_session():
213
    if session.is_active:
214
        print "session is active. closing it."
2823 chandransh 215
        session.close()
3376 rajveer 216
 
217
def is_alive():
218
    try:
219
        session.query(Awb.id).limit(1).one()
220
        return True
221
    except:
222
        return False