Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
4741 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 BlueDart api to know whether they are picked up by BlueDart
7
     and changes the status to DOA_RETURN_IN_TRANSIT if it is done.
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 BlueDart api to know whether they are picked up by BlueDart
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
13
     were in SHIPPED_FROM_WH status from database and 
14
     calls BlueDart api to know whether they are picked up by BlueDart
15
     and changes the status to SHIPPED_TO_LOGST if it is done.
16
 4. Orders in SHIPPED_TO_LOGST status: get details of orders that
17
     were in SHIPPED_TO_LOGST status from database and 
18
     calls BlueDart api to know their status and changes the status accordingly.
19
 
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
22
 
23
http://www.bluedart.com/servlet/RoutingServlet?handler=tnt&action=custawbquery&loginid=DEL24119&awb=ref&format=XML&lickey=6265d61bafa6292c5ddfdb1ee335ca80&verno=1.3&scan=1&numbers={variable1} is hard coded
24
to track DOA orders and for other orders ConfigClient is called to get bluedart_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
4741 phani.kuma 44
from shop2020.config.client.ConfigClient import ConfigClient
4910 phani.kuma 45
from shop2020.clients.CRMClient import CRMClient
4741 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 *
4741 phani.kuma 51
 
4910 phani.kuma 52
try:
53
    config_client = ConfigClient()
54
    BLUEDART_URL = config_client.get_property("bluedart_update_url")
55
except ConfigException as cex:
56
    print cex.message
57
    traceback.print_exc()
58
 
4741 phani.kuma 59
from_user = 'cnc.center@shop2020.in'
60
from_pwd = '5h0p2o2o'
4924 phani.kuma 61
#to = ['cnc.center@shop2020.in', "suraj.sharma@shop2020.in", "sandeep.sachdeva@shop2020.in", "manoj.kumar@shop2020.in"]
62
to=['phani.kumar@shop2020.in']
4741 phani.kuma 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)
4741 phani.kuma 69
    except:
70
        print "Some issue while processing the orders in DOA_PICKUP_CONFIRMED status"
71
        traceback.print_exc()
72
 
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
 
83
def process_pickup_records(provider):
84
    try:
4910 phani.kuma 85
        orders_tobe_picked_up = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH])
4741 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)
4741 phani.kuma 89
    except:
90
        print "Some issue while processing the orders in SHIPPED_FROM_WH status"
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
 
4741 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])
4741 phani.kuma 126
        delivered_orders, returned_orders, undelivered_orders = read_delivery_orders(orders_tobe_delivered)
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)
4741 phani.kuma 133
    except:
4910 phani.kuma 134
        print "Some issue while processing the orders for delivery status"
4741 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
 
4741 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):
4741 phani.kuma 296
    txnClient = TransactionClient().get_client()
297
    try:
4910 phani.kuma 298
        doas_tobe_picked_up = txnClient.getOrdersForProviderForStatus(provider_id, order_status_list)
4741 phani.kuma 299
        return doas_tobe_picked_up
300
    except TransactionServiceException as tex:
301
        print tex.message
302
 
303
def read_dao_return_pickup_orders(orders_tobe_picked_up):
304
    #uri=http://www.bluedart.com/servlet/RoutingServlet?handler=tnt&action=custawbquery&loginid=DEL24119&awb=ref&format=XML&lickey=6265d61bafa6292c5ddfdb1ee335ca80&verno=1.3&scan=1&numbers=82390
305
    picked_up_orders = {}
306
    for order in orders_tobe_picked_up:
307
        try:
308
            uri = 'http://www.bluedart.com/servlet/RoutingServlet?handler=tnt&action=custawbquery&loginid=DEL24119&awb=ref&format=XML&lickey=6265d61bafa6292c5ddfdb1ee335ca80&verno=1.3&scan=1&numbers=' + str(order.pickupRequestNo)
309
            root = parse(urllib2.urlopen(uri)).getroot()
310
            children = root.getchildren()
4910 phani.kuma 311
            for child in children:
312
                nodes = child.findall('Scans/ScanDetail')
313
                for element in reversed(nodes):
314
                    datestring = element.findtext('ScanDate', '')
