Rev 10298 | Blame | Compare with Previous | Last modification | View Log | RSS feed
'''Created on 08-Jul-2013@author: anupam'''import MySQLdbimport datetimeimport smtplibimport xlwtimport tracebackfrom email import encodersfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipart#from pyExcelerator import Workbook, Font, XFStylefrom datetime import date# Initialize db connection settings.DB_HOST = "192.168.190.114"DB_USER = "root"DB_PASSWORD = "shop2020"DB_NAME = "transaction"# KEY NAMESSENDER = "cnc.center@shop2020.in"PASSWORD = "5h0p2o2o"SUBJECT = "Recharge report for week ending on " + date.today().isoformat()SMTP_SERVER = "smtp.gmail.com"SMTP_PORT = 587TMP_FILE="/tmp/recharge_report.xls"def getDbConnection():return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)def closeConnection(conn):conn.close()def getProductSaleData():selectSql = '''SELECT clusterEmail, s.name, COUNT(*) AS TransactionCount, SUM(amount) AS AmountFROM rechargetransaction rJOIN hotspotstore h ON h.id = r.storeIdJOIN serviceprovider s ON s.id = r.operatorIdWHERE transactionTime BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE() AND r.status = 5GROUP BY clusterEmail, operatorId;'''conn = getDbConnection()try:# prepare a cursor object using cursor() methodcursor = conn.cursor()# Execute the SQL command# Fetch source id.cursor.execute(selectSql)result = cursor.fetchall()msg = """\<html><body>\n<table border="1">\n<thead>\n<th>Operator</th>\n<th>Count</th>\n<th>Amount</th>\n</thead>\n<tr><td colspan="1"><b>Total</b></td><td>======QuantityToBeReplaced======</td><td>======ValueToBeReplaced======</td></tr><tr>"""column = 0grossTotal = 0grossQuantity = 0clusterData = []currentEmail = ""for r in result:for data in r:if column == 0:if currentEmail != data:#if email id has changed then we need to create XLScreateXlsReport(clusterData)#and close the messagemsg = msg + '</tr></table>\n</body>\n</html>'msg = msg.replace('======QuantityToBeReplaced======', str(grossQuantity))msg = msg.replace('======ValueToBeReplaced======', str(grossTotal))#and send the mailsendmail(currentEmail, msg)#Now we reset fieldsgrossQuantity = 0grossTotal = 0clusterData = []currentEmail = datamsg = """\<html><body>\n<table border="1">\n<thead>\n<th>Operator</th>\n<th>Count</th>\n<th>Amount</th>\n</thead>\n<tr><td colspan="1"><b>Total</b></td><td>======QuantityToBeReplaced======</td><td>======ValueToBeReplaced======</td></tr><tr>"""#We need not do anything for this column so we just move oncolumn += 1continueif column == 2 :grossQuantity += dataif column == 3 :grossTotal += datamsg = msg + '<td>' + str(data) + '</td>'column += 1msg = msg + '</tr><tr>'#Append this row to a list which will be used to create a xls sheet per clusterclusterData.append(r)column = 0#After the last row we need to send mail for last clustercreateXlsReport(clusterData)msg = msg + '</table>\n</body>\n</html>'msg = msg.replace('======QuantityToBeReplaced======', str(grossQuantity))msg = msg.replace('======ValueToBeReplaced======', str(grossTotal))grossQuantity = 0grossTotal = 0sendmail(currentEmail, msg)except Exception as e:print etraceback.print_exc()return msg, resultdef createXlsReport(resultSet):if len(resultSet) == 0:returnworkbook = xlwt.Workbook()worksheet = workbook.add_sheet("ClusterReport")boldStyle = xlwt.XFStyle()f = xlwt.Font()f.bold = TrueboldStyle.font = fcolumn = 0row = 0worksheet.write(row, 0, 'Operator', boldStyle)worksheet.write(row, 1, 'Count', boldStyle)worksheet.write(row, 2, 'Amount', boldStyle)row = 2grossTotal = 0grossQuantity = 0for r in resultSet:for data in r :if column == 0:column += 1continueif column == 2 :grossQuantity += int(data)if column == 3 :grossTotal += int(data)worksheet.write(row, column - 1, str(data))column += 1column = 0row += 1worksheet.write(1, 0, 'Total')worksheet.write(1, 1, str(grossQuantity), boldStyle)worksheet.write(1, 2, str(grossTotal), boldStyle)workbook.save(TMP_FILE)def sendmail(email, message):if email == "":returnmailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)mailServer.ehlo()mailServer.starttls()mailServer.ehlo()# Create the container (outer) email message.msg = MIMEMultipart()msg['Subject'] = SUBJECT + ' for ' + emailmsg['From'] = "ClusterWiseReport@saholic.com"msg['To'] = 'cluster-heads@saholic.com'msg.preamble = SUBJECT + ' for ' + emailhtml_msg = MIMEText(message, 'html')msg.attach(html_msg)fileMsg = MIMEBase('application','vnd.ms-excel')fileMsg.set_payload(file(TMP_FILE).read())encoders.encode_base64(fileMsg)fileMsg.add_header('Content-Disposition','attachment;filename=recharge-report-for-week-ending-on-' + date.today().isoformat() + '.xls')msg.attach(fileMsg)MAILTO = [email, 'kshitij.sood@shop2020.in', 'digamber.chauhan@spiceretail.co.in', 'adarsh.verma@spiceretail.co.in']mailServer.login(SENDER, PASSWORD)mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())def main():getProductSaleData()if __name__ == '__main__':main()