Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
442 rajveer 1
'''
2
Created on 13-Sep-2010
3
 
4
@author: rajveer
5
'''
6
 
16025 amit.gupta 7
from elixir import session
8
from shop2020.clients.CatalogClient import CatalogClient
9
from shop2020.clients.InventoryClient import InventoryClient
442 rajveer 10
from shop2020.logistics.service.impl import DataService
644 chandransh 11
from shop2020.logistics.service.impl.DataService import Awb, AwbUpdate, Provider, \
16025 amit.gupta 12
    DeliveryEstimate, WarehouseAllocation, PublicHolidays, \
19413 amit.gupta 13
    ServiceableLocationDetails, PickupStore, Locations
16025 amit.gupta 14
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
19413 amit.gupta 15
    DeliveryType, LogisticsLocationInfo, LocationInfo, ProviderInfo
16
from shop2020.thriftpy.model.v1.inventory.ttypes import Warehouse, BillingType, \
16025 amit.gupta 17
    WarehouseType
442 rajveer 18
from shop2020.utils.Utils import log_entry, to_py_date, to_java_date
5964 amar.kumar 19
from sqlalchemy.sql import or_
16025 amit.gupta 20
import datetime
3355 chandransh 21
import logging
13146 manish.sha 22
import os
16025 amit.gupta 23
import sys
24
import time
19413 amit.gupta 25
from collections import namedtuple
26
 
3355 chandransh 27
logging.basicConfig(level=logging.DEBUG)
442 rajveer 28
 
19413 amit.gupta 29
PincodeProvider = namedtuple("PincodeProvider", ["dest_pin", "provider"])
30
 
3217 rajveer 31
warehouse_allocation_cache = {}
32
serviceable_location_cache = {}
33
delivery_estimate_cache = {}
16025 amit.gupta 34
warehouse_location_cache = {}
19413 amit.gupta 35
location_state={}
36
state_locations = {}
6370 rajveer 37
 
19413 amit.gupta 38
#pincode location map is ab
39
#{'110001':{1:{"sameState":False, "providerInfo":{1:(1,1), 2:(1,1)}}},}
40
pincode_locations = {}
41
#{(dest_pin, provider):(otgAvailable,providerCodLimit, websiteCodLimit, storeCodLimit, providerPrepaidLimit)} 
42
serviceable_map = {}
43
 
44
#Need to identify a better way
45
statepinmap={'11':0, 
46
             '40':1,'41':1,'42':1,'43':1,'44':1,
47
             '56':2, '57':2, '58':2, '59':2,
48
             '12':3, '13':3, 
49
             '30':4, '31':4, '32':4, '33':4, '34':4,
50
             '36':6,'37':6,'38':6,'39':6
51
             }
52
 
3218 rajveer 53
'''
54
This class is for only data transfer. Never used outside this module.
55
'''
56
class _DeliveryEstimateObject:
6537 rajveer 57
    def __init__(self, delivery_time, delivery_delay, provider_id, codAllowed, otgAvailable):
3218 rajveer 58
        self.delivery_time = delivery_time
6537 rajveer 59
        self.delivery_delay = delivery_delay
3218 rajveer 60
        self.provider_id = provider_id
4866 rajveer 61
        self.codAllowed = codAllowed
6524 rajveer 62
        self.otgAvailable = otgAvailable
3218 rajveer 63
 
3187 rajveer 64
def initialize(dbname="logistics", db_hostname="localhost"):
442 rajveer 65
    log_entry("initialize@DataAccessor", "Initializing data service")
3187 rajveer 66
    DataService.initialize(dbname, db_hostname)
3218 rajveer 67
    print "Starting cache population at: " + str(datetime.datetime.now())
16025 amit.gupta 68
    #__cache_warehouse_allocation_table()
69
    __cache_warehouse_locations()
3217 rajveer 70
    __cache_serviceable_location_details_table()
71
    __cache_delivery_estimate_table()
19413 amit.gupta 72
    __cache_locations()
73
    __cache_pincode_estimates()    
3217 rajveer 74
    close_session()
3218 rajveer 75
    print "Done cache population at: " + str(datetime.datetime.now())
442 rajveer 76
 
19413 amit.gupta 77
def __cache_locations():
78
    locations = Locations.query.all()
