Subversion Repositories SmartDukaan

Rev

Rev 19413 | Rev 19421 | 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():
19420 amit.gupta 169
                    pp = PincodeProvider(destination_pin, provider_id)
170
                    if not serviceable_map.has_key(pp):
171
                        continue
172
                    iscod, isotg, providerCodLimit, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_map[pp]  
19413 amit.gupta 173
                    if item_selling_price <= providerPrepaidLimit:
174
                        if not serviceable:
175
                            serviceable = True
176
                            minDelay = delay_days
177
                            maxDelay = delay_days
178
                        else:
179
                            minDelay = min(delay_days,minDelay)
180
                            maxDelay = max(delay_days,maxDelay)
181
                        iscod = iscod and item_selling_price <= min(providerCodLimit, websiteCodLimit)
182
                        isotg = (isotg and item_selling_price >= 2000)
183
                        otgAvailable = otgAvailable or isotg
184
                        codAvailable = codAvailable or iscod
185
                if serviceable:        
186
                    returnMap[item_selling_price][location_id].otgAvailable = otgAvailable
187
                    returnMap[item_selling_price][location_id].codAvailable = codAvailable
188
                    returnMap[item_selling_price][location_id].minDelay = minDelay
189
                    returnMap[item_selling_price][location_id].maxDelay = maxDelay
190
    return returnMap
191
 
7608 rajveer 192
def get_logistics_estimation(destination_pin, item_selling_price, weight, type, billingWarehouseId):
5692 rajveer 193
    logging.info("Getting logistics estimation for pincode:" + destination_pin )
1504 ankur.sing 194
 
7608 rajveer 195
    provider_id, codAllowed, otgAvailable = __get_logistics_provider_for_destination_pincode(destination_pin, item_selling_price, weight, type, billingWarehouseId)
9964 anupam.sin 196
 
17530 manish.sha 197
    logging.info("Provider Id:  " + str(provider_id) +" codAllowed: "+str(codAllowed)+" otgAvailable: "+str(otgAvailable)+ " item_selling_price: "+str(item_selling_price))
198
 
199
    if item_selling_price > 60000:# or item_selling_price <= 250:
9964 anupam.sin 200
        codAllowed = False
201
 
16025 amit.gupta 202
    warehouse_location = warehouse_location_cache.get(billingWarehouseId)
203
    if warehouse_location is None:
204
        warehouse_location = 0
7857 rajveer 205
 
3217 rajveer 206
    if not provider_id:
5692 rajveer 207
        raise LogisticsServiceException(101, "No provider assigned for pincode: " + str(destination_pin))
644 chandransh 208
    try:
16025 amit.gupta 209
        logging.info( "destination_pin %s, provider_id %s, warehouse_location %s"%(destination_pin, provider_id, warehouse_location))
210
        logging.info( "Estimates %s, %s"%(delivery_estimate_cache[destination_pin, provider_id, warehouse_location]))
7857 rajveer 211
        delivery_time = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][0]
212
        delivery_delay = delivery_estimate_cache[destination_pin, provider_id, warehouse_location][1]
6537 rajveer 213
        delivery_estimate = _DeliveryEstimateObject(delivery_time, delivery_delay, provider_id, codAllowed, otgAvailable)
3218 rajveer 214
        return delivery_estimate
1504 ankur.sing 215
    except Exception as ex:
216
        print ex
644 chandransh 217
        raise LogisticsServiceException(103, "No Logistics partner listed for this destination pincode and the primary warehouse")
3150 rajveer 218
 
7608 rajveer 219
def __get_logistics_provider_for_destination_pincode(destination_pin, item_selling_price, weight, type, billingWarehouseId):
13357 manish.sha 220
    '''
221
    if serviceable_location_cache.get(6).has_key(destination_pin):
222
        if weight < 480 and serviceable_location_cache.get(3).has_key(destination_pin) and type == DeliveryType.PREPAID:
223
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(3).get(destination_pin)
224
            if item_selling_price <= providerPrepaidLimit:
225
                iscod = iscod and item_selling_price <= websiteCodLimit
226
                otgAvailable = otgAvailable and item_selling_price >= 2000
227
                return 3, iscod, otgAvailable
228
        else:
229
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(6).get(destination_pin)
230
            if item_selling_price <= providerPrepaidLimit:
231
                iscod = iscod and item_selling_price <= websiteCodLimit
232
                otgAvailable = otgAvailable and item_selling_price >= 2000
233
                return 6, iscod, otgAvailable
234
    '''        
