Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
5262 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 Delhivery api to know whether they are picked up by Delhivery
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 Delhivery api to know whether they are picked up by Delhivery
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 Delhivery api to know whether they are picked up by Delhivery
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 Delhivery 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
to track DOA orders and for other orders ConfigClient is called to get Delhivery_update_url
24
 
25
@author: Phani Kumar
26
'''
6561 amit.gupta 27
from shop2020.clients.CRMClient import CRMClient
28
from shop2020.clients.LogisticsClient import LogisticsClient
29
from shop2020.clients.TransactionClient import TransactionClient
30
from shop2020.config.client.ConfigClient import ConfigClient
13085 amit.gupta 31
from shop2020.model.v1.order.script.LogisticUtils import \
32
    create_crm_tickets_for_delivey_attempted_orders
6561 amit.gupta 33
from shop2020.thriftpy.config.ttypes import ConfigException
13085 amit.gupta 34
from shop2020.thriftpy.crm.ttypes import SearchFilter, TicketCategory, \
35
    TicketPriority, TicketStatus, Activity, ActivityType
6561 amit.gupta 36
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
37
    OrderStatus
38
from shop2020.utils.EmailAttachmentSender import get_attachment_part, mail
39
from shop2020.utils.Utils import to_py_date
40
from xml.etree.ElementTree import parse
41
import csv
5262 phani.kuma 42
import datetime
43
import optparse
44
import sys
6561 amit.gupta 45
import time
5262 phani.kuma 46
import traceback
47
import urllib2
48
 
13085 amit.gupta 49
 
5262 phani.kuma 50
if __name__ == '__main__' and __package__ is None:
51
    import os
52
    sys.path.insert(0, os.getcwd())
53
 
54
 
55
try:
56
    config_client = ConfigClient()
57
    Delhivery_URL = config_client.get_property("Delhivery_update_url")
58
except ConfigException as cex:
59
    print cex.message
60
    traceback.print_exc()
61
 
8292 manish.sha 62
defaultUndeliveredAsssigneeId = 47
13085 amit.gupta 63
dtrUndeliveredAsssigneeId = 33
5262 phani.kuma 64
from_user = 'cnc.center@shop2020.in'
65
from_pwd = '5h0p2o2o'
9173 manish.sha 66
to = ["amit.sirohi@shop2020.in", "sandeep.sachdeva@shop2020.in", "sunil.kumar@shop2020.in"]
5262 phani.kuma 67
 
68
def process_dao_pickup_orders(provider):
69
    try:
70
        doas_tobe_picked_up = fetch_data(provider.id, [OrderStatus.DOA_PICKUP_CONFIRMED])
71
        doa_pickup_details = read_dao_return_pickup_orders(doas_tobe_picked_up)
72
        if doa_pickup_details:
73
            update_picked_doas(provider.id, doa_pickup_details)
74
    except:
75
        print "Some issue while processing the orders in DOA_PICKUP_CONFIRMED status"
76
        traceback.print_exc()
77
 
78
def process_return_pickup_orders(provider):
79
    try:
80
        returns_tobe_picked_up = fetch_data(provider.id, [OrderStatus.RET_PICKUP_CONFIRMED])
81
        returns_pickup_details = read_dao_return_pickup_orders(returns_tobe_picked_up)
82
        if returns_pickup_details:
83
            update_picked_returns(provider.id, returns_pickup_details)
84
    except:
85
        print "Some issue while processing the orders in RET_PICKUP_CONFIRMED status"
86
        traceback.print_exc()
87
 
88
def process_pickup_records(provider):
89
    try:
90
        orders_tobe_picked_up = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH])
91
        pickup_details = read_pickup_orders(orders_tobe_picked_up)
92
        if pickup_details:
93
            update_picked_orders(provider.id, pickup_details)
94
    except:
95
        print "Some issue while processing the orders in SHIPPED_FROM_WH status"
96
        traceback.print_exc()
97
 
98
def process_local_connection_orders(provider):
99
    try:
100
        orders_tobe_local_connected = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST])
101
        local_connected_orders = read_local_connection_orders(orders_tobe_local_connected)
102
        if local_connected_orders:
103
            update_local_connected_orders(provider.id, local_connected_orders)
104
    except:
105
        print "Some issue while processing the orders for local connection status"
106
        traceback.print_exc()
107
 
108
def process_reached_destination_city_orders(provider):
109
    try:
110
        orders_tobe_reached_destination_city = fetch_data(provider.id, [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY])
111
        destination_city_reached_orders = read_reached_destination_orders(orders_tobe_reached_destination_city)
112
        if destination_city_reached_orders:
113
            update_destination_city_reached_orders(provider.id, destination_city_reached_orders)
114
    except:
115
        print "Some issue while processing the orders for Reached Destination City status"
116
        traceback.print_exc()
117
 
118
def process_first_delivery_attempt_orders(provider):
119
    try:
120
        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])
121
        first_atdl_orders = read_first_delivery_attempt_orders(orders_tobe_first_delivery_attempted)
122
        if first_atdl_orders:
123
            update_first_atdl_orders(provider.id, first_atdl_orders)
124
    except:
125
        print "Some issue while processing the orders for First delivery attempt status"
126
        traceback.print_exc()
127
 
128
def process_delivery_report(provider):
129
    try:
130
        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])
131
        delivered_orders, returned_orders, undelivered_orders = read_delivery_orders(orders_tobe_delivered)
132
        if delivered_orders:
133
            update_delivered_orders(provider.id, delivered_orders)
134
        if returned_orders:
135
            update_returned_orders(provider.id, returned_orders)
136
        if undelivered_orders:
137
            update_reason_of_undelivered_orders(provider.id, undelivered_orders)
138
    except:
139
        print "Some issue while processing the orders for delivery status"
140
        traceback.print_exc()
141
 
142
def generate_reports(provider):
143
    get_doas_not_picked_up(provider)
144
    get_returns_not_picked_up(provider)
145
    get_orders_not_picked_up(provider)
146
    get_orders_pending_local_connection(provider)
147
    get_returned_orders(provider)
148
    get_orders_not_delivered(provider)
149
 
150
def get_doas_not_picked_up(provider):
151
    txnClient = TransactionClient().get_client()
152
    try:
153
        doas_not_picked_up = txnClient.getDoasNotPickedUp(provider.id)
154
    except TransactionServiceException as tex:
155
        print tex.message
156
 
157
    try:
158
        if doas_not_picked_up:
159
            print "DOAs not Picked up:"
160
            print doas_not_picked_up
161
            mismatch_file = "/tmp/Delhivery_DoaPickupMismatch.csv"
162
            print "Some of our DOA orders were not picked up. Printing report to:" + mismatch_file
163
            print_dao_return_pickup_mismatch_report(mismatch_file, doas_not_picked_up)
164
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
165
            mail(from_user, from_pwd, to,\
166
                 "DOA Pickup Mismatch for " + provider.name,\
167
                 "This is a system generated email.Please don't reply to it.",\
168
                 pickup_mismatch_part)
169
    except Exception:
170
        print "Some issue sending the DOA mismatch report"
171
        traceback.print_exc()
172
 
173
def get_returns_not_picked_up(provider):
174
    txnClient = TransactionClient().get_client()
175
    try:
176
        returns_not_picked_up = txnClient.getReturnOrdersNotPickedUp(provider.id)
177
    except TransactionServiceException as tex:
178
        print tex.message
179
 
180
    try:
181
        if returns_not_picked_up:
182
            print "Return Orders not Picked up:"
183
            print returns_not_picked_up
184
            mismatch_file = "/tmp/Delhivery_ReturnsPickupMismatch.csv"
185
            print "Some of our Return orders were not picked up. Printing report to:" + mismatch_file
186
            print_dao_return_pickup_mismatch_report(mismatch_file, returns_not_picked_up)
187
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
188
            mail(from_user, from_pwd, to,\
189
                 "Return orders Pickup Mismatch for " + provider.name,\
190
                 "This is a system generated email.Please don't reply to it.",\
191
                 pickup_mismatch_part)
192
    except Exception:
193
        print "Some issue sending the Return orders mismatch report"
194
        traceback.print_exc()
195
 
196
def get_orders_not_picked_up(provider):
197
    txnClient = TransactionClient().get_client()
198
    try:
199
        orders_not_picked_up = txnClient.getOrdersNotPickedUp(provider.id)
200
    except TransactionServiceException as tex:
201
        print tex.message
202
 
203
    try:
204
        if orders_not_picked_up:
205
            print "Orders not Picked up:"
206
            print orders_not_picked_up
207
            mismatch_file = "/tmp/Delhivery_PickupMismatch.csv"
208
            print "Some of our orders were not picked up. Printing report to:" + mismatch_file
209
            print_pickup_mismatch_report(mismatch_file, orders_not_picked_up)
210
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
211
            mail(from_user, from_pwd, to,\
212
                 "Order Pickup Mismatch for " + provider.name,\
213
                 "This is a system generated email.Please don't reply to it.",\
214
                 pickup_mismatch_part)
215
    except Exception:
216
        print "Some issue sending the pickup mismatch report"
217
        traceback.print_exc()
218
 
219
def get_orders_pending_local_connection(provider):
220
    txnClient = TransactionClient().get_client()
221
    try:
222
        orders_pending_local_connection = txnClient.getOrdersNotLocalConnected(provider.id)
223
    except TransactionServiceException as tex:
224
        print tex.message
225
 
226
    try:
227
        if orders_pending_local_connection:
228
            print "Local Connection Pending Orders:"
229
            print orders_pending_local_connection
230
            mismatch_file = "/tmp/Delhivery_LocalConnectionPendingOrders.csv"
231
            print "Some of our Orders were not Shipped to Destination yet. Printing report to:" + mismatch_file
232
            print_undelivered_orders_report(mismatch_file, orders_pending_local_connection)
233
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
234
            mail(from_user, from_pwd, to,\
235
                 "Orders that are not Shipped to Destination yet for " + provider.name,\
236
                 "This is a system generated email.Please don't reply to it.",\
237
                 pickup_mismatch_part)
238
    except Exception:
239
        print "Some issue updating and sending the Local Connection orders report"
240
        traceback.print_exc()
241
 
242
def get_returned_orders(provider):
243
    txnClient = TransactionClient().get_client()
244
    try:
245
        returned_orders = txnClient.getRTOrders(provider.id)
246
    except TransactionServiceException as tex:
247
        print tex.message
248
 
249
    try:
250
        if returned_orders:
251
            print "Returned Orders:"
252
            print returned_orders
253
            returned_orders_file = "/tmp/Delhivery_ReturnedOrders.csv"
254
            print "Some of our Orders were returned by logistics provider. Printing report to:" + returned_orders_file
255
            print_rto_orders_report(returned_orders_file, returned_orders)
256
            returned_orders_report = [get_attachment_part(returned_orders_file)]
257
            mail(from_user, from_pwd, to,\
258
                 "Returned Orders Report for " + provider.name,\
259
                 "This is a system generated email.Please don't reply to it.",\
260
                 returned_orders_report)
261
    except:
262
        print "Some issue sending the returned orders report"
263
        traceback.print_exc()
264
 
265
def get_orders_not_delivered(provider):
266
    txnClient = TransactionClient().get_client()
267
    try:
268
        orders_not_delivered = txnClient.getNonDeliveredOrdersbyCourier(provider.id)
269
    except TransactionServiceException as tex:
270
        print tex.message
271
 
272
    try:
273
        if orders_not_delivered:
274
            print "Undelivered Orders:"
275
            print orders_not_delivered
276
            mismatch_file = "/tmp/Delhivery_UndeliveredOrders.csv"
277
            print "Some of our Orders were not delivered. Printing report to:" + mismatch_file
278
            print_undelivered_orders_report(mismatch_file, orders_not_delivered)
279
            pickup_mismatch_part = [get_attachment_part(mismatch_file)]
280
            mail(from_user, from_pwd, to,\
281
                 "Orders that are undelivered but picked up or shipped four days ago for " + provider.name,\
282
                 "This is a system generated email.Please don't reply to it.",\
283
                 pickup_mismatch_part)
284
    except Exception:
285
        print "Some issue updating and sending the undelivered orders report"
286
        traceback.print_exc()
287
 
288
def get_provider_by_name(provider_name):
289
    logistics_client = LogisticsClient().get_client()
290
    provider = None
291
    providers = logistics_client.getAllProviders()
292
    for p in providers:
293
        if p.name == provider_name:
294
            provider=p
295
            break
296
    if provider == None:
297
        sys.exit("Can't continue execution: No such provider")
298
    return provider
299
 
300
def fetch_data(provider_id, order_status_list):
301
    txnClient = TransactionClient().get_client()
302
    try:
303
        doas_tobe_picked_up = txnClient.getOrdersForProviderForStatus(provider_id, order_status_list)
304
        return doas_tobe_picked_up
305
    except TransactionServiceException as tex:
306
        print tex.message
307
 
308
def read_dao_return_pickup_orders(orders_tobe_picked_up):
309
    picked_up_orders = {}
5325 phani.kuma 310
    list_of_order = []
5262 phani.kuma 311
    for order in orders_tobe_picked_up:
5325 phani.kuma 312
        list_of_order.append(str(order.pickupRequestNo))
12961 manish.sha 313
 
314
    parentAwbList = [list_of_order[x:x+10] for x in xrange(0, len(list_of_order), 10)]
5325 phani.kuma 315
 
12961 manish.sha 316
    for awbList in parentAwbList:     
317
        try:
318
            uri = Delhivery_URL + 'ref_nos=' + ','.join(awbList)
319
            root = parse(urllib2.urlopen(uri)).getroot()
320
            shipments = root.findall('Shipment')
321
            for shipment in shipments:
322
                nodes = shipment.findall('Scans/ScanDetail')
323
                for element in nodes:
324
                    delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
325
                    picked_up_orders[shipment.findtext('ReferenceNo', '')] = str(delivery_date)
326
                    break
327
        except:
328
            pass
5262 phani.kuma 329
 
330
    print "Picked up Orders:"
331
    print picked_up_orders
332
    return picked_up_orders
333
 
334
def read_pickup_orders(orders_tobe_picked_up):
335
    picked_up_orders = {}
5325 phani.kuma 336
    list_of_order = []
5262 phani.kuma 337
    for order in orders_tobe_picked_up:
5325 phani.kuma 338
        list_of_order.append(str(order.airwaybill_no))
12961 manish.sha 339
 
340
    parentAwbList = [list_of_order[x:x+10] for x in xrange(0, len(list_of_order), 10)]
5325 phani.kuma 341
 
12961 manish.sha 342
    for awbList in parentAwbList:    
343
        try:
344
            uri = Delhivery_URL + 'waybill=' + ','.join(awbList)
345
            root = parse(urllib2.urlopen(uri)).getroot()
346
            shipments = root.findall('Shipment')
347
            for shipment in shipments:
348
                nodes = shipment.findall('Scans/ScanDetail')
349
                for element in nodes:
350
                    delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
351
                    picked_up_orders[shipment.findtext('AWB', '')] = str(delivery_date)
352
                    break
353
        except:
354
            pass
5262 phani.kuma 355
 
356
    print "Picked up Orders:"
357
    print picked_up_orders
358
    return picked_up_orders
359
 
360
def read_local_connection_orders(orders_tobe_local_connected):
361
    local_connected_orders = {}
5325 phani.kuma 362
    list_of_order = []
5262 phani.kuma 363
    for order in orders_tobe_local_connected:
5325 phani.kuma 364
        list_of_order.append(str(order.airwaybill_no))
365
 
12961 manish.sha 366
    parentAwbList = [list_of_order[x:x+10] for x in xrange(0, len(list_of_order), 10)]
5262 phani.kuma 367
 
12961 manish.sha 368
    for awbList in parentAwbList:    
369
        try:
370
            uri = Delhivery_URL + 'waybill=' + ','.join(awbList)
371
            root = parse(urllib2.urlopen(uri)).getroot()
372
            shipments = root.findall('Shipment')
373
            for shipment in shipments:
374
                nodes = shipment.findall('Scans/ScanDetail')
375
                for element in nodes:
376
                    if element.findtext('ScanType', '') == 'UD' and getTrimedString(element.findtext('Scan', '')) == getTrimedString('In Transit'):
377
                        delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
378
                        local_connected_orders[shipment.findtext('AWB', '')] = str(delivery_date)
379
                        break
380
        except:
381
            pass
382
 
5262 phani.kuma 383
    print "Local Connected Orders"
384
    print local_connected_orders
385
 
386
    return local_connected_orders
387
 
388
def read_reached_destination_orders(orders_tobe_reached_destination_city):
389
    destination_city_reached_orders = {}
5325 phani.kuma 390
    list_of_order = []
5262 phani.kuma 391
    for order in orders_tobe_reached_destination_city:
5325 phani.kuma 392
        list_of_order.append(str(order.airwaybill_no))
393
 
12961 manish.sha 394
    parentAwbList = [list_of_order[x:x+10] for x in xrange(0, len(list_of_order), 10)]
5262 phani.kuma 395
 
12961 manish.sha 396
    for awbList in parentAwbList:
397
        try:
398
            uri = Delhivery_URL + 'waybill=' + ','.join(awbList)
399
            root = parse(urllib2.urlopen(uri)).getroot()
400
            shipments = root.findall('Shipment')
401
            for shipment in shipments:
402
                nodes = shipment.findall('Scans/ScanDetail')
403
                for element in nodes:
404
                    if element.findtext('ScanType', '') == 'UD' and getTrimedString(element.findtext('Scan', '')) == getTrimedString('Pending'):
405
                        delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
406
                        destination_city_reached_orders[shipment.findtext('AWB', '')] = str(delivery_date)
407
                        break
408
        except:
409
            pass
410
 
5262 phani.kuma 411
    print "Destination City Reached Orders"
412
    print destination_city_reached_orders
413
 
414
    return destination_city_reached_orders
415
 
416
def read_first_delivery_attempt_orders(orders_tobe_first_delivery_attempted):
417
    first_atdl_orders = {}
5325 phani.kuma 418
    list_of_order = []
5262 phani.kuma 419
    for order in orders_tobe_first_delivery_attempted:
5325 phani.kuma 420
        list_of_order.append(str(order.airwaybill_no))
12961 manish.sha 421
 
422
    parentAwbList = [list_of_order[x:x+10] for x in xrange(0, len(list_of_order), 10)]
5325 phani.kuma 423
 
12961 manish.sha 424
    for awbList in parentAwbList:
425
        try:
426
            uri = Delhivery_URL + 'waybill=' + ','.join(awbList)
427
            root = parse(urllib2.urlopen(uri)).getroot()
428
            shipments = root.findall('Shipment')
429
            for shipment in shipments:
430
                nodes = shipment.findall('Scans/ScanDetail')
431
                node_number = 0
432
                for element in nodes:
433
                    if element.findtext('ScanType', '') == 'UD' and getTrimedString(element.findtext('Scan', '')) == getTrimedString('Dispatched'):
434
                        if node_number != len(nodes)-1 and nodes[node_number+1].findtext('ScanType', '') == 'UD':
435
                            element = nodes[node_number+1]
436
                            delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
437
                            reason_for_nondelivery = element.findtext('Instructions', '')
438
                            first_atdl_orders[shipment.findtext('AWB', '')] = str(delivery_date) + "|" + reason_for_nondelivery
439
                            break
440
                    node_number = node_number + 1
441
        except:
442
            pass
5262 phani.kuma 443
 
444
    print "FIRST DELIVERY ATTEMPT MADE Orders"
445
    print first_atdl_orders
446
 
447
    return first_atdl_orders
448
 
449
def read_delivery_orders(orders_tobe_delivered):
450
    delivered_orders = {}
451
    returned_orders = {}
452
    undelivered_orders = {}
5325 phani.kuma 453
    list_of_order = []
5262 phani.kuma 454
    for order in orders_tobe_delivered:
5325 phani.kuma 455
        list_of_order.append(str(order.airwaybill_no))
456
 
12961 manish.sha 457
    parentAwbList = [list_of_order[x:x+10] for x in xrange(0, len(list_of_order), 10)]
5262 phani.kuma 458
 
12960 manish.sha 459
    for awbList in parentAwbList:        
460
        try:
461
            uri = Delhivery_URL + 'waybill=' + ','.join(awbList)
462
            data = urllib2.urlopen(uri)
463
            root = parse(data).getroot()
464
            shipments = root.findall('Shipment')
465
            for shipment in shipments:
466
                nodes = shipment.findall('Scans/ScanDetail')
467
                node_number = 0
468
                for element in nodes:
469
 
470
                    if element.findtext('ScanType', '') == 'DL' and getTrimedString('Delivered') in getTrimedString(element.findtext('Scan', '')) :
471
                        delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
472
                        receiver = shipment.findtext('Status/RecievedBy', '')
473
                        delivered_orders[shipment.findtext('AWB', '')] = str(delivery_date) + "|" +  receiver
474
                        break
475
                    elif element.findtext('ScanType', '') == 'RT' and getTrimedString(element.findtext('Scan', '')) == getTrimedString('Returned'):
476
                        delivery_date = get_py_datetime(element.findtext('ScanDateTime', ''))
477
                        reason_for_return = element.findtext('Instructions', '')
478
                        returned_orders[shipment.findtext('AWB', '')] = str(delivery_date) + "|" + reason_for_return
479
                        break
480
                    elif node_number == len(nodes)-1:
481
                        reason = element.findtext('Instructions', '')
482
                        undelivered_orders[shipment.findtext('AWB', '')] = reason
483
                        break
484
                    node_number = node_number + 1
485
        except:
486
            pass
487
 
5262 phani.kuma 488
    print "Delivered Orders:"
489
    print delivered_orders
490
 
491
    print "Returned Orders:"
492
    print returned_orders
493
 
494
    print "Undelivered Orders"
495
    print undelivered_orders
496
 
497
    return delivered_orders, returned_orders, undelivered_orders
498
 
499
def update_picked_orders(provider_id, pickup_details):
500
    txnClient = TransactionClient().get_client()
501
    try:
502
        txnClient.markOrdersAsPickedUp(provider_id, pickup_details)
503
    except TransactionServiceException as tex:
504
        print tex.message
505
 
506
def update_picked_doas(provider_id, doa_pickup_details):
507
    txnClient = TransactionClient().get_client()
508
    try:
509
        txnClient.markDoasAsPickedUp(provider_id, doa_pickup_details)
510
    except TransactionServiceException as tex:
511
        print tex.message
512
 
513
def update_picked_returns(provider_id, returns_pickup_details):
514
    txnClient = TransactionClient().get_client()
515
    try:
516
        txnClient.markReturnOrdersAsPickedUp(provider_id, returns_pickup_details)
517
    except TransactionServiceException as tex:
518
        print tex.message
519
 
520
def update_delivered_orders(provider_id, delivered_orders):
521
    txnClient = TransactionClient().get_client()
522
    try:
523
        txnClient.markOrdersAsDelivered(provider_id, delivered_orders)
524
    except TransactionServiceException as tex:
525
        print tex.message
526
 
527
def update_returned_orders(provider_id, returned_orders):
528
    txnClient = TransactionClient().get_client()
529
    try:
530
        txnClient.markAsRTOrders(provider_id, returned_orders)
531
    except TransactionServiceException as tex:
532
        print tex.message
533
 
534
def update_reason_of_undelivered_orders(provider_id, undelivered_orders):
535
    txnClient = TransactionClient().get_client()
536
    try:
537
        txnClient.updateNonDeliveryReason(provider_id, undelivered_orders)
538
    except TransactionServiceException as tex:
539
        print tex.message
540
 
541
def update_local_connected_orders(provider_id, local_connected_orders):
542
    txnClient = TransactionClient().get_client()
543
    try:
544
        txnClient.markOrdersAsLocalConnected(provider_id, local_connected_orders)
545
    except TransactionServiceException as tex:
546
        print tex.message
547
 
548
def update_destination_city_reached_orders(provider_id, destination_city_reached_orders):
549
    txnClient = TransactionClient().get_client()
550
    try:
551
        txnClient.markOrdersAsDestinationCityReached(provider_id, destination_city_reached_orders)
552
    except TransactionServiceException as tex:
553
        print tex.message
554
 
555
def update_first_atdl_orders(provider_id, first_atdl_orders):
556
    txnClient = TransactionClient().get_client()
557
    try:
558
        txnClient.markOrdersAsFirstDeliveryAttempted(provider_id, first_atdl_orders)
559
    except TransactionServiceException as tex:
560
        print tex.message
561
 
562
def print_pickup_mismatch_report(filename, orders):
563
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
564
    writer.writerow(['Order Id', 'AWB No', 'Shipping timestamp'])
565
    for order in orders:
566
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.shipping_timestamp)])
567
 
568
def print_dao_return_pickup_mismatch_report(filename, orders):
569
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
570
    writer.writerow(['Order Id', 'Pickup Request No', 'Authorization timestamp'])
571
    for order in orders:
572
        writer.writerow([order.id, order.pickupRequestNo, to_py_date(order.doa_auth_timestamp)])
573
 
574
def print_rto_orders_report(filename, orders):
575
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
576
    writer.writerow(['Order Id', 'AWB No', 'Return date', 'Reason'])
577
    for order in orders:
578
        statusDescription = ''
579
        if order.statusDescription is not None:
580
            statusDescription = order.statusDescription.replace(","," ")
581
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.delivery_timestamp), statusDescription])
582
 
583
def print_undelivered_orders_report(filename, orders):
584
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
6703 rajveer 585
    writer.writerow(['Order Id', 'AWB No', 'Status', 'Status Description', 'Shipping timestamp', 'Pickup timestamp', 'Promised delivery date', 'Expected delivery date', 'OTG'])
5262 phani.kuma 586
    for order in orders:
587
        statusDescription = ''
588
        if order.statusDescription is not None:
589
            statusDescription = order.statusDescription.replace(","," ")
6703 rajveer 590
        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), 'True'  if order.otg else 'False'])
5262 phani.kuma 591
 
592
 
593
def auto_close_crm_tickets_created():
594
    try:
595
        ticket_created_orders = []
596
        tickets_map = {}
597
        crmServiceClient = CRMClient().get_client()
598
        searchFilter = SearchFilter()
599
        searchFilter.ticketCategory = TicketCategory.UNDELIVERED
600
        searchFilter.ticketAssigneeIds = [defaultUndeliveredAsssigneeId]
601
        searchFilter.ticketPriority = TicketPriority.HIGH
602
        searchFilter.ticketStatuses = [TicketStatus.OPEN]
603
        tickets = crmServiceClient.getTickets(searchFilter)
604
        print tickets
605
        for old_ticket in tickets:
606
            ticket_created_orders.append(old_ticket.orderId)
607
            tickets_map[old_ticket.orderId] = old_ticket
608
        print ticket_created_orders
609
        txnClient = TransactionClient().get_client()
610
        orders = txnClient.getOrderList(ticket_created_orders)
611
        for order in orders:
13085 amit.gupta 612
            if order.status not in [OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.RTO_IN_TRANSIT]:
5262 phani.kuma 613
                old_ticket = tickets_map.get(order.id)
614
                old_ticket.status = TicketStatus.CLOSED
615
                activity = Activity()
616
                activity.creatorId = 1
617
                activity.ticketAssigneeId = old_ticket.assigneeId
618
                activity.type = ActivityType.OTHER
619
                activity.description = "Ticket Closed bcoz order status changed to:" + order.statusDescription
620
                activity.ticketCategory = old_ticket.category
621
                activity.ticketDescription = old_ticket.description
622
                activity.ticketPriority = old_ticket.priority
623
                activity.ticketStatus = old_ticket.status
624
 
625
                if old_ticket.customerId is None or old_ticket.customerId == -1:
626
                    activity.customerEmailId = old_ticket.customerEmailId
627
                    activity.customerMobileNumber = old_ticket.customerMobileNumber
628
                    activity.customerName = old_ticket.customerName
629
                else:
630
                    activity.customerId = old_ticket.customerId
631
 
632
                crmServiceClient.updateTicket(old_ticket, activity)
633
    except:
634
        print "Some issue while closing crm tickets for orders in DELIVERY_SUCCESS status"
635
        traceback.print_exc()
636
 
637
def get_py_datetime(time_string):
638
    # This should be a command line argument.
639
    # Refer http://docs.python.org/library/time.html#time.strftime to
640
    # get a complete list of format specifiers available for date time.
641
    time_format = "%Y-%m-%d %H:%M:%S"
642
    if time_string == '':
643
        return None
644
    date_time_array = time_string.split('T')
645
    datestring = date_time_array[0]
646
    timestring = date_time_array[1]
647
    if timestring == '':
648
        timestring = '00:00:00'
649
    else:
650
        timestring = timestring.split('.')[0]
651
    time_string = datestring + ' ' + timestring
652
    mytime = time.strptime(time_string, time_format)
653
    return datetime.datetime(*mytime[:6])
654
 
655
def getTrimedString(text):
656
    if text is None or text == '':
657
        return ''
658
    else:
659
        text = text.strip().lower()
660
        text_list = list(text)
661
        new_text = ''
662
        for letter in text_list:
663
            if letter.isalnum():
664
                new_text = new_text + str(letter)
665
        return new_text
666
 
667
def main():
668
    parser = optparse.OptionParser()
669
    parser.add_option("-p", "--pickup", dest="pickup_report",
670
                   action="store_true",
671
                   help="Run the pickup reconciliation")
672
    parser.add_option("-d", "--delivery", dest="delivery_report",
673
                   action="store_true",
674
                   help="Run the delivery reconciliation")
675
    parser.add_option("-r", "--reports", dest="gen_reports",
676
                   action="store_true",
677
                   help="Generate logistic reconciliation reports")
678
    parser.add_option("-a", "--all", dest="all_reports",
679
                   action="store_true",
680
                   help="Run all reconciliations")
681
    parser.add_option("-P", "--provider", dest="provider",
682
                   default="Delhivery", type="string",
683
                   help="The PROVIDER this report is for",
684
                   metavar="PROVIDER")
685
    parser.set_defaults(pickup_report=False, delivery_report=False, gen_reports=False, all_reports=False)
686
    (options, args) = parser.parse_args()
687
    if len(args) != 0:
688
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
689
 
690
    if options.all_reports:
691
        options.pickup_report = True
692
        options.delivery_report = True
693
 
694
    provider = get_provider_by_name(options.provider)
695
 
696
    if options.pickup_report:
697
        process_pickup_records(provider)
698
        process_dao_pickup_orders(provider)
699
        process_return_pickup_orders(provider)
700
    if options.delivery_report:
701
        process_local_connection_orders(provider)
702
        process_reached_destination_city_orders(provider)
703
        process_first_delivery_attempt_orders(provider)
704
        process_delivery_report(provider)
12961 manish.sha 705
        create_crm_tickets_for_delivey_attempted_orders(provider)
5262 phani.kuma 706
        auto_close_crm_tickets_created()
707
    if options.gen_reports:
708
        generate_reports(provider)
709
 
710
if __name__ == '__main__':
6619 amit.gupta 711
    main()