Subversion Repositories SmartDukaan

Rev

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