Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1132 chandransh 1
#!/usr/bin/python 
2
 
1246 chandransh 3
import time
1132 chandransh 4
import datetime
5
import optparse
6
import sys
7
import csv
8
import xlrd
9
 
10
if __name__ == '__main__' and __package__ is None:
11
    import os
12
    sys.path.insert(0, os.getcwd())
13
 
14
from shop2020.clients.LogisticsClient import LogisticsClient
15
from shop2020.clients.TransactionClient import TransactionClient
16
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException
17
from shop2020.utils.EmailAttachmentDownloader import download_attachment
1246 chandransh 18
from shop2020.utils.EmailAttachmentSender import get_attachment_part, mail
1132 chandransh 19
from shop2020.utils.Utils import to_py_date
20
 
1246 chandransh 21
from_user = 'cnc.center@shop2020.in'
22
from_pwd = '5h0p2o2o'
23
to = 'cnc.center@shop2020.in'
24
 
1132 chandransh 25
def process_pickup_records(provider):
2001 chandransh 26
    try:
27
        filename = fetch_report(provider.name.upper() + ' PICKUP REPORT')
2764 chandransh 28
        pickup_details, doa_pickup_details = read_pickup_report(filename)
2001 chandransh 29
        orders_not_picked_up = update_picked_orders(provider.id, pickup_details)
2764 chandransh 30
        try:
31
            if orders_not_picked_up:
32
                mismatch_file = "PickupMismatch.csv"
33
                print "Some of our orders were not picked up. Printing report to:" + mismatch_file
34
                print_pickup_mismatch_report(mismatch_file, orders_not_picked_up)
35
                pickup_mismatch_part = get_attachment_part(mismatch_file)
36
                mail(from_user, from_pwd, to,\
37
                     "Order Pickup Mismatch for " + provider.name,\
38
                     "This is a system generated email.Please don't reply to it.",\
39
                     pickup_mismatch_part)
40
        except Exception:
41
            print "Some issue sending the mismatch report"
42
 
43
        doas_not_picked_up = update_picked_doas(provider.id, doa_pickup_details)
44
        try:
45
            if doas_not_picked_up:
46
                mismatch_file = "DoaPickupMismatch.csv"
47
                print "Some of our DOA orders were not picked up. Printing report to:" + mismatch_file
48
                print_pickup_mismatch_report(mismatch_file, doas_not_picked_up)
49
                pickup_mismatch_part = get_attachment_part(mismatch_file)
50
                mail(from_user, from_pwd, to,\
51
                     "DOA Pickup Mismatch for " + provider.name,\
52
                     "This is a system generated email.Please don't reply to it.",\
53
                     pickup_mismatch_part)
54
        except Exception:
55
            print "Some issue sending the mismatch report"
2001 chandransh 56
    finally:
57
        os.remove(filename)
1132 chandransh 58
 
59
def process_delivery_report(provider):
2001 chandransh 60
    try:
61
        filename = fetch_report(provider.name.upper() + ' DELIVERED AND RTO REPORT')
62
        #filename = 'delivery_report.xls'
63
        delivered_orders, returned_orders = read_delivery_report(filename)
64
        if delivered_orders:
65
            update_delivered_orders(provider.id, delivered_orders)
66
        if returned_orders:
67
            update_returned_orders(provider.id, returned_orders)
68
 
69
            mail(from_user, from_pwd, to,\
70
                 "Returned Orders Report for " + provider.name,\
71
                 "This is a system generated email.Please don't reply to it.",\
72
                 None)
73
    finally:
74
        os.remove(filename)
1132 chandransh 75
 
76
def process_non_delivery_report(provider):
2001 chandransh 77
    try:
78
        filename = fetch_report(provider.name.upper() + ' UNDELIVERED REPORT')
79
        undelivered_orders = read_undelivered_report(filename)
80
        update_reason_of_undelivered_orders(provider.id, undelivered_orders)
81
    finally:
82
        os.remove(filename)
1246 chandransh 83
 
