Subversion Repositories SmartDukaan

Rev

Rev 22031 | Rev 22237 | 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
 
21096 amit.gupta 7
from collections import namedtuple
16025 amit.gupta 8
from elixir import session
9
from shop2020.clients.CatalogClient import CatalogClient
10
from shop2020.clients.InventoryClient import InventoryClient
20724 kshitij.so 11
from shop2020.clients.TransactionClient import TransactionClient
21096 amit.gupta 12
from shop2020.logistics.service.impl import BluedartService, DataService
644 chandransh 13
from shop2020.logistics.service.impl.DataService import Awb, AwbUpdate, Provider, \
16025 amit.gupta 14
    DeliveryEstimate, WarehouseAllocation, PublicHolidays, \
21096 amit.gupta 15
    ServiceableLocationDetails, PickupStore, Locations, ProviderCosting, \
16
    BluedartAttribute, PincodeStates
16025 amit.gupta 17
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
21096 amit.gupta 18
    DeliveryType, LogisticsLocationInfo, LocationInfo, ProviderInfo, \
19
    DeliveryEstimateAndCosting
19413 amit.gupta 20
from shop2020.thriftpy.model.v1.inventory.ttypes import Warehouse, BillingType, \
16025 amit.gupta 21
    WarehouseType
442 rajveer 22
from shop2020.utils.Utils import log_entry, to_py_date, to_java_date
5964 amar.kumar 23
from sqlalchemy.sql import or_
16025 amit.gupta 24
import datetime
3355 chandransh 25
import logging
21096 amit.gupta 26
import math
13146 manish.sha 27
import os
16025 amit.gupta 28
import sys
29
import time
20724 kshitij.so 30
import traceback
19413 amit.gupta 31
 
3355 chandransh 32
logging.basicConfig(level=logging.DEBUG)
442 rajveer 33
 
19413 amit.gupta 34
PincodeProvider = namedtuple("PincodeProvider", ["dest_pin", "provider"])
35
 
3217 rajveer 36
warehouse_allocation_cache = {}
37
serviceable_location_cache = {}
38
delivery_estimate_cache = {}
16025 amit.gupta 39
warehouse_location_cache = {}
19413 amit.gupta 40
location_state={}
20275 amit.gupta 41
 
42
'Delhivery Bluedart, Fedex Surface, Fedex Air'
19413 amit.gupta 43
state_locations = {}
19421 manish.sha 44
provider_costing_sheet = {}
45
DELHIVERY = 3
6370 rajveer 46
 
19413 amit.gupta 47
#pincode location map is ab
48
#{'110001':{1:{"sameState":False, "providerInfo":{1:(1,1), 2:(1,1)}}},}
49
pincode_locations = {}
50
#{(dest_pin, provider):(otgAvailable,providerCodLimit, websiteCodLimit, storeCodLimit, providerPrepaidLimit)} 
51
serviceable_map = {}
52
 
53
#Need to identify a better way
54
statepinmap={'11':0, 
55
             '40':1,'41':1,'42':1,'43':1,'44':1,
56
             '56':2, '57':2, '58':2, '59':2,
57
             '12':3, '13':3, 
58
             '30':4, '31':4, '32':4, '33':4, '34':4,
59
             '36':6,'37':6,'38':6,'39':6
60
             }
61
 
3218 rajveer 62
'''
63
This class is for only data transfer. Never used outside this module.
64
'''
65
class _DeliveryEstimateObject:
6537 rajveer 66
    def __init__(self, delivery_time, delivery_delay, provider_id, codAllowed, otgAvailable):
3218 rajveer 67
        self.delivery_time = delivery_time
6537 rajveer 68
        self.delivery_delay = delivery_delay
3218 rajveer 69
        self.provider_id = provider_id
4866 rajveer 70
        self.codAllowed = codAllowed
6524 rajveer 71
        self.otgAvailable = otgAvailable
3218 rajveer 72
 
3187 rajveer 73
def initialize(dbname="logistics", db_hostname="localhost"):
442 rajveer 74
    log_entry("initialize@DataAccessor", "Initializing data service")
3187 rajveer 75
    DataService.initialize(dbname, db_hostname)
3218 rajveer 76
    print "Starting cache population at: " + str(datetime.datetime.now())
16025 amit.gupta 77
    #__cache_warehouse_allocation_table()
78
    __cache_warehouse_locations()
3217 rajveer 79
    __cache_serviceable_location_details_table()
80
    __cache_delivery_estimate_table()
20275 amit.gupta 81
    __cache_pincode_provider_serviceability()
19413 amit.gupta 82
    __cache_locations()
83
    __cache_pincode_estimates()    
19421 manish.sha 84
    __cache_courier_costing_table()
3217 rajveer 85
    close_session()
3218 rajveer 86
    print "Done cache population at: " + str(datetime.datetime.now())
442 rajveer 87
 
19413 amit.gupta 88
def __cache_locations():
89
    locations = Locations.query.all()
90
    for location in locations:
91
        location_state[location.id] = location.state_id
92
        if not state_locations.has_key(location.state_id):
93
            state_locations[location.state_id] = []
94
        state_locations[location.state_id] = state_locations[location.state_id].append(location.state_id)
95
 
96
def __cache_pincode_estimates():
97
    delivery_estimates = DeliveryEstimate.query.all()
98
    for delivery_estimate in delivery_estimates:
99
        if not pincode_locations.has_key(delivery_estimate.destination_pin):
100
            pincode_locations[delivery_estimate.destination_pin] = {}
101
        destination_pinMap = pincode_locations[delivery_estimate.destination_pin] 
102
        if not destination_pinMap.has_key(delivery_estimate.warehouse_location):
103
            destination_pinMap[delivery_estimate.warehouse_location] = {}
104
            state_id = location_state.get(delivery_estimate.warehouse_location)
105
            sameState = __getStateFromPin(delivery_estimate.destination_pin) == state_id
106
            destination_pinMap[delivery_estimate.warehouse_location]['sameState']=sameState
107
            destination_pinMap[delivery_estimate.warehouse_location]['providerInfo'] = {} 
108
        destination_pinMap[delivery_estimate.warehouse_location]['providerInfo'][delivery_estimate.provider_id] = delivery_estimate.delivery_time + delivery_estimate.delivery_delay
109
 
110
 
111
 
112
def __cache_pincode_provider_serviceability():
113
    pincode_providers = ServiceableLocationDetails.query.filter(ServiceableLocationDetails.exp==1)
