Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
4506 phani.kuma 1
#!/usr/bin/python
2
'''
3
It processes the following orders:
4
 1. Orders in DOA_PICKUP_CONFIRMED status : get details of orders that 
5
     were in DOA_PICKUP_CONFIRMED status from database and 
6
     calls aramex api to know whether they are picked up by armaex
7
     and changes the status to DOA_RETURN_IN_TRANSIT if it is done.
4741 phani.kuma 8
 2. Orders in RET_PICKUP_CONFIRMED status : get details of orders that 
9
     were in RET_PICKUP_CONFIRMED status from database and 
10
     calls aramex api to know whether they are picked up by armaex
11
     and changes the status to RET_RETURN_IN_TRANSIT if it is done.
12
 3. Orders in SHIPPED_FROM_WH status: get details of orders that
4506 phani.kuma 13
     were in SHIPPED_FROM_WH status from database and 
14
     calls aramex api to know whether they are picked up by armaex
15
     and changes the status to SHIPPED_TO_LOGST if it is done.
4741 phani.kuma 16
 4. Orders in SHIPPED_TO_LOGST status: get details of orders that
4506 phani.kuma 17
     were in SHIPPED_TO_LOGST status from database and 
18
     calls aramex api to know their status and changes the status accordingly.
19
 
4741 phani.kuma 20
It sends out a Pickup mismatch report, Return orders Pickup Mismatch report, Doa Pickup mismatch report,
21
Undelivered orders report and Returned Orders report to cnc.center@shop2020.in
4506 phani.kuma 22
 
23
http://www.aramex.com/track_xml.asp?ShipperRef={variable1}&OrgCntry=In&FromDate={variable2}&ToDate={variable3} is hard coded
24
to track DOA orders and for other orders ConfigClient is called to get aramex_update_url
25
 
26
@author: Phani Kumar
27
'''
28
import time
29
import datetime
30
import optparse
31
import sys
32
import csv
33
import traceback
34
import urllib2
35
from xml.etree.ElementTree import parse
36
 
37
if __name__ == '__main__' and __package__ is None:
38
    import os
39
    sys.path.insert(0, os.getcwd())
40
 
41
from shop2020.clients.LogisticsClient import LogisticsClient
42
from shop2020.clients.TransactionClient import TransactionClient
4910 phani.kuma 43
from shop2020.clients.UserClient import UserClient
4506 phani.kuma 44
from shop2020.config.client.ConfigClient import ConfigClient
4910 phani.kuma 45
from shop2020.clients.CRMClient import CRMClient
4506 phani.kuma 46
from shop2020.thriftpy.config.ttypes import ConfigException
47
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, OrderStatus
48
from shop2020.utils.EmailAttachmentSender import get_attachment_part, mail
49
from shop2020.utils.Utils import to_py_date
4910 phani.kuma 50
from shop2020.thriftpy.crm.ttypes import *
4506 phani.kuma 51
 
4910 phani.kuma 52
try:
53
    config_client = ConfigClient()
54
    ARAMEX_URL = config_client.get_property("aramex_update_url")
55
except ConfigException as cex:
56
    print cex.message
57
    traceback.print_exc()
58
 
4506 phani.kuma 59
from_user = 'cnc.center@shop2020.in'
60
from_pwd = '5h0p2o2o'
4760 phani.kuma 61
to = ['cnc.center@shop2020.in', "suraj.sharma@shop2020.in", "sandeep.sachdeva@shop2020.in", "manoj.kumar@shop2020.in"]
4506 phani.kuma 62
 
63
def process_dao_pickup_orders(provider):
64
    try:
4910 phani.kuma 65
        doas_tobe_picked_up = fetch_data(provider.id, [OrderStatus.DOA_PICKUP_CONFIRMED])
4741 phani.kuma 66
        doa_pickup_details = read_dao_return_pickup_orders(doas_tobe_picked_up)
4910 phani.kuma 67
        if doa_pickup_details:
68
            update_picked_doas(provider.id, doa_pickup_details)
4559 phani.kuma 69
    except:
70
        print "Some issue while processing the orders in DOA_PICKUP_CONFIRMED status"
4506 phani.kuma 71
        traceback.print_exc()
72
 