315
                    timestring = element.findtext('ScanTime', '')
316
                    delivery_date = get_py_datetime(datestring, timestring)
317
                    picked_up_orders[order.pickupRequestNo] = str(delivery_date)
318
                    break
4741 phani.kuma 319
        except:
320
            pass
321
 
322
    print "Picked up Orders:"
323
    print picked_up_orders
324
    return picked_up_orders
325
 
326
def read_pickup_orders(orders_tobe_picked_up):
327
    picked_up_orders = {}
328
    for order in orders_tobe_picked_up:
329
        try:
330
            uri = BLUEDART_URL + order.airwaybill_no
331
            root = parse(urllib2.urlopen(uri)).getroot()
332
            children = root.getchildren()
4910 phani.kuma 333
            for child in children:
334
                nodes = child.findall('Scans/ScanDetail')
335
                for element in reversed(nodes):
336
                    datestring = element.findtext('ScanDate', '')
337
                    timestring = element.findtext('ScanTime', '')
338
                    delivery_date = get_py_datetime(datestring, timestring)
339
                    picked_up_orders[order.airwaybill_no] = str(delivery_date)
340
                    break
4741 phani.kuma 341
        except:
342
            pass
343
 
344
    print "Picked up Orders:"
345
    print picked_up_orders
346
    return picked_up_orders
347
 
4910 phani.kuma 348
def read_local_connection_orders(orders_tobe_local_connected):
349
    local_connected_orders = {}
350
    for order in orders_tobe_local_connected:
351
        try:
352
            uri = BLUEDART_URL + order.airwaybill_no
353
            root = parse(urllib2.urlopen(uri)).getroot()
354
            children = root.getchildren()
355
            for child in children:
356
                nodes = child.findall('Scans/ScanDetail')
357
                for element in reversed(nodes):
358
                    if (getTrimedString(element.findtext('ScannedLocation', '')) == getTrimedString('RAMA ROAD HUB') or getTrimedString(element.findtext('ScannedLocation', '')) == getTrimedString('DELHI HUB')) and element.findtext('ScanType', '') == 'UD' and getTrimedString(element.findtext('Scan', '')) == getTrimedString('SHIPMENT OUTSCANNED TO NETWORK'):
359
                        datestring = element.findtext('ScanDate', '')
360
                        timestring = element.findtext('ScanTime', '')
361
                        delivery_date = get_py_datetime(datestring, timestring)
362
                        local_connected_orders[order.airwaybill_no] = str(delivery_date)
363
                        break
364
        except:
365
            pass
366
 
367
    print "Local Connected Orders"
368
    print local_connected_orders
369
 
370
    return local_connected_orders
371
 
372
def read_reached_destination_orders(orders_tobe_reached_destination_city):
373
    destination_city_reached_orders = {}
374
    for order in orders_tobe_reached_destination_city:
375
        try:
376
            uri = BLUEDART_URL + order.airwaybill_no
377
            root = parse(urllib2.urlopen(uri)).getroot()
378
            children = root.getchildren()
379
            child_number = 0
380
            for child in children:
381
                child_number = child_number + 1
382
                nodes = child.findall('Scans/ScanDetail')
383
                orderstatus = None
384
                for element in nodes:
385
                    if element.findtext('ScanType', '') == 'UD' and (getTrimedString(element.findtext('Scan', '')) == getTrimedString('Shipment Inscan') or getTrimedString(element.findtext('Scan', '')) == getTrimedString('Shipment-Autoscan')):
386
                        datestring = element.findtext('ScanDate', '')
387
                        timestring = element.findtext('ScanTime', '')
388
                        delivery_date = get_py_datetime(datestring, timestring)
389
                        destination_city_reached_orders[order.airwaybill_no] = str(delivery_date)
390
                        orderstatus = 'UD'
391
                        break
392
                    elif element.findtext('ScanType', '') == 'RD':
393
                        if child_number < len(children):
394
                            orderstatus = 'RD'
395
                            break
396
                if orderstatus != 'RD':
397
                    break
398
        except:
399
            pass
400
 
401
    print "Destination City Reached Orders"