114
    for pp in pincode_providers:
115
        serviceable_map[PincodeProvider(pp.dest_pincode, pp.provider_id)] = (pp.cod, pp.otgAvailable,pp.providerCodLimit, pp.websiteCodLimit, pp.storeCodLimit, pp.providerPrepaidLimit)
116
 
117
 
3217 rajveer 118
def __cache_delivery_estimate_table():
119
    delivery_estimates = DeliveryEstimate.query.all()
120
    for delivery_estimate in delivery_estimates:
7857 rajveer 121
        delivery_estimate_cache[delivery_estimate.destination_pin, delivery_estimate.provider_id, delivery_estimate.warehouse_location]\
19421 manish.sha 122
        =delivery_estimate.delivery_time, delivery_estimate.delivery_delay, delivery_estimate.providerZoneCode
3217 rajveer 123
 
124
def __cache_serviceable_location_details_table():
5964 amar.kumar 125
    serviceable_locations = ServiceableLocationDetails.query.filter(or_("exp!=0","cod!=0"))
3217 rajveer 126
    for serviceable_location in serviceable_locations:
22147 amit.gupta 127
        #Bluedart is temporarily not serviceable
128
        if serviceable_location.provider_id==1:
129
            continue
3217 rajveer 130
        try:
131
            provider_pincodes = serviceable_location_cache[serviceable_location.provider_id]
132
        except:
133
            provider_pincodes = {}
134
            serviceable_location_cache[serviceable_location.provider_id] = provider_pincodes 
19474 manish.sha 135
        provider_pincodes[serviceable_location.dest_pincode] = serviceable_location.dest_code, serviceable_location.exp, serviceable_location.cod, serviceable_location.otgAvailable, serviceable_location.websiteCodLimit, serviceable_location.storeCodLimit, serviceable_location.providerPrepaidLimit, serviceable_location.providerCodLimit
3217 rajveer 136
 
137
def __cache_warehouse_allocation_table():
138
    warehouse_allocations = WarehouseAllocation.query.all()
139
    for warehouse_allocation in warehouse_allocations:
140
        warehouse_allocation_cache[warehouse_allocation.pincode]=warehouse_allocation.primary_warehouse_location
141
 
16025 amit.gupta 142
def __cache_warehouse_locations():
143
    client = InventoryClient().get_client()
19413 amit.gupta 144
    #client.getAllWarehouses(True)
16025 amit.gupta 145
    for warehouse in client.getAllWarehouses(True):
146
        warehouse_location_cache[warehouse.billingWarehouseId]=warehouse.logisticsLocation
19421 manish.sha 147
 
148
def __cache_courier_costing_table():
149
    allCostings = ProviderCosting.query.all()
150
    for costing in allCostings:
151
        if provider_costing_sheet.has_key(costing.provider_id):
152
            costingMap = provider_costing_sheet.get(costing.provider_id)
153
            costingMap[costing.zoneCode] = costing
154
            provider_costing_sheet[costing.provider_id] = costingMap
155
        else:
156
            costingMap = {}
157
            costingMap[costing.zoneCode] = costing
158
            provider_costing_sheet[costing.provider_id] = costingMap
159
 
16025 amit.gupta 160
 
644 chandransh 161
def get_provider(provider_id):
766 rajveer 162
    provider =  Provider.get_by(id=provider_id)
163
    return provider
644 chandransh 164
 
165
def get_providers():
5387 rajveer 166
    providers = Provider.query.filter_by(isActive = 1).all()
19413 amit.gupta 167
    return providers
644 chandransh 168
 
19413 amit.gupta 169
#it would return only states where our warehouses are present else return -1
170
def __getStateFromPin(pin):
171
    if pin[:3] in ['744', '682']:
172
        return -1
173
    elif statepinmap.has_key(pin[:2]):
174
        return statepinmap[pin[:2]]
175
    else:
176
        return -1
177
 
178
 
179
def get_logistics_locations(destination_pin, selling_price_list):
180
    #pincode_locations = {1:{"sameState":False, "providerInfo":{<provider_id>:<delay_days>}},}
181
    #pp.otgAvailable,pp.providerCodLimit, pp.websiteCodLimit, pp.storeCodLimit, pp.providerPrepaidLimit
182
    returnMap = {}
183
    if pincode_locations.has_key(destination_pin):
184
        locations = pincode_locations[destination_pin]
185
        for item_selling_price in selling_price_list:
186
            returnMap[item_selling_price] = {}
187
            for location_id, value in locations.iteritems():
188
                #put weight logic here
189
                otgAvailable = False
190
                codAvailable = False
191
                minDelay = -1
192
                maxDelay = -1
193
                serviceable = False
194
                for provider_id, delay_days in value['providerInfo'].iteritems():
19420 amit.gupta 195
                    pp = PincodeProvider(destination_pin, provider_id)
196
                    if not serviceable_map.has_key(pp):
197
                        continue
198
                    iscod, isotg, providerCodLimit, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_map[pp]  
19413 amit.gupta 199
                    if item_selling_price <= providerPrepaidLimit:
200
                        if not serviceable:
20275 amit.gupta 201
                            returnMap[item_selling_price][location_id] = LocationInfo(locationId = location_id, sameState=value['sameState'])
19413 amit.gupta 202
                            serviceable = True
203
                            minDelay = delay_days
204
                            maxDelay = delay_days
205
                        else:
206
                            minDelay = min(delay_days,minDelay)
207
                            maxDelay = max(delay_days,maxDelay)
208
                        iscod = iscod and item_selling_price <= min(providerCodLimit, websiteCodLimit)
209
                        isotg = (isotg and item_selling_price >= 2000)
210
                        otgAvailable = otgAvailable or isotg
211
                        codAvailable = codAvailable or iscod
212
                if serviceable:        
20275 amit.gupta 213
                    returnMap[item_selling_price][location_id].isOtg = otgAvailable
214
                    returnMap[item_selling_price][location_id].isCod = codAvailable
19413 amit.gupta 215
                    returnMap[item_selling_price][location_id].minDelay = minDelay
216
                    returnMap[item_selling_price][location_id].maxDelay = maxDelay
217
    return returnMap
218
 
7608 rajveer 219
def get_logistics_estimation(destination_pin, item_selling_price, weight, type, billingWarehouseId):
5692 rajveer 220
    logging.info("Getting logistics estimation for pincode:" + destination_pin )
1504 ankur.sing 221
 
