Subversion Repositories SmartDukaan

Rev

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