Rev 15057 | Rev 15512 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
'''Created on Mar 10, 2015@author: amit'''from datetime import datefrom email import encodersfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport MySQLdbimport datetimeimport smtplibimport tracebackimport xlwtDB_HOST = "localhost"DB_USER = "root"DB_PASSWORD = "shop2020"DB_NAME = "dtr"TMP_FILE = "/tmp/usersegmentreport.xls"# KEY NAMESSENDER = "cnc.center@shop2020.in"PASSWORD = "5h0p2o2o"SUBJECT = "DTR User Segmentation report for " + date.today().isoformat()SMTP_SERVER = "smtp.gmail.com"SMTP_PORT = 587SEGMENTATION_QUERY = """select casewhen created >= date(now()) - interval 3 day and total > 0 then 'ABU'when created < date(now()) - interval 3 day and total > 0 then 'IBU'when last_active >= date(now()) - interval 3 day and total = 0 and date(last_active) <> date(ucreated) then 'ANBU'when ucreated < date(now()) - interval 3 day and total = 0 and last_active < date(now()) - interval 3 day then 'INU'when ucreated >= date(now()) - interval 3 day and total = 0 and date(last_active) = date(ucreated) then 'FIU'else 'OTH'endusersegment, final.*from (select u.id, u.username, u.first_name, u.mobile_number, u.mobile_verified,u.usergroup_id,if(bp.user_id is null, 'FALSE', 'TRUE') as bpref,if(pp.user_id is null, 'FALSE', 'TRUE') as ppref, u.created ucreated, ua.last_active, ow.created, if(ow.total is null, 0, ow.total) as total,u.referrer,u.utm_campaign, u.utm_content, u.utm_term, u.utm_medium, u.utm_source, u.activatedfrom users u left join useractive ua on ua.user_id=u.idleft join (select distinct user_id from price_preferences) pp on pp.user_id=u.idleft join (select distinct user_id from brand_preferences) bp on bp.user_id=u.idleft join (select *, count(*) as total from (select user_id, created from order_view where status = 'ORDER_CREATED' order by id desc) as a1 group by user_id) as ow on ow.user_id = u.idwhere lower(u.referrer) not like 'emp%' or u.referrer is null) final;"""date_format = xlwt.XFStyle()date_format.num_format_str = 'dd/mm/yyyy'datetime_format = xlwt.XFStyle()datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'default_format = xlwt.XFStyle()def getDbConnection():return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)def generateSegmentationReport():selectSql = SEGMENTATION_QUERYconn = getDbConnection()try:# prepare a cursor object using cursor() methodcursor = conn.cursor()# Execute the SQL command# Fetch source id.cursor.execute(selectSql)result = cursor.fetchall()workbook = xlwt.Workbook()worksheet = workbook.add_sheet("Segmented User")boldStyle = xlwt.XFStyle()f = xlwt.Font()f.bold = TrueboldStyle.font = fcolumn = 0row = 0worksheet.write(row, 0, 'User Segment', boldStyle)worksheet.write(row, 1, 'User Id', boldStyle)worksheet.write(row, 2, 'Username', boldStyle)worksheet.write(row, 3, 'Name', boldStyle)worksheet.write(row, 4, 'Mobile', boldStyle)worksheet.write(row, 5, 'Mobile Verified', boldStyle)worksheet.write(row, 6, 'UserGroupId', boldStyle)worksheet.write(row, 7, 'Brand Preference', boldStyle)worksheet.write(row, 8, 'Pricing Preference', boldStyle)worksheet.write(row, 9, 'User Created On', boldStyle)worksheet.write(row, 10, 'User Last Active On', boldStyle)worksheet.write(row, 11, 'Order Last Created On', boldStyle)worksheet.write(row, 12, 'Total Orders', boldStyle)worksheet.write(row, 13, 'Referrer', boldStyle)worksheet.write(row, 14, 'Campaign', boldStyle)worksheet.write(row, 15, 'Content', boldStyle)worksheet.write(row, 16, 'Term', boldStyle)worksheet.write(row, 17, 'Medium', boldStyle)worksheet.write(row, 18, 'Utm Source', boldStyle)worksheet.write(row, 19, 'Activation Flag', boldStyle)for r in result:row += 1column = 0for data in r :worksheet.write(row, column, int(data) if type(data) is float else data, datetime_format if type(data) is datetime.datetime else default_format)column += 1workbook.save(TMP_FILE)sendmail(["rajneesh.arora@saholic.com", "chaitnaya.vats@saholic.com", ], "", TMP_FILE, SUBJECT)except:traceback.print_exc()print "Could not create report"def sendmail(email, message, fileName, title):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'] = titlemsg.preamble = titlehtml_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=' + fileName)msg.attach(fileMsg)email.append('amit.gupta@shop2020.in')MAILTO = emailmailServer.login(SENDER, PASSWORD)mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())def main():generateSegmentationReport()if __name__ == '__main__':main()