Subversion Repositories SmartDukaan

Rev

Rev 14544 | Go to most recent revision | Details | 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.*
42
from (select u.id, u.username, u.first_name, u.mobile_number, u.referrer, 
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)
90
        worksheet.write(row, 5, 'Referrer', boldStyle)
91
        worksheet.write(row, 6, 'Brand Preference', boldStyle)
92
        worksheet.write(row, 7, 'Pricing Preference', boldStyle)
93
        worksheet.write(row, 8, 'User Created On', boldStyle)
94
        worksheet.write(row, 9, 'User Last Active On', boldStyle)
95
        worksheet.write(row, 10, 'Order Last Created On', boldStyle)
96
        worksheet.write(row, 11, 'Total Orders', boldStyle)
97
 
98
        for r in result:
99
            row += 1
100
            column = 0
101
            for data in r :
102
                worksheet.write(row, column, int(data) if type(data) is float else data, datetime_format if type(data) is datetime.datetime else default_format)
103
                column += 1
104
        workbook.save(TMP_FILE)
105
        sendmail(["amit.gupta@shop2020.in"], "", TMP_FILE, SUBJECT)
106
    except:
107
        print "Could not create report"
108
 
109
def sendmail(email, message, fileName, title):
110
    if email == "":
111
        return
112
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
113
    mailServer.ehlo()
114
    mailServer.starttls()
115
    mailServer.ehlo()
116
 
117
    # Create the container (outer) email message.
118
    msg = MIMEMultipart()
119
    msg['Subject'] = title
120
    msg.preamble = title
121
    html_msg = MIMEText(message, 'html')
122
    msg.attach(html_msg)
123
 
124
    fileMsg = MIMEBase('application', 'vnd.ms-excel')
125
    fileMsg.set_payload(file(TMP_FILE).read())
126
    encoders.encode_base64(fileMsg)
127
    fileMsg.add_header('Content-Disposition', 'attachment;filename=' + fileName)
128
    msg.attach(fileMsg)
129
 
130
 
131
    email.append('amit.gupta@shop2020.in')
132
    MAILTO = email 
133
    mailServer.login(SENDER, PASSWORD)
134
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
135
 
136
def main():
137
    generateSegmentationReport()
138
 
139
if __name__ == '__main__':
140
    main()