Subversion Repositories SmartDukaan

Rev

Rev 5652 | Rev 5666 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5652 anupam.sin 1
import json
2
import urllib2, cookielib
3
import MySQLdb
4
import datetime
5
import sys
6
import smtplib
7
 
8
from email import encoders
9
from email.mime.text import MIMEText
10
from email.mime.base import MIMEBase
11
from email.mime.multipart import MIMEMultipart
12
from pyExcelerator import Workbook, Font, XFStyle
13
from datetime import date
14
 
15
# Initialize db connection settings.
16
DB_HOST = "localhost"
17
DB_USER = "root"
18
DB_PASSWORD = "shop2020"
19
DB_NAME = "sales"
20
 
21
# KEY NAMES
22
MONTHNAME = 'monthname'
23
DATES = 'dates'
24
 
5653 anupam.sin 25
MAILTO = ['rajneesharora@spiceretail.co.in', 'pankaj.kankar@shop2020.in', 'ashutosh.saxena@shop2020.in', 'anupam.singh@shop2020.in']
5652 anupam.sin 26
SENDER = "cnc.center@shop2020.in"
27
PASSWORD = "5h0p2o2o"
28
SUBJECT = "Previous Day Accessory Sales Report"
29
SMTP_SERVER = "smtp.gmail.com"
30
SMTP_PORT = 587    
31
 
32
TMP_FILE="/tmp/previous_accessory_sales.xls"
33
 
34
def getDbConnection():
35
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
36
 
37
def closeConnection(conn):
38
    conn.close()
39
 
40
def getProductSaleData():
41
    selectSql = '''SELECT i.parent_category, i.category, i.brand, IFNULL(i.model_name, ''),
42
                    IFNULL(i.model_number, ''), i.color, sum(quantity) AS quantity
43
                    FROM sales s join item i on (i.id = s.item_id) 
44
                    JOIN datedim d on (d.date_id = s.date_id) 
45
                    JOIN orderstatus os on (s.status = os.status) 
46
                    WHERE d.fulldate in (DATE_SUB(curdate(), INTERVAL 1 DAY)) 
47
                    AND os.statusGroup in ('In process', 'Delivered', 'Cancelled', 'Return in process', 'Reshipped', 'Refunded') 
48
                    AND i.parent_category = 'Mobile Accessories' 
49
                    AND os.statusSubGroup != 'Cod verification failed' 
50
                    GROUP BY i.parent_category, i.category, i.brand, IFNULL(i.model_name, ''), IFNULL(i.model_number, ''), i.color;
51
                '''
52
 
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
        msg =   """\
65
                    <html>
66
                    <body>\n<table border="1">
67
                    \n<thead>\n
68
                    <th>Category\n</th>
69
                    <th>Sub Category\n</th>
70
                    <th>Brand\n</th>
71
                    <th>Model Name\n</th>
72
                    <th>Model Number\n</th>
73
                    <th>Color\n</th>
74
                    <th>Quantity\n</th>
75
                    \n</thead>
76
                """ 
77
        for r in result:
78
            #(parent, category, brand, model_name, model_number, color) = r[0:6]
79
            #dayofmonth = r[8]
80
            msg = msg + '<tr>'
81
            for col in r:
82
                msg = msg + '<td>' + str(col) + '</td>'
83
            msg = msg + '</tr>'
84
    except Exception as e:
85
      print "Error: unable to fetch data"
86
      print e
87
 
88
    msg = msg + '</table>\n</body>\n</html>'
89
    return msg, result
90
 
91
def createXlsReport(result):
92
    workbook = Workbook()
93
    worksheet = workbook.add_sheet("Sheet 1")
94
    boldStyle = XFStyle()
95
    f = Font()
96
    f.bold = True
97
    boldStyle.font = f
98
 
99
    datecolmap = {}
100
    column = 0
101
    row = 0
102
 
103
    worksheet.write(row, 0, 'Category', boldStyle)
104
    worksheet.write(row, 1, 'Sub Category', boldStyle)
105
    worksheet.write(row, 2, 'Brand', boldStyle)
106
    worksheet.write(row, 3, 'Model Name', boldStyle)
107
    worksheet.write(row, 4, 'Model Number', boldStyle)
108
    worksheet.write(row, 5, 'Color', boldStyle)
109
    worksheet.write(row, 6, 'Quantity', boldStyle)
110
 
111
    row = 1
112
 
113
    for r in result:
114
        #(parent, category, brand, model_name, model_number, color) = r[0:6]
115
        #dayofmonth = r[8]
116
        for data in r :
117
            worksheet.write(row, column, str(data))
118
            column += 1
119
        column = 0
120
        row += 1
121
    workbook.save(TMP_FILE)
122
 
123
def sendmail(message):
124
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
125
    mailServer.ehlo()
126
    mailServer.starttls()
127
    mailServer.ehlo()
128
 
129
    # Create the container (outer) email message.
130
    msg = MIMEMultipart()
131
    msg['Subject'] = SUBJECT + ' - ' + date.today().isoformat()
132
    msg['From'] = "bi@saholic.com"
133
    msg['To'] = 'sku-recipients@saholic.com'
134
    msg.preamble = SUBJECT + ' - ' + date.today().isoformat()
135
    html_msg = MIMEText(message, 'html')
136
    msg.attach(html_msg)
137
 
138
    fileMsg = MIMEBase('application','vnd.ms-excel')
139
    fileMsg.set_payload(file(TMP_FILE).read())
140
    encoders.encode_base64(fileMsg)
141
    fileMsg.add_header('Content-Disposition','attachment;filename=Yesterday-Accessory-Sales' + ' - ' + date.today().isoformat() + '.xls')
142
    msg.attach(fileMsg)
143
 
144
    mailServer.login(SENDER, PASSWORD)
145
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
146
 
147
def main():
148
    message, result = getProductSaleData()
149
    createXlsReport(result)
150
    sendmail(message)
151
 
152
if __name__ == '__main__':
153
    main()