79
    for location in locations:
80
        location_state[location.id] = location.state_id
81
        if not state_locations.has_key(location.state_id):
82
            state_locations[location.state_id] = []
83
        state_locations[location.state_id] = state_locations[location.state_id].append(location.state_id)
84
 
85
def __cache_pincode_estimates():
86
    delivery_estimates = DeliveryEstimate.query.all()
87
    for delivery_estimate in delivery_estimates:
88
        if not pincode_locations.has_key(delivery_estimate.destination_pin):
89
            pincode_locations[delivery_estimate.destination_pin] = {}
90
        destination_pinMap = pincode_locations[delivery_estimate.destination_pin] 
91
        if not destination_pinMap.has_key(delivery_estimate.warehouse_location):
92
            destination_pinMap[delivery_estimate.warehouse_location] = {}
93
            state_id = location_state.get(delivery_estimate.warehouse_location)
94
            sameState = __getStateFromPin(delivery_estimate.destination_pin) == state_id
95
            destination_pinMap[delivery_estimate.warehouse_location]['sameState']=sameState
96
            destination_pinMap[delivery_estimate.warehouse_location]['providerInfo'] = {} 
97
        destination_pinMap[delivery_estimate.warehouse_location]['providerInfo'][delivery_estimate.provider_id] = delivery_estimate.delivery_time + delivery_estimate.delivery_delay
98
 
99
 
100
 
101
def __cache_pincode_provider_serviceability():
102
    pincode_providers = ServiceableLocationDetails.query.filter(ServiceableLocationDetails.exp==1)
103
    for pp in pincode_providers:
104
        serviceable_map[PincodeProvider(pp.dest_pincode, pp.provider_id)] = (pp.cod, pp.otgAvailable,pp.providerCodLimit, pp.websiteCodLimit, pp.storeCodLimit, pp.providerPrepaidLimit)
105
 
106
 
3217 rajveer 107
def __cache_delivery_estimate_table():
108
    delivery_estimates = DeliveryEstimate.query.all()
109
    for delivery_estimate in delivery_estimates:
7857 rajveer 110
        delivery_estimate_cache[delivery_estimate.destination_pin, delivery_estimate.provider_id, delivery_estimate.warehouse_location]\
6537 rajveer 111
        =delivery_estimate.delivery_time, delivery_estimate.delivery_delay
3217 rajveer 112
 
113
def __cache_serviceable_location_details_table():
5964 amar.kumar 114
    serviceable_locations = ServiceableLocationDetails.query.filter(or_("exp!=0","cod!=0"))
3217 rajveer 115
    for serviceable_location in serviceable_locations:
116
        try:
117
            provider_pincodes = serviceable_location_cache[serviceable_location.provider_id]
118
        except:
119
            provider_pincodes = {}
120
            serviceable_location_cache[serviceable_location.provider_id] = provider_pincodes 
7627 rajveer 121
        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
3217 rajveer 122
 
123
def __cache_warehouse_allocation_table():
124
    warehouse_allocations = WarehouseAllocation.query.all()
125
    for warehouse_allocation in warehouse_allocations:
126
        warehouse_allocation_cache[warehouse_allocation.pincode]=warehouse_allocation.primary_warehouse_location
127
 
16025 amit.gupta 128
def __cache_warehouse_locations():
129
    client = InventoryClient().get_client()
19413 amit.gupta 130
    #client.getAllWarehouses(True)
16025 amit.gupta 131
    for warehouse in client.getAllWarehouses(True):
132
        warehouse_location_cache[warehouse.billingWarehouseId]=warehouse.logisticsLocation
133
 
644 chandransh 134
def get_provider(provider_id):
766 rajveer 135
    provider =  Provider.get_by(id=provider_id)
136
    return provider
644 chandransh 137
 
138
def get_providers():
5387 rajveer 139
    providers = Provider.query.filter_by(isActive = 1).all()
19413 amit.gupta 140
    return providers
644 chandransh 141
 
19413 amit.gupta 142
#it would return only states where our warehouses are present else return -1
143
def __getStateFromPin(pin):
144
    if pin[:3] in ['744', '682']:
145
        return -1
146
    elif statepinmap.has_key(pin[:2]):
147
        return statepinmap[pin[:2]]
148
    else:
149
        return -1
150
 
151
 
152
def get_logistics_locations(destination_pin, selling_price_list):
153
    #pincode_locations = {1:{"sameState":False, "providerInfo":{<provider_id>:<delay_days>}},}
154
    #pp.otgAvailable,pp.providerCodLimit, pp.websiteCodLimit, pp.storeCodLimit, pp.providerPrepaidLimit
155
    returnMap = {}
156
    if pincode_locations.has_key(destination_pin):
157
        locations = pincode_locations[destination_pin]
158
        for item_selling_price in selling_price_list:
159
            returnMap[item_selling_price] = {}
160
            for location_id, value in locations.iteritems():
161
                returnMap[item_selling_price][location_id] = LocationInfo(locationId = location_id, sameState=value['sameState'])
162
                #put weight logic here
163
                otgAvailable = False
164
                codAvailable = False
165
                minDelay = -1
166
                maxDelay = -1
167
                serviceable = False
168
                for provider_id, delay_days in value['providerInfo'].iteritems():
169
                    iscod, isotg, providerCodLimit, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_map[PincodeProvider(destination_pin, provider_id)]
170
                    if item_selling_price <= providerPrepaidLimit:
171
                        if not serviceable:
172
                            serviceable = True
173
                            minDelay = delay_days
174
                            maxDelay = delay_days
175
                        else:
176
                            minDelay = min(delay_days,minDelay)
177
                            maxDelay = max(delay_days,maxDelay)
178
                        iscod = iscod and item_selling_price <= min(providerCodLimit, websiteCodLimit)
179
                        isotg = (isotg and item_selling_price >= 2000)
180
                        otgAvailable = otgAvailable or isotg
181
                        codAvailable = codAvailable or iscod
182
                if serviceable:        
183
                    returnMap[item_selling_price][location_id].otgAvailable = otgAvailable
184
                    returnMap[item_selling_price][location_id].codAvailable = codAvailable
185
                    returnMap[item_selling_price][location_id].minDelay = minDelay
186
                    returnMap[item_selling_price][location_id].maxDelay = maxDelay
187
    return returnMap
188
 
7608 rajveer 189
def get_logistics_estimation(destination_pin, item_selling_price, weight, type, billingWarehouseId):
5692 rajveer 190
    logging.info("Getting logistics estimation for pincode:" + destination_pin )
1504 ankur.sing 191
 
7608 rajveer 192
    provider_id, codAllowed, otgAvailable = __get_logistics_provider_for_destination_pincode(destination_pin, item_selling_price, weight, type, billingWarehouseId)
9964 anupam.sin 193
 
17530 manish.sha 194
    logging.info("Provider Id:  " + str(provider_id) +" codAllowed: "+str(codAllowed)+" otgAvailable: "+str(otgAvailable)+ " item_selling_price: "+str(item_selling_price))
195
 
196
    if item_selling_price > 60000:# or item_selling_price <= 250:
9964 anupam.sin 197
        codAllowed = False
198
 
16025 amit.gupta 199
    warehouse_location = warehouse_location_cache.get(billingWarehouseId)
200
    if warehouse_location is None:
201
        warehouse_location = 0
7857 rajveer 202
 
3217 rajveer 203
    if not provider_id:
5692 rajveer 204
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin))
644 chandransh 205
    try:
16025 amit.gupta 206
        logging.info( "destination_pin %s, provider_id %s, warehouse_location %s"%(destination_pin, provider_id, warehouse_location))
207
        logging.info( "Estimates %s, %s"%(delivery_estimate_cache[destination_pin, provider_id, warehouse_location]))
7857 rajveer 208
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
209
        delivery_delay = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
6537 rajveer 210
        delivery_estimate = _DeliveryEstimateObject(delivery_time, delivery_delay, provider_id, codAllowed, otgAvailable)
3218 rajveer 211
        return delivery_estimate
1504 ankur.sing 212
    except Exception as ex:
213
        print ex
644 chandransh 214
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")
3150 rajveer 215
 