402
    print destination_city_reached_orders
403
 
404
    return destination_city_reached_orders
405
 
406
def read_first_delivery_attempt_orders(orders_tobe_first_delivery_attempted):
407
    first_atdl_orders = {}
408
    for order in orders_tobe_first_delivery_attempted:
409
        try:
410
            uri = BLUEDART_URL + order.airwaybill_no
411
            root = parse(urllib2.urlopen(uri)).getroot()
412
            children = root.getchildren()
413
            child_number = 0
414
            for child in children:
415
                child_number = child_number + 1
416
                nodes = child.findall('Scans/ScanDetail')
417
                orderstatus = None
418
                node_number = len(nodes)-1
419
                for element in reversed(nodes):
420
                    if element.findtext('ScanType', '') == 'UD' and getTrimedString(element.findtext('Scan', '')) == getTrimedString('Shipment Outscan'):
421
                        if node_number != 0 and nodes[node_number-1].findtext('ScanType', '') == 'UD':
422
                            element = nodes[node_number-1]
423
                            datestring = element.findtext('ScanDate', '')
424
                            timestring = element.findtext('ScanTime', '')
425
                            delivery_date = get_py_datetime(datestring, timestring)
426
                            reason_for_nondelivery = element.findtext('Scan', '')
427
                            first_atdl_orders[order.airwaybill_no] = str(delivery_date) + "|" + reason_for_nondelivery
428
                        orderstatus = 'UD'
429
                        break
430
                    elif element.findtext('ScanType', '') == 'RD':
431
                        if child_number < len(children):
432
                            orderstatus = 'RD'
433
                            break
434
                    node_number = node_number - 1
435
                if orderstatus != 'RD':
436
                    break
437
        except:
438
            pass
439
 
440
    print "FIRST DELIVERY ATTEMPT MADE Orders"
441
    print first_atdl_orders
442
 
443
    return first_atdl_orders
444
 
4741 phani.kuma 445
def read_delivery_orders(orders_tobe_delivered):
446
    delivered_orders = {}
447
    returned_orders = {}
448
    undelivered_orders = {}
449
    for order in orders_tobe_delivered:
450
        try:
451
            uri = BLUEDART_URL + order.airwaybill_no
452
            root = parse(urllib2.urlopen(uri)).getroot()
453
            children = root.getchildren()
454
            child_number = 0
455
            for child in children:
456
                child_number = child_number + 1
457
                nodes = child.findall('Scans/ScanDetail')
458
                orderstatus = None
459
                if len(nodes):
4910 phani.kuma 460
                    node_number = len(nodes)-1
461
                    for element in reversed(nodes):
4741 phani.kuma 462
                        if element.findtext('ScanType', '') == 'DL':
463
                            orderstatus = 'DL'
464
                            datestring = element.findtext('ScanDate', '')
465
                            timestring = element.findtext('ScanTime', '')
466
                            delivery_date = get_py_datetime(datestring, timestring)
467
                            receiver = child.findtext('ReceivedBy', '')
468
                            delivered_orders[order.airwaybill_no] = str(delivery_date) + "|" +  receiver
469
                            break
470
                        elif element.findtext('ScanType', '') == 'RT':
471
                            orderstatus = 'RT'
472
                            datestring = element.findtext('ScanDate', '')
473
                            timestring = element.findtext('ScanTime', '')
474
                            delivery_date = get_py_datetime(datestring, timestring)
4910 phani.kuma 475
                            if node_number < len(nodes)-1:
476
                                reason_for_return = nodes[node_number+1].findtext('Scan', '')
4741 phani.kuma 477
                            else:
478
                                reason_for_return = element.findtext('Scan', '')
479
                            returned_orders[order.airwaybill_no] = str(delivery_date) + "|" + reason_for_return
480
                            break
481
                        elif element.findtext('ScanType', '') == 'RD':
4910 phani.kuma 482
                            if child_number < len(children):
483
                                orderstatus = 'RD'
484
                                break
485
                        elif node_number == 0:
4920 phani.kuma 486
                            if child.findtext('StatusType', '') == 'RT':
487
                                orderstatus = 'RT'
