Subversion Repositories SmartDukaan

Rev

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