Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13020 amit.gupta 1
'''
2
Created on 08-Jul-2013
3
 
4
@author: anupam
5
'''
6
 
7
import MySQLdb
8
import datetime
9
import smtplib
10
import xlwt
11
import traceback
12
 
13
from email import encoders
14
from email.mime.text import MIMEText
15
from email.mime.base import MIMEBase
16
from email.mime.multipart import MIMEMultipart
17
from datetime import date
18
 
19
# Initialize db connection settings.
20
DB_HOST = "192.168.190.114"
21
DB_USER = "root"
22
DB_PASSWORD = "shop2020"
23
DB_NAME = "transaction"
24
 
25
# KEY NAMES
26
SENDER = "cnc.center@shop2020.in"
27
PASSWORD = "5h0p2o2o"
28
SUBJECT = "Recharge report for week ending on " + date.today().isoformat()
29
SMTP_SERVER = "smtp.gmail.com"
30
SMTP_PORT = 587    
31
 
32
TMP_FILE="/tmp/dtrshipped_report.xls"
33
 
34
report_map = {}
35
 
36
 
37
SHIPPED_ORDER_GROUP_SQL="""     select c.name, concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, count(*),sum(o.total_amount) as amount 
38
                                from transaction.order o join user.privatedealuser pd on o.customer_id=pd.id  
39
                                join user.counter c on c.id = pd.counter_id join transaction.lineitem li on li.order_id=o.id  
40
                                where o.status in (9,10,16,17,40) and o.total_amount > 1 group by c.name, prodname  with rollup
41
 
42
                        """
43
SHIPPED_ORDER_SQL=      """
44
                          select c.code,c.name, w.displayName as warehouse, o.id, date(o.created_timestamp) as orderedon, date(o.shipping_timestamp) as shiipedon, os.statusName , date(o.expected_delivery_time), 
45
                          concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, li.quantity, o.total_amount as amount from transaction.order o 
46
                          join user.privatedealuser pd on o.customer_id=pd.id  join user.counter c on c.id = pd.counter_id join transaction.lineitem li on li.order_id=o.id 
47
                          join inventory.warehouse w on w.id = o.fulfilmentWarehouseId join orderstatus os on o.status = os.status 
48
                          where o.status in (9,10,16,17,40) and o.total_amount > 1 order by code, prodname   
49
                        """
50
 
51
SOLD_OUT_GROUP_SQL="""
52
                    select c.name, concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, count(*),  sum(o.total_amount) as total_sale 
53
                        from transaction.order o join user.privatedealuser pd on o.customer_id=pd.id 
54
                        join mobileactivationrecord mar on mar.orderId = o.id join user.counter c on c.id = pd.counter_id 
55
                        join transaction.lineitem li on li.order_id=o.id  where date(mar.activationTime) = curdate()-1 group by c.name, prodname  with rollup;
56
                   """
57
SOLD_OUT_SQL="""
58
                          select c.code,c.name, o.id, date(o.created_timestamp) as orderedon, date(delivery_timestamp), mar.activationTime, 
59
                          concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, li.quantity, o.total_amount as amount from transaction.order o 
60
                          join user.privatedealuser pd on o.customer_id=pd.id  join user.counter c on c.id = pd.counter_id join transaction.lineitem li on li.order_id=o.id 
61
                          join mobileactivationrecord mar on mar.orderId = o.id where date(mar.activationTime) = curdate()-1 order by code, prodname
62
             """
63
PENDING_ORDER_GROUP_SQL="""     select c.name, concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, count(*),sum(o.total_amount) as amount 
64
                                from transaction.order o join user.privatedealuser pd on o.customer_id=pd.id  
65
                                join user.counter c on c.id = pd.counter_id join transaction.lineitem li on li.order_id=o.id  
66
                                where o.status in (3,4,5,7) and o.total_amount > 1 group by c.name, prodname  with rollup
67
 
68
                        """
69
PENDING_ORDER_SQL= """
70
                          select c.code,c.name, w.displayName as warehouse, o.id, date(o.created_timestamp) as orderedon, date(o.shipping_timestamp) as shiipedon, os.statusName , date(o.expected_delivery_time), 
71
                          concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, li.quantity, o.total_amount as amount from transaction.order o 
72
                          join user.privatedealuser pd on o.customer_id=pd.id  join user.counter c on c.id = pd.counter_id join transaction.lineitem li on li.order_id=o.id 
73
                          join inventory.warehouse w on w.id = o.fulfilmentWarehouseId join orderstatus os on o.status = os.status 
74
                          where o.status in (3,4,5,7) and o.total_amount > 1 order by code, prodname   
75
                        """