488
                                datestring = child.findtext('ScanDate', '')
489
                                timestring = child.findtext('ScanTime', '')
490
                                delivery_date = get_py_datetime(datestring, timestring)
491
                                reason_for_return = child.findtext('Status', '')
492
                                returned_orders[order.airwaybill_no] = str(delivery_date) + "|" + reason_for_return
493
                                break
494
                            elif child.findtext('StatusType', '') == 'DL':
495
                                orderstatus = 'DL'
496
                                datestring = child.findtext('ScanDate', '')
497
                                timestring = child.findtext('ScanTime', '')
498
                                delivery_date = get_py_datetime(datestring, timestring)
499
                                receiver = child.findtext('ReceivedBy', '')
500
                                delivered_orders[order.airwaybill_no] = str(delivery_date) + "|" +  receiver
501
                                break
502
                            else:
503
                                orderstatus = 'UD'
504
                                reason = child.findtext('Status', '')
505
                                undelivered_orders[order.airwaybill_no] = reason
506
                                break
4910 phani.kuma 507
                        node_number = node_number - 1
4741 phani.kuma 508
                else:
509
                    if child_number > 1:
510
                        reason = children[child_number-1].findtext('Status', '')
511
                        undelivered_orders[order.airwaybill_no] = reason
512
                if orderstatus != 'RD':
513
                    break
514
        except:
515
            pass
516
 
517
    print "Delivered Orders:"
518
    print delivered_orders
519
 
520
    print "Returned Orders:"
521
    print returned_orders
522
 
523
    print "Undelivered Orders"
524
    print undelivered_orders
525
 
526
    return delivered_orders, returned_orders, undelivered_orders
527
 
528
def update_picked_orders(provider_id, pickup_details):
529
    txnClient = TransactionClient().get_client()
530
    try:
4910 phani.kuma 531
        txnClient.markOrdersAsPickedUp(provider_id, pickup_details)
4741 phani.kuma 532
    except TransactionServiceException as tex:
533
        print tex.message
534
 
535
def update_picked_doas(provider_id, doa_pickup_details):
536
    txnClient = TransactionClient().get_client()
537
    try:
4910 phani.kuma 538
        txnClient.markDoasAsPickedUp(provider_id, doa_pickup_details)
4741 phani.kuma 539
    except TransactionServiceException as tex:
540
        print tex.message
541
 
542
def update_picked_returns(provider_id, returns_pickup_details):
543
    txnClient = TransactionClient().get_client()
544
    try:
4910 phani.kuma 545
        txnClient.markReturnOrdersAsPickedUp(provider_id, returns_pickup_details)
4741 phani.kuma 546
    except TransactionServiceException as tex:
547
        print tex.message
548
 
549
def update_delivered_orders(provider_id, delivered_orders):
550
    txnClient = TransactionClient().get_client()
551
    try:
552
        txnClient.markOrdersAsDelivered(provider_id, delivered_orders)
553
    except TransactionServiceException as tex:
554
        print tex.message
555
 
556
def update_returned_orders(provider_id, returned_orders):
557
    txnClient = TransactionClient().get_client()
558
    try:
4910 phani.kuma 559
        txnClient.markAsRTOrders(provider_id, returned_orders)
4741 phani.kuma 560
    except TransactionServiceException as tex:
561
        print tex.message
562
 
563
def update_reason_of_undelivered_orders(provider_id, undelivered_orders):
564
    txnClient = TransactionClient().get_client()
565
    try:
4910 phani.kuma 566
        txnClient.updateNonDeliveryReason(provider_id, undelivered_orders)
4741 phani.kuma 567
    except TransactionServiceException as tex:
568
        print tex.message
569
 
4910 phani.kuma 570
def update_local_connected_orders(provider_id, local_connected_orders):
571
    txnClient = TransactionClient().get_client()
572
    try:
573
        txnClient.markOrdersAsLocalConnected(provider_id, local_connected_orders)
574
    except TransactionServiceException as tex:
575
        print tex.message
576
 
577
def update_destination_city_reached_orders(provider_id, destination_city_reached_orders):
578
    txnClient = TransactionClient().get_client()
579
    try:
580
        txnClient.markOrdersAsDestinationCityReached(provider_id, destination_city_reached_orders)
581
    except TransactionServiceException as tex:
582
        print tex.message
583
 
584
def update_first_atdl_orders(provider_id, first_atdl_orders):
585
    txnClient = TransactionClient().get_client()
586
    try:
587
        txnClient.markOrdersAsFirstDeliveryAttempted(provider_id, first_atdl_orders)
588
    except TransactionServiceException as tex:
589
        print tex.message
590
 
4741 phani.kuma 591
def print_pickup_mismatch_report(filename, orders):
592
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
593
    writer.writerow(['Order Id', 'AWB No', 'Shipping timestamp'])
594
    for order in orders:
595
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.shipping_timestamp)])
596
 
4783 phani.kuma 597
def print_dao_return_pickup_mismatch_report(filename, orders):
598
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
599
    writer.writerow(['Order Id', 'Pickup Request No', 'Authorization timestamp'])
600
    for order in orders:
601
        writer.writerow([order.id, order.pickupRequestNo, to_py_date(order.doa_auth_timestamp)])
602
 
4910 phani.kuma 603
def print_rto_orders_report(filename, orders):
4741 phani.kuma 604
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
4910 phani.kuma 605
    writer.writerow(['Order Id', 'AWB No', 'Return date', 'Reason'])
606
    for order in orders:
607
        statusDescription = ''
608
        if order.statusDescription is not None:
609
            statusDescription = order.statusDescription.replace(","," ")
610
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.delivery_timestamp), statusDescription])
4741 phani.kuma 611
 
612
def print_undelivered_orders_report(filename, orders):
613
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
4924 phani.kuma 614
    writer.writerow(['Order Id', 'AWB No', 'Status', 'Status Description', 'Shipping timestamp', 'Pickup timestamp', 'Promised delivery date', 'Expected delivery date'])
4741 phani.kuma 615
    for order in orders:
4792 phani.kuma 616
        statusDescription = ''
617
        if order.statusDescription is not None:
618
            statusDescription = order.statusDescription.replace(","," ")
4924 phani.kuma 619
        writer.writerow([order.id, order.airwaybill_no, order.status, statusDescription, to_py_date(order.shipping_timestamp), to_py_date(order.pickup_timestamp), to_py_date(order.promised_delivery_time), to_py_date(order.expected_delivery_time)])
4741 phani.kuma 620
 
4910 phani.kuma 621
def create_crm_tickets_for_delivey_attempted_orders(provider):
622
    try:
623
        tickets_tobe_created = fetch_data(provider.id, [OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE])
624
        userClient = UserClient().get_client()
625
        crmServiceClient = CRMClient().get_client()
626
        for order in tickets_tobe_created:
627
            ticket_created = False
628
            searchFilter = SearchFilter()
629
            user = userClient.getUserByEmail(order.customer_email)
630
            if user is None or user.userId == -1:
631
                searchFilter.customerEmailId = order.customer_email
632
                searchFilter.customerMobileNumber = order.customer_mobilenumber
633
            else:
634
                searchFilter.customerId = user.userId
635
            tickets = crmServiceClient.getTickets(searchFilter)
636
            print tickets
637
            for old_ticket in tickets:
638
                if old_ticket.orderId == order.id:
639
                    ticket_created = True
640
                    break
641
            if not ticket_created:
642
                print "creating ticket for orderId:"+str(order.id)
643
                ticket = Ticket()
644
                activity = Activity()
645
                description = order.statusDescription + "\n\nOrder not delivered by courier due to problems at customer end."
646
                ticket.creatorId = 1
647
                ticket.category = TicketCategory.DELIVERY_PROBLEM
648
                ticket.priority = TicketPriority.HIGH
649
                ticket.status = TicketStatus.OPEN
650
                ticket.description = description
651
                ticket.orderId = order.id
652
                ticket.airwayBillNo = order.airwaybill_no
653
 
654
                activity.creatorId = 1
655
                activity.type = ActivityType.OTHER
656
                activity.description = description
657
                activity.ticketCategory = ticket.category
658
                activity.ticketDescription = ticket.description
