Subversion Repositories SmartDukaan

Rev

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