4741 phani.kuma 73
def process_return_pickup_orders(provider):
74
    try:
4910 phani.kuma 75
        returns_tobe_picked_up = fetch_data(provider.id, [OrderStatus.RET_PICKUP_CONFIRMED])
4741 phani.kuma 76
        returns_pickup_details = read_dao_return_pickup_orders(returns_tobe_picked_up)
4910 phani.kuma 77
        if returns_pickup_details:
78
            update_picked_returns(provider.id, returns_pickup_details)
4741 phani.kuma 79
    except:
80
        print "Some issue while processing the orders in RET_PICKUP_CONFIRMED status"
81
        traceback.print_exc()
82
 
4506 phani.kuma 83
def process_pickup_records(provider):
84
    try:
4910 phani.kuma 85
        orders_tobe_picked_up = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH])
4559 phani.kuma 86
        pickup_details = read_pickup_orders(orders_tobe_picked_up)
4910 phani.kuma 87
        if pickup_details:
88
            update_picked_orders(provider.id, pickup_details)
4559 phani.kuma 89
    except:
90
        print "Some issue while processing the orders in SHIPPED_FROM_WH status"
4506 phani.kuma 91
        traceback.print_exc()
92
 
4910 phani.kuma 93
def process_local_connection_orders(provider):
94
    try:
95
        orders_tobe_local_connected = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST])
96
        local_connected_orders = read_local_connection_orders(orders_tobe_local_connected)
97
        if local_connected_orders:
98
            update_local_connected_orders(provider.id, local_connected_orders)
99
    except:
100
        print "Some issue while processing the orders for local connection status"
101
        traceback.print_exc()
102
 
103
def process_reached_destination_city_orders(provider):
104
    try:
105
        orders_tobe_reached_destination_city = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY])
106
        destination_city_reached_orders = read_reached_destination_orders(orders_tobe_reached_destination_city)
107
        if destination_city_reached_orders:
108
            update_destination_city_reached_orders(provider.id, destination_city_reached_orders)
109
    except:
110
        print "Some issue while processing the orders for Reached Destination City status"
111
        traceback.print_exc()
112
 
113
def process_first_delivery_attempt_orders(provider):
114
    try:
115
        orders_tobe_first_delivery_attempted = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY])
116
        first_atdl_orders = read_first_delivery_attempt_orders(orders_tobe_first_delivery_attempted)
117
        if first_atdl_orders:
118
            update_first_atdl_orders(provider.id, first_atdl_orders)
119
    except:
120
        print "Some issue while processing the orders for First delivery attempt status"
121
        traceback.print_exc()
122
 
4506 phani.kuma 123
def process_delivery_report(provider):
124
    try:
4910 phani.kuma 125
        orders_tobe_delivered = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE])
126
        delivered_orders, returned_orders, undelivered_orders = read_delivery_orders(orders_tobe_delivered)
4506 phani.kuma 127
        if delivered_orders:
128
            update_delivered_orders(provider.id, delivered_orders)
129
        if returned_orders:
130
            update_returned_orders(provider.id, returned_orders)
4910 phani.kuma 131
        if undelivered_orders:
132
            update_reason_of_undelivered_orders(provider.id, undelivered_orders)
4506 phani.kuma 133
    except:
4910 phani.kuma 134
        print "Some issue while processing the orders for delivery status"
4506 phani.kuma 135
        traceback.print_exc()
136
 
4910 phani.kuma 137
def generate_reports(provider):
138
    get_doas_not_picked_up(provider)
139
    get_returns_not_picked_up(provider)
140
    get_orders_not_picked_up(provider)
141
    get_orders_pending_local_connection(provider)
142
    get_returned_orders(provider)
143
    get_orders_not_delivered(provider)
144
 
145
def get_doas_not_picked_up(provider):
146
    txnClient = TransactionClient().get_client()
147
    try:
148
        doas_not_picked_up = txnClient.getDoasNotPickedUp(provider.id)
149
    except TransactionServiceException as tex:
150
        print tex.message
151
 
152
    try:
153
        if doas_not_picked_up:
154
            print "DOAs not Picked up:"
155
            print doas_not_picked_up
156
            mismatch_file = "/tmp/DoaPickupMismatch.csv"