659
                activity.ticketPriority = ticket.priority
660
                activity.ticketStatus = ticket.status
661
 
662
                if user is None or user.userId == -1:
663
                    ticket.customerEmailId = order.customer_email
664
                    ticket.customerMobileNumber = order.customer_mobilenumber
665
                    ticket.customerName = order.customer_name
666
                    activity.customerEmailId = order.customer_email
667
                    activity.customerMobileNumber = order.customer_mobilenumber
668
                    activity.customerName = order.customer_name
669
                else:
670
                    ticket.customerId = user.userId
671
                    activity.customerId = user.userId
672
 
673
                crmServiceClient.insertTicket(ticket, activity)
674
    except:
675
        print "Some issue while creating crm tickets for orders in FIRST_DELIVERY_ATTEMPT_MADE status"
676
        traceback.print_exc()
677
 
4741 phani.kuma 678
def get_py_datetime(datestring, timestring):
679
    # This should be a command line argument.
680
    # Refer http://docs.python.org/library/time.html#time.strftime to
681
    # get a complete list of format specifiers available for date time.
682
    if datestring == '':
683
        return None
4920 phani.kuma 684
    if datestring.find('-') == -1:
685
        time_format = "%d %B %Y %H:%M:%S"
686
    else:
687
        time_format = "%d-%b-%Y %H:%M:%S"
4741 phani.kuma 688
    if timestring == '':
689
        timestring = '00:00:00'
690
    time_array = timestring.split(':')
691
    if len(time_array) < 3:
692
        timestring = timestring + ':00'
693
    time_string = datestring + ' ' + timestring
694
    mytime = time.strptime(time_string, time_format)
695
    return datetime.datetime(*mytime[:6])
696
 
4910 phani.kuma 697
def getTrimedString(text):
698
    if text is None or text == '':
699
        return ''
700
    else:
701
        text = text.strip().lower()
702
        text_list = list(text)
703
        new_text = ''
704
        for letter in text_list:
705
            if letter.isalnum():
706
                new_text = new_text + str(letter)
707
        return new_text
708
 
4741 phani.kuma 709
def main():
710
    parser = optparse.OptionParser()
711
    parser.add_option("-p", "--pickup", dest="pickup_report",
712
                   action="store_true",
713
                   help="Run the pickup reconciliation")
714
    parser.add_option("-d", "--delivery", dest="delivery_report",
715
                   action="store_true",
716
                   help="Run the delivery reconciliation")
4910 phani.kuma 717
    parser.add_option("-r", "--reports", dest="gen_reports",
718
                   action="store_true",
719
                   help="Generate logistic reconciliation reports")
4741 phani.kuma 720
    parser.add_option("-a", "--all", dest="all_reports",
721
                   action="store_true",
722
                   help="Run all reconciliations")
723
    parser.add_option("-P", "--provider", dest="provider",
724
                   default="BlueDart", type="string",
725
                   help="The PROVIDER this report is for",
726
                   metavar="PROVIDER")
4910 phani.kuma 727
    parser.set_defaults(pickup_report=False, delivery_report=False, gen_reports=False, all_reports=False)
4741 phani.kuma 728
    (options, args) = parser.parse_args()
729
    if len(args) != 0:
730
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
731
 
732
    if options.all_reports:
733
        options.pickup_report = True
734
        options.delivery_report = True
735
 
736
    provider = get_provider_by_name(options.provider)
737
 
738
    if options.pickup_report:
739
        process_pickup_records(provider)
4815 phani.kuma 740
        process_dao_pickup_orders(provider)
741
        process_return_pickup_orders(provider)
4741 phani.kuma 742
    if options.delivery_report:
4910 phani.kuma 743
        process_local_connection_orders(provider)
744
        process_reached_destination_city_orders(provider)
745
        process_first_delivery_attempt_orders(provider)
4741 phani.kuma 746
        process_delivery_report(provider)
4910 phani.kuma 747
        create_crm_tickets_for_delivey_attempted_orders(provider)
748
    if options.gen_reports:
749
        generate_reports(provider)
4741 phani.kuma 750
 
751
if __name__ == '__main__':
752
    main()