Subversion Repositories SmartDukaan

Rev

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

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