157
            print "Some of our DOA orders were not picked up. Printing report to:" + mismatch_file
158
            print_dao_return_pickup_mismatch_report(mismatch_file, doas_not_picked_up)
159
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
160
            mail(from_user, from_pwd, to,\
161
                 "DOA Pickup Mismatch for " + provider.name,\
162
                 "This is a system generated email.Please don't reply to it.",\
163
                 pickup_mismatch_part)
164
    except Exception:
165
        print "Some issue sending the DOA mismatch report"
166
        traceback.print_exc()
167
 
168
def get_returns_not_picked_up(provider):
169
    txnClient = TransactionClient().get_client()
170
    try:
171
        returns_not_picked_up = txnClient.getReturnOrdersNotPickedUp(provider.id)
172
    except TransactionServiceException as tex:
173
        print tex.message
174
 
175
    try:
176
        if returns_not_picked_up:
177
            print "Return Orders not Picked up:"
178
            print returns_not_picked_up
179
            mismatch_file = "/tmp/ReturnsPickupMismatch.csv"
180
            print "Some of our Return orders were not picked up. Printing report to:" + mismatch_file
181
            print_dao_return_pickup_mismatch_report(mismatch_file, returns_not_picked_up)
182
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
183
            mail(from_user, from_pwd, to,\
184
                 "Return orders Pickup Mismatch for " + provider.name,\
185
                 "This is a system generated email.Please don't reply to it.",\
186
                 pickup_mismatch_part)
187
    except Exception:
188
        print "Some issue sending the Return orders mismatch report"
189
        traceback.print_exc()
190
 
191
def get_orders_not_picked_up(provider):
192
    txnClient = TransactionClient().get_client()
193
    try:
194
        orders_not_picked_up = txnClient.getOrdersNotPickedUp(provider.id)
195
    except TransactionServiceException as tex:
196
        print tex.message
197
 
198
    try:
199
        if orders_not_picked_up:
200
            print "Orders not Picked up:"
201
            print orders_not_picked_up
202
            mismatch_file = "/tmp/PickupMismatch.csv"
203
            print "Some of our orders were not picked up. Printing report to:" + mismatch_file
204
            print_pickup_mismatch_report(mismatch_file, orders_not_picked_up)
205
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
206
            mail(from_user, from_pwd, to,\
207
                 "Order Pickup Mismatch for " + provider.name,\
208
                 "This is a system generated email.Please don't reply to it.",\
209
                 pickup_mismatch_part)
210
    except Exception:
211
        print "Some issue sending the pickup mismatch report"
212
        traceback.print_exc()
213
 
214
def get_orders_pending_local_connection(provider):
215
    txnClient = TransactionClient().get_client()
216
    try:
217
        orders_pending_local_connection = txnClient.getOrdersNotLocalConnected(provider.id)
218
    except TransactionServiceException as tex:
219
        print tex.message
220
 
221
    try:
222
        if orders_pending_local_connection:
223
            print "Local Connection Pending Orders:"
224
            print orders_pending_local_connection
225
            mismatch_file = "/tmp/LocalConnectionPendingOrders.csv"
226
            print "Some of our Orders were not Shipped to Destination yet. Printing report to:" + mismatch_file
227
            print_undelivered_orders_report(mismatch_file, orders_pending_local_connection)
228
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
229
            mail(from_user, from_pwd, to,\
230
                 "Orders that are not Shipped to Destination yet for " + provider.name,\
231
                 "This is a system generated email.Please don't reply to it.",\
232
                 pickup_mismatch_part)
233
    except Exception:
234
        print "Some issue updating and sending the Local Connection orders report"
235
        traceback.print_exc()
236
 
237
def get_returned_orders(provider):
238
    txnClient = TransactionClient().get_client()
239
    try:
240
        returned_orders = txnClient.getRTOrders(provider.id)
241
    except TransactionServiceException as tex:
242
        print tex.message
243
 
244
    try:
245
        if returned_orders:
246
            print "Returned Orders:"
247
            print returned_orders
248
            returned_orders_file = "/tmp/ReturnedOrders.csv"
249
            print "Some of our Orders were returned by logistics provider. Printing report to:" + returned_orders_file
250
            print_rto_orders_report(returned_orders_file, returned_orders)