7981 rajveer 235
    if serviceable_location_cache.get(3).has_key(destination_pin):
236
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(3).get(destination_pin)
7627 rajveer 237
        if item_selling_price <= providerPrepaidLimit:
7608 rajveer 238
            iscod = iscod and item_selling_price <= websiteCodLimit
239
            otgAvailable = otgAvailable and item_selling_price >= 2000
7981 rajveer 240
            return 3, iscod, otgAvailable
8575 rajveer 241
 
17992 manish.sha 242
    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 243
        if item_selling_price < 3000 and serviceable_location_cache.get(1).has_key(destination_pin):
244
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(1).get(destination_pin)
245
            if item_selling_price <= providerPrepaidLimit:
246
                iscod = iscod and item_selling_price <= websiteCodLimit
247
                otgAvailable = otgAvailable and item_selling_price >= 2000
248
                return 1, iscod, otgAvailable
249
        else:
250
            dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(7).get(destination_pin)
251
            if item_selling_price <= providerPrepaidLimit:
252
                iscod = iscod and item_selling_price <= websiteCodLimit
253
                otgAvailable = otgAvailable and item_selling_price >= 2000
254
                return 7, iscod, otgAvailable
255
 
7627 rajveer 256
    if serviceable_location_cache.get(1).has_key(destination_pin):
257
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit, providerPrepaidLimit = serviceable_location_cache.get(1).get(destination_pin)
258
        if item_selling_price <= providerPrepaidLimit:
7608 rajveer 259
            iscod = iscod and item_selling_price <= websiteCodLimit
260
            otgAvailable = otgAvailable and item_selling_price >= 2000
7627 rajveer 261
            return 1, iscod, otgAvailable
7981 rajveer 262
 
10185 amit.gupta 263
    return None, False, False    
5278 rajveer 264
 
6017 amar.kumar 265
def get_destination_code(providerId, pinCode):
266
    serviceableLocationDetail = ServiceableLocationDetails.query.filter_by(provider_id = providerId, dest_pincode = pinCode).one()
267
    return serviceableLocationDetail.dest_code
268
 
644 chandransh 269
def add_empty_AWBs(numbers, provider_id, type):
442 rajveer 270
    for number in numbers:
644 chandransh 271
        query = Awb.query.filter_by(awb_number = number, provider_id = provider_id)
444 rajveer 272
        try:
273
            query.one()
274
        except:    
644 chandransh 275
            awb = Awb()
444 rajveer 276
            awb.awb_number = number
644 chandransh 277
            awb.provider_id = provider_id
444 rajveer 278
            awb.is_available = True
644 chandransh 279
            awb.type = type
280
    session.commit()
19413 amit.gupta 281
 
282
def get_pincode_item_serviceability():
283
    pass
442 rajveer 284
 
444 rajveer 285
def set_AWB_as_used(awb_number):
644 chandransh 286
    query = Awb.query.filter_by(awb_number = awb_number)
444 rajveer 287
    awb = query.one() 
288
    awb.is_available=False
289
    session.commit()
290
 
3044 chandransh 291
def get_empty_AWB(provider_id, type = DeliveryType.PREPAID):
2342 chandransh 292
    query = Awb.query.with_lockmode("update").filter_by(provider_id = provider_id, is_available = True)  #check the provider thing
3044 chandransh 293
    if type == DeliveryType.PREPAID:
294
        query = query.filter_by(type="Prepaid")
295
    if type == DeliveryType.COD:
296
        query = query.filter_by(type="COD")
297
 
13158 manish.sha 298
    additionalQuery = query
299
    query = query.filter_by(awbUsedFor=0)
300
 
442 rajveer 301
    try:
644 chandransh 302
        awb = query.first()
13158 manish.sha 303
        if awb is None:
304
            additionalQuery = additionalQuery.filter_by(awbUsedFor=2)
305
            awb = additionalQuery.first()
644 chandransh 306
        awb.is_available = False
307
        session.commit()
444 rajveer 308
        return awb.awb_number
442 rajveer 309
    except:
644 chandransh 310
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(provider_id))
1137 chandransh 311
 
3103 chandransh 312
def get_free_awb_count(provider_id, type):
313
    count = Awb.query.filter_by(provider_id = provider_id, is_available = True, type=type).count()
