Subversion Repositories SmartDukaan

Rev

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