251
            returned_orders_report = [get_attachment_part(returned_orders_file)]
252
            mail(from_user, from_pwd, to,\
253
                 "Returned Orders Report for " + provider.name,\
254
                 "This is a system generated email.Please don't reply to it.",\
255
                 returned_orders_report)
256
    except:
257
        print "Some issue sending the returned orders report"
258
        traceback.print_exc()
259
 
260
def get_orders_not_delivered(provider):
261
    txnClient = TransactionClient().get_client()
262
    try:
263
        orders_not_delivered = txnClient.getNonDeliveredOrdersbyCourier(provider.id)
264
    except TransactionServiceException as tex:
265
        print tex.message
266
 
267
    try:
268
        if orders_not_delivered:
269
            print "Undelivered Orders:"
270
            print orders_not_delivered
271
            mismatch_file = "/tmp/UndeliveredOrders.csv"
272
            print "Some of our Orders were not delivered. Printing report to:" + mismatch_file
273
            print_undelivered_orders_report(mismatch_file, orders_not_delivered)
274
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
275
            mail(from_user, from_pwd, to,\
276
                 "Orders that are undelivered but picked up or shipped four days ago for " + provider.name,\
277
                 "This is a system generated email.Please don't reply to it.",\
278
                 pickup_mismatch_part)
279
    except Exception:
280
        print "Some issue updating and sending the undelivered orders report"
281
        traceback.print_exc()
282
 
4506 phani.kuma 283
def get_provider_by_name(provider_name):
284
    logistics_client = LogisticsClient().get_client()
285
    provider = None
286
    providers = logistics_client.getAllProviders()
287
    for p in providers:
288
        if p.name == provider_name:
289
            provider=p
290
            break
291
    if provider == None:
292
        sys.exit("Can't continue execution: No such provider")
293
    return provider
294
 
4910 phani.kuma 295
def fetch_data(provider_id, order_status_list):
4506 phani.kuma 296
    txnClient = TransactionClient().get_client()
297
    try:
4910 phani.kuma 298
        doas_tobe_picked_up = txnClient.getOrdersForProviderForStatus(provider_id, order_status_list)
4506 phani.kuma 299
        return doas_tobe_picked_up
300
    except TransactionServiceException as tex:
301
        print tex.message
302
 
4741 phani.kuma 303
def read_dao_return_pickup_orders(orders_tobe_picked_up):
4506 phani.kuma 304
    #uri=http://www.aramex.com/track_xml.asp?ShipperRef=61582&OrgCntry=In&FromDate=2-6-2012&ToDate=2-6-2012
4741 phani.kuma 305
    picked_up_orders = {}
306
    for order in orders_tobe_picked_up:
4506 phani.kuma 307
        try:
4741 phani.kuma 308
            uri = 'http://www.aramex.com/track_xml.asp?ShipperRef=' + str(order.pickupRequestNo) + '&OrgCntry=In&FromDate=' + to_py_date(order.doa_auth_timestamp).strftime("%m-%d-%Y") +'&ToDate=' + datetime.date.today().strftime("%m-%d-%Y")
309
            root = parse(urllib2.urlopen(uri)).getroot()
4506 phani.kuma 310
            nodes = root.findall('HAWBDetails/HAWBHistory/HAWBUpdate')
4910 phani.kuma 311
            for element in reversed(nodes):
312
                delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
313
                picked_up_orders[order.pickupRequestNo] = str(delivery_date)
314
                break
4506 phani.kuma 315
        except:
316
            pass
317
 
4741 phani.kuma 318
    print "Picked up Orders:"
319
    print picked_up_orders
320
    return picked_up_orders
4506 phani.kuma 321
 
322
def read_pickup_orders(orders_tobe_picked_up):
323
    picked_up_orders = {}
324
    for order in orders_tobe_picked_up:
325
        try:
4741 phani.kuma 326
            uri = ARAMEX_URL + order.airwaybill_no
327
            root = parse(urllib2.urlopen(uri)).getroot()
4506 phani.kuma 328
            nodes = root.findall('HAWBDetails/HAWBHistory/HAWBUpdate')
4910 phani.kuma 329
            for element in reversed(nodes):
330
                delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
331
                picked_up_orders[order.airwaybill_no] = str(delivery_date)