1137 chandransh 314
    if count == None:
315
        count = 0
316
    return count
442 rajveer 317
 
644 chandransh 318
def get_shipment_info(awb_number, provider_id):
319
    awb = Awb.get_by(awb_number = awb_number, provider_id = provider_id)
320
    query = AwbUpdate.query.filter_by(awb = awb)
766 rajveer 321
    info = query.all()
322
    return info
323
 
6643 rajveer 324
def store_shipment_info(update):
325
    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()
326
    if not updates:
327
        dupdate = AwbUpdate()
328
        dupdate.providerId = update.providerId
329
        dupdate.awbNumber  = update.awbNumber
330
        dupdate.location = update.location
331
        dupdate.date = to_py_date(update.date)
332
        dupdate.status = update.status
333
        dupdate.description = update.description
334
        session.commit()
335
 
1730 ankur.sing 336
def get_holidays(start_date, end_date):
337
    query = PublicHolidays.query
338
    if start_date != -1:
339
        query = query.filter(PublicHolidays.date >= to_py_date(start_date))
340
    if end_date != -1:
341
        query = query.filter(PublicHolidays.date <= to_py_date(end_date))
342
    holidays = query.all()
343
    holiday_dates = [to_java_date(datetime.datetime(*time.strptime(str(holiday.date), '%Y-%m-%d')[:3])) for holiday in holidays] 
344
    return holiday_dates
345
 
5527 anupam.sin 346
def get_provider_for_pickup_type(pickUp):
347
    return Provider.query.filter(Provider.pickup == pickUp).first().id
348
 
766 rajveer 349
def close_session():
350
    if session.is_active:
351
        print "session is active. closing it."
2823 chandransh 352
        session.close()
3376 rajveer 353
 
354
def is_alive():
355
    try:
356
        session.query(Awb.id).limit(1).one()
357
        return True
358
    except:
5555 rajveer 359
        return False
360
 
361
def get_all_pickup_stores():
5572 anupam.sin 362
    pickupStores = PickupStore.query.all()
363
    return pickupStores
5555 rajveer 364
 
365
def get_pickup_store(storeId):
5719 rajveer 366
    return PickupStore.query.filter_by(id = storeId).one()
367
 
368
def get_pickup_store_by_hotspot_id(hotspotId):
369
    return PickupStore.query.filter_by(hotspotId = hotspotId).one()
6322 amar.kumar 370
 
6524 rajveer 371
def add_pincode(provider, pincode, destCode, exp, cod, stationType, otgAvailable):
7914 rajveer 372
    provider = Provider.query.filter_by(id = provider).one()
6322 amar.kumar 373
    serviceableLocationDetails = ServiceableLocationDetails()
374
    serviceableLocationDetails.provider = provider
375
    serviceableLocationDetails.dest_pincode = pincode
376
    serviceableLocationDetails.dest_code = destCode
377
    serviceableLocationDetails.exp = exp
378
    serviceableLocationDetails.cod = cod
379
    serviceableLocationDetails.station_type = stationType
6524 rajveer 380
    serviceableLocationDetails.otgAvailable = otgAvailable
7733 manish.sha 381
    if provider.id == 1:
7627 rajveer 382
        codlimit = 10000
383
        prepaidlimit = 50000
7733 manish.sha 384
    elif provider.id == 3:
7627 rajveer 385
        codlimit = 25000
386
        prepaidlimit = 100000
7733 manish.sha 387
    elif provider.id == 6:
7627 rajveer 388
        codlimit = 25000
389
        prepaidlimit = 100000
390
    serviceableLocationDetails.providerPrepaidLimit = prepaidlimit
391
    serviceableLocationDetails.providerCodLimit = codlimit
392
    serviceableLocationDetails.websiteCodLimit = codlimit
393
    serviceableLocationDetails.storeCodLimit = codlimit
6322 amar.kumar 394
    session.commit()
395
 
6524 rajveer 396
def update_pincode(providerId, pincode, exp, cod, otgAvailable):
6615 amar.kumar 397
    serviceableLocationDetails = ServiceableLocationDetails.get_by(provider_id = providerId, dest_pincode = pincode)
6322 amar.kumar 398
    serviceableLocationDetails.exp = exp
399
    serviceableLocationDetails.cod = cod
