Rev 5265 | Rev 9340 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
#!/usr/bin/pythonimport jsonimport urllib2, cookielibimport MySQLdbimport datetimeimport sysimport smtplibfrom email import encodersfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipartfrom 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 = ['rajneesharora@spiceretail.co.in', 'yukti.jain@spiceretail.co.in', 'sandeep.sachdeva@shop2020.in', 'chaitnaya.vats@shop2020.in', 'anupam.singh@shop2020.in']SENDER = "cnc.center@shop2020.in"PASSWORD = "5h0p2o2o"SUBJECT = "Product Report"SMTP_SERVER = "smtp.gmail.com"SMTP_PORT = 587TMP_FILE="/tmp/product_report.xls"def getDbConnection():return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)def closeConnection(conn):conn.close()def getProductSaleData():selectSql = '''select i.parent_category, i.category, i.brand, IFNULL(i.model_name, ''), IFNULL(i.model_number, ''),i.color, d.monthname, d.monthnumber, d.dayofmonth, sum(quantity) as quantityfrom sales sjoin item i on (i.id = s.item_id)join datedim d on (d.date_id = s.date_id)join orderstatus os on (s.status = os.status)where d.monthnumber in (month(now()), month(now())-1)and d.year in (year(now()))and os.statusGroup in ('In process', 'Delivered', 'Cancelled', 'Return in process', 'Reshipped', 'Refunded')and os.statusSubGroup != 'Cod verification failed'group by i.parent_category, i.category, i.brand, IFNULL(i.model_name, ''),IFNULL(i.model_number, ''), i.color, d.monthname, d.monthnumber, d.dayofmonth'''conn = getDbConnection()monthdatesmap = {}prodsalesmap = {}try:# prepare a cursor object using cursor() methodcursor = conn.cursor()# Execute the SQL command# Fetch source id.cursor.execute(selectSql)result = cursor.fetchall()for r in result:(parent, category, brand, model_name, model_number, color) = r[0:6]monthname, monthnumber = r[6:8]dayofmonth = r[8]if monthdatesmap.has_key(monthnumber):monthmap = monthdatesmap.get(monthnumber)monthmap.get(DATES).add(dayofmonth)else:monthmap = {}monthmap[MONTHNAME] = monthnamedates = set([])dates.add(dayofmonth)monthmap[DATES] = datesmonthdatesmap[monthnumber] = monthmapif prodsalesmap.has_key((parent, category, brand, model_name, model_number, color)):prodsales = prodsalesmap.get((parent, category, brand, model_name, model_number, color))if prodsales.has_key(monthnumber):monthprodsales = prodsales.get(monthnumber)monthprodsales[dayofmonth] = r[9]monthprodsales[0] += r[9]else:monthprodsales = {}monthprodsales[dayofmonth] = r[9]monthprodsales[0] = r[9]prodsales[monthnumber] = monthprodsaleselse:prodsale = {}monthprodsales = {}monthprodsales[dayofmonth] = r[9]monthprodsales[0] = r[9]prodsale[monthnumber] = monthprodsalesprodsalesmap[(parent, category, brand, model_name, model_number, color)] = prodsaleexcept Exception as e:print "Error: unable to fetch data"print ereturn monthdatesmap, prodsalesmapdef createXlsReport(monthdatesmap, prodsalesmap):workbook = Workbook()worksheet = workbook.add_sheet("Sheet 1")boldStyle = XFStyle()f = Font()f.bold = TrueboldStyle.font = fdatecolmap = {}col = 6for monthnumber in monthdatesmap.keys():monthname = monthdatesmap[monthnumber][MONTHNAME]worksheet.write(0, col, monthname, boldStyle)worksheet.write(1, col, 'Month', boldStyle)datemap ={}datemap[0] = coldatecolmap[monthnumber] = datemapcol += 1worksheet.write(1, 0, 'Category', boldStyle)worksheet.write(1, 1, 'Sub Category', boldStyle)worksheet.write(1, 2, 'Brand', boldStyle)worksheet.write(1, 3, 'Model Name', boldStyle)worksheet.write(1, 4, 'Model Number', boldStyle)worksheet.write(1, 5, 'Color', boldStyle)for dayofmonth in monthdatesmap[monthnumber][DATES]:worksheet.write(1, col, dayofmonth, boldStyle)datemap[dayofmonth] = colcol += 1row = 2prodkeys = prodsalesmap.keys()prodkeys.sort()for prodsale in prodkeys:(parent, category, brand, model_name, model_number, color) = prodsaleworksheet.write(row, 0, parent, boldStyle)worksheet.write(row, 1, category, boldStyle)worksheet.write(row, 2, brand, boldStyle)worksheet.write(row, 3, model_name if model_name is not None else '', boldStyle)worksheet.write(row, 4, model_number if model_number is not None else '', boldStyle)worksheet.write(row, 5, color if color is not None else 'NA', boldStyle)for monthnumber in prodsalesmap[prodsale].keys():for dayofmonth in prodsalesmap[prodsale][monthnumber]:quantity = prodsalesmap[prodsale][monthnumber][dayofmonth]worksheet.write(row, datecolmap[monthnumber][dayofmonth], quantity)row += 1worksheet.panes_frozen = Trueworksheet.horz_split_pos = 2worksheet.vert_split_pos = 6workbook.save(TMP_FILE)def sendmail():mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)mailServer.ehlo()mailServer.starttls()mailServer.ehlo()# Create the container (outer) email message.msg = MIMEMultipart()msg['Subject'] = SUBJECT + ' - ' + date.today().isoformat()msg['From'] = "bi@saholic.com"msg['To'] = 'sku-recipients@saholic.com'msg.preamble = SUBJECT + ' - ' + date.today().isoformat()fileMsg = MIMEBase('application','vnd.ms-excel')fileMsg.set_payload(file(TMP_FILE).read())encoders.encode_base64(fileMsg)fileMsg.add_header('Content-Disposition','attachment;filename=Product-Report' + ' - ' + date.today().isoformat() + '.xls')msg.attach(fileMsg)mailServer.login(SENDER, PASSWORD)mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())def main():(monthdatesmap, prodsalesmap) = getProductSaleData()createXlsReport(monthdatesmap, prodsalesmap)sendmail()if __name__ == '__main__':main()