Subversion Repositories SmartDukaan

Rev

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