Subversion Repositories SmartDukaan

Rev

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