Subversion Repositories SmartDukaan

Rev

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