76
 
77
STOCK_REPORT_GROUP_SQL= """
78
                        select c.name, concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as product,  count(*) as delivered,
79
                            sum(if(mar.activationTime is not null, 1, 0)) as sold, sum(if(mar.activationTime is not null, 0, 1)) as instock,  
80
                            sum(if(mar.activationTime is not null, 0,o.total_amount)) as valueinstock 
81
                        from transaction.order o join user.privatedealuser pd on o.customer_id=pd.id 
82
                            left join mobileactivationrecord mar on mar.orderId = o.id  join user.counter c on c.id = pd.counter_id 
83
                            join transaction.lineitem li on li.order_id=o.id 
84
                        where o.status=12 and o.total_amount > 0 and li.brand = 'Spice' and li.item_id not in (select itemId from catalog.spiceuntraceable) group by name, product  with rollup
85
                        """
86
STOCK_REPORT_SQL=       """
87
                        select c.code, c.name, o.id, date(o.created_timestamp) createddate, date(o.delivery_timestamp) delivereddate, os.statusName, 
88
                        concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as product,  li.quantity, o.total_amount, 
89
                        datediff(curdate(),date(o.delivery_timestamp)) as ageing  from transaction.order o join user.privatedealuser 
90
                        pd on o.customer_id=pd.id left join mobileactivationrecord mar on mar.orderId = o.id  
91
                        join user.counter c on c.id = pd.counter_id join transaction.lineitem li on li.order_id=o.id join orderstatus os on o.status = os.status
92
                        where o.status=12 and o.total_amount > 0 and mar.activationTime is null and li.brand = 'Spice' and li.item_id not in (select itemId from catalog.spiceuntraceable)
93
                        """
94
 
95
MIS_REPORT_GROUP_SQL="""
96
                        select c.name, sum(if(date(o.created_timestamp)=curdate()-1, 1, 0)) as lastDayQty, 
97
                            sum(if(date(o.created_timestamp)=curdate()-1, o.total_amount , 0)) lastDayValue, 
98
                            count(*) as MTDQty, sum(o.total_amount) as MTDValue from transaction.order o 
99
                            join user.privatedealuser pd on o.customer_id=pd.id join user.counter c on c.id = pd.counter_id 
100
                            join transaction.lineitem li on li.order_id=o.id        where o.status in (2,3,4,5,7,9,10,12,16,17,40) 
101
                            and o.total_amount > 1 and o.created_timestamp between CURDATE() - INTERVAL DAY(CURDATE())-1 DAY and CURDATE() 
102
                            group by c.name with rollup;
103
                     """
104
MIS_REPORT_SQL="""
105
                select c.code,c.name, w.displayName as warehouse, o.id, date(o.created_timestamp) as orderedon, os.statusName , date(mar.activationTime) activatedon, 
106
                concat_ws(' ',li.brand, li.model_name, li.model_number, li.color) as prodname, li.quantity, o.total_amount as amount 
107
                from transaction.order o join user.privatedealuser pd on o.customer_id=pd.id  join user.counter c on c.id = pd.counter_id 
108
                join transaction.lineitem li on li.order_id=o.id join inventory.warehouse w on w.id = o.fulfilmentWarehouseId 
109
                join orderstatus os on o.status = os.status left join mobileactivationrecord mar on mar.orderId = o.id 
110
                where o.status in (2,3,4,5,7,9,10,12,16,17,40) and o.total_amount > 1 
111
                and o.created_timestamp between CURDATE() - INTERVAL DAY(CURDATE())-1 DAY and CURDATE() order by orderedon desc, c.code 
112
                """
113
date_format = xlwt.XFStyle()
114
date_format.num_format_str = 'dd/mm/yyyy'
115
 
13060 amit.gupta 116
datetime_format = xlwt.XFStyle()
117
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
118
 
13020 amit.gupta 119
number_format = xlwt.XFStyle()
120
number_format.num_format_str = '#,##0'
121
 
122
 
123
 
124
 
