Subversion Repositories SmartDukaan

Rev

Rev 13020 | Rev 13022 | 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
 
116
number_format = xlwt.XFStyle()
117
number_format.num_format_str = '#,##0'
118
 
119
 
120
 
121
 
122
valueformat = "{0:,.0f}"
123
 
124
default_format = xlwt.XFStyle()
125
 
126
shipped_headers=['Counter', 'Product', 'Quantity', 'Value']
127
tertiary_headers=shipped_headers
128
pending_headers=shipped_headers
129
ageing_headers=['Counter','Product','QtyDelivered','QtySold','QtyInStock','ValueInStock']
130
mis_headers=['Counter','Last Day Qty', 'Last Day Value','MTD Qty', 'MTD Value']
131
 
132
report_map['shipped'] = {'title':'Shipped Orders Report', 'query' : SHIPPED_ORDER_GROUP_SQL, 'group':2, 'headers':shipped_headers}
133
report_map['tertiary'] = {'title':'Tertiary Report', 'query' : SOLD_OUT_GROUP_SQL, 'group':2, 'headers':tertiary_headers}
134
report_map['pending'] = {'title':'Pending Orders Report', 'query' : PENDING_ORDER_GROUP_SQL, 'group':2, 'headers':pending_headers}
135
report_map['ageing'] = {'title':'Spice Stock Ageing Report', 'query' : STOCK_REPORT_GROUP_SQL, 'group':2, 'headers':ageing_headers}
136
report_map['mis'] = {'title':'Daily Counter wise Sales Report', 'query' : MIS_REPORT_GROUP_SQL, 'group':1, 'headers':mis_headers}
137
 
138
#recipients = []
139
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']
140
 
141
 
142
def getDbConnection():
143
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
144
 
145
def closeConnection(conn):
146
    conn.close()
147
 
148
 
149
 
150
def sendmail(email, message, fileName, title):
151
    if email == "":
152
        return
153
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
154
    mailServer.ehlo()
155
    mailServer.starttls()
156
    mailServer.ehlo()
157
 
158
    # Create the container (outer) email message.
159
    msg = MIMEMultipart()
160
    msg['Subject'] = title
161
    msg.preamble = title
162
    html_msg = MIMEText(message, 'html')
163
    msg.attach(html_msg)
164
 
165
    fileMsg = MIMEBase('application','vnd.ms-excel')
166
    fileMsg.set_payload(file(TMP_FILE).read())
167
    encoders.encode_base64(fileMsg)
168
    fileMsg.add_header('Content-Disposition','attachment;filename=' + fileName)
169
    msg.attach(fileMsg)
13021 amit.gupta 170
    email = email.append('amit.gupta@shop2020.in')
171
    MAILTO = email 
13020 amit.gupta 172
    mailServer.login(SENDER, PASSWORD)
173
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
174
 
175
def getMailAttachmentShipped():
176
    selectSql = SHIPPED_ORDER_SQL
177
    conn = getDbConnection()
178
    try:
179
        # prepare a cursor object using cursor() method
180
        cursor = conn.cursor()
181
        # Execute the SQL command
182
        # Fetch source id.
183
        cursor.execute(selectSql)
184
        result = cursor.fetchall()
185
        createXlsReport(result)
186
 
187
    except Exception:
188
        traceback.print_exc()
189
        print "Could not execute query"
190
 
191
def createXlsReport(result):
192
    workbook = xlwt.Workbook()
193
    worksheet = workbook.add_sheet("Shipped Orders")
194
    boldStyle = xlwt.XFStyle()
195
    f = xlwt.Font()
196
    f.bold = True
197
    boldStyle.font = f
198
    column = 0
199
    row = 0
200
 
201
    worksheet.write(row, 0, 'Counter Code', boldStyle)
202
    worksheet.write(row, 1, 'Counter Name', boldStyle)
203
    worksheet.write(row, 2, 'Warehouse', boldStyle)
204
    worksheet.write(row, 3, 'Order Id', boldStyle)
205
    worksheet.write(row, 4, 'Order Date', boldStyle)
206
    worksheet.write(row, 5, 'Shipped Date', boldStyle)
207
    worksheet.write(row, 6, 'Order Status', boldStyle)
208
    worksheet.write(row, 7, 'Expected Delivery Date', boldStyle)
