Rev 7717 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
'''Created on 08-Jul-2013@author: anupam'''import jsonimport urllib2, cookielibimport MySQLdbimport datetimeimport sysimport smtplibimport xlwtfrom 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 = "localhost"DB_USER = "root"DB_PASSWORD = "shop2020"DB_NAME = "sales"# KEY NAMESMONTHNAME = 'monthname'DATES = 'dates'MAILTO = ['anupam.singh@shop2020.in']SENDER = "cnc.center@shop2020.in"PASSWORD = "5h0p2o2o"SUBJECT = "Recharge report for week ending on " + datetime.datetime.today()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"""column = 0grossTotal = 0grossQuantity = 0clusterData = []currentEmail = ""for r in result:msg = '<tr><td colspan="1"><b>Total</b></td><td>======QuantityToBeReplaced======</td><td>======ValueToBeReplaced======</td></tr><tr>'for data in r:if column == 0:if currentEmail != data:createXlsReport(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)currentEmail = dataif column == 2 :grossQuantity += dataif column == 3 :grossTotal += datamsg = msg + '<td>' + str(data) + '</td>'column += 1clusterData.append(r)column = 0createXlsReport(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 "Error: unable to fetch data"print ereturn msg, resultdef createXlsReport(result):workbook = 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 result:#(parent, category, brand, model_name, model_number, color) = r[0:6]#dayofmonth = r[8]for data in r :if column == 1 :grossQuantity += dataif column == 2 :grossTotal += dataworksheet.write(row, column, str(data))column += 1column = 0row += 1worksheet.write_merge(1, 1, 'Total')worksheet.write(1, 2, str(grossQuantity), boldStyle)worksheet.write(1, 3, str(grossTotal), boldStyle)workbook.save(TMP_FILE)def sendmail(email, message):mailServer = 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)mailServer.login(SENDER, PASSWORD)mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())def main():message, result = getProductSaleData()createXlsReport(result)sendmail(message)if __name__ == '__main__':main()