7608 rajveer 216
def __get_logistics_provider_for_destination_pincode(destination_pin, item_selling_price, weight, type, billingWarehouseId):
13357 manish.sha 217
    '''
218
    if serviceable_location_cache.get(6).has_key(destination_pin):
219
        if weight < 480 and serviceable_location_cache.get(3).has_key(destination_pin) and type == DeliveryType.PREPAID:
220
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(3).get(destination_pin)
221
            if item_selling_price <= providerPrepaidLimit:
222
                iscod = iscod and item_selling_price <= websiteCodLimit
223
                otgAvailable = otgAvailable and item_selling_price >= 2000
224
                return 3, iscod, otgAvailable
225
        else:
226
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(6).get(destination_pin)
227
            if item_selling_price <= providerPrepaidLimit:
228
                iscod = iscod and item_selling_price <= websiteCodLimit
229
                otgAvailable = otgAvailable and item_selling_price >= 2000
230
                return 6, iscod, otgAvailable
231
    '''        
7981 rajveer 232
    if serviceable_location_cache.get(3).has_key(destination_pin):
233
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(3).get(destination_pin)
7627 rajveer 234
        if item_selling_price <= providerPrepaidLimit:
7608 rajveer 235
            iscod = iscod and item_selling_price <= websiteCodLimit
236
            otgAvailable = otgAvailable and item_selling_price >= 2000
7981 rajveer 237
            return 3, iscod, otgAvailable
8575 rajveer 238
 
17992 manish.sha 239
    if billingWarehouseId not in [12,13] and serviceable_location_cache.has_key(7) and serviceable_location_cache.get(7).has_key(destination_pin):
8575 rajveer 240
        if item_selling_price < 3000 and serviceable_location_cache.get(1).has_key(destination_pin):
241
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(1).get(destination_pin)
242
            if item_selling_price <= providerPrepaidLimit:
243
                iscod = iscod and item_selling_price <= websiteCodLimit
244
                otgAvailable = otgAvailable and item_selling_price >= 2000
245
                return 1, iscod, otgAvailable
246
        else:
247
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(7).get(destination_pin)
248
            if item_selling_price <= providerPrepaidLimit:
249
                iscod = iscod and item_selling_price <= websiteCodLimit
250
                otgAvailable = otgAvailable and item_selling_price >= 2000
251
                return 7, iscod, otgAvailable
252
 
7627 rajveer 253
    if serviceable_location_cache.get(1).has_key(destination_pin):
254
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(1).get(destination_pin)
255
        if item_selling_price <= providerPrepaidLimit:
7608 rajveer 256
            iscod = iscod and item_selling_price <= websiteCodLimit
257
            otgAvailable = otgAvailable and item_selling_price >= 2000
7627 rajveer 258
            return 1, iscod, otgAvailable
7981 rajveer 259
 
10185 amit.gupta 260
    return None, False, False    
5278 rajveer 261
 
6017 amar.kumar 262
def get_destination_code(providerId, pinCode):
263
    serviceableLocationDetail = ServiceableLocationDetails.query.filter_by(provider_id = providerId, dest_pincode = pinCode).one()
264
    return serviceableLocationDetail.dest_code
265
 
644 chandransh 266
def add_empty_AWBs(numbers, provider_id, type):
442 rajveer 267
    for number in numbers:
644 chandransh 268
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
444 rajveer 269
        try:
270
            query.one()
271
        except:    
644 chandransh 272
            awb = Awb()
444 rajveer 273
            awb.awb_number = number
644 chandransh 274
            awb.provider_id = provider_id
444 rajveer 275
            awb.is_available = True
644 chandransh 276
            awb.type = type
277
    session.commit()
19413 amit.gupta 278
 
279
def get_pincode_item_serviceability():
280
    pass
442 rajveer 281
 
444 rajveer 282
def set_AWB_as_used(awb_number):
644 chandransh 283
    query = Awb.query.filter_by(awb_number = awb_number)
444 rajveer 284
    awb = query.one() 
285
    awb.is_available=False
286
    session.commit()
287
 
3044 chandransh 288
def get_empty_AWB(provider_id, type = DeliveryType.PREPAID):
2342 chandransh 289
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
3044 chandransh 290
    if type == DeliveryType.PREPAID:
291
        query = query.filter_by(type="Prepaid")
292
    if type == DeliveryType.COD:
293
        query = query.filter_by(type="COD")
294
 
13158 manish.sha 295
    additionalQuery = query
296
    query = query.filter_by(awbUsedFor=0)