332
                break
4506 phani.kuma 333
        except:
334
            pass
335
 
336
    print "Picked up Orders:"
337
    print picked_up_orders
338
    return picked_up_orders
339
 
4910 phani.kuma 340
def read_local_connection_orders(orders_tobe_local_connected):
341
    local_connected_orders = {}
342
    for order in orders_tobe_local_connected:
343
        try:
344
            uri = ARAMEX_URL + order.airwaybill_no
345
            root = parse(urllib2.urlopen(uri)).getroot()
346
            nodes = root.findall('HAWBDetails/HAWBHistory/HAWBUpdate')
347
            for element in reversed(nodes):
348
                # For local delivery source city and destination city will be same
349
                if root.findtext('HAWBDetails/HAWBOriginEntity', '') == root.findtext('HAWBDetails/HAWBDestEntity', '') and element.findtext('Status', '') == 'SHMF' and element.findtext('Condition', '') == 'MNOB':
350
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
351
                    local_connected_orders[order.airwaybill_no] = str(delivery_date)
352
                    break
353
                # For outside delivery source city and destination city will be different, so checking for last scan at source city branch.
354
                elif root.findtext('HAWBDetails/HAWBOriginEntity', '') != root.findtext('HAWBDetails/HAWBDestEntity', '') and element.findtext('BranchID', '') == getOriginCityBranchID(root.findtext('HAWBDetails/HAWBOriginEntity', '')) and element.findtext('Status', '') == 'SHMF' and element.findtext('Condition', '') == 'MNOB':
355
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
356
                    local_connected_orders[order.airwaybill_no] = str(delivery_date)
357
                    break
358
        except:
359
            pass
360
 
361
    print "Local Connected Orders"
362
    print local_connected_orders
363
 
364
    return local_connected_orders
365
 
366
def read_reached_destination_orders(orders_tobe_reached_destination_city):
367
    destination_city_reached_orders = {}
368
    for order in orders_tobe_reached_destination_city:
369
        try:
370
            uri = ARAMEX_URL + order.airwaybill_no
371
            root = parse(urllib2.urlopen(uri)).getroot()
372
            nodes = root.findall('HAWBDetails/HAWBHistory/HAWBUpdate')
373
            for element in reversed(nodes):
374
                if root.findtext('HAWBDetails/HAWBOriginEntity', '') == root.findtext('HAWBDetails/HAWBDestEntity', '') and element.findtext('UpdateEntity', '') == root.findtext('HAWBDetails/HAWBDestEntity', ''):
375
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
376
                    destination_city_reached_orders[order.airwaybill_no] = str(delivery_date)
377
                    break
378
                elif root.findtext('HAWBDetails/HAWBOriginEntity', '') != root.findtext('HAWBDetails/HAWBDestEntity', '') and element.findtext('UpdateEntity', '') == root.findtext('HAWBDetails/HAWBDestEntity', '') and element.findtext('Status', '') == 'SHIB' and element.findtext('Condition', '') == 'SHSC':
379
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
380
                    destination_city_reached_orders[order.airwaybill_no] = str(delivery_date)
381
                    break
382
        except:
383
            pass
384
 
385
    print "Destination City Reached Orders"
386
    print destination_city_reached_orders
387
 
388
    return destination_city_reached_orders
389
 
390
def read_first_delivery_attempt_orders(orders_tobe_first_delivery_attempted):
391
    first_atdl_orders = {}
392
    for order in orders_tobe_first_delivery_attempted:
393
        try:
394
            uri = ARAMEX_URL + order.airwaybill_no
395
            root = parse(urllib2.urlopen(uri)).getroot()
396
            nodes = root.findall('HAWBDetails/HAWBHistory/HAWBUpdate')
397
            for element in reversed(nodes):
398
                if element.findtext('Status', '') == 'SHUD' and (element.findtext('Condition', '') == 'ATDL' or element.findtext('Condition', '') == 'CSCN'):
399
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
400
                    reason_for_nondelivery = element.findtext('CustomerDescription', '')
401
                    first_atdl_orders[order.airwaybill_no] = str(delivery_date) + "|" + reason_for_nondelivery
402
                    break
403
        except:
404
            pass
405
 
