Subversion Repositories SmartDukaan

Rev

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