297
 
442 rajveer 298
    try:
644 chandransh 299
        awb = query.first()
13158 manish.sha 300
        if awb is None:
301
            additionalQuery = additionalQuery.filter_by(awbUsedFor=2)
302
            awb = additionalQuery.first()
644 chandransh 303
        awb.is_available = False
304
        session.commit()
444 rajveer 305
        return awb.awb_number
442 rajveer 306
    except:
644 chandransh 307
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
1137 chandransh 308
 
3103 chandransh 309
def get_free_awb_count(provider_id, type):
310
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
1137 chandransh 311
    if count == None:
312
        count = 0
313
    return count
442 rajveer 314
 
644 chandransh 315
def get_shipment_info(awb_number, provider_id):
316
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
317
    query = AwbUpdate.query.filter_by(awb = awb)
766 rajveer 318
    info = query.all()
319
    return info
320
 
6643 rajveer 321
def store_shipment_info(update):
322
    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()
323
    if not updates:
324
        dupdate = AwbUpdate()
325
        dupdate.providerId = update.providerId
326
        dupdate.awbNumber  = update.awbNumber
327
        dupdate.location = update.location
328
        dupdate.date = to_py_date(update.date)
329
        dupdate.status = update.status
330
        dupdate.description = update.description
331
        session.commit()
332
 
1730 ankur.sing 333
def get_holidays(start_date, end_date):
334
    query = PublicHolidays.query
335
    if start_date != -1:
336
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
337
    if end_date != -1:
338
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
339
    holidays = query.all()
340
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
341
    return holiday_dates
342
 
5527 anupam.sin 343
def get_provider_for_pickup_type(pickUp):
344
    return Provider.query.filter(Provider.pickup == pickUp).first().id
345
 
766 rajveer 346
def close_session():
347
    if session.is_active:
348
        print "session is active. closing it."
2823 chandransh 349
        session.close()
3376 rajveer 350
 
351
def is_alive():
352
    try:
353
        session.query(Awb.id).limit(1).one()
354
        return True
355
    except:
5555 rajveer 356
        return False
357
 
358
def get_all_pickup_stores():
5572 anupam.sin 359
    pickupStores = PickupStore.query.all()
360
    return pickupStores
5555 rajveer 361
 
362
def get_pickup_store(storeId):
5719 rajveer 363
    return PickupStore.query.filter_by(id = storeId).one()
364
 
365
def get_pickup_store_by_hotspot_id(hotspotId):
366
    return PickupStore.query.filter_by(hotspotId = hotspotId).one()
6322 amar.kumar 367
 
6524 rajveer 368
def add_pincode(provider, pincode, destCode, exp, cod, stationType, otgAvailable):
7914 rajveer 369
    provider = Provider.query.filter_by(id = provider).one()
6322 amar.kumar 370
    serviceableLocationDetails = ServiceableLocationDetails()
371
    serviceableLocationDetails.provider = provider
372
    serviceableLocationDetails.dest_pincode = pincode
373
    serviceableLocationDetails.dest_code = destCode
374
    serviceableLocationDetails.exp = exp
375
    serviceableLocationDetails.cod = cod
376
    serviceableLocationDetails.station_type = stationType
6524 rajveer 377
    serviceableLocationDetails.otgAvailable = otgAvailable
7733 manish.sha 378
    if provider.id == 1:
7627 rajveer 379
        codlimit = 10000
380
        prepaidlimit = 50000
7733 manish.sha 381
    elif provider.id == 3:
7627 rajveer 382
        codlimit = 25000
383
        prepaidlimit = 100000
7733 manish.sha 384
    elif provider.id == 6:
7627 rajveer 385
        codlimit = 25000
386
        prepaidlimit = 100000
387
    serviceableLocationDetails.providerPrepaidLimit = prepaidlimit
388
    serviceableLocationDetails.providerCodLimit = codlimit
389
    serviceableLocationDetails.websiteCodLimit = codlimit
390
    serviceableLocationDetails.storeCodLimit = codlimit
6322 amar.kumar 391
    session.commit()
392
 
6524 rajveer 393
def update_pincode(providerId, pincode, exp, cod, otgAvailable):
6615 amar.kumar 394
    serviceableLocationDetails = ServiceableLocationDetails.get_by(provider_id = providerId, dest_pincode = pincode)