406
    print "FIRST DELIVERY ATTEMPT MADE Orders"
407
    print first_atdl_orders
408
 
409
    return first_atdl_orders
410
 
4506 phani.kuma 411
def read_delivery_orders(orders_tobe_delivered):
412
    delivered_orders = {}
413
    returned_orders = {}
414
    undelivered_orders = {}
415
    for order in orders_tobe_delivered:
416
        try:
4741 phani.kuma 417
            uri = ARAMEX_URL + order.airwaybill_no
418
            root = parse(urllib2.urlopen(uri)).getroot()
4506 phani.kuma 419
            nodes = root.findall('HAWBDetails/HAWBHistory/HAWBUpdate')
4910 phani.kuma 420
            node_number = len(nodes)-1
421
            for element in reversed(nodes):
422
                if element.findtext('Status', '') == 'SHDL' and (element.findtext('Condition', '') == 'DLVD' or element.findtext('Condition', '') == 'DPTT' or element.findtext('Condition', '') == 'DLPT' or element.findtext('Condition', '') == 'LTRB'):
423
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
424
                    receiver = root.findtext('HAWBDetails/DeliveredTo', '')
425
                    delivered_orders[order.airwaybill_no] = str(delivery_date) + "|" +  receiver
426
                    break
427
                elif element.findtext('Condition', '') == 'RTRN' and (element.findtext('Status', '') == 'SHRH' or element.findtext('Status', '') == 'SHUP'):
428
                    delivery_date = get_py_datetime(element.findtext('ActionDate', ''))
429
                    if node_number < len(nodes)-1:
430
                        reason_for_return = nodes[node_number+1].findtext('CustomerDescription', '')
431
                    else:
432
                        reason_for_return = element.findtext('CustomerDescription', '')
433
                    returned_orders[order.airwaybill_no] = str(delivery_date) + "|" + reason_for_return
434
                    break
435
                elif node_number == 0:
436
                    reason = root.findtext('HAWBDetails/CurrentStatus', '')
437
                    undelivered_orders[order.airwaybill_no] = reason
438
                    break
439
                node_number = node_number - 1
4506 phani.kuma 440
        except:
441
            pass
442
 
443
    print "Delivered Orders:"
444
    print delivered_orders
445
 
446
    print "Returned Orders:"
447
    print returned_orders
448
 
449
    print "Undelivered Orders"
450
    print undelivered_orders
451
 
4910 phani.kuma 452
    return delivered_orders, returned_orders, undelivered_orders
4506 phani.kuma 453
 
454
def update_picked_orders(provider_id, pickup_details):
455
    txnClient = TransactionClient().get_client()
456
    try:
4910 phani.kuma 457
        txnClient.markOrdersAsPickedUp(provider_id, pickup_details)
4506 phani.kuma 458
    except TransactionServiceException as tex:
459
        print tex.message
460
 
461
def update_picked_doas(provider_id, doa_pickup_details):
462
    txnClient = TransactionClient().get_client()
463
    try:
4910 phani.kuma 464
        txnClient.markDoasAsPickedUp(provider_id, doa_pickup_details)
4506 phani.kuma 465
    except TransactionServiceException as tex:
466
        print tex.message
467
 
4741 phani.kuma 468
def update_picked_returns(provider_id, returns_pickup_details):
469
    txnClient = TransactionClient().get_client()
470
    try:
4910 phani.kuma 471
        txnClient.markReturnOrdersAsPickedUp(provider_id, returns_pickup_details)
4741 phani.kuma 472
    except TransactionServiceException as tex:
473
        print tex.message
474
 
4506 phani.kuma 475
def update_delivered_orders(provider_id, delivered_orders):
476
    txnClient = TransactionClient().get_client()
477
    try:
478
        txnClient.markOrdersAsDelivered(provider_id, delivered_orders)
479
    except TransactionServiceException as tex:
480
        print tex.message
481
 
482
def update_returned_orders(provider_id, returned_orders):
483
    txnClient = TransactionClient().get_client()
484
    try:
4910 phani.kuma 485
        txnClient.markAsRTOrders(provider_id, returned_orders)
4506 phani.kuma 486
    except TransactionServiceException as tex:
487
        print tex.message
488
 