7608 rajveer 222
    provider_id, codAllowed, otgAvailable = __get_logistics_provider_for_destination_pincode(destination_pin, item_selling_price, weight, type, billingWarehouseId)
9964 anupam.sin 223
 
17530 manish.sha 224
    logging.info("Provider Id:  " + str(provider_id) +" codAllowed: "+str(codAllowed)+" otgAvailable: "+str(otgAvailable)+ " item_selling_price: "+str(item_selling_price))
225
 
226
    if item_selling_price > 60000:# or item_selling_price <= 250:
9964 anupam.sin 227
        codAllowed = False
228
 
16025 amit.gupta 229
    warehouse_location = warehouse_location_cache.get(billingWarehouseId)
230
    if warehouse_location is None:
231
        warehouse_location = 0
7857 rajveer 232
 
3217 rajveer 233
    if not provider_id:
5692 rajveer 234
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin))
644 chandransh 235
    try:
16025 amit.gupta 236
        logging.info( "destination_pin %s, provider_id %s, warehouse_location %s"%(destination_pin, provider_id, warehouse_location))
19481 manish.sha 237
        logging.info( "Estimates %s, %s, %s"%(delivery_estimate_cache[destination_pin, provider_id, warehouse_location]))
7857 rajveer 238
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
239
        delivery_delay = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
6537 rajveer 240
        delivery_estimate = _DeliveryEstimateObject(delivery_time, delivery_delay, provider_id, codAllowed, otgAvailable)
3218 rajveer 241
        return delivery_estimate
1504 ankur.sing 242
    except Exception as ex:
243
        print ex
644 chandransh 244
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")
3150 rajveer 245
 
7608 rajveer 246
def __get_logistics_provider_for_destination_pincode(destination_pin, item_selling_price, weight, type, billingWarehouseId):
20641 amit.gupta 247
    #As of now we are dealing with Aramex and Bluedart. i.e. 1 and 2 and we have just one location i.e. gurgaon will generailise this 
248
    #Once bandwidth is available these things will be derived through improved logic.
249
    #As of now otg is set to False
250
    otg=False
21096 amit.gupta 251
    aramexServiceable = serviceable_location_cache.has_key(2) and serviceable_location_cache.get(2).has_key(destination_pin)
22147 amit.gupta 252
    blueDartServiceable =  serviceable_location_cache.has_key(1) and serviceable_location_cache.get(1).has_key(destination_pin)
253
 
254
    #blueDartServiceable =  False
21096 amit.gupta 255
    if blueDartServiceable and aramexServiceable:
256
        state = __getStateByPin(destination_pin)
257
        if state is None:
258
            state = 'DELHI'
259
        #Prioritise Bluedart in Gujarat and Rajasthan
260
        if state in ['GUJARAT', 'RAJASTHAN']:
261
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(1).get(destination_pin)
262
            if item_selling_price <= providerPrepaidLimit:
263
                iscod = iscod and item_selling_price <= websiteCodLimit
264
                if iscod:
265
                    return 1, True, otg
266
                else:
267
                    dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(2).get(destination_pin)
268
                    if item_selling_price <= providerPrepaidLimit:
269
                        iscod = iscod and item_selling_price <= websiteCodLimit
270
                        if iscod:
271
                            return 2, True, otg
272
                        else:
273
                            return 1, False, otg
274
        else:
275
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(2).get(destination_pin)
276
            if item_selling_price <= providerPrepaidLimit:
277
                iscod = iscod and item_selling_price <= websiteCodLimit
278
                if iscod:
279
                    return 2, True, otg
280
                else:
281
                    dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(1).get(destination_pin)
282
                    if item_selling_price <= providerPrepaidLimit:
283
                        iscod = iscod and item_selling_price <= websiteCodLimit
284
                        if iscod:
285
                            return 1, True, otg
286
                        else:
287
                            return 2, False, otg
288
 
289
    else:
290
        provider = 1 if blueDartServiceable else 2
291
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(provider).get(destination_pin)
20641 amit.gupta 292
        if item_selling_price <= providerPrepaidLimit:
293
            iscod = iscod and item_selling_price <= websiteCodLimit
21096 amit.gupta 294
            return provider, iscod, otg
20641 amit.gupta 295
 
296
 
297
    return None, False, False
298
 
21096 amit.gupta 299
def __getStateByPin(destination_pin):
300
    pinCodeState = PincodeStates.get_by(pin=destination_pin)
301
    if pinCodeState is not None:
302
        return pinCodeState.statename
303
    else:
304
        return None 
305
 
20641 amit.gupta 306
def __get_logistics_provider_for_destination_pincode_old(destination_pin, item_selling_price, weight, type, billingWarehouseId):
13357 manish.sha 307
    '''
308
    if serviceable_location_cache.get(6).has_key(destination_pin):
309
        if weight < 480 and serviceable_location_cache.get(3).has_key(destination_pin) and type == DeliveryType.PREPAID:
310
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(3).get(destination_pin)
311
            if item_selling_price <= providerPrepaidLimit:
312
                iscod = iscod and item_selling_price <= websiteCodLimit
313
                otgAvailable = otgAvailable and item_selling_price >= 2000
314
                return 3, iscod, otgAvailable
315
        else:
316
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(6).get(destination_pin)
317
            if item_selling_price <= providerPrepaidLimit:
318
                iscod = iscod and item_selling_price <= websiteCodLimit
319
                otgAvailable = otgAvailable and item_selling_price >= 2000
320
                return 6, iscod, otgAvailable
20641 amit.gupta 321
    '''        
322
    if serviceable_location_cache.has_key(3) and serviceable_location_cache.get(3).has_key(destination_pin):
323
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(3).get(destination_pin)
324
        if item_selling_price <= providerPrepaidLimit:
325
            iscod = iscod and item_selling_price <= websiteCodLimit
326
            otgAvailable = otgAvailable and item_selling_price >= 2000
327
            return 3, iscod, otgAvailable
8575 rajveer 328
 
17992 manish.sha 329
    if billingWarehouseId not in [12,13] and serviceable_location_cache.has_key(7) and serviceable_location_cache.get(7).has_key(destination_pin):
19533 manish.sha 330
        if item_selling_price < 3000 and serviceable_location_cache.has_key(1) and serviceable_location_cache.get(1).has_key(destination_pin):
19476 manish.sha 331
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(1).get(destination_pin)
8575 rajveer 332
            if item_selling_price <= providerPrepaidLimit:
333
                iscod = iscod and item_selling_price <= websiteCodLimit
334
                otgAvailable = otgAvailable and item_selling_price >= 2000
20275 amit.gupta 335
                if iscod:
336
                    return 1, iscod, otgAvailable
8575 rajveer 337
        else:
19476 manish.sha 338
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(7).get(destination_pin)
8575 rajveer 339
            if item_selling_price <= providerPrepaidLimit:
340
                iscod = iscod and item_selling_price <= websiteCodLimit
341
                otgAvailable = otgAvailable and item_selling_price >= 2000
20275 amit.gupta 342
                if iscod:
343
                    return 7, iscod, otgAvailable
19533 manish.sha 344
 
345
    if billingWarehouseId not in [12,13] and serviceable_location_cache.has_key(46) and serviceable_location_cache.get(46).has_key(destination_pin):
346
        if item_selling_price < 3000 and serviceable_location_cache.has_key(1) and serviceable_location_cache.get(1).has_key(destination_pin):
347
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(1).get(destination_pin)
348
            if item_selling_price <= providerPrepaidLimit:
349
                iscod = iscod and item_selling_price <= websiteCodLimit
350
                otgAvailable = otgAvailable and item_selling_price >= 2000
20275 amit.gupta 351
                if iscod:
352
                    return 1, iscod, otgAvailable
19533 manish.sha 353
        else:
354
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(46).get(destination_pin)
355
            if item_selling_price <= providerPrepaidLimit:
356
                iscod = iscod and item_selling_price <= websiteCodLimit
357
                otgAvailable = otgAvailable and item_selling_price >= 2000
20275 amit.gupta 358
                if iscod:
359
                    return 46, iscod, otgAvailable
8575 rajveer 360
 
19533 manish.sha 361
    if serviceable_location_cache.has_key(1) and serviceable_location_cache.get(1).has_key(destination_pin):
19476 manish.sha 362
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(1).get(destination_pin)
7627 rajveer 363
        if item_selling_price <= providerPrepaidLimit:
7608 rajveer 364
            iscod = iscod and item_selling_price <= websiteCodLimit
365
            otgAvailable = otgAvailable and item_selling_price >= 2000
20275 amit.gupta 366
            if iscod:
367
                return 1, iscod, otgAvailable
7981 rajveer 368
 
20275 amit.gupta 369
    if serviceable_location_cache.has_key(3) and serviceable_location_cache.get(3).has_key(destination_pin):
370
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(3).get(destination_pin)
371
        if item_selling_price <= providerPrepaidLimit:
372
            iscod = iscod and item_selling_price <= websiteCodLimit
373
            otgAvailable = otgAvailable and item_selling_price >= 2000
374
            return 3, iscod, otgAvailable
10185 amit.gupta 375
    return None, False, False    
5278 rajveer 376
 
6017 amar.kumar 377
def get_destination_code(providerId, pinCode):
378
    serviceableLocationDetail = ServiceableLocationDetails.query.filter_by(provider_id = providerId, dest_pincode = pinCode).one()
379
    return serviceableLocationDetail.dest_code
380
 
644 chandransh 381
def add_empty_AWBs(numbers, provider_id, type):
442 rajveer 382
    for number in numbers:
644 chandransh 383
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
444 rajveer 384
        try:
385
            query.one()
386
        except:    
644 chandransh 387
            awb = Awb()
444 rajveer 388
            awb.awb_number = number
644 chandransh 389
            awb.provider_id = provider_id
444 rajveer 390
            awb.is_available = True
644 chandransh 391
            awb.type = type
392
    session.commit()
442 rajveer 393
 
444 rajveer 394
def set_AWB_as_used(awb_number):
644 chandransh 395
    query = Awb.query.filter_by(awb_number = awb_number)
444 rajveer 396
    awb = query.one() 
397
    awb.is_available=False
398
    session.commit()
399
 
20924 kshitij.so 400
def get_awb(provider_id, logisticsTransactionId, type):
401
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
402
    if type == DeliveryType.PREPAID:
403
        query = query.filter_by(type="Prepaid")
404
    if type == DeliveryType.COD:
405
        query = query.filter_by(type="COD")
406
 
407
    additionalQuery = query
408
    query = query.filter_by(awbUsedFor=0)
409
 
410
    try:
411
        awb = query.first()
412
        if awb is None:
413
            additionalQuery = additionalQuery.filter_by(awbUsedFor=2)
414
            awb = additionalQuery.first()
415
        awb.is_available = False
416
        session.commit()
417
        return awb.awb_number
418
    except:
419
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
20724 kshitij.so 420
 
421
def get_empty_AWB(provider_id, logisticsTransactionId):
442 rajveer 422
    try:
20724 kshitij.so 423
        if logisticsTransactionId is None:
424
            return ""
425
        if provider_id ==1:
20745 kshitij.so 426
            bluedartAttribute = BluedartAttribute.get_by(logisticsTransactionId=logisticsTransactionId,name="awb")
427
            if bluedartAttribute is None:
428
                client = TransactionClient().get_client()
429
                orders_list = client.getGroupOrdersByLogisticsTxnId(logisticsTransactionId)
430
                bluedartResponse = BluedartService.generate_awb(orders_list)
431
                bluedartAttribute = BluedartAttribute()
432
                bluedartAttribute.logisticsTransactionId = logisticsTransactionId
433
                bluedartAttribute.name = "awb"
434
                bluedartAttribute.value = bluedartResponse.awbNo
435
                bluedartAttribute_destcode = BluedartAttribute()
436
                bluedartAttribute_destcode.logisticsTransactionId = logisticsTransactionId
437
                bluedartAttribute_destcode.name = "destCode"
438
                bluedartAttribute_destcode.value = bluedartResponse.destArea +"/"+ bluedartResponse.destLocation
439
                session.commit()
440
            return bluedartAttribute.value
20924 kshitij.so 441
        if provider_id  ==4:
442
            return get_awb(provider_id, logisticsTransactionId, DeliveryType.PREPAID)
442 rajveer 443
    except:
20724 kshitij.so 444
        traceback.print_exc()
644 chandransh 445
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
20724 kshitij.so 446
 
1137 chandransh 447
 
3103 chandransh 448
def get_free_awb_count(provider_id, type):
449
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
1137 chandransh 450
    if count == None:
451
        count = 0
452
    return count
442 rajveer 453
 