125
valueformat = "{0:,.0f}"
126
 
127
default_format = xlwt.XFStyle()
128
 
129
shipped_headers=['Counter', 'Product', 'Quantity', 'Value']
130
tertiary_headers=shipped_headers
131
pending_headers=shipped_headers
132
ageing_headers=['Counter','Product','QtyDelivered','QtySold','QtyInStock','ValueInStock']
133
mis_headers=['Counter','Last Day Qty', 'Last Day Value','MTD Qty', 'MTD Value']
134
 
135
report_map['shipped'] = {'title':'Shipped Orders Report', 'query' : SHIPPED_ORDER_GROUP_SQL, 'group':2, 'headers':shipped_headers}
136
report_map['tertiary'] = {'title':'Tertiary Report', 'query' : SOLD_OUT_GROUP_SQL, 'group':2, 'headers':tertiary_headers}
137
report_map['pending'] = {'title':'Pending Orders Report', 'query' : PENDING_ORDER_GROUP_SQL, 'group':2, 'headers':pending_headers}
138
report_map['ageing'] = {'title':'Spice Stock Ageing Report', 'query' : STOCK_REPORT_GROUP_SQL, 'group':2, 'headers':ageing_headers}
139
report_map['mis'] = {'title':'Daily Counter wise Sales Report', 'query' : MIS_REPORT_GROUP_SQL, 'group':1, 'headers':mis_headers}
140
 
141
#recipients = []
142
recipients = ['rajneesh.arora@saholic.com', 'lakshman.g@smobility.in', 'sandeep.sachdeva@shop2020.in', 'amit.sirohi@shop2020.in', 'khushal.bhatia@saholic.com', 'chaitnaya.vats@saholic.com']
143
 
144
 
145
def getDbConnection():
146
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
147
 
148
def closeConnection(conn):
149
    conn.close()
150
 
151
 
152
 
153
def sendmail(email, message, fileName, title):
154
    if email == "":
155
        return
156
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
157
    mailServer.ehlo()
158
    mailServer.starttls()
159
    mailServer.ehlo()
160
 
161
    # Create the container (outer) email message.
162
    msg = MIMEMultipart()
163
    msg['Subject'] = title
164
    msg.preamble = title
165
    html_msg = MIMEText(message, 'html')
166
    msg.attach(html_msg)
167
 
168
    fileMsg = MIMEBase('application','vnd.ms-excel')
169
    fileMsg.set_payload(file(TMP_FILE).read())
170
    encoders.encode_base64(fileMsg)
171
    fileMsg.add_header('Content-Disposition','attachment;filename=' + fileName)
172
    msg.attach(fileMsg)
13022 amit.gupta 173
    email.append('amit.gupta@shop2020.in')
13021 amit.gupta 174
    MAILTO = email 
13020 amit.gupta 175
    mailServer.login(SENDER, PASSWORD)
176
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
177
 
178
def getMailAttachmentShipped():
179
    selectSql = SHIPPED_ORDER_SQL
180
    conn = getDbConnection()
181
    try:
182
        # prepare a cursor object using cursor() method
183
        cursor = conn.cursor()
184
        # Execute the SQL command
185
        # Fetch source id.
186
        cursor.execute(selectSql)
187
        result = cursor.fetchall()
188
        createXlsReport(result)
189
 
190
    except Exception:
191
        traceback.print_exc()
192
        print "Could not execute query"
193
 
194
def createXlsReport(result):
195
    workbook = xlwt.Workbook()
196
    worksheet = workbook.add_sheet("Shipped Orders")
197
    boldStyle = xlwt.XFStyle()
198
    f = xlwt.Font()
199
    f.bold = True
200
    boldStyle.font = f
201
    column = 0
202
    row = 0
203
 
204
    worksheet.write(row, 0, 'Counter Code', boldStyle)
205
    worksheet.write(row, 1, 'Counter Name', boldStyle)
206
    worksheet.write(row, 2, 'Warehouse', boldStyle)
207
    worksheet.write(row, 3, 'Order Id', boldStyle)
208
    worksheet.write(row, 4, 'Order Date', boldStyle)
209
    worksheet.write(row, 5, 'Shipped Date', boldStyle)
210
    worksheet.write(row, 6, 'Order Status', boldStyle)
211
    worksheet.write(row, 7, 'Expected Delivery Date', boldStyle)