6524 rajveer 400
    serviceableLocationDetails.otgAvailable = otgAvailable
7256 rajveer 401
    session.commit()
7567 rajveer 402
 
13146 manish.sha 403
def add_new_awbs(provider_id, isCod, awbs, awbUsedFor):
7567 rajveer 404
    provider = get_provider(provider_id)
405
    if isCod:
406
        dtype = 'Cod'
407
    else:
408
        dtype = 'Prepaid'
409
    for awb in awbs:
410
        a = Awb()
411
        a.type =  dtype
412
        a.is_available = True
413
        a.awb_number = awb
13146 manish.sha 414
        a.awbUsedFor = awbUsedFor
7567 rajveer 415
        a.provider = provider 
416
    session.commit()
7608 rajveer 417
    return True
7256 rajveer 418
 
419
def adjust_delivery_time(start_time, delivery_days):
420
    '''
421
    Returns the actual no. of days which will pass while 'delivery_days'
422
    no. of business days will pass since 'order_time'. 
423
    '''
424
    start_date = start_time.date()
425
    end_date = start_date + datetime.timedelta(days = delivery_days)
7272 amit.gupta 426
    holidays = get_holidays(to_java_date(start_time), -1)
7256 rajveer 427
    holidays = [to_py_date(holiday).date() for holiday in holidays]
428
 
429
    while start_date <= end_date:
430
        if start_date.weekday() == 6 or start_date in holidays:
431
            delivery_days = delivery_days + 1
432
            end_date = end_date + datetime.timedelta(days = 1)
433
        start_date = start_date + datetime.timedelta(days = 1)
434
 
435
    return delivery_days
7275 rajveer 436
 
437
def get_min_advance_amount(itemId, destination_pin, providerId, codAllowed):
438
    client = CatalogClient().get_client()
439
    sp = client.getStorePricing(itemId)
440
 
441
    if codAllowed:
442
        return sp.minAdvancePrice, True
443
    else:
7857 rajveer 444
        dest_code, exp, iscod, otgAvailable, websiteCodLimit, storeCodLimit = serviceable_location_cache.get(providerId).get(destination_pin)
7275 rajveer 445
        if iscod:
446
            if providerId == 6:
7489 rajveer 447
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 448
            if providerId == 3:
7489 rajveer 449
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 450
            if providerId == 1:
7489 rajveer 451
                return max(sp.minAdvancePrice, sp.recommendedPrice - storeCodLimit), True
7275 rajveer 452
        else:
7425 rajveer 453
            return sp.recommendedPrice, False
7733 manish.sha 454
#Start:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013
455
 
7786 manish.sha 456
def run_Logistics_Location_Info_Update(logisticsLocationInfoList, runCompleteUpdate):
457
    if runCompleteUpdate == True :
458
        serviceableLocationDetails = ServiceableLocationDetails.query.all()
459
        for serviceableLocationDetail in serviceableLocationDetails:
7841 manish.sha 460
            serviceableLocationDetail.exp = False
461
            serviceableLocationDetail.cod = False
7786 manish.sha 462
    for logisticsLocationInfo in logisticsLocationInfoList:
7841 manish.sha 463
        serviceableLocationDetail = ServiceableLocationDetails.get_by(provider_id = logisticsLocationInfo.providerId, dest_pincode = logisticsLocationInfo.pinCode)
7914 rajveer 464
        provider = Provider.query.filter_by(id = logisticsLocationInfo.providerId).one()
7841 manish.sha 465
        if serviceableLocationDetail:
466
            serviceableLocationDetail.exp = logisticsLocationInfo.expAvailable
467
            serviceableLocationDetail.cod = logisticsLocationInfo.codAvailable
468
            serviceableLocationDetail.otgAvailable = logisticsLocationInfo.otgAvailable
469
            serviceableLocationDetail.providerCodLimit = logisticsLocationInfo.codLimit
470
            serviceableLocationDetail.providerPrepaidLimit = logisticsLocationInfo.prepaidLimit
471
            serviceableLocationDetail.storeCodLimit = logisticsLocationInfo.codLimit
8219 manish.sha 472
            serviceableLocationDetail.websiteCodLimit = min(26000,logisticsLocationInfo.codLimit)
7841 manish.sha 473
        else:
474
            serviceableLocationDetail= ServiceableLocationDetails()
475
            serviceableLocationDetail.provider = provider