489
def update_reason_of_undelivered_orders(provider_id, undelivered_orders):
490
    txnClient = TransactionClient().get_client()
491
    try:
4910 phani.kuma 492
        txnClient.updateNonDeliveryReason(provider_id, undelivered_orders)
4506 phani.kuma 493
    except TransactionServiceException as tex:
494
        print tex.message
495
 
4910 phani.kuma 496
def update_local_connected_orders(provider_id, local_connected_orders):
497
    txnClient = TransactionClient().get_client()
498
    try:
499
        txnClient.markOrdersAsLocalConnected(provider_id, local_connected_orders)
500
    except TransactionServiceException as tex:
501
        print tex.message
502
 
503
def update_destination_city_reached_orders(provider_id, destination_city_reached_orders):
504
    txnClient = TransactionClient().get_client()
505
    try:
506
        txnClient.markOrdersAsDestinationCityReached(provider_id, destination_city_reached_orders)
507
    except TransactionServiceException as tex:
508
        print tex.message
509
 
510
def update_first_atdl_orders(provider_id, first_atdl_orders):
511
    txnClient = TransactionClient().get_client()
512
    try:
513
        txnClient.markOrdersAsFirstDeliveryAttempted(provider_id, first_atdl_orders)
514
    except TransactionServiceException as tex:
515
        print tex.message
516
 
4506 phani.kuma 517
def print_pickup_mismatch_report(filename, orders):
518
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
519
    writer.writerow(['Order Id', 'AWB No', 'Shipping timestamp'])
520
    for order in orders:
521
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.shipping_timestamp)])
522
 
4783 phani.kuma 523
def print_dao_return_pickup_mismatch_report(filename, orders):
524
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
525
    writer.writerow(['Order Id', 'Pickup Request No', 'Authorization timestamp'])
526
    for order in orders:
527
        writer.writerow([order.id, order.pickupRequestNo, to_py_date(order.doa_auth_timestamp)])
528
 
4910 phani.kuma 529
def print_rto_orders_report(filename, orders):
4506 phani.kuma 530
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
4910 phani.kuma 531
    writer.writerow(['Order Id', 'AWB No', 'Return date', 'Reason'])
532
    for order in orders:
533
        statusDescription = ''
534
        if order.statusDescription is not None:
535
            statusDescription = order.statusDescription.replace(","," ")
536
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.delivery_timestamp), statusDescription])
4506 phani.kuma 537
 
4581 phani.kuma 538
def print_undelivered_orders_report(filename, orders):
539
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
540
    writer.writerow(['Order Id', 'AWB No', 'Status', 'Status Description', 'Shipping timestamp', 'Pickup timestamp'])
541
    for order in orders:
4792 phani.kuma 542
        statusDescription = ''
543
        if order.statusDescription is not None:
544
            statusDescription = order.statusDescription.replace(","," ")
545
        writer.writerow([order.id, order.airwaybill_no, order.status, statusDescription, to_py_date(order.shipping_timestamp), to_py_date(order.pickup_timestamp)])
4581 phani.kuma 546
 
4910 phani.kuma 547
def create_crm_tickets_for_delivey_attempted_orders(provider):
548
    try:
549
        tickets_tobe_created = fetch_data(provider.id, [OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE])
550
        userClient = UserClient().get_client()
551
        crmServiceClient = CRMClient().get_client()
552
        for order in tickets_tobe_created:
553
            ticket_created = False
554
            searchFilter = SearchFilter()
555
            user = userClient.getUserByEmail(order.customer_email)
556
            if user is None or user.userId == -1:
557
                searchFilter.customerEmailId = order.customer_email
558
                searchFilter.customerMobileNumber = order.customer_mobilenumber
559
            else:
560
                searchFilter.customerId = user.userId
561
            tickets = crmServiceClient.getTickets(searchFilter)
562
            print tickets
563
            for old_ticket in tickets:
564
                if old_ticket.orderId == order.id:
565
                    ticket_created = True
566
                    break
567
            if not ticket_created:
568
                print "creating ticket for orderId:"+str(order.id)
569
                ticket = Ticket()
570
                activity = Activity()
571
                description = order.statusDescription + "\n\nOrder not delivered by courier due to problems at customer end."
572
                ticket.creatorId = 1