84
def update_reason_of_undelivered_orders(provider_id, undelivered_orders):
85
    txnClient = TransactionClient().get_client()
86
    try:
87
        txnClient.updateNonDeliveryReason(provider_id, undelivered_orders)
88
    except TransactionServiceException as tex:
89
        print tex.message
90
 
1132 chandransh 91
def get_provider_by_name(provider_name):
92
    logistics_client = LogisticsClient().get_client()
1246 chandransh 93
    #TODO: Write a thrift call to get a provider by name
1132 chandransh 94
    provider = None
95
    providers = logistics_client.getAllProviders()
96
    for p in providers:
97
        if p.name == provider_name:
98
            provider=p
99
            break
100
    if provider == None:
101
        sys.exit("Can't continue execution: No such provider")
102
    return provider
103
 
104
def fetch_report(type):
105
    filename = download_attachment(type, todays_date_string())
106
    if filename is None:
107
        sys.exit("The " + type + " report is not yet available.")
108
    return filename
109
 
110
def read_pickup_report(filename):
111
    print "Reading pickup report from:" + filename
112
    workbook = xlrd.open_workbook(filename)
113
    sheet = workbook.sheet_by_index(0)
114
    num_rows = sheet.nrows
115
    picked_up_orders = {}
2764 chandransh 116
    picked_up_doas = {}
1132 chandransh 117
    for rownum in range(1, num_rows):
2764 chandransh 118
        unused_customer_code, awb, ref_no, timeval, date = sheet.row_values(rownum)[0:5]
1263 chandransh 119
        picked_up_orders[awb] = str(get_py_datetime(date, timeval))
2764 chandransh 120
        picked_up_doas[ref_no] = str(get_py_datetime(date, timeval))
1135 chandransh 121
 
122
    print "Picked up Orders:"
123
    print picked_up_orders
2764 chandransh 124
    print picked_up_doas
125
    return picked_up_orders, picked_up_doas
1132 chandransh 126
 
127
def read_delivery_report(filename):
128
    print "Reading delivery details from:" + filename
129
    workbook = xlrd.open_workbook(filename)
130
    sheet = workbook.sheet_by_index(0)
131
    num_rows = sheet.nrows
132
    delivered_orders = {}
133
    returned_orders = {}
134
    for rownum in range(1, num_rows):
2625 chandransh 135
        unused_customer_code, awb, unused_ref_no, timeval, date, unused_status, receiver, reason_for_return = sheet.row_values(rownum)[0:8]
1265 chandransh 136
        delivery_date = str(get_py_datetime(date, timeval))
1132 chandransh 137
        if receiver: #TODO: Use status for this check
1246 chandransh 138
            delivered_orders[awb] = delivery_date + "|" +  receiver
1132 chandransh 139
        else:
1246 chandransh 140
            returned_orders[awb] = delivery_date + "|" + reason_for_return
1135 chandransh 141
 
1132 chandransh 142
    print "Delivered Orders:"
143
    print delivered_orders
144
 
145
    print "Returned Orders:"
146
    print returned_orders
147
    return delivered_orders, returned_orders
148
 
1246 chandransh 149
def read_undelivered_report(filename):
150
    print "Reading undelivered details from:" + filename
151
    workbook = xlrd.open_workbook(filename)
152
    sheet = workbook.sheet_by_index(0)
153
    num_rows = sheet.nrows
154
    undelivered_orders = {}
155
    for rownum in range(1, num_rows):
2625 chandransh 156
        unused_cusotmer_code, awb, unused_ref_no, reason, timeval, date = sheet.row_values(rownum)[0:6]
2001 chandransh 157
        try:
158
            unused_status_date = str(get_py_datetime(date, timeval))
159
        except ValueError:
160
            #ValueError can be expected if the date or time are not in the expected format
161
            #Harmless error for now since we are not storing the status date
162
            print sys.exc_info()[0]
1246 chandransh 163
        undelivered_orders[awb] = reason
164
 
165
    print "Undelivered Orders"
166
    print undelivered_orders
167
 
168
    return undelivered_orders
169
 
