Subversion Repositories SmartDukaan

Rev

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