Subversion Repositories SmartDukaan

Rev

Rev 7717 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7713 anupam.sin 1
'''
2
Created on 08-Jul-2013
3
 
4
@author: anupam
5
'''
6
 
7
import json
8
import urllib2, cookielib
9
import MySQLdb
10
import datetime
11
import sys
12
import smtplib
13
import xlwt
14
 
15
from email import encoders
16
from email.mime.text import MIMEText
17
from email.mime.base import MIMEBase
18
from email.mime.multipart import MIMEMultipart
19
#from pyExcelerator import Workbook, Font, XFStyle
20
from datetime import date
21
 
22
# Initialize db connection settings.
23
DB_HOST = "localhost"
24
DB_USER = "root"
25
DB_PASSWORD = "shop2020"
26
DB_NAME = "sales"
27
 
28
# KEY NAMES
29
MONTHNAME = 'monthname'
30
DATES = 'dates'
31
 
32
MAILTO = ['anupam.singh@shop2020.in']
33
SENDER = "cnc.center@shop2020.in"
34
PASSWORD = "5h0p2o2o"
35
SUBJECT = "Recharge report for week ending on " + datetime.datetime.today()
36
SMTP_SERVER = "smtp.gmail.com"
37
SMTP_PORT = 587    
38
 
39
TMP_FILE="/tmp/recharge_report.xls"
40
 
41
def getDbConnection():
42
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
43
 
44
def closeConnection(conn):
45
    conn.close()
46
 
47
def getProductSaleData():
48
    selectSql = '''SELECT clusterEmail, s.name, COUNT(*) AS TransactionCount, SUM(amount) AS Amount 
49
                   FROM rechargetransaction r 
50
                   JOIN hotspotstore h ON h.id = r.storeId 
51
                   JOIN serviceprovider s ON s.id = r.operatorId 
52
                   WHERE transactionTime BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE() AND r.status = 5 
53
                   GROUP BY clusterEmail, operatorId;
54
                '''
55
    conn = getDbConnection()
56
    try:
57
        # prepare a cursor object using cursor() method
58
        cursor = conn.cursor()
59
        # Execute the SQL command
60
        # Fetch source id.
61
        cursor.execute(selectSql)
62
        result = cursor.fetchall()
63
        msg =   """\
64
                    <html>
65
                    <body>\n<table border="1">
66
                    \n<thead>\n
67
                    <th>Operator</th>\n
68
                    <th>Count</th>\n
69
                    <th>Amount</th>\n
70
                    </thead>\n
71
                """ 
72
        column = 0
73
        grossTotal = 0
74
        grossQuantity = 0
75
        clusterData = []
76
        currentEmail = ""
77
        for r in result:
78
            msg = '<tr><td colspan="1"><b>Total</b></td><td>======QuantityToBeReplaced======</td><td>======ValueToBeReplaced======</td></tr><tr>'
79
            for data in r:
80
                if column == 0:
81
                    if currentEmail != data:
82
                        createXlsReport(clusterData)
83
                        msg = msg + '</table>\n</body>\n</html>'
84
                        msg = msg.replace('======QuantityToBeReplaced======', str(grossQuantity))
85
                        msg = msg.replace('======ValueToBeReplaced======', str(grossTotal))
86
                        grossQuantity = 0
87
                        grossTotal = 0
88
                        sendmail(currentEmail, msg)
89
                        currentEmail = data
90
 
91
                if column == 2 :
92
                    grossQuantity += data
93
                if column == 3 :
94
                    grossTotal += data
95
                msg = msg + '<td>' + str(data) + '</td>'
96
                column += 1
97
            clusterData.append(r)
98
            column = 0
99
 
100
        createXlsReport(clusterData)
101
        msg = msg + '</table>\n</body>\n</html>'
102
        msg = msg.replace('======QuantityToBeReplaced======', str(grossQuantity))
103
        msg = msg.replace('======ValueToBeReplaced======', str(grossTotal))
104
        grossQuantity = 0
105
        grossTotal = 0
106
        sendmail(currentEmail, msg)
107
    except Exception as e:
108
        print "Error: unable to fetch data"
109
        print e
110
 
111
    return msg, result
112
 
113
def createXlsReport(result):
114
    workbook = xlwt.Workbook()
115
    worksheet = workbook.add_sheet("ClusterReport")
116
    boldStyle = xlwt.XFStyle()
117
    f = xlwt.Font()
118
    f.bold = True
119
    boldStyle.font = f
120
    column = 0
121
    row = 0
122
 
123
    worksheet.write(row, 0, 'Operator', boldStyle)
124
    worksheet.write(row, 1, 'Count', boldStyle)
125
    worksheet.write(row, 2, 'Amount', boldStyle)
126
    row = 2
127
    grossTotal = 0
128
    grossQuantity = 0
129
 
130
    for r in result:
131
        #(parent, category, brand, model_name, model_number, color) = r[0:6]
132
        #dayofmonth = r[8]
133
        for data in r :
134
            if column == 1 :
135
                grossQuantity += data
136
            if column == 2 :
137
                grossTotal += data
138
            worksheet.write(row, column, str(data))
139
            column += 1
140
        column = 0
141
        row += 1
142
 
143
    worksheet.write_merge(1, 1, 'Total')
144
    worksheet.write(1, 2, str(grossQuantity), boldStyle)
145
    worksheet.write(1, 3, str(grossTotal), boldStyle)
146
    workbook.save(TMP_FILE)
147
 
148
def sendmail(email, message):
149
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
150
    mailServer.ehlo()
151
    mailServer.starttls()
152
    mailServer.ehlo()
153
 
154
    # Create the container (outer) email message.
155
    msg = MIMEMultipart()
156
    msg['Subject'] = SUBJECT + ' for ' + email
157
    msg['From'] = "ClusterWiseReport@saholic.com"
158
    msg['To'] = 'cluster-heads@saholic.com'
159
    msg.preamble = SUBJECT + ' for ' + email
160
    html_msg = MIMEText(message, 'html')
161
    msg.attach(html_msg)
162
 
163
    fileMsg = MIMEBase('application','vnd.ms-excel')
164
    fileMsg.set_payload(file(TMP_FILE).read())
165
    encoders.encode_base64(fileMsg)
166
    fileMsg.add_header('Content-Disposition','attachment;filename=recharge-report-for-week-ending-on-' + date.today().isoformat() + '.xls')
167
    msg.attach(fileMsg)
168
 
169
    mailServer.login(SENDER, PASSWORD)
170
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
171
 
172
def main():
173
    message, result = getProductSaleData()
174
    createXlsReport(result)
175
    sendmail(message)
176
 
177
if __name__ == '__main__':
178
    main()