6322 amar.kumar 395
    serviceableLocationDetails.exp = exp
396
    serviceableLocationDetails.cod = cod
6524 rajveer 397
    serviceableLocationDetails.otgAvailable = otgAvailable
7256 rajveer 398
    session.commit()
7567 rajveer 399
 
13146 manish.sha 400
def add_new_awbs(provider_id, isCod, awbs, awbUsedFor):
7567 rajveer 401
    provider = get_provider(provider_id)
402
    if isCod:
403
        dtype = 'Cod'
404
    else:
405
        dtype = 'Prepaid'
406
    for awb in awbs:
407
        a = Awb()
408
        a.type =  dtype
409
        a.is_available = True
410
        a.awb_number = awb
13146 manish.sha 411
        a.awbUsedFor = awbUsedFor
7567 rajveer 412
        a.provider = provider 
413
    session.commit()
7608 rajveer 414
    return True
7256 rajveer 415
 
416
def adjust_delivery_time(start_time, delivery_days):
417
    '''
418
    Returns the actual no. of days which will pass while 'delivery_days'
419
    no. of business days will pass since 'order_time'. 
420
    '''
421
    start_date = start_time.date()
422
    end_date = start_date + datetime.timedelta(days = delivery_days)
7272 amit.gupta 423
    holidays = get_holidays(to_java_date(start_time), -1)
7256 rajveer 424
    holidays = [to_py_date(holiday).date() for holiday in holidays]
425
 
426
    while start_date <= end_date:
427
        if start_date.weekday() == 6 or start_date in holidays:
428
            delivery_days = delivery_days + 1
429
            end_date = end_date + datetime.timedelta(days = 1)
430
        start_date = start_date + datetime.timedelta(days = 1)
431
 
432
    return delivery_days
7275 rajveer 433
 
434
def get_min_advance_amount(itemId, destination_pin, providerId, codAllowed):
435
    client = CatalogClient().get_client()
436
    sp = client.getStorePricing(itemId)
437
 
438
    if codAllowed:
439
        return sp.minAdvancePrice, True
440
    else:
7857 rajveer 441
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit = serviceable_location_cache.get(providerId).get(destination_pin)
7275 rajveer 442
        if iscod:
443
            if providerId == 6:
7489 rajveer 444
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 445
            if providerId == 3:
7489 rajveer 446
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 447
            if providerId == 1:
7489 rajveer 448
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 449
        else:
7425 rajveer 450
            return sp.recommendedPrice, False
7733 manish.sha 451
#Start:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
452
 
7786 manish.sha 453
def run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate):
454
    if runCompleteUpdate == True :
455
        serviceableLocationDetails = ServiceableLocationDetails.query.all()
456
        for serviceableLocationDetail in serviceableLocationDetails:
7841 manish.sha 457
            serviceableLocationDetail.exp = False
458
            serviceableLocationDetail.cod = False
7786 manish.sha 459
    for logisticsLocationInfo in logisticsLocationInfoList:
7841 manish.sha 460
        serviceableLocationDetail = ServiceableLocationDetails.get_by(provider_id = logisticsLocationInfo.providerId, dest_pincode = logisticsLocationInfo.pinCode)
7914 rajveer 461
        provider = Provider.query.filter_by(id = logisticsLocationInfo.providerId).one()
7841 manish.sha 462
        if serviceableLocationDetail:
463
            serviceableLocationDetail.exp = logisticsLocationInfo.expAvailable
464
            serviceableLocationDetail.cod = logisticsLocationInfo.codAvailable
465
            serviceableLocationDetail.otgAvailable = logisticsLocationInfo.otgAvailable
466
            serviceableLocationDetail.providerCodLimit = logisticsLocationInfo.codLimit
467
            serviceableLocationDetail.providerPrepaidLimit = logisticsLocationInfo.prepaidLimit
468
            serviceableLocationDetail.storeCodLimit = logisticsLocationInfo.codLimit
8219 manish.sha 469
            serviceableLocationDetail.websiteCodLimit = min(26000,logisticsLocationInfo.codLimit)
7841 manish.sha 470
        else:
471
            serviceableLocationDetail= ServiceableLocationDetails()
