Subversion Repositories SmartDukaan

Rev

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