Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
4066 vikas 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
 
16
# Initialize db connection settings.
17
DB_HOST = "localhost"
18
DB_USER = "root"
19
DB_PASSWORD = "shop2020"
20
DB_NAME = "sales"
21
 
22
# KEY NAMES
23
MONTHNAME = 'monthname'
24
DATES = 'dates'
25
 
26
MAILTO = ['vikas.malik@shop2020.in']
27
#MAILTO = ['rajneesharora@spiceretail.co.in', 'yukti.jain@spiceretail.co.in', 'anand.sinha@shop2020.in', \
28
#'chaitnaya.vats@shop2020.in', 'pankaj.kankar@shop2020.in', 'pankaj.jain@spiceglobal.com', 'vikas.malik@shop2020.in']
29
SENDER = "help@shop2020.in"
30
PASSWORD = "5h0p2o2o"
31
SUBJECT = "Product Report"
32
SMTP_SERVER = "smtp.gmail.com"
33
SMTP_PORT = 587    
34
 
35
TMP_FILE="/tmp/product_report.xls"
36
 
37
def getDbConnection():
38
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
39
 
40
def closeConnection(conn):
41
    conn.close()
42
 
43
def getProductSaleData():
44
    selectSql = '''select i.parent_category, i.category, i.brand, IFNULL(i.model_name, ''), IFNULL(i.model_number, ''), 
45
                          i.color, d.monthname, d.monthnumber, d.dayofmonth, count(*) as quantity 
46
                          from sales s 
47
                          join item i on (i.id = s.item_id) 
48
                          join datedim d on (d.date_id = s.date_id) 
49
                          where d.monthnumber in (month(now()) -2, month(now())-1) 
50
                          group by i.parent_category, i.category, i.brand, IFNULL(i.model_name, ''), 
51
                                   IFNULL(i.model_number, ''), i.color, d.monthname, d.monthnumber, d.dayofmonth
52
                '''
53
    conn = getDbConnection()
54
    monthdatesmap = {}
55
    prodsalesmap = {}
56
    try:
57
        # prepare a cursor object using cursor() method
58
        cursor = conn.cursor()
59
        # Execute the SQL command
60
        # Fetch source id.
61
        cursor.execute(selectSql)
62
        result = cursor.fetchall()
63
        for r in result:
64
            (parent, category, brand, model_name, model_number, color) = r[0:6]
65
            monthname, monthnumber = r[6:8]
66
            dayofmonth = r[8]
67
 
68
            if monthdatesmap.has_key(monthnumber):
69
                monthmap = monthdatesmap.get(monthnumber)
70
                monthmap.get(DATES).add(dayofmonth)
71
            else:
72
                monthmap = {}
73
                monthmap[MONTHNAME] = monthname
74
                dates = set([])
75
                dates.add(dayofmonth)
76
                monthmap[DATES] = dates
77
                monthdatesmap[monthnumber] = monthmap
78
 
79
            if prodsalesmap.has_key((parent, category, brand, model_name, model_number, color)):
80
                prodsales = prodsalesmap.get((parent, category, brand, model_name, model_number, color))
81
                if prodsales.has_key(monthnumber):
82
                    monthprodsales = prodsales.get(monthnumber)
83
                    monthprodsales[dayofmonth] = r[9]
84
                    monthprodsales[0] += r[9]
85
                else:
86
                    monthprodsales = {}
87
                    monthprodsales[dayofmonth] = r[9]
88
                    monthprodsales[0] = r[9]
89
                    prodsales[monthnumber] = monthprodsales
90
            else:
91
                prodsale = {}
92
                monthprodsales = {}
93
                monthprodsales[dayofmonth] = r[9]
94
                monthprodsales[0] = r[9]
95
                prodsale[monthnumber] = monthprodsales
96
                prodsalesmap[(parent, category, brand, model_name, model_number, color)] = prodsale
97
 
98
    except Exception as e:
99
      print "Error: unable to fetch data"
100
      print e
101
 
102
    return monthdatesmap, prodsalesmap
103
 
104
def createXlsReport(monthdatesmap, prodsalesmap):
105
    workbook = Workbook()
106
    worksheet = workbook.add_sheet("Sheet 1")
107
    boldStyle = XFStyle()
108
    f = Font()
109
    f.bold = True
110
    boldStyle.font = f
111
 
112
    datecolmap = {}
113
    col = 6
114
    for monthnumber in monthdatesmap.keys():
115
        monthname = monthdatesmap[monthnumber][MONTHNAME]
116
        worksheet.write(0, col, monthname)
117
        worksheet.write(1, col, 'Month', boldStyle)
118
        datemap ={}
119
        datemap[0] = col
120
        datecolmap[monthnumber] = datemap
121
        col += 1
122
 
123
        worksheet.write(1, 0, 'Category', boldStyle)
124
        worksheet.write(1, 1, 'Sub Category', boldStyle)
125
        worksheet.write(1, 2, 'Brand', boldStyle)
126
        worksheet.write(1, 3, 'Model Name', boldStyle)
127
        worksheet.write(1, 4, 'Model Number', boldStyle)
128
        worksheet.write(1, 5, 'Color', boldStyle)
129
        for dayofmonth in monthdatesmap[monthnumber][DATES]:
130
            worksheet.write(1, col, dayofmonth, boldStyle)
131
            datemap[dayofmonth] = col
132
            col += 1
133
 
134
    row = 2
135
    prodkeys = prodsalesmap.keys()
136
    prodkeys.sort()
137
    for prodsale in prodkeys:
138
        (parent, category, brand, model_name, model_number, color) = prodsale
139
        worksheet.write(row, 0, parent, boldStyle)
140
        worksheet.write(row, 1, category, boldStyle)
141
        worksheet.write(row, 2, brand, boldStyle)
142
        worksheet.write(row, 3, model_name if model_name is not None else '', boldStyle)
143
        worksheet.write(row, 4, model_number if model_number is not None else '', boldStyle)
144
        worksheet.write(row, 5, color if color is not None else 'NA', boldStyle)
145
        for monthnumber in prodsalesmap[prodsale].keys():
146
            for dayofmonth in prodsalesmap[prodsale][monthnumber]:
147
                quantity = prodsalesmap[prodsale][monthnumber][dayofmonth]
148
                worksheet.write(row, datecolmap[monthnumber][dayofmonth], quantity)
149
        row += 1
150
 
151
    worksheet.panes_frozen = True
152
    worksheet.horz_split_pos = 2
153
    worksheet.vert_split_pos = 6
154
    workbook.save(TMP_FILE)
155
 
156
def sendmail():
157
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
158
    mailServer.ehlo()
159
    mailServer.starttls()
160
    mailServer.ehlo()
161
 
162
    # Create the container (outer) email message.
163
    msg = MIMEMultipart()
164
    msg['Subject'] = SUBJECT
165
    msg['From'] = "bi@saholic.com"
166
    msg['To'] = 'sku-recipients@saholic.com'
167
    msg.preamble = SUBJECT
168
 
169
    fileMsg = MIMEBase('application','vnd.ms-excel')
170
    fileMsg.set_payload(file(TMP_FILE).read())
171
    encoders.encode_base64(fileMsg)
172
    fileMsg.add_header('Content-Disposition','attachment;filename=Product-Report.xls')
173
    msg.attach(fileMsg)
174
 
175
    mailServer.login(SENDER, PASSWORD)
176
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
177
 
178
def main():
179
    (monthdatesmap, prodsalesmap) = getProductSaleData()
180
    createXlsReport(monthdatesmap, prodsalesmap)
181
    sendmail()
182
 
183
if __name__ == '__main__':
184
    main()