209
    worksheet.write(row, 8, 'Product', boldStyle)
210
    worksheet.write(row, 9, 'Qty', boldStyle)
211
    worksheet.write(row, 10, 'Value', boldStyle)
212
 
213
    for r in result:
214
        row += 1
215
        column = 0
216
        for data in r :
217
            worksheet.write(row, column, str(int(data) if type(data) is float else data), date_format if type(data) is datetime.date else default_format)
218
            column += 1
219
    workbook.save(TMP_FILE)
220
 
221
def getMailAttachmentTertiary():
222
    selectSql = SOLD_OUT_SQL
223
    conn = getDbConnection()
224
    try:
225
        # prepare a cursor object using cursor() method
226
        cursor = conn.cursor()
227
        # Execute the SQL command
228
        # Fetch source id.
229
        cursor.execute(selectSql)
230
        result = cursor.fetchall()
231
        workbook = xlwt.Workbook()
232
        worksheet = workbook.add_sheet("Tertiary Report")
233
        boldStyle = xlwt.XFStyle()
234
        f = xlwt.Font()
235
        f.bold = True
236
        boldStyle.font = f
237
        column = 0
238
        row = 0
239
 
240
        worksheet.write(row, 0, 'Counter Code', boldStyle)
241
        worksheet.write(row, 1, 'Counter Name', boldStyle)
242
        worksheet.write(row, 2, 'Order Id', boldStyle)
243
        worksheet.write(row, 3, 'Order Date', boldStyle)
244
        worksheet.write(row, 4, 'Delivered Date', boldStyle)
245
        worksheet.write(row, 5, 'Activated Timestamp', boldStyle)
246
        worksheet.write(row, 6, 'Product', boldStyle)
247
        worksheet.write(row, 7, 'Qty', boldStyle)
248
        worksheet.write(row, 8, 'Value', boldStyle)
249
 
250
        for r in result:
251
            row += 1
252
            column = 0
253
            for data in r :
254
                worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
255
                column += 1
256
        workbook.save(TMP_FILE)
257
 
258
    except Exception:
259
        traceback.print_exc()
260
        print "Could not execute query"
261
 
262
def getMailAttachmentPending():
263
    selectSql = PENDING_ORDER_SQL
264
    conn = getDbConnection()
265
    try:
266
        # prepare a cursor object using cursor() method
267
        cursor = conn.cursor()
268
        # Execute the SQL command
269
        # Fetch source id.
270
        cursor.execute(selectSql)
271
        result = cursor.fetchall()
272
        workbook = xlwt.Workbook()
273
        worksheet = workbook.add_sheet("Pending Orders")
274
        boldStyle = xlwt.XFStyle()
275
        f = xlwt.Font()
276
        f.bold = True
277
        boldStyle.font = f
278
        column = 0
279
        row = 0
280
 
281
        worksheet.write(row, 0, 'Counter Code', boldStyle)
282
        worksheet.write(row, 1, 'Counter Name', boldStyle)
283
        worksheet.write(row, 2, 'Warehouse', boldStyle)
284
        worksheet.write(row, 3, 'Order Id', boldStyle)
285
        worksheet.write(row, 4, 'Order Date', boldStyle)
286
        worksheet.write(row, 5, 'Shipped Date', boldStyle)
287
        worksheet.write(row, 6, 'Order Status', boldStyle)
288
        worksheet.write(row, 7, 'Expected Delivery Date', boldStyle)
289
        worksheet.write(row, 8, 'Product', boldStyle)
290
        worksheet.write(row, 9, 'Qty', boldStyle)
291
        worksheet.write(row, 10, 'Value', boldStyle)
292
 
293
        for r in result:
294
            row += 1
295
            column = 0
296
            for data in r :
297
                worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
298
                column += 1
299
        workbook.save(TMP_FILE)
300
 
301
    except Exception:
302
            traceback.print_exc()
303
            print "Could not execute query"
304
 
305
def getMailAttachmenAgeing():
306
    selectSql = STOCK_REPORT_SQL
307
    conn = getDbConnection()
308
    try:
309
        # prepare a cursor object using cursor() method
310
        cursor = conn.cursor()
311
        # Execute the SQL command
312
        # Fetch source id.
313
        cursor.execute(selectSql)
314
        result = cursor.fetchall()
315
        workbook = xlwt.Workbook()