1132 chandransh 170
def update_picked_orders(provider_id, pickup_details):
171
    txnClient = TransactionClient().get_client()
172
    try:
173
        orders_not_picked_up = txnClient.markOrdersAsPickedUp(provider_id, pickup_details)
174
        return orders_not_picked_up
175
    except TransactionServiceException as tex:
176
        print tex.message
177
 
2764 chandransh 178
def update_picked_doas(provider_id, doa_pickup_details):
179
    txnClient = TransactionClient().get_client()
180
    try:
181
        doas_not_picked_up = txnClient.markDoasAsPickedUp(provider_id, doa_pickup_details)
182
        return doas_not_picked_up
183
    except TransactionServiceException as tex:
184
        print tex.message
185
 
1135 chandransh 186
def update_delivered_orders(provider_id, delivered_orders):
1132 chandransh 187
    txnClient = TransactionClient().get_client()
188
    try:
1135 chandransh 189
        txnClient.markOrdersAsDelivered(provider_id, delivered_orders)
1132 chandransh 190
    except TransactionServiceException as tex:
191
        print tex.message
192
 
1135 chandransh 193
def update_returned_orders(provider_id, returned_orders):
194
    txnClient = TransactionClient().get_client()
195
    try:
196
        txnClient.markOrdersAsFailed(provider_id, returned_orders)
197
    except TransactionServiceException as tex:
198
        print tex.message
1132 chandransh 199
 
1246 chandransh 200
def print_pickup_mismatch_report(filename, orders):
1132 chandransh 201
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
202
    writer.writerow(['Order Id', 'AWB No', 'Shipping timestamp'])
203
    for order in orders:
204
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.shipping_timestamp)])
205
 
206
def todays_date_string():
1246 chandransh 207
    today_date = time.strftime("%d-%b-%Y")
208
    return '"' + today_date + '"'
1132 chandransh 209
 
1263 chandransh 210
def get_py_datetime(date, timeval):
1246 chandransh 211
    # This should be a command line argument.
212
    # Refer http://docs.python.org/library/time.html#time.strftime to
213
    # get a complete list of format specifiers available for date time.
214
    time_format = "%d-%b-%y %H%M"
2693 chandransh 215
    if timeval is None or timeval == '--':
216
        timeval='0000'
1263 chandransh 217
    time_string = date + " " + timeval
1246 chandransh 218
    mytime = time.strptime(time_string, time_format)
219
    return datetime.datetime(*mytime[:6])
220
 
1132 chandransh 221
def main():
222
    parser = optparse.OptionParser()
223
    parser.add_option("-p", "--pickup", dest="pickup_report",
224
                   action="store_true",
225
                   help="Run the pickup reconciliation")
226
    parser.add_option("-d", "--delivery", dest="delivery_report",
227
                   action="store_true",
228
                   help="Run the delivery reconciliation")
229
    parser.add_option("-n", "--non-delivery", dest="non_delivery_report",
230
                   action="store_true",
231
                   help="Run the non delivery reconciliation")
232
    parser.add_option("-a", "--all", dest="all_reports",
233
                   action="store_true",
234
                   help="Run all reconciliations")
235
    parser.add_option("-P", "--provider", dest="provider",
236
                   default="BlueDart", type="string",
237
                   help="The PROVIDER this report is for",
238
                   metavar="PROVIDER")
239
    parser.set_defaults(pickup_report=False, delivery_report=False, non_delivery_report=False, all_reports=False)
240
    (options, args) = parser.parse_args()
241
    if len(args) != 0:
242
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
243
 
244
    if options.all_reports:
245
        options.pickup_report = True
246
        options.delivery_report = True
247
        options.non_delivery_report = True
248
 
249
    provider = get_provider_by_name(options.provider)
250
 
251
    if options.pickup_report:
252
        process_pickup_records(provider)
253
    if options.delivery_report:
254
        process_delivery_report(provider)
255
    if options.non_delivery_report:
256
        process_non_delivery_report(provider)
257
 
258
if __name__ == '__main__':
1718 chandransh 259
    main()