472
            serviceableLocationDetail.provider = provider
473
            serviceableLocationDetail.dest_pincode = logisticsLocationInfo.pinCode
474
            serviceableLocationDetail.dest_code = logisticsLocationInfo.destinationCode
475
            serviceableLocationDetail.exp = logisticsLocationInfo.expAvailable
476
            serviceableLocationDetail.cod = logisticsLocationInfo.codAvailable
477
            serviceableLocationDetail.station_type = 0
478
            serviceableLocationDetail.otgAvailable = logisticsLocationInfo.otgAvailable
479
            serviceableLocationDetail.providerCodLimit = logisticsLocationInfo.codLimit
480
            serviceableLocationDetail.providerPrepaidLimit = logisticsLocationInfo.prepaidLimit
481
            serviceableLocationDetail.storeCodLimit = logisticsLocationInfo.codLimit
8219 manish.sha 482
            serviceableLocationDetail.websiteCodLimit = min(26000,logisticsLocationInfo.codLimit)
7841 manish.sha 483
 
7870 rajveer 484
        deliveryEstimate = DeliveryEstimate.get_by(provider_id = logisticsLocationInfo.providerId, destination_pin = logisticsLocationInfo.pinCode, warehouse_location = logisticsLocationInfo.warehouseId) 
7841 manish.sha 485
        if deliveryEstimate:
486
            deliveryEstimate.warehouse_location= logisticsLocationInfo.warehouseId
487
            deliveryEstimate.delivery_time= logisticsLocationInfo.deliveryTime
488
            deliveryEstimate.delivery_delay= logisticsLocationInfo.delivery_delay
489
        else:
490
            deliveryEstimate = DeliveryEstimate()
491
            deliveryEstimate.destination_pin= logisticsLocationInfo.pinCode
492
            deliveryEstimate.provider = provider
493
            deliveryEstimate.warehouse_location= logisticsLocationInfo.warehouseId
494
            deliveryEstimate.delivery_time= logisticsLocationInfo.deliveryTime
495
            deliveryEstimate.delivery_delay= logisticsLocationInfo.delivery_delay
7733 manish.sha 496
    session.commit()
7786 manish.sha 497
 
7733 manish.sha 498
#End:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013             
7275 rajveer 499
 
12895 manish.sha 500
def get_first_delivery_estimate_for_wh_location(pincode, whLocation):
501
    delEstimate = DeliveryEstimate.query.filter(DeliveryEstimate.destination_pin == pincode).filter(DeliveryEstimate.warehouse_location == whLocation).first()
502
    if delEstimate is None:
503
        return -1
504
    else:
505
        return 1
13146 manish.sha 506
 
507
def get_provider_limit_details_for_pincode(provider, pincode):
508
    serviceAbleDetails = ServiceableLocationDetails.get_by(provider_id = provider, dest_pincode = pincode)
509
    returnDataMap = {}
510
    if serviceAbleDetails:
511
        returnDataMap["websiteCodLimit"] = str(serviceAbleDetails.websiteCodLimit)
19230 manish.sha 512
        returnDataMap["providerCodLimit"] = str(serviceAbleDetails.providerCodLimit)
13146 manish.sha 513
        returnDataMap["providerPrepaidLimit"] = str(serviceAbleDetails.providerPrepaidLimit)
514
 
515
    return returnDataMap
516
 
517
def get_new_empty_awb(providerId, type, orderQuantity):
518
    query = Awb.query.with_lockmode("update").filter_by(provider_id = providerId, is_available = True)  #check the provider thing
519
    if type == DeliveryType.PREPAID:
520
        query = query.filter_by(type="Prepaid")
521
    if type == DeliveryType.COD:
522
        query = query.filter_by(type="COD")
523
 
524
    additionalQuery = query
525
    if orderQuantity == 1:
526
        query = query.filter_by(awbUsedFor=0)
527
    if orderQuantity >1:
528
        query = query.filter_by(awbUsedFor=1) 
529
 
530
    try:
531
        awb = query.first()
532
        if awb is None:
533
            additionalQuery = additionalQuery.filter_by(awbUsedFor=2)
534
            awb = additionalQuery.first()
535
        awb.is_available = False
536
        session.commit()
537
        return awb.awb_number
538
    except:
539
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(providerId))
540