212
    worksheet.write(row, 8, 'Product', boldStyle)
213
    worksheet.write(row, 9, 'Qty', boldStyle)
214
    worksheet.write(row, 10, 'Value', boldStyle)
215
 
216
    for r in result:
217
        row += 1
218
        column = 0
219
        for data in r :
13059 amit.gupta 220
            worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
13020 amit.gupta 221
            column += 1
222
    workbook.save(TMP_FILE)
223
 
224
def getMailAttachmentTertiary():
225
    selectSql = SOLD_OUT_SQL
226
    conn = getDbConnection()
227
    try:
228
        # prepare a cursor object using cursor() method
229
        cursor = conn.cursor()
230
        # Execute the SQL command
231
        # Fetch source id.
232
        cursor.execute(selectSql)
233
        result = cursor.fetchall()
234
        workbook = xlwt.Workbook()
235
        worksheet = workbook.add_sheet("Tertiary Report")
236
        boldStyle = xlwt.XFStyle()
237
        f = xlwt.Font()
238
        f.bold = True
239
        boldStyle.font = f
240
        column = 0
241
        row = 0
242
 
243
        worksheet.write(row, 0, 'Counter Code', boldStyle)
244
        worksheet.write(row, 1, 'Counter Name', boldStyle)
245
        worksheet.write(row, 2, 'Order Id', boldStyle)
246
        worksheet.write(row, 3, 'Order Date', boldStyle)
247
        worksheet.write(row, 4, 'Delivered Date', boldStyle)
248
        worksheet.write(row, 5, 'Activated Timestamp', boldStyle)
249
        worksheet.write(row, 6, 'Product', boldStyle)
250
        worksheet.write(row, 7, 'Qty', boldStyle)
251
        worksheet.write(row, 8, 'Value', boldStyle)
252
 
253
        for r in result:
254
            row += 1
255
            column = 0
256
            for data in r :
13060 amit.gupta 257
                worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else datetime_format if type(data) is datetime.datetime else default_format)
13020 amit.gupta 258
                column += 1
259
        workbook.save(TMP_FILE)
260
 
261
    except Exception:
262
        traceback.print_exc()
263
        print "Could not execute query"
264
 
265
def getMailAttachmentPending():
266
    selectSql = PENDING_ORDER_SQL
267
    conn = getDbConnection()
268
    try:
269
        # prepare a cursor object using cursor() method
270
        cursor = conn.cursor()
271
        # Execute the SQL command
272
        # Fetch source id.
273
        cursor.execute(selectSql)
274
        result = cursor.fetchall()
275
        workbook = xlwt.Workbook()
276
        worksheet = workbook.add_sheet("Pending Orders")
277
        boldStyle = xlwt.XFStyle()
278
        f = xlwt.Font()
279
        f.bold = True
280
        boldStyle.font = f
281
        column = 0
282
        row = 0
283
 
284
        worksheet.write(row, 0, 'Counter Code', boldStyle)
285
        worksheet.write(row, 1, 'Counter Name', boldStyle)
286
        worksheet.write(row, 2, 'Warehouse', boldStyle)
287
        worksheet.write(row, 3, 'Order Id', boldStyle)
288
        worksheet.write(row, 4, 'Order Date', boldStyle)
289
        worksheet.write(row, 5, 'Shipped Date', boldStyle)
290
        worksheet.write(row, 6, 'Order Status', boldStyle)
291
        worksheet.write(row, 7, 'Expected Delivery Date', boldStyle)
292
        worksheet.write(row, 8, 'Product', boldStyle)
293
        worksheet.write(row, 9, 'Qty', boldStyle)
294
        worksheet.write(row, 10, 'Value', boldStyle)
295
 
296
        for r in result:
297
            row += 1
298
            column = 0
299
            for data in r :
300
                worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
301
                column += 1
302
        workbook.save(TMP_FILE)
303
 
304
    except Exception:
305
            traceback.print_exc()
306
            print "Could not execute query"
307
 
308
def getMailAttachmenAgeing():
309
    selectSql = STOCK_REPORT_SQL
310
    conn = getDbConnection()
311
    try:
312
        # prepare a cursor object using cursor() method
313
        cursor = conn.cursor()
314
        # Execute the SQL command
315
        # Fetch source id.
316
        cursor.execute(selectSql)
