Subversion Repositories SmartDukaan

Rev

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