476
            serviceableLocationDetail.dest_pincode = logisticsLocationInfo.pinCode
477
            serviceableLocationDetail.dest_code = logisticsLocationInfo.destinationCode
478
            serviceableLocationDetail.exp = logisticsLocationInfo.expAvailable
479
            serviceableLocationDetail.cod = logisticsLocationInfo.codAvailable
480
            serviceableLocationDetail.station_type = 0
481
            serviceableLocationDetail.otgAvailable = logisticsLocationInfo.otgAvailable
482
            serviceableLocationDetail.providerCodLimit = logisticsLocationInfo.codLimit
483
            serviceableLocationDetail.providerPrepaidLimit = logisticsLocationInfo.prepaidLimit
484
            serviceableLocationDetail.storeCodLimit = logisticsLocationInfo.codLimit
8219 manish.sha 485
            serviceableLocationDetail.websiteCodLimit = min(26000,logisticsLocationInfo.codLimit)
7841 manish.sha 486
 
7870 rajveer 487
        deliveryEstimate = DeliveryEstimate.get_by(provider_id = logisticsLocationInfo.providerId, destination_pin = logisticsLocationInfo.pinCode, warehouse_location = logisticsLocationInfo.warehouseId) 
7841 manish.sha 488
        if deliveryEstimate:
489
            deliveryEstimate.warehouse_location= logisticsLocationInfo.warehouseId
490
            deliveryEstimate.delivery_time= logisticsLocationInfo.deliveryTime
491
            deliveryEstimate.delivery_delay= logisticsLocationInfo.delivery_delay
492
        else:
493
            deliveryEstimate = DeliveryEstimate()
494
            deliveryEstimate.destination_pin= logisticsLocationInfo.pinCode
495
            deliveryEstimate.provider = provider
496
            deliveryEstimate.warehouse_location= logisticsLocationInfo.warehouseId
497
            deliveryEstimate.delivery_time= logisticsLocationInfo.deliveryTime
498
            deliveryEstimate.delivery_delay= logisticsLocationInfo.delivery_delay
7733 manish.sha 499
    session.commit()
7786 manish.sha 500
 
7733 manish.sha 501
#End:- Added by Manish Sharma for Multiple Pincode Updation on 05-Jul-2013             
7275 rajveer 502
 
12895 manish.sha 503
def get_first_delivery_estimate_for_wh_location(pincode, whLocation):
504
    delEstimate = DeliveryEstimate.query.filter(DeliveryEstimate.destination_pin == pincode).filter(DeliveryEstimate.warehouse_location == whLocation).first()
505
    if delEstimate is None:
506
        return -1
507
    else:
508
        return 1
13146 manish.sha 509
 
510
def get_provider_limit_details_for_pincode(provider, pincode):
511
    serviceAbleDetails = ServiceableLocationDetails.get_by(provider_id = provider, dest_pincode = pincode)
512
    returnDataMap = {}
513
    if serviceAbleDetails:
514
        returnDataMap["websiteCodLimit"] = str(serviceAbleDetails.websiteCodLimit)
19230 manish.sha 515
        returnDataMap["providerCodLimit"] = str(serviceAbleDetails.providerCodLimit)
13146 manish.sha 516
        returnDataMap["providerPrepaidLimit"] = str(serviceAbleDetails.providerPrepaidLimit)
517
 
518
    return returnDataMap
519
 
520
def get_new_empty_awb(providerId, type, orderQuantity):
521
    query = Awb.query.with_lockmode("update").filter_by(provider_id = providerId, is_available = True)  #check the provider thing
522
    if type == DeliveryType.PREPAID:
523
        query = query.filter_by(type="Prepaid")
524
    if type == DeliveryType.COD:
525
        query = query.filter_by(type="COD")
526
 
527
    additionalQuery = query
528
    if orderQuantity == 1:
529
        query = query.filter_by(awbUsedFor=0)
530
    if orderQuantity >1:
531
        query = query.filter_by(awbUsedFor=1) 
532
 
533
    try:
534
        awb = query.first()
535
        if awb is None:
536
            additionalQuery = additionalQuery.filter_by(awbUsedFor=2)
537
            awb = additionalQuery.first()
538
        awb.is_available = False
539
        session.commit()
540
        return awb.awb_number
541
    except:
542
        raise LogisticsServiceException(103, "Unable to get an AWB for the given Provider: " + str(providerId))
543