Subversion Repositories SmartDukaan

Rev

Rev 20924 | Rev 22031 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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