573
                ticket.category = TicketCategory.DELIVERY_PROBLEM
574
                ticket.priority = TicketPriority.HIGH
575
                ticket.status = TicketStatus.OPEN
576
                ticket.description = description
577
                ticket.orderId = order.id
578
                ticket.airwayBillNo = order.airwaybill_no
579
 
580
                activity.creatorId = 1
581
                activity.type = ActivityType.OTHER
582
                activity.description = description
583
                activity.ticketCategory = ticket.category
584
                activity.ticketDescription = ticket.description
585
                activity.ticketPriority = ticket.priority
586
                activity.ticketStatus = ticket.status
587
 
588
                if user is None or user.userId == -1:
589
                    ticket.customerEmailId = order.customer_email
590
                    ticket.customerMobileNumber = order.customer_mobilenumber
591
                    ticket.customerName = order.customer_name
592
                    activity.customerEmailId = order.customer_email
593
                    activity.customerMobileNumber = order.customer_mobilenumber
594
                    activity.customerName = order.customer_name
595
                else:
596
                    ticket.customerId = user.userId
597
                    activity.customerId = user.userId
598
 
599
                crmServiceClient.insertTicket(ticket, activity)
600
    except:
601
        print "Some issue while creating crm tickets for orders in FIRST_DELIVERY_ATTEMPT_MADE status"
602
        traceback.print_exc()
603
 
4506 phani.kuma 604
def get_py_datetime(time_string):
605
    # This should be a command line argument.
606
    # Refer http://docs.python.org/library/time.html#time.strftime to
607
    # get a complete list of format specifiers available for date time.
608
    time_format = "%m/%d/%Y %I:%M:%S %p"
609
    if time_string == '':
610
        return None
611
    mytime = time.strptime(time_string, time_format)
612
    return datetime.datetime(*mytime[:6])
613
 
4910 phani.kuma 614
def getOriginCityBranchID(originCity):
615
    branchId_OriginCitymap = {'DEL':'7933'}
616
    if originCity is None or originCity == '':
617
        return ''
618
    else:
619
        return branchId_OriginCitymap.get(originCity)
620
 
4506 phani.kuma 621
def main():
622
    parser = optparse.OptionParser()
623
    parser.add_option("-p", "--pickup", dest="pickup_report",
624
                   action="store_true",
625
                   help="Run the pickup reconciliation")
626
    parser.add_option("-d", "--delivery", dest="delivery_report",
627
                   action="store_true",
628
                   help="Run the delivery reconciliation")
4910 phani.kuma 629
    parser.add_option("-r", "--reports", dest="gen_reports",
630
                   action="store_true",
631
                   help="Generate logistic reconciliation reports")
4506 phani.kuma 632
    parser.add_option("-a", "--all", dest="all_reports",
633
                   action="store_true",
634
                   help="Run all reconciliations")
635
    parser.add_option("-P", "--provider", dest="provider",
4508 phani.kuma 636
                   default="Aramex", type="string",
4506 phani.kuma 637
                   help="The PROVIDER this report is for",
638
                   metavar="PROVIDER")
4910 phani.kuma 639
    parser.set_defaults(pickup_report=False, delivery_report=False, gen_reports=False, all_reports=False)
4506 phani.kuma 640
    (options, args) = parser.parse_args()
641
    if len(args) != 0:
642
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
643
 
644
    if options.all_reports:
645
        options.pickup_report = True
646
        options.delivery_report = True
647
 
648
    provider = get_provider_by_name(options.provider)
649
 
650
    if options.pickup_report:
651
        process_pickup_records(provider)
4815 phani.kuma 652
        process_dao_pickup_orders(provider)
653
        process_return_pickup_orders(provider)
4506 phani.kuma 654
    if options.delivery_report:
4910 phani.kuma 655
        process_local_connection_orders(provider)
656
        process_reached_destination_city_orders(provider)
657
        process_first_delivery_attempt_orders(provider)
4506 phani.kuma 658
        process_delivery_report(provider)
4910 phani.kuma 659
        create_crm_tickets_for_delivey_attempted_orders(provider)
660
    if options.gen_reports:
661
        generate_reports(provider)
4506 phani.kuma 662
 
663
if __name__ == '__main__':
664
    main()