644 chandransh 454
def get_shipment_info(awb_number, provider_id):
455
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
456
    query = AwbUpdate.query.filter_by(awb = awb)
766 rajveer 457
    info = query.all()
458
    return info
459
 
6643 rajveer 460
def store_shipment_info(update):
461
    updates = AwbUpdate.query.filter_by(providerId = update.providerId, awbNumber  = update.awbNumber, location = update.location, date = to_py_date(update.date), status = update.status, description = update.description).all()
462
    if not updates:
463
        dupdate = AwbUpdate()
464
        dupdate.providerId = update.providerId
465
        dupdate.awbNumber  = update.awbNumber
466
        dupdate.location = update.location
467
        dupdate.date = to_py_date(update.date)
468
        dupdate.status = update.status
469
        dupdate.description = update.description
470
        session.commit()
471
 
1730 ankur.sing 472
def get_holidays(start_date, end_date):
473
    query = PublicHolidays.query
474
    if start_date != -1:
475
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
476
    if end_date != -1:
477
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
478
    holidays = query.all()
479
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
480
    return holiday_dates
481
 
5527 anupam.sin 482
def get_provider_for_pickup_type(pickUp):
483
    return Provider.query.filter(Provider.pickup == pickUp).first().id
484
 
766 rajveer 485
def close_session():
486
    if session.is_active:
487
        print "session is active. closing it."
2823 chandransh 488
        session.close()
3376 rajveer 489
 
490
def is_alive():
491
    try:
492
        session.query(Awb.id).limit(1).one()
493
        return True
494
    except:
5555 rajveer 495
        return False
496
 
497
def get_all_pickup_stores():
5572 anupam.sin 498
    pickupStores = PickupStore.query.all()
499
    return pickupStores
5555 rajveer 500
 
501
def get_pickup_store(storeId):
5719 rajveer 502
    return PickupStore.query.filter_by(id = storeId).one()
503
 
504
def get_pickup_store_by_hotspot_id(hotspotId):
505
    return PickupStore.query.filter_by(hotspotId = hotspotId).one()
6322 amar.kumar 506
 
6524 rajveer 507
def add_pincode(provider, pincode, destCode, exp, cod, stationType, otgAvailable):
7914 rajveer 508
    provider = Provider.query.filter_by(id = provider).one()
6322 amar.kumar 509
    serviceableLocationDetails = ServiceableLocationDetails()
510
    serviceableLocationDetails.provider = provider
511
    serviceableLocationDetails.dest_pincode = pincode
512
    serviceableLocationDetails.dest_code = destCode
513
    serviceableLocationDetails.exp = exp
514
    serviceableLocationDetails.cod = cod
515
    serviceableLocationDetails.station_type = stationType
6524 rajveer 516
    serviceableLocationDetails.otgAvailable = otgAvailable
7733 manish.sha 517
    if provider.id == 1:
7627 rajveer 518
        codlimit = 10000
519
        prepaidlimit = 50000
7733 manish.sha 520
    elif provider.id == 3:
7627 rajveer 521
        codlimit = 25000
522
        prepaidlimit = 100000
7733 manish.sha 523
    elif provider.id == 6:
7627 rajveer 524
        codlimit = 25000
525
        prepaidlimit = 100000
526
    serviceableLocationDetails.providerPrepaidLimit = prepaidlimit
527
    serviceableLocationDetails.providerCodLimit = codlimit
528
    serviceableLocationDetails.websiteCodLimit = codlimit
529
    serviceableLocationDetails.storeCodLimit = codlimit
6322 amar.kumar 530
    session.commit()
531
 
6524 rajveer 532
def update_pincode(providerId, pincode, exp, cod, otgAvailable):
6615 amar.kumar 533
    serviceableLocationDetails = ServiceableLocationDetails.get_by(provider_id = providerId, dest_pincode = pincode)
6322 amar.kumar 534
    serviceableLocationDetails.exp = exp
535
    serviceableLocationDetails.cod = cod
6524 rajveer 536
    serviceableLocationDetails.otgAvailable = otgAvailable
7256 rajveer 537
    session.commit()
7567 rajveer 538
 
13146 manish.sha 539
def add_new_awbs(provider_id, isCod, awbs, awbUsedFor):
7567 rajveer 540
    provider = get_provider(provider_id)
541
    if isCod:
542
        dtype = 'Cod'
543
    else:
544
        dtype = 'Prepaid'
545
    for awb in awbs:
546
        a = Awb()
547
        a.type =  dtype
548
        a.is_available = True
549
        a.awb_number = awb
13146 manish.sha 550
        a.awbUsedFor = awbUsedFor
7567 rajveer 551
        a.provider = provider 
552
    session.commit()
7608 rajveer 553
    return True
7256 rajveer 554
 
555
def adjust_delivery_time(start_time, delivery_days):
556
    '''
557
    Returns the actual no. of days which will pass while 'delivery_days'
558
    no. of business days will pass since 'order_time'. 
559
    '''
560
    start_date = start_time.date()
561
    end_date = start_date + datetime.timedelta(days = delivery_days)
7272 amit.gupta 562
    holidays = get_holidays(to_java_date(start_time), -1)
7256 rajveer 563
    holidays = [to_py_date(holiday).date() for holiday in holidays]
564
 
565
    while start_date <= end_date:
566
        if start_date.weekday() == 6 or start_date in holidays:
567
            delivery_days = delivery_days + 1
568
            end_date = end_date + datetime.timedelta(days = 1)
569
        start_date = start_date + datetime.timedelta(days = 1)
570
 
571
    return delivery_days
7275 rajveer 572
 
573
def get_min_advance_amount(itemId, destination_pin, providerId, codAllowed):
574
    client = CatalogClient().get_client()
575
    sp = client.getStorePricing(itemId)
576
 
577
    if codAllowed:
578
        return sp.minAdvancePrice, True
579
    else:
20275 amit.gupta 580
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit  = serviceable_location_cache.get(providerId).get(destination_pin)
7275 rajveer 581
        if iscod:
582
            if providerId == 6:
7489 rajveer 583
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 584
            if providerId == 3:
7489 rajveer 585
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 586
            if providerId == 1:
7489 rajveer 587
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 588
        else:
7425 rajveer 589
            return sp.recommendedPrice, False
7733 manish.sha 590
#Start:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
591
 
7786 manish.sha 592
def run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate):
593
    if runCompleteUpdate == True :
594
        serviceableLocationDetails = ServiceableLocationDetails.query.all()
