Subversion Repositories SmartDukaan

Rev

Rev 16994 | Rev 20474 | 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,
15924 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, d.versioncode
16994 amit.gupta 47
, uas.comment, aua.store_name, aua.address,  aua.city, aua.pincode,aua.state, aua.source
15924 amit.gupta 48
from users u left join useractive ua on ua.user_id=u.id 
49
left join usergroups ug on ug.id=u.usergroup_id 
14460 amit.gupta 50
left join (select distinct user_id from price_preferences) pp on pp.user_id=u.id
51
left join (select distinct user_id from brand_preferences) bp on bp.user_id=u.id 
15924 amit.gupta 52
left join (select *, count(*) as total from (select user_id, created from order_view where status in ('ORDER_CREATED', 'DETAIL_CREATED') union all (select user_id, created from flipkartorders where date(created) >'2015-03-22') order by created desc) as a1 group by user_id) as ow on ow.user_id = u.id
53
left join user_activity_status uas on uas.user_id=u.id  
15929 amit.gupta 54
left join (select * from (select * from all_user_addresses order by source) s group by user_id)aua on aua.user_id=u.id
15924 amit.gupta 55
left join (select * from (select user_id, versioncode from devices order by created desc) c group by user_id) d on d.user_id=u.id
15885 amit.gupta 56
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.utm_campaign is not null) and u.activated = 1) final;
14460 amit.gupta 57
"""
15666 amit.gupta 58
GROUP_SEGMENTATION_QUERY = """
59
select case  
60
when created >= date(now()) - interval 3 day and total > 0 then 'ABU'
61
when created <  date(now()) - interval 3 day and total > 0 then 'IBU'
62
when last_active >=  date(now()) - interval 3 day and total = 0 and date(last_active) <> date(ucreated) then 'ANBU'
63
when ucreated <  date(now()) - interval 3 day and total = 0 and last_active <  date(now()) - interval 3 day then 'INU'
64
when ucreated >=  date(now()) - interval 3 day and total = 0 and date(last_active) = date(ucreated) then 'FIU'
65
else 'OTH'
66
end
67
usersegment, final.*  
15714 amit.gupta 68
from (select min(u.id), max(u.id), u.username, u.first_name, u.mobile_number, u.usergroup_id, ug.groupbasis, count(*),
15712 amit.gupta 69
max(u.created) ucreated, min(u.created) minucreated, max(ua.last_active) last_active, max(ow.created) created, if(sum(ow.total) is null, 0, sum(ow.total)) as total
15666 amit.gupta 70
from users u left join useractive ua on ua.user_id=u.id left join usergroups ug on ug.id=u.usergroup_id 
71
left join (select *, count(*) as total from (select user_id, created from order_view where status in ('ORDER_CREATED', 'DETAIL_CREATED') 
72
            union all (select user_id, created from flipkartorders where date(created) >'2015-03-22') order by created desc) as a1 group by user_id) as ow 
73
on ow.user_id = u.id  
15885 amit.gupta 74
where (lower(u.referrer) not like 'emp%' or u.utm_campaign is not null) and u.activated=1 group by usergroup_id) final;
15666 amit.gupta 75
"""
14460 amit.gupta 76
 
15666 amit.gupta 77
 
14460 amit.gupta 78
date_format = xlwt.XFStyle()
79
date_format.num_format_str = 'dd/mm/yyyy'
80
 
81
datetime_format = xlwt.XFStyle()
82
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
83
 
84
default_format = xlwt.XFStyle()
85
 
86
 
87
def getDbConnection():
88
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
89
 
90
 
91
def generateSegmentationReport():
92
    selectSql = SEGMENTATION_QUERY
93
    conn = getDbConnection()
94
    try:
95
        # prepare a cursor object using cursor() method
96
        cursor = conn.cursor()
97
        # Execute the SQL command
98
        # Fetch source id.
99
        cursor.execute(selectSql)
100
        result = cursor.fetchall()
15930 amit.gupta 101
        workbook = xlwt.Workbook("ISO-8859-1")
14460 amit.gupta 102
        worksheet = workbook.add_sheet("Segmented User")
103
        boldStyle = xlwt.XFStyle()
104
        f = xlwt.Font()
105
        f.bold = True
106
        boldStyle.font = f
107
        column = 0
108
        row = 0
109
 
110
        worksheet.write(row, 0, 'User Segment', boldStyle)
111
        worksheet.write(row, 1, 'User Id', boldStyle)
112
        worksheet.write(row, 2, 'Username', boldStyle)
113
        worksheet.write(row, 3, 'Name', boldStyle)
114
        worksheet.write(row, 4, 'Mobile', boldStyle)
14544 amit.gupta 115
        worksheet.write(row, 5, 'Mobile Verified', boldStyle)
15507 amit.gupta 116
        worksheet.write(row, 6, 'UserGroupId', boldStyle)
15512 amit.gupta 117
        worksheet.write(row, 7, 'Group basis', boldStyle)
118
        worksheet.write(row, 8, 'Brand Preference', boldStyle)
119
        worksheet.write(row, 9, 'Pricing Preference', boldStyle)
120
        worksheet.write(row, 10, 'User Created On', boldStyle)
121
        worksheet.write(row, 11, 'User Last Active On', boldStyle)
122
        worksheet.write(row, 12, 'Order Last Created On', boldStyle)
123
        worksheet.write(row, 13, 'Total Orders', boldStyle)
124
        worksheet.write(row, 14, 'Referrer', boldStyle)
125
        worksheet.write(row, 15, 'Campaign', boldStyle)
126
        worksheet.write(row, 16, 'Content', boldStyle)
127
        worksheet.write(row, 17, 'Term', boldStyle)
128
        worksheet.write(row, 18, 'Medium', boldStyle)
129
        worksheet.write(row, 19, 'Utm Source', boldStyle)
130
        worksheet.write(row, 20, 'Activation Flag', boldStyle)
15637 amit.gupta 131
        worksheet.write(row, 21, 'Retailer Id', boldStyle)
132
        worksheet.write(row, 22, 'Retailer Status', boldStyle)
15924 amit.gupta 133
        worksheet.write(row, 23, 'Version Code', boldStyle)
134
        worksheet.write(row, 24, 'Install', boldStyle)
135
        worksheet.write(row, 25, 'Store', boldStyle)
16994 amit.gupta 136
        worksheet.write(row, 26, 'Address', boldStyle)
137
        worksheet.write(row, 27, 'City', boldStyle)
138
        worksheet.write(row, 28, 'Pincode', boldStyle)
139
        worksheet.write(row, 29, 'State', boldStyle)
140
        worksheet.write(row, 30, 'Source', boldStyle)
14460 amit.gupta 141
 
142
        for r in result:
143
            row += 1
144
            column = 0
145
            for data in r :
146
                worksheet.write(row, column, int(data) if type(data) is float else data, datetime_format if type(data) is datetime.datetime else default_format)
147
                column += 1
148
        workbook.save(TMP_FILE)
15666 amit.gupta 149
        generateGroupSegmentationReport(workbook)
20172 aman.kumar 150
        sendmail(["rajneesh.arora@saholic.com","khushal.bhatia@saholic.com"], "", TMP_FILE, SUBJECT)
15666 amit.gupta 151
        #sendmail([], "", TMP_FILE, SUBJECT)
14460 amit.gupta 152
    except:
14721 amit.gupta 153
        traceback.print_exc()
14460 amit.gupta 154
        print "Could not create report"
155
 
15666 amit.gupta 156
def generateGroupSegmentationReport(workbook):
157
    selectSql = GROUP_SEGMENTATION_QUERY
158
    conn = getDbConnection()
159
    try:
160
        # prepare a cursor object using cursor() method
161
        cursor = conn.cursor()
162
        # Execute the SQL command
163
        # Fetch source id.
164
        cursor.execute(selectSql)
165
        result = cursor.fetchall()
166
        worksheet = workbook.add_sheet("Segmented User Group")
167
        boldStyle = xlwt.XFStyle()
168
        f = xlwt.Font()
169
        f.bold = True
170
        boldStyle.font = f
171
        column = 0
172
        row = 0
173
        worksheet.write(row, 0, 'User Segment', boldStyle)
15714 amit.gupta 174
        worksheet.write(row, 1, 'First Id', boldStyle)
15715 amit.gupta 175
        worksheet.write(row, 2, 'Last Id', boldStyle)
176
        worksheet.write(row, 3, 'Username', boldStyle)
177
        worksheet.write(row, 4, 'Name', boldStyle)
178
        worksheet.write(row, 5, 'Mobile', boldStyle)
179
        worksheet.write(row, 6, 'UserGroupId', boldStyle)
180
        worksheet.write(row, 7, 'Group basis', boldStyle)
181
        worksheet.write(row, 8, 'Users Count', boldStyle)
182
        worksheet.write(row, 9, 'User last created', boldStyle)
183
        worksheet.write(row, 10, 'User first created', boldStyle)
184
        worksheet.write(row, 11, 'User Last Active On', boldStyle)
185
        worksheet.write(row, 12, 'Order Last Created On', boldStyle)
186
        worksheet.write(row, 13, 'Total Orders', boldStyle)
15666 amit.gupta 187
        for r in result:
188
            row += 1
189
            column = 0
190
            for data in r :
191
                worksheet.write(row, column, int(data) if type(data) is float else data, datetime_format if type(data) is datetime.datetime else default_format)
192
                column += 1
193
        workbook.save(TMP_FILE)
194
    except:
195
        traceback.print_exc()
196
        print "Could not create report"
197
 
14460 amit.gupta 198
def sendmail(email, message, fileName, title):
199
    if email == "":
200
        return
201
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
202
    mailServer.ehlo()
203
    mailServer.starttls()
204
    mailServer.ehlo()
205
 
206
    # Create the container (outer) email message.
207
    msg = MIMEMultipart()
208
    msg['Subject'] = title
209
    msg.preamble = title
210
    html_msg = MIMEText(message, 'html')
211
    msg.attach(html_msg)
212
 
213
    fileMsg = MIMEBase('application', 'vnd.ms-excel')
214
    fileMsg.set_payload(file(TMP_FILE).read())
215
    encoders.encode_base64(fileMsg)
216
    fileMsg.add_header('Content-Disposition', 'attachment;filename=' + fileName)
217
    msg.attach(fileMsg)
218
 
219
 
220
    email.append('amit.gupta@shop2020.in')
221
    MAILTO = email 
222
    mailServer.login(SENDER, PASSWORD)
223
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
224
 
225
def main():
226
    generateSegmentationReport()
227
 
228
if __name__ == '__main__':
229
    main()