Subversion Repositories SmartDukaan

Rev

Rev 1284 | Rev 2001 | 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):
1246 chandransh 26
    filename = fetch_report(provider.name.upper() + ' PICKUP REPORT')
1132 chandransh 27
    pickup_details = read_pickup_report(filename)
28
    orders_not_picked_up = update_picked_orders(provider.id, pickup_details)
29
    if orders_not_picked_up:
1246 chandransh 30
        mismatch_file = "PickupMismatch.csv"
31
        print "Some of our orders were not picked up. Printing report to:" + mismatch_file
32
        print_pickup_mismatch_report(mismatch_file, orders_not_picked_up)
33
        pickup_mismatch_part = get_attachment_part(mismatch_file)
34
        mail(from_user, from_pwd, to,\
1284 chandransh 35
             "Pickup Mismatch for " + provider.name,\
1246 chandransh 36
             "This is a system generated email.Please don't reply to it.",\
37
             pickup_mismatch_part)
1718 chandransh 38
    os.remove(filename)
1132 chandransh 39
 
40
def process_delivery_report(provider):
1246 chandransh 41
    filename = fetch_report(provider.name.upper() + ' DELIVERED AND RTO REPORT')
1135 chandransh 42
    #filename = 'delivery_report.xls'
1132 chandransh 43
    delivered_orders, returned_orders = read_delivery_report(filename)
1246 chandransh 44
    if delivered_orders:
45
        update_delivered_orders(provider.id, delivered_orders)
46
    if returned_orders:
47
        update_returned_orders(provider.id, returned_orders)
48
 
49
        mail(from_user, from_pwd, to,\
50
             "Returned Orders Report for " + provider.name,\
51
             "This is a system generated email.Please don't reply to it.",\
52
             None)
1718 chandransh 53
    os.remove(filename)
1132 chandransh 54
 
55
def process_non_delivery_report(provider):
1246 chandransh 56
    filename = fetch_report(provider.name.upper() + ' UNDELIVERED REPORT')
57
    undelivered_orders = read_undelivered_report(filename)
58
    update_reason_of_undelivered_orders(provider.id, undelivered_orders)
1718 chandransh 59
    os.remove(filename)
1246 chandransh 60
 
61
def update_reason_of_undelivered_orders(provider_id, undelivered_orders):
62
    txnClient = TransactionClient().get_client()
63
    try:
64
        txnClient.updateNonDeliveryReason(provider_id, undelivered_orders)
65
    except TransactionServiceException as tex:
66
        print tex.message
67
 
1132 chandransh 68
def get_provider_by_name(provider_name):
69
    logistics_client = LogisticsClient().get_client()
1246 chandransh 70
    #TODO: Write a thrift call to get a provider by name
1132 chandransh 71
    provider = None
72
    providers = logistics_client.getAllProviders()
73
    for p in providers:
74
        if p.name == provider_name:
75
            provider=p
76
            break
77
    if provider == None:
78
        sys.exit("Can't continue execution: No such provider")
79
    return provider
80
 
81
def fetch_report(type):
82
    filename = download_attachment(type, todays_date_string())
83
    if filename is None:
84
        sys.exit("The " + type + " report is not yet available.")
85
    return filename
86
 
87
def read_pickup_report(filename):
88
    print "Reading pickup report from:" + filename
89
    workbook = xlrd.open_workbook(filename)
90
    sheet = workbook.sheet_by_index(0)
91
    num_rows = sheet.nrows
92
    picked_up_orders = {}
93
    for rownum in range(1, num_rows):
1263 chandransh 94
        unused_customer_code, awb, timeval, date = sheet.row_values(rownum)[0:4]
95
        picked_up_orders[awb] = str(get_py_datetime(date, timeval))
1135 chandransh 96
 
97
    print "Picked up Orders:"
98
    print picked_up_orders
1132 chandransh 99
    return picked_up_orders
100
 
101
def read_delivery_report(filename):
102
    print "Reading delivery details from:" + filename
103
    workbook = xlrd.open_workbook(filename)
104
    sheet = workbook.sheet_by_index(0)
105
    num_rows = sheet.nrows
106
    delivered_orders = {}
107
    returned_orders = {}
108
    for rownum in range(1, num_rows):
1265 chandransh 109
        unused_customer_code, awb, timeval, date, unused_status, receiver, reason_for_return = sheet.row_values(rownum)[0:7]
110
        delivery_date = str(get_py_datetime(date, timeval))
1132 chandransh 111
        if receiver: #TODO: Use status for this check
1246 chandransh 112
            delivered_orders[awb] = delivery_date + "|" +  receiver
1132 chandransh 113
        else:
1246 chandransh 114
            returned_orders[awb] = delivery_date + "|" + reason_for_return
1135 chandransh 115
 
1132 chandransh 116
    print "Delivered Orders:"
117
    print delivered_orders
118
 
119
    print "Returned Orders:"
120
    print returned_orders
121
    return delivered_orders, returned_orders
122
 
1246 chandransh 123
def read_undelivered_report(filename):
124
    print "Reading undelivered details from:" + filename
125
    workbook = xlrd.open_workbook(filename)
126
    sheet = workbook.sheet_by_index(0)
127
    num_rows = sheet.nrows
128
    undelivered_orders = {}
129
    for rownum in range(1, num_rows):
1265 chandransh 130
        unused_cusotmer_code, awb, reason, timeval, date = sheet.row_values(rownum)[0:5]
131
        unused_status_date = str(get_py_datetime(date, timeval))
1246 chandransh 132
        undelivered_orders[awb] = reason
133
 
134
    print "Undelivered Orders"
135
    print undelivered_orders
136
 
137
    return undelivered_orders
138
 
1132 chandransh 139
def update_picked_orders(provider_id, pickup_details):
140
    txnClient = TransactionClient().get_client()
141
    try:
142
        orders_not_picked_up = txnClient.markOrdersAsPickedUp(provider_id, pickup_details)
143
        return orders_not_picked_up
144
    except TransactionServiceException as tex:
145
        print tex.message
146
 
1135 chandransh 147
def update_delivered_orders(provider_id, delivered_orders):
1132 chandransh 148
    txnClient = TransactionClient().get_client()
149
    try:
1135 chandransh 150
        txnClient.markOrdersAsDelivered(provider_id, delivered_orders)
1132 chandransh 151
    except TransactionServiceException as tex:
152
        print tex.message
153
 
1135 chandransh 154
def update_returned_orders(provider_id, returned_orders):
155
    txnClient = TransactionClient().get_client()
156
    try:
157
        txnClient.markOrdersAsFailed(provider_id, returned_orders)
158
    except TransactionServiceException as tex:
159
        print tex.message
1132 chandransh 160
 
1246 chandransh 161
def print_pickup_mismatch_report(filename, orders):
1132 chandransh 162
    writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_NONE)
163
    writer.writerow(['Order Id', 'AWB No', 'Shipping timestamp'])
164
    for order in orders:
165
        writer.writerow([order.id, order.airwaybill_no, to_py_date(order.shipping_timestamp)])
166
 
167
def todays_date_string():
1246 chandransh 168
    today_date = time.strftime("%d-%b-%Y")
169
    return '"' + today_date + '"'
1132 chandransh 170
 
1263 chandransh 171
def get_py_datetime(date, timeval):
1246 chandransh 172
    # This should be a command line argument.
173
    # Refer http://docs.python.org/library/time.html#time.strftime to
174
    # get a complete list of format specifiers available for date time.
175
    time_format = "%d-%b-%y %H%M"
1263 chandransh 176
    time_string = date + " " + timeval
1246 chandransh 177
    mytime = time.strptime(time_string, time_format)
178
    return datetime.datetime(*mytime[:6])
179
 
1132 chandransh 180
def main():
181
    parser = optparse.OptionParser()
182
    parser.add_option("-p", "--pickup", dest="pickup_report",
183
                   action="store_true",
184
                   help="Run the pickup reconciliation")
185
    parser.add_option("-d", "--delivery", dest="delivery_report",
186
                   action="store_true",
187
                   help="Run the delivery reconciliation")
188
    parser.add_option("-n", "--non-delivery", dest="non_delivery_report",
189
                   action="store_true",
190
                   help="Run the non delivery reconciliation")
191
    parser.add_option("-a", "--all", dest="all_reports",
192
                   action="store_true",
193
                   help="Run all reconciliations")
194
    parser.add_option("-P", "--provider", dest="provider",
195
                   default="BlueDart", type="string",
196
                   help="The PROVIDER this report is for",
197
                   metavar="PROVIDER")
198
    parser.set_defaults(pickup_report=False, delivery_report=False, non_delivery_report=False, all_reports=False)
199
    (options, args) = parser.parse_args()
200
    if len(args) != 0:
201
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
202
 
203
    if options.all_reports:
204
        options.pickup_report = True
205
        options.delivery_report = True
206
        options.non_delivery_report = True
207
 
208
    provider = get_provider_by_name(options.provider)
209
 
210
    if options.pickup_report:
211
        process_pickup_records(provider)
212
    if options.delivery_report:
213
        process_delivery_report(provider)
214
    if options.non_delivery_report:
215
        process_non_delivery_report(provider)
216
 
217
if __name__ == '__main__':
1718 chandransh 218
    main()