317
        result = cursor.fetchall()
318
        workbook = xlwt.Workbook()
13060 amit.gupta 319
        worksheet = workbook.add_sheet("Stock Aeging Orders")
13020 amit.gupta 320
        boldStyle = xlwt.XFStyle()
321
        f = xlwt.Font()
322
        f.bold = True
323
        boldStyle.font = f
324
        column = 0
325
        row = 0
326
 
327
        worksheet.write(row, 0, 'Counter Code', boldStyle)
328
        worksheet.write(row, 1, 'Counter Name', boldStyle)
329
        worksheet.write(row, 2, 'Order Id', boldStyle)
330
        worksheet.write(row, 3, 'Order Date', boldStyle)
331
        worksheet.write(row, 4, 'Delivered Date', boldStyle)
332
        worksheet.write(row, 5, 'Order Status', boldStyle)
333
        worksheet.write(row, 6, 'Product', boldStyle)
334
        worksheet.write(row, 7, 'Qty', boldStyle)
335
        worksheet.write(row, 8, 'Value', boldStyle)
336
        worksheet.write(row, 9, 'Ageing(Days)', boldStyle)
337
 
338
        for r in result:
339
            row += 1
340
            column = 0
341
            for data in r :
342
                worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
343
                column += 1
344
        workbook.save(TMP_FILE)
345
    except Exception:
346
        traceback.print_exc()
347
        print "Could not execute query"
348
 
349
def sendShippedReport():
350
    mailbody = getMailBody(report_map['shipped'])
351
    getMailAttachmentShipped()
352
    sendmail(recipients, mailbody, 'dtrshipped_report.xls', 'DTR Shipped Product Report')
353
 
354
def sendTertiaryReport():
355
    mailbody = getMailBody(report_map['tertiary'])
356
    getMailAttachmentTertiary()
357
    sendmail(recipients, mailbody, 'dtrtertiary_report.xls', 'DTR Tertiary Report')
358
 
359
def sendPendingReport():
360
    mailbody = getMailBody(report_map['pending'])
361
    getMailAttachmentPending()
362
    sendmail(recipients, mailbody, 'dtrpending_report.xls', 'DTR Pending Orders Report')
363
 
364
def getSpiceStockAgeingReport():
365
    mailbody = getMailBody(report_map['ageing'])
366
    getMailAttachmenAgeing()
367
    sendmail(recipients, mailbody, 'dtrstockageing_report.xls', 'DTR Spice Stock Ageing Report')
368
 
369
def getMisReport():
370
    mailbody = getMailBody(report_map['mis'])
371
    getMailAttachmentMis()
372
    sendmail(recipients, mailbody, 'dtrcountersale_report.xls', 'DTR Counterwise Sales Report')
373
 
374
def getMailBody(reportmap):
375
    conn = getDbConnection()
376
    mailBodyTemplate="""
377
    <html>
378
        <body>
379
        <table cellspacing="0" border="1" style="text-align:right">
380
            <thead>
381
                <tr>
382
                    <th colspan="{4}" style="text-align:center">{2}</th>
383
                    <th colspan="{5}" style="text-align:center">Total Amount - {0}</th>
384
                </tr>
385
                <tr>
386
                    {3}
387
                </tr>
388
            </thead>
389
            <tbody>
390
                {1}
391
            </tbody>
392
        </table>
393
        </body>
394
    </html>
395
    """
396
    try:
397
        # prepare a cursor object using cursor() method
398
        cursor = conn.cursor()
399
        # Execute the SQL command
400
        # Fetch source id.
401
        cursor.execute(reportmap['query'])
402
        result = cursor.fetchall()
403
        grandTotal = 0
404
        tbody=[]
405
        headerLen = len(reportmap['headers'])
406
        for rowindex in range(-1, len(result)-1):
407
            row = result[rowindex]
408
            nullColumn = -1
409
            tag="<td>"
410
            closeTag="</td>"
411
            for grColumn in range(0, reportmap['group']):
412
                if row[grColumn] is None:
413
                    tag="""<th text-align="right">"""
414
                    closeTag="</th>"
415
                    nullColumn = grColumn
416
                    break
417
 
418
            tbody.append("<tr>")
419
 
420
            for column in range(0, headerLen):      
421
                tbody.append(tag)
422
                if nullColumn==column:
423
                    if nullColumn==0:
424
                        tbody.append('Grand Total')
425
                        grandTotal = row[headerLen-1]
426
                    else:
427
                        tbody.append('Sub Total')
428
                elif row[column] is None:
429
                        tbody.append('')
430
                else:
431
                    data = row[column]
432
                    tbody.append(intWithCommas(int(data)) if type(data) is float else (data if data!=0 else '-'))
433
                tbody.append(closeTag)
434
 
435
            tbody.append("</tr>")
436
 
437
        tblbody = ''.join([str(x) for x in tbody])
438
        theader = ''.join(["<th>%s</th>"%header for header in reportmap['headers']])
439
        return mailBodyTemplate.format(intWithCommas(int(grandTotal)), tblbody, reportmap['title'], theader, (headerLen)/2, (headerLen+1)/2)
440
    except:
441
        traceback.print_exc()
442
        print "Could not execute query"
443
    return ""
444
 
445
def getMailAttachmentMis():
446
    selectSql = MIS_REPORT_SQL
447
    conn = getDbConnection()
448
    try:
449
        # prepare a cursor object using cursor() method
450
        cursor = conn.cursor()
451
        # Execute the SQL command
452
        # Fetch source id.
453
        cursor.execute(selectSql)
454
        result = cursor.fetchall()
455
        workbook = xlwt.Workbook()
456
        worksheet = workbook.add_sheet("Last Day Sale Report")
457
        worksheet1 = workbook.add_sheet("MTD Sale Report")
458
        boldStyle = xlwt.XFStyle()
459
        f = xlwt.Font()
460
        f.bold = True
461
        boldStyle.font = f
462
        column = 0
463
        row = 0
464
 
465
        worksheet.write(row, 0, 'Counter Code', boldStyle)
466
        worksheet.write(row, 1, 'Counter Name', boldStyle)
467
        worksheet.write(row, 2, 'Warehouse', boldStyle)
468
        worksheet.write(row, 3, 'Order Id', boldStyle)
469
        worksheet.write(row, 4, 'Order Date', boldStyle)
470
        worksheet.write(row, 5, 'Order Status', boldStyle)
471
        worksheet.write(row, 6, 'Activation Date', boldStyle)
472
        worksheet.write(row, 7, 'Product', boldStyle)
473
        worksheet.write(row, 8, 'Qty', boldStyle)
474
        worksheet.write(row, 9, 'Value', boldStyle)
475
 
476
        worksheet1.write(row, 0, 'Counter Code', boldStyle)
477
        worksheet1.write(row, 1, 'Counter Name', boldStyle)
478
        worksheet1.write(row, 2, 'Warehouse', boldStyle)
479
        worksheet1.write(row, 3, 'Order Id', boldStyle)
480
        worksheet1.write(row, 4, 'Order Date', boldStyle)
481
        worksheet1.write(row, 5, 'Order Status', boldStyle)
482
        worksheet1.write(row, 6, 'Activation Date', boldStyle)
483
        worksheet1.write(row, 7, 'Product', boldStyle)
484
        worksheet1.write(row, 8, 'Qty', boldStyle)
485
        worksheet1.write(row, 9, 'Value', boldStyle)
486
 
487
        yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
488
        for r in result:
489
            row += 1
490
            column = 0
491
            for data in r :
492
                if data is not None:
493
                    if r[4] == yesterday:
494
                        worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
495
                    worksheet1.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
496
                column += 1
497
        workbook.save(TMP_FILE)
498
    except Exception:
499
        traceback.print_exc()
500
        print "Could not execute query"
501
 
502
 
503
 
504
def main():
505
    sendShippedReport()
506
    #print getMailBody()
507
    sendTertiaryReport()
508
    sendPendingReport()
509
    getSpiceStockAgeingReport()
510
    getMisReport()
511
 
512
def intWithCommas(x):
513
    if type(x) not in [type(0), type(0L)]:
514
        raise TypeError("Parameter must be an integer.")
515
    if x==0:
516
        return '-'
517
    if x < 0:
518
        return '-' + intWithCommas(-x)
519
    result = ''
520
    while x >= 1000:
521
        x, r = divmod(x, 1000)
522
        result = ",%03d%s" % (r, result)
523
    return "%d%s" % (x, result)
524
 
525
 
526
if __name__ == '__main__':
527
    main()