Subversion Repositories SmartDukaan

Rev

Rev 15646 | Rev 15648 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14460 amit.gupta 1
'''
2
Created on Mar 10, 2015
3
 
4
@author: amit
5
'''
6
from datetime import date
7
from email import encoders
8
from email.mime.base import MIMEBase
9
from email.mime.multipart import MIMEMultipart
10
from email.mime.text import MIMEText
11
import MySQLdb
12
import datetime
13
import smtplib
14721 amit.gupta 14
import traceback
14460 amit.gupta 15
import xlwt
16
 
17
 
18
 
19
DB_HOST = "localhost"
20
DB_USER = "root"
21
DB_PASSWORD = "shop2020"
22
DB_NAME = "dtr"
23
TMP_FILE = "/tmp/usersegmentreport.xls"  
24
 
25
# KEY NAMES
26
SENDER = "cnc.center@shop2020.in"
27
PASSWORD = "5h0p2o2o"
28
SUBJECT = "DTR User Segmentation report for " + date.today().isoformat()
29
SMTP_SERVER = "smtp.gmail.com"
30
SMTP_PORT = 587    
31
 
32
 
33
SEGMENTATION_QUERY = """
34
select case  
35
when created >= date(now()) - interval 3 day and total > 0 then 'ABU'
36
when created <  date(now()) - interval 3 day and total > 0 then 'IBU'
37
when last_active >=  date(now()) - interval 3 day and total = 0 and date(last_active) <> date(ucreated) then 'ANBU'
38
when ucreated <  date(now()) - interval 3 day and total = 0 and last_active <  date(now()) - interval 3 day then 'INU'
39
when ucreated >=  date(now()) - interval 3 day and total = 0 and date(last_active) = date(ucreated) then 'FIU'
40
else 'OTH'
41
end
42
usersegment, final.*
15512 amit.gupta 43
from (select u.id, u.username, u.first_name, u.mobile_number, u.mobile_verified,u.usergroup_id, ug.groupbasis,
14460 amit.gupta 44
if(bp.user_id is null, 'FALSE', 'TRUE') as bpref,
14721 amit.gupta 45
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,
15637 amit.gupta 46
u.referrer,u.utm_campaign, u.utm_content, u.utm_term, u.utm_medium, u.utm_source, u.activated, r.id as retailer_id, r.status   
15512 amit.gupta 47
from users u left join useractive ua on ua.user_id=u.id left join usergroups ug on ug.id=u.usergroup_id 
14460 amit.gupta 48
left join (select distinct user_id from price_preferences) pp on pp.user_id=u.id
49
left join (select distinct user_id from brand_preferences) bp on bp.user_id=u.id 
15647 amit.gupta 50
left join (select *, count(*) as total from (select user_id, created from order_view where status in ('ORDER_CREATED', 'DETAIL_CREATED') union select user_id, created from flipkartorders order by created desc) as a1 group by user_id) as ow on ow.user_id = u.id  
15637 amit.gupta 51
left join retailerlinks rl on rl.user_id=u.id left join retailers r on r.id=rl.retailer_id where lower(u.referrer) not like 'emp%' or u.referrer is null) final;
14460 amit.gupta 52
"""
53
 
54
 
55
date_format = xlwt.XFStyle()
56
date_format.num_format_str = 'dd/mm/yyyy'
57
 
58
datetime_format = xlwt.XFStyle()
59
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
60
 
61
default_format = xlwt.XFStyle()
62
 
63
 
64
def getDbConnection():
65
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
66
 
67
 
68
def generateSegmentationReport():
69
    selectSql = SEGMENTATION_QUERY
70
    conn = getDbConnection()
71
    try:
72
        # prepare a cursor object using cursor() method
73
        cursor = conn.cursor()
74
        # Execute the SQL command
75
        # Fetch source id.
76
        cursor.execute(selectSql)
77
        result = cursor.fetchall()
78
        workbook = xlwt.Workbook()
79
        worksheet = workbook.add_sheet("Segmented User")
80
        boldStyle = xlwt.XFStyle()
81
        f = xlwt.Font()
82
        f.bold = True
83
        boldStyle.font = f
84
        column = 0
85
        row = 0
86
 
87
        worksheet.write(row, 0, 'User Segment', boldStyle)
88
        worksheet.write(row, 1, 'User Id', boldStyle)
89
        worksheet.write(row, 2, 'Username', boldStyle)
90
        worksheet.write(row, 3, 'Name', boldStyle)
91
        worksheet.write(row, 4, 'Mobile', boldStyle)
14544 amit.gupta 92
        worksheet.write(row, 5, 'Mobile Verified', boldStyle)
15507 amit.gupta 93
        worksheet.write(row, 6, 'UserGroupId', boldStyle)
15512 amit.gupta 94
        worksheet.write(row, 7, 'Group basis', boldStyle)
95
        worksheet.write(row, 8, 'Brand Preference', boldStyle)
96
        worksheet.write(row, 9, 'Pricing Preference', boldStyle)
97
        worksheet.write(row, 10, 'User Created On', boldStyle)
98
        worksheet.write(row, 11, 'User Last Active On', boldStyle)
99
        worksheet.write(row, 12, 'Order Last Created On', boldStyle)
100
        worksheet.write(row, 13, 'Total Orders', boldStyle)
101
        worksheet.write(row, 14, 'Referrer', boldStyle)
102
        worksheet.write(row, 15, 'Campaign', boldStyle)
103
        worksheet.write(row, 16, 'Content', boldStyle)
104
        worksheet.write(row, 17, 'Term', boldStyle)
105
        worksheet.write(row, 18, 'Medium', boldStyle)
106
        worksheet.write(row, 19, 'Utm Source', boldStyle)
107
        worksheet.write(row, 20, 'Activation Flag', boldStyle)
15637 amit.gupta 108
        worksheet.write(row, 21, 'Retailer Id', boldStyle)
109
        worksheet.write(row, 22, 'Retailer Status', boldStyle)
14460 amit.gupta 110
 
111
        for r in result:
112
            row += 1
113
            column = 0
114
            for data in r :
115
                worksheet.write(row, column, int(data) if type(data) is float else data, datetime_format if type(data) is datetime.datetime else default_format)
116
                column += 1
117
        workbook.save(TMP_FILE)
15637 amit.gupta 118
        sendmail(["rajneesh.arora@saholic.com"], "", TMP_FILE, SUBJECT)
14460 amit.gupta 119
    except:
14721 amit.gupta 120
        traceback.print_exc()
14460 amit.gupta 121
        print "Could not create report"
122
 
123
def sendmail(email, message, fileName, title):
124
    if email == "":
125
        return
126
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
127
    mailServer.ehlo()
128
    mailServer.starttls()
129
    mailServer.ehlo()
130
 
131
    # Create the container (outer) email message.
132
    msg = MIMEMultipart()
133
    msg['Subject'] = title
134
    msg.preamble = title
135
    html_msg = MIMEText(message, 'html')
136
    msg.attach(html_msg)
137
 
138
    fileMsg = MIMEBase('application', 'vnd.ms-excel')
139
    fileMsg.set_payload(file(TMP_FILE).read())
140
    encoders.encode_base64(fileMsg)
141
    fileMsg.add_header('Content-Disposition', 'attachment;filename=' + fileName)
142
    msg.attach(fileMsg)
143
 
144
 
145
    email.append('amit.gupta@shop2020.in')
146
    MAILTO = email 
147
    mailServer.login(SENDER, PASSWORD)
148
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
149
 
150
def main():
151
    generateSegmentationReport()
152
 
153
if __name__ == '__main__':
154
    main()