Subversion Repositories SmartDukaan

Rev

Rev 5091 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5087 anupam.sin 1
#!/usr/bin/python
2
 
3
import json
4
import urllib2, cookielib
5
import MySQLdb
6
import datetime
7
import sys
8
import smtplib
9
 
10
from email import encoders
11
from email.mime.text import MIMEText
12
from email.mime.base import MIMEBase
13
from email.mime.multipart import MIMEMultipart
14
from pyExcelerator import Workbook, Font, XFStyle
15
from datetime import date
16
 
17
from datetime import datetime, timedelta
18
 
19
# Initialize db connection settings.
20
DB_HOST = "localhost"
21
DB_USER = "root"
22
DB_PASSWORD = "shop2020"
23
DB_NAME = "sales"
24
 
25
# KEY NAMES
26
 
27
MAILTO = ['abhishek.mathur@shop2020.in', 'anupam.singh@shop2020.in']
28
SENDER = "cnc.center@shop2020.in"
29
PASSWORD = "5h0p2o2o"
30
SUBJECT = "MySmartPrice Report"
31
SMTP_SERVER = "smtp.gmail.com"
32
SMTP_PORT = 587    
33
 
34
TMP_FILE="/tmp/mysmartprice_report.xls"
35
 
36
def getDbConnection():
37
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
38
 
39
def closeConnection(conn):
40
    conn.close()
41
 
42
def getCount(dateYesterday):
43
    selectCount = "select count(*) from productactivity where date_id = (select date_id from datedim where fulldate = '" + dateYesterday + "')"
44
 
45
    conn = getDbConnection()
46
    try:
47
        # prepare a cursor object using cursor() method
48
        cursor = conn.cursor()
49
        # Execute the SQL command
50
        # Fetch source id.
51
        cursor.execute(selectCount)
52
        result = cursor.fetchall()
53
        for r in result:
54
            count = r[0]
55
 
56
    except Exception as e:
57
      print "Error: unable to fetch data"
58
      print e
59
 
60
    return count
61
 
62
def getProductSaleData():
63
    selectSql = '''select concat_ws(' ', catalog_item.brand, catalog_item.model_name, catalog_item.model_number) as Product,
64
                   sum(p.unique_view) as Views, sum(p.unique_add_to_cart) as AddToCarts 
65
                   from productactivity p 
66
                   join catalog_item catalog_item on (catalog_item.catalog_item_id = p.catalog_item_id) 
67
                   where date_id = (select MAX(date_id) from productactivity) and session_source_id in (980) group by p.catalog_item_id
68
                '''
69
    conn = getDbConnection()
70
    productTuples = []
71
 
72
    try:
73
        # prepare a cursor object using cursor() method
74
        cursor = conn.cursor()
75
        # Execute the SQL command
76
        # Fetch source id.
77
        cursor.execute(selectSql)
78
        result = cursor.fetchall()
79
        for r in result:
80
            productTuple = r[0:3]
81
            productTuples.append(productTuple)
82
 
83
    except Exception as e:
84
      print "Error: unable to fetch data"
85
      print e
86
 
87
    return productTuples
88
 
89
def createXlsReport(productTuples):
90
    workbook = Workbook()
91
    worksheet = workbook.add_sheet("Sheet 1")
92
    boldStyle = XFStyle()
93
    f = Font()
94
    f.bold = True
95
    boldStyle.font = f
96
 
97
    timeNow = datetime.now()
98
    worksheet.write(0, 0, dateYesterday, boldStyle)
99
    row = 3
100
 
101
    worksheet.write(row, 0, 'Product', boldStyle)
102
    worksheet.write(row, 1, 'Views', boldStyle)
103
    worksheet.write(row, 2, 'Add to Carts', boldStyle)
104
 
105
    for productTuple in productTuples:
106
        row += 1
107
        worksheet.write(row, 0, productTuple[0])
108
        worksheet.write(row, 1, str(productTuple[1]))
109
        worksheet.write(row, 2, str(productTuple[2]))
110
 
111
    workbook.save(TMP_FILE)
112
    print "Spreadsheet Saved"
113
 
114
def sendmail():
115
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
116
    mailServer.ehlo()
117
    mailServer.starttls()
118
    mailServer.ehlo()
119
 
120
    # Create the container (outer) email message.
121
    msg = MIMEMultipart()
122
    msg['Subject'] = SUBJECT + ' - ' + dateYesterday
123
    msg['From'] = "bi@saholic.com"
124
    msg['To'] = 'sku-recipients@saholic.com'
125
    msg.preamble = SUBJECT + ' - ' + date.today().isoformat() 
126
 
127
    fileMsg = MIMEBase('application','vnd.ms-excel')
128
    fileMsg.set_payload(file(TMP_FILE).read())
129
    encoders.encode_base64(fileMsg)
130
    fileMsg.add_header('Content-Disposition','attachment;filename=MySmartPrice-Report' + ' - ' + dateYesterday + '.xls')
131
    msg.attach(fileMsg)
132
 
133
    mailServer.login(SENDER, PASSWORD)
134
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
135
    print "Mail Sent"
136
 
137
def main():
138
    dateYesterday = str((datetime.now() - timedelta(days=1)).date())
139
    count = getCount(dateYesterday)
140
    if count == 0:
141
        print "No data found for date : " + dateYesterday
142
        exit(1)
143
 
144
    productTuples = getProductSaleData()
145
    print "Number of tuples on " + dateYesterday + " : " + str(len(productTuples))
146
    createXlsReport(productTuples, dateYesterday)
147
    sendmail()
148
 
149
if __name__ == '__main__':
150
    main()