595
        for serviceableLocationDetail in serviceableLocationDetails:
7841 manish.sha 596
            serviceableLocationDetail.exp = False
597
            serviceableLocationDetail.cod = False
7786 manish.sha 598
    for logisticsLocationInfo in logisticsLocationInfoList:
7841 manish.sha 599
        serviceableLocationDetail = ServiceableLocationDetails.get_by(provider_id = logisticsLocationInfo.providerId, dest_pincode = logisticsLocationInfo.pinCode)
7914 rajveer 600
        provider = Provider.query.filter_by(id = logisticsLocationInfo.providerId).one()
7841 manish.sha 601
        if serviceableLocationDetail:
602
            serviceableLocationDetail.exp = logisticsLocationInfo.expAvailable
603
            serviceableLocationDetail.cod = logisticsLocationInfo.codAvailable
604
            serviceableLocationDetail.otgAvailable = logisticsLocationInfo.otgAvailable
605
            serviceableLocationDetail.providerCodLimit = logisticsLocationInfo.codLimit
606
            serviceableLocationDetail.providerPrepaidLimit = logisticsLocationInfo.prepaidLimit
607
            serviceableLocationDetail.storeCodLimit = logisticsLocationInfo.codLimit
8219 manish.sha 608
            serviceableLocationDetail.websiteCodLimit = min(26000,logisticsLocationInfo.codLimit)
7841 manish.sha 609
        else:
610
            serviceableLocationDetail= ServiceableLocationDetails()
611
            serviceableLocationDetail.provider = provider
612
            serviceableLocationDetail.dest_pincode = logisticsLocationInfo.pinCode
613
            serviceableLocationDetail.dest_code = logisticsLocationInfo.destinationCode
614
            serviceableLocationDetail.exp = logisticsLocationInfo.expAvailable
615
            serviceableLocationDetail.cod = logisticsLocationInfo.codAvailable
616
            serviceableLocationDetail.station_type = 0
617
            serviceableLocationDetail.otgAvailable = logisticsLocationInfo.otgAvailable
618
            serviceableLocationDetail.providerCodLimit = logisticsLocationInfo.codLimit
619
            serviceableLocationDetail.providerPrepaidLimit = logisticsLocationInfo.prepaidLimit
620
            serviceableLocationDetail.storeCodLimit = logisticsLocationInfo.codLimit
8219 manish.sha 621
            serviceableLocationDetail.websiteCodLimit = min(26000,logisticsLocationInfo.codLimit)
7841 manish.sha 622
 
7870 rajveer 623
        deliveryEstimate = DeliveryEstimate.get_by(provider_id = logisticsLocationInfo.providerId, destination_pin = logisticsLocationInfo.pinCode, warehouse_location = logisticsLocationInfo.warehouseId) 
7841 manish.sha 624
        if deliveryEstimate:
625
            deliveryEstimate.warehouse_location= logisticsLocationInfo.warehouseId
626
            deliveryEstimate.delivery_time= logisticsLocationInfo.deliveryTime
627
            deliveryEstimate.delivery_delay= logisticsLocationInfo.delivery_delay
19421 manish.sha 628
            deliveryEstimate.providerZoneCode = logisticsLocationInfo.zoneCode
7841 manish.sha 629
        else:
630
            deliveryEstimate = DeliveryEstimate()
631
            deliveryEstimate.destination_pin= logisticsLocationInfo.pinCode
632
            deliveryEstimate.provider = provider
633
            deliveryEstimate.warehouse_location= logisticsLocationInfo.warehouseId
634
            deliveryEstimate.delivery_time= logisticsLocationInfo.deliveryTime
635
            deliveryEstimate.delivery_delay= logisticsLocationInfo.delivery_delay
19421 manish.sha 636
            deliveryEstimate.providerZoneCode = logisticsLocationInfo.zoneCode
7733 manish.sha 637
    session.commit()
7786 manish.sha 638
 
7733 manish.sha 639
#End:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013             
7275 rajveer 640
 
12895 manish.sha 641
def get_first_delivery_estimate_for_wh_location(pincode, whLocation):
642
    delEstimate = DeliveryEstimate.query.filter(DeliveryEstimate.destination_pin == pincode).filter(DeliveryEstimate.warehouse_location == whLocation).first()
643
    if delEstimate is None:
644
        return -1
645
    else:
646
        return 1
13146 manish.sha 647
 
648
def get_provider_limit_details_for_pincode(provider, pincode):
649
    serviceAbleDetails = ServiceableLocationDetails.get_by(provider_id = provider, dest_pincode = pincode)
650
    returnDataMap = {}
651
    if serviceAbleDetails:
652
        returnDataMap["websiteCodLimit"] = str(serviceAbleDetails.websiteCodLimit)
19230 manish.sha 653
        returnDataMap["providerCodLimit"] = str(serviceAbleDetails.providerCodLimit)
13146 manish.sha 654
        returnDataMap["providerPrepaidLimit"] = str(serviceAbleDetails.providerPrepaidLimit)
655
 
656
    return returnDataMap
657
 
658
def get_new_empty_awb(providerId, type, orderQuantity):
659
    query = Awb.query.with_lockmode("update").filter_by(provider_id = providerId, is_available = True)  #check the provider thing
660
    if type == DeliveryType.PREPAID:
661
        query = query.filter_by(type="Prepaid")
662
    if type == DeliveryType.COD:
663
        query = query.filter_by(type="COD")
664
 
665
    additionalQuery = query
666
    if orderQuantity == 1:
667
        query = query.filter_by(awbUsedFor=0)
668
    if orderQuantity >1:
669
        query = query.filter_by(awbUsedFor=1) 
670
 
671
    try:
672
        awb = query.first()
673
        if awb is None:
674
            additionalQuery = additionalQuery.filter_by(awbUsedFor=2)
675
            awb = additionalQuery.first()
676
        awb.is_available = False
677
        session.commit()
678
        return awb.awb_number
679
    except:
680
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(providerId))
19421 manish.sha 681
 
19474 manish.sha 682
def get_costing_and_delivery_estimate_for_pincode(pincode, transactionAmount, isCod, weight, billingWarehouseId, isCompleteTxn):
683
    print pincode, transactionAmount, isCod, weight, billingWarehouseId
19421 manish.sha 684
    deliveryEstimate = {}
685
    logsiticsCosting = {}
686
    providerCostingMap = {}
687
    serviceability = {}
688
 
