Subversion Repositories SmartDukaan

Rev

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