316
        worksheet = workbook.add_sheet("Pending Orders")
317
        boldStyle = xlwt.XFStyle()
318
        f = xlwt.Font()
319
        f.bold = True
320
        boldStyle.font = f
321
        column = 0
322
        row = 0
323
 
324
        worksheet.write(row, 0, 'Counter Code', boldStyle)
325
        worksheet.write(row, 1, 'Counter Name', boldStyle)
326
        worksheet.write(row, 2, 'Order Id', boldStyle)
327
        worksheet.write(row, 3, 'Order Date', boldStyle)
328
        worksheet.write(row, 4, 'Delivered Date', boldStyle)
329
        worksheet.write(row, 5, 'Order Status', boldStyle)
330
        worksheet.write(row, 6, 'Product', boldStyle)
331
        worksheet.write(row, 7, 'Qty', boldStyle)
332
        worksheet.write(row, 8, 'Value', boldStyle)
333
        worksheet.write(row, 9, 'Ageing(Days)', boldStyle)
334
 
335
        for r in result:
336
            row += 1
337
            column = 0
338
            for data in r :
339
                worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
340
                column += 1
341
        workbook.save(TMP_FILE)
342
    except Exception:
343
        traceback.print_exc()
344
        print "Could not execute query"
345
 
346
def sendShippedReport():
347
    mailbody = getMailBody(report_map['shipped'])
348
    getMailAttachmentShipped()
349
    sendmail(recipients, mailbody, 'dtrshipped_report.xls', 'DTR Shipped Product Report')
350
 
351
def sendTertiaryReport():
352
    mailbody = getMailBody(report_map['tertiary'])
353
    getMailAttachmentTertiary()
354
    sendmail(recipients, mailbody, 'dtrtertiary_report.xls', 'DTR Tertiary Report')
355
 
356
def sendPendingReport():
357
    mailbody = getMailBody(report_map['pending'])
358
    getMailAttachmentPending()
359
    sendmail(recipients, mailbody, 'dtrpending_report.xls', 'DTR Pending Orders Report')
360
 
361
def getSpiceStockAgeingReport():
362
    mailbody = getMailBody(report_map['ageing'])
363
    getMailAttachmenAgeing()
364
    sendmail(recipients, mailbody, 'dtrstockageing_report.xls', 'DTR Spice Stock Ageing Report')
365
 
366
def getMisReport():
367
    mailbody = getMailBody(report_map['mis'])
368
    getMailAttachmentMis()
369
    sendmail(recipients, mailbody, 'dtrcountersale_report.xls', 'DTR Counterwise Sales Report')
370
 
371
def getMailBody(reportmap):
372
    conn = getDbConnection()
373
    mailBodyTemplate="""
374
    <html>
375
        <body>
376
        <table cellspacing="0" border="1" style="text-align:right">
377
            <thead>
378
                <tr>
379
                    <th colspan="{4}" style="text-align:center">{2}</th>
380
                    <th colspan="{5}" style="text-align:center">Total Amount - {0}</th>
381
                </tr>
382
                <tr>
383
                    {3}
384
                </tr>
385
            </thead>
386
            <tbody>
387
                {1}
388
            </tbody>
389
        </table>
390
        </body>
391
    </html>
392
    """
393
    try:
394
        # prepare a cursor object using cursor() method
395
        cursor = conn.cursor()
396
        # Execute the SQL command
397
        # Fetch source id.
398
        cursor.execute(reportmap['query'])
399
        result = cursor.fetchall()
400
        grandTotal = 0
401
        tbody=[]
402
        headerLen = len(reportmap['headers'])
403
        for rowindex in range(-1, len(result)-1):
404
            row = result[rowindex]
405
            nullColumn = -1
406
            tag="<td>"
407
            closeTag="</td>"
408
            for grColumn in range(0, reportmap['group']):
409
                if row[grColumn] is None:
410
                    tag="""<th text-align="right">"""
411
                    closeTag="</th>"
412
                    nullColumn = grColumn
413
                    break
414
 
415
            tbody.append("<tr>")
416
 
417
            for column in range(0, headerLen):      
418
                tbody.append(tag)
419
                if nullColumn==column:
420
                    if nullColumn==0:
421
                        tbody.append('Grand Total')
422
                        grandTotal = row[headerLen-1]