689
    for providerId in serviceable_location_cache.keys():
690
        if serviceable_location_cache.has_key(providerId) and serviceable_location_cache.get(providerId).has_key(pincode):
19474 manish.sha 691
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit, providerCodLimit = serviceable_location_cache.get(providerId).get(pincode)
19421 manish.sha 692
            if isCod and iscod:
19474 manish.sha 693
                if not isCompleteTxn:
694
                    if transactionAmount <= providerCodLimit:
695
                        serviceability[providerId] = serviceable_location_cache.get(providerId).get(pincode)
696
                    else:
697
                        continue
698
                else:
699
                    serviceability[providerId] = serviceable_location_cache.get(providerId).get(pincode)
19421 manish.sha 700
            elif isCod and not iscod:
701
                continue
702
            else:
19474 manish.sha 703
                if not isCompleteTxn:
704
                    if transactionAmount <= providerPrepaidLimit:
705
                        serviceability[providerId] = serviceable_location_cache.get(providerId).get(pincode)
706
                    else:
707
                        continue
708
                else:
709
                    serviceability[providerId] = serviceable_location_cache.get(providerId).get(pincode)
19421 manish.sha 710
 
711
    warehouse_location = warehouse_location_cache.get(billingWarehouseId)
712
    if warehouse_location is None:
713
        warehouse_location = 0
714
 
715
    noCostFoundCount = 0
716
    if len(serviceability)>0:
717
        for providerId, serviceableDetails in serviceability.items():
718
            delivery_time = delivery_estimate_cache[pincode, providerId, warehouse_location][0]
719
            delivery_delay = delivery_estimate_cache[pincode, providerId, warehouse_location][1]
720
            zoneCode = delivery_estimate_cache[pincode, providerId, warehouse_location][2]
721
            sla = delivery_time + delivery_delay
722
            if deliveryEstimate.has_key(sla):
723
                estimate = deliveryEstimate.get(sla)
724
                estimate.append(providerId)
725
                deliveryEstimate[sla] = estimate
726
            else:
727
                estimate = []
728
                estimate.append(providerId)
729
                deliveryEstimate[sla] = estimate
730
 
731
            logisticsCost = 0
732
            codCollectionCharges = 0    
733
            logisticsCostObj = None 
734
            if provider_costing_sheet.has_key(providerId) and provider_costing_sheet.get(providerId).has_key(zoneCode):
735
                logisticsCostObj = provider_costing_sheet.get(providerId).get(zoneCode)
736
                logisticsCost = logisticsCostObj.initialLogisticsCost
737
                if weight > logisticsCostObj.initialWeightUpperLimit:
738
                    additionalWeight = weight-logisticsCostObj.initialWeightUpperLimit
19663 manish.sha 739
                    additionalWeight = round(additionalWeight,0)
19483 manish.sha 740
                    additionalCostMultiplier = math.ceil(additionalWeight/logisticsCostObj.additionalUnitWeight)
19421 manish.sha 741
                    additionalCost = additionalCostMultiplier*logisticsCostObj.additionalUnitLogisticsCost
742
                    logisticsCost = logisticsCost + additionalCost
743
                if isCod:
744
                    if logisticsCostObj.codCollectionFactor:
19474 manish.sha 745
                        codCollectionCharges = max(logisticsCostObj.minimumCodCollectionCharges, (transactionAmount*logisticsCostObj.codCollectionFactor)/100)
746
                        logisticsCost = logisticsCost + max(logisticsCostObj.minimumCodCollectionCharges, (transactionAmount*logisticsCostObj.codCollectionFactor)/100)
19421 manish.sha 747
                    else:
748
                        codCollectionCharges = logisticsCostObj.minimumCodCollectionCharges
749
                        logisticsCost = logisticsCost + logisticsCostObj.minimumCodCollectionCharges
750
 
19474 manish.sha 751
                if logsiticsCosting.has_key(round(logisticsCost,0)):
752
                    costingList = logsiticsCosting.get(round(logisticsCost,0))
19421 manish.sha 753
                    costingList.append(providerId)
19474 manish.sha 754
                    logsiticsCosting[round(logisticsCost,0)] = costingList
19421 manish.sha 755
                else:
756
                    costingList = []
757
                    costingList.append(providerId)
19474 manish.sha 758
                    logsiticsCosting[round(logisticsCost,0)] = costingList                    
19421 manish.sha 759
 
760
                providerCostingMap[providerId] = [logisticsCost,codCollectionCharges]
761
            else:
762
                noCostFoundCount = noCostFoundCount +1
763
                continue
764
    else:
19474 manish.sha 765
        print "No provider assigned for pincode: " + str(pincode)
19535 manish.sha 766
        raise LogisticsServiceException(103, "Unable to get Provider for given pincode: " + str(pincode)+" Amount:- "+str(transactionAmount)+" Weight:- "+ str(weight))
19421 manish.sha 767
 
768
 
769
    if noCostFoundCount == len(serviceability):
19474 manish.sha 770
        print "No Costing Found for this pincode: " + str(pincode) +" for any of the provider"
19535 manish.sha 771
        raise LogisticsServiceException(103, "Unable to get Provider for given pincode: " + str(pincode)+" Amount:- "+str(transactionAmount)+" Weight:- "+ str(weight)+". Due to no costing found")
19421 manish.sha 772
 
773
    allSla = sorted(deliveryEstimate.keys())
774
    if len(allSla)==1:
775
        allEligibleProviders = deliveryEstimate.get(allSla[0])
776
        if len(allEligibleProviders)==1:
19474 manish.sha 777
            try:
19421 manish.sha 778
                costingDetails = providerCostingMap.get(allEligibleProviders[0])
779
                delEstCostObj = DeliveryEstimateAndCosting()
780
                delEstCostObj.logistics_provider_id = allEligibleProviders[0]
781
                delEstCostObj.pincode = pincode
782
                delEstCostObj.deliveryTime = delivery_estimate_cache[pincode, allEligibleProviders[0], warehouse_location][0]
783
                delEstCostObj.delivery_delay = delivery_estimate_cache[pincode, allEligibleProviders[0], warehouse_location][1]
784
                delEstCostObj.codAllowed = serviceability[allEligibleProviders[0]][2]
785
                delEstCostObj.otgAvailable = serviceability[allEligibleProviders[0]][3]
786
                delEstCostObj.logisticsCost = costingDetails[0]-costingDetails[1]
787
                delEstCostObj.codCollectionCharges = costingDetails[1]