423
                    else:
424
                        tbody.append('Sub Total')
425
                elif row[column] is None:
426
                        tbody.append('')
427
                else:
428
                    data = row[column]
429
                    tbody.append(intWithCommas(int(data)) if type(data) is float else (data if data!=0 else '-'))
430
                tbody.append(closeTag)
431
 
432
            tbody.append("</tr>")
433
 
434
        tblbody = ''.join([str(x) for x in tbody])
435
        theader = ''.join(["<th>%s</th>"%header for header in reportmap['headers']])
436
        return mailBodyTemplate.format(intWithCommas(int(grandTotal)), tblbody, reportmap['title'], theader, (headerLen)/2, (headerLen+1)/2)
437
    except:
438
        traceback.print_exc()
439
        print "Could not execute query"
440
    return ""
441
 
442
def getMailAttachmentMis():
443
    selectSql = MIS_REPORT_SQL
444
    conn = getDbConnection()
445
    try:
446
        # prepare a cursor object using cursor() method
447
        cursor = conn.cursor()
448
        # Execute the SQL command
449
        # Fetch source id.
450
        cursor.execute(selectSql)
451
        result = cursor.fetchall()
452
        workbook = xlwt.Workbook()
453
        worksheet = workbook.add_sheet("Last Day Sale Report")
454
        worksheet1 = workbook.add_sheet("MTD Sale Report")
455
        boldStyle = xlwt.XFStyle()
456
        f = xlwt.Font()
457
        f.bold = True
458
        boldStyle.font = f
459
        column = 0
460
        row = 0
461
 
462
        worksheet.write(row, 0, 'Counter Code', boldStyle)
463
        worksheet.write(row, 1, 'Counter Name', boldStyle)
464
        worksheet.write(row, 2, 'Warehouse', boldStyle)
465
        worksheet.write(row, 3, 'Order Id', boldStyle)
466
        worksheet.write(row, 4, 'Order Date', boldStyle)
467
        worksheet.write(row, 5, 'Order Status', boldStyle)
468
        worksheet.write(row, 6, 'Activation Date', boldStyle)
469
        worksheet.write(row, 7, 'Product', boldStyle)
470
        worksheet.write(row, 8, 'Qty', boldStyle)
471
        worksheet.write(row, 9, 'Value', boldStyle)
472
 
473
        worksheet1.write(row, 0, 'Counter Code', boldStyle)
474
        worksheet1.write(row, 1, 'Counter Name', boldStyle)
475
        worksheet1.write(row, 2, 'Warehouse', boldStyle)
476
        worksheet1.write(row, 3, 'Order Id', boldStyle)
477
        worksheet1.write(row, 4, 'Order Date', boldStyle)
478
        worksheet1.write(row, 5, 'Order Status', boldStyle)
479
        worksheet1.write(row, 6, 'Activation Date', boldStyle)
480
        worksheet1.write(row, 7, 'Product', boldStyle)
481
        worksheet1.write(row, 8, 'Qty', boldStyle)
482
        worksheet1.write(row, 9, 'Value', boldStyle)
483
 
484
        yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
485
        for r in result:
486
            row += 1
487
            column = 0
488
            for data in r :
489
                if data is not None:
490
                    if r[4] == yesterday:
491
                        worksheet.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
492
                    worksheet1.write(row, column, int(data) if type(data) is float else data, date_format if type(data) is datetime.date else default_format)
493
                column += 1
494
        workbook.save(TMP_FILE)
495
    except Exception:
496
        traceback.print_exc()
497
        print "Could not execute query"
498
 
499
 
500
 
501
def main():
502
    sendShippedReport()
503
    #print getMailBody()
504
    sendTertiaryReport()
505
    sendPendingReport()
506
    getSpiceStockAgeingReport()
507
    getMisReport()
508
 
509
def intWithCommas(x):
510
    if type(x) not in [type(0), type(0L)]:
511
        raise TypeError("Parameter must be an integer.")
512
    if x==0:
513
        return '-'
514
    if x < 0:
515
        return '-' + intWithCommas(-x)
516
    result = ''
517
    while x >= 1000:
518
        x, r = divmod(x, 1000)
519
        result = ",%03d%s" % (r, result)
520
    return "%d%s" % (x, result)
521
 
522
 
523
if __name__ == '__main__':
524
    main()