788
                return delEstCostObj
19474 manish.sha 789
            except:
19535 manish.sha 790
                raise LogisticsServiceException(103, "Unable to get Provider for given pincode: " + str(pincode)+" Amount:- "+str(transactionAmount)+" Weight:- "+ str(weight)+".")
19421 manish.sha 791
        else:
792
            costingListOrder = []
793
            for providerId in allEligibleProviders:
19474 manish.sha 794
                costingDetails = providerCostingMap.get(providerId)
795
                if costingDetails and costingDetails[0] not in costingListOrder:
796
                    costingListOrder.append(round(costingDetails[0],0))
797
 
798
            costingListOrder = sorted(costingListOrder)
799
            eligibleProviders = logsiticsCosting.get(costingListOrder[0])
800
            for providerId in eligibleProviders:
801
                if providerCostingMap.has_key(providerId):
802
                    costingDetails = providerCostingMap.get(providerId)
19421 manish.sha 803
                    delEstCostObj = DeliveryEstimateAndCosting()
19474 manish.sha 804
                    delEstCostObj.logistics_provider_id = providerId
19421 manish.sha 805
                    delEstCostObj.pincode = pincode
19474 manish.sha 806
                    delEstCostObj.deliveryTime = delivery_estimate_cache[pincode, providerId, warehouse_location][0]
807
                    delEstCostObj.delivery_delay = delivery_estimate_cache[pincode, providerId, warehouse_location][1]
808
                    delEstCostObj.codAllowed = serviceability[providerId][2]
809
                    delEstCostObj.otgAvailable = serviceability[providerId][3]
19421 manish.sha 810
                    delEstCostObj.logisticsCost = costingDetails[0]-costingDetails[1]
811
                    delEstCostObj.codCollectionCharges = costingDetails[1]
812
                    return delEstCostObj
19474 manish.sha 813
                else:
814
                    continue
19535 manish.sha 815
            raise LogisticsServiceException(103, "Unable to get Provider for given pincode: " + str(pincode)+" Amount:- "+str(transactionAmount)+" Weight:- "+ str(weight)+".")
19474 manish.sha 816
    else:
817
        allEligibleProviders = []
818
        virtualDelayCostMap = {}
819
        virtualCommercialsCostMap = {} 
820
        for sla in allSla:
821
            if sla-allSla[0]<=1:
822
                consideredProviders = deliveryEstimate.get(sla)
823
                for providerId in consideredProviders:
824
                    if isCod and providerId in [7,46]:
825
                        virtualCommercialsCostMap[providerId] = 10
826
                    if providerId not in allEligibleProviders:
827
                        allEligibleProviders.append(providerId)
828
                    virtualDelayCostMap[providerId] = 0
829
            elif sla-allSla[0]==2:
830
                consideredProviders = deliveryEstimate.get(sla)
831
                for providerId in consideredProviders:
832
                    if isCod and providerId in [7,46]:
833
                        virtualCommercialsCostMap[providerId] = 10
834
                    if providerId not in allEligibleProviders:
835
                        allEligibleProviders.append(providerId)
836
                    virtualDelayCostMap[providerId] = 20+round((0.3*transactionAmount)/100,0)
837
            elif sla-allSla[0]==3:
838
                consideredProviders = deliveryEstimate.get(sla)
839
                for providerId in consideredProviders:
840
                    if isCod and providerId in [7,46]:
841
                        virtualCommercialsCostMap[providerId] = 10
842
                    if providerId not in allEligibleProviders:
843
                        allEligibleProviders.append(providerId)
844
                    virtualDelayCostMap[providerId] = 40+round((0.6*transactionAmount)/100,0)
845
 
846
        costingListOrder = []
847
        costingListMap = {}
848
        for providerId in allEligibleProviders:
849
            costingDetails = providerCostingMap.get(providerId)
850
            if costingDetails:
851
                cost = round(costingDetails[0],0)
852
                if virtualDelayCostMap.has_key(providerId):
853
                    cost = cost + virtualDelayCostMap.get(providerId)
854
                if virtualCommercialsCostMap.has_key(providerId):
855
                    cost = cost + virtualCommercialsCostMap.get(providerId)
856
                if costingListMap.has_key(cost):
857
                    providers = costingListMap.get(cost)
858
                    providers.append(providerId)                       
859
                    costingListMap[cost] = providers 
860
                else:
861
                    providers = []
862
                    providers.append(providerId)                       
863
                    costingListMap[cost] = providers  
864
                if cost not in costingListOrder:
865
                    costingListOrder.append(cost)
866
 
867
        costingListOrder = sorted(costingListOrder)
868
 
869
        print costingListMap
870
        eligibleProviders = costingListMap.get(costingListOrder[0])
871
        for providerId in eligibleProviders:
872
            if providerCostingMap.has_key(providerId):
873
                costingDetails = providerCostingMap.get(providerId)
19421 manish.sha 874
                delEstCostObj = DeliveryEstimateAndCosting()
19474 manish.sha 875
                delEstCostObj.logistics_provider_id = providerId
19421 manish.sha 876
                delEstCostObj.pincode = pincode
19474 manish.sha 877
                delEstCostObj.deliveryTime = delivery_estimate_cache[pincode, providerId, warehouse_location][0]
878
                delEstCostObj.delivery_delay = delivery_estimate_cache[pincode, providerId, warehouse_location][1]
879
                delEstCostObj.codAllowed = serviceability[providerId][2]
880
                delEstCostObj.otgAvailable = serviceability[providerId][3]
19421 manish.sha 881
                delEstCostObj.logisticsCost = costingDetails[0]-costingDetails[1]
882
                delEstCostObj.codCollectionCharges = costingDetails[1]
883
                return delEstCostObj
19474 manish.sha 884
            else:
885
                continue
20745 kshitij.so 886
        raise LogisticsServiceException(103, "Unable to get Provider for given pincode: " + str(pincode)+" Amount:- "+str(transactionAmount)+" Weight:- "+ str(weight)+".")
887
 
888
def get_bluedart_attributes_for_logistics_txn_id(logisticsTxnId, name):
889
    bluedartAttr =  BluedartAttribute.get_by(logisticsTransactionId=logisticsTxnId,name=name)
890
    if bluedartAttr is None:
891
        raise LogisticsServiceException(103, "Unable to get bluedart attributes for logisticsTxnId "+logisticsTxnId+" and name "+name)
892
    return bluedartAttr