Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
5494 anupam.sin 1
'''
2
Created on 25-Jun-2012
3
 
4
@author: anupam
5
'''
6
 
7
#!/usr/bin/python
8
 
9
import json
10
import urllib2, cookielib
11
import MySQLdb
12
import datetime
13
import sys
14
import smtplib
15
 
16
from email import encoders
17
from email.mime.text import MIMEText
18
from email.mime.base import MIMEBase
19
from email.mime.multipart import MIMEMultipart
20
from pyExcelerator import Workbook, Font, XFStyle
21
from datetime import date, timedelta
22
 
23
# Initialize db connection settings.
24
DB_HOST = "localhost"
25
DB_USER = "root"
26
DB_PASSWORD = "shop2020"
27
DB_NAME = "warehouse"
28
 
29
MAILTO = ['anupam.singh@shop2020.in', 'amar.kumar@shop2020.in']
30
SENDER = "cnc.center@shop2020.in"
31
PASSWORD = "5h0p2o2o"
32
SUBJECT = "Vendor Fulfilment Report"
33
SMTP_SERVER = "smtp.gmail.com"
34
SMTP_PORT = 587    
35
 
36
TMP_FILE="/tmp/vendor_fulfilment.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(fromDate, toDate):
45
    selectSql = '''SELECT s.name, 
46
                          CONCAT_WS(' ', l.brand, ifnull(l.modelname, ''), l.modelnumber, ifnull(l.color, '')) AS Product, 
47
                          SUM(l.quantity) AS `Qty Ordered`, 
48
                          SUM(l.unfulfilledQuantity) AS `Qty Unfulfilled` 
49
                          FROM lineitem l 
50
                          JOIN purchaseorder p ON l.purchaseOrder_id = p.id 
51
                          JOIN supplier s ON p.supplierId = s.id 
52
                          WHERE l.createdAt BETWEEN \'''' + fromDate + '''\' AND \'''' + toDate + '''\' GROUP BY s.name, l.itemId;'''
53
    conn = getDbConnection()
54
    data = {}
55
    try:
56
        # prepare a cursor object using cursor() method
57
        cursor = conn.cursor()
58
        # Execute the SQL command
59
        # Fetch source id.
60
        cursor.execute(selectSql)
61
        result = cursor.fetchall()
62
        for r in result:
63
            supplier = r[0:1][0]
64
            if data.get(supplier):
65
                data.get(supplier).append(r[1:4])
66
            else:
67
                data[supplier] = [r[1:4]]
68
    except Exception as e:
69
      print "Error: unable to fetch data"
70
      print e
71
 
72
    return data
73
 
74
def createXlsReport(wb, data, sheetNumber):
75
    if sheetNumber == 1:
76
        sheetName = "Yesterday"
77
    if sheetNumber == 2:
78
        sheetName = "MTD"
79
    worksheet = wb.add_sheet(sheetName)
80
    boldStyle = XFStyle()
81
    f = Font()
82
    f.bold = True
83
    boldStyle.font = f
84
 
85
    row = -3
86
    for supplier in data.keys():
87
        row += 3
88
        worksheet.write(row, 0, supplier, boldStyle)
89
        row += 2
90
        worksheet.write(row, 0, "PRODUCT", boldStyle)
91
        worksheet.write(row, 1, "QTY REQUIRED", boldStyle)
92
        worksheet.write(row, 2, "QTY UNFULFILLED", boldStyle) 
93
        lineitems = data.get(supplier)
94
        for lineitem in lineitems:
95
            row += 1
96
            worksheet.write(row, 0, lineitem[0])
97
            worksheet.write(row, 1, lineitem[1])
98
            worksheet.write(row, 2, lineitem[2])
99
 
100
    wb.save(TMP_FILE)
101
 
102
def sendmail():
103
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
104
    mailServer.ehlo()
105
    mailServer.starttls()
106
    mailServer.ehlo()
107
 
108
    # Create the container (outer) email message.
109
    msg = MIMEMultipart()
110
    msg['Subject'] = SUBJECT + ' - ' + date.today().isoformat()
111
    msg['From'] = "PO@saholic.com"
112
    msg['To'] = 'sku-recipients@saholic.com'
113
    msg.preamble = SUBJECT + ' - ' + date.today().isoformat() 
114
 
115
    fileMsg = MIMEBase('application','vnd.ms-excel')
116
    fileMsg.set_payload(file(TMP_FILE).read())
117
    encoders.encode_base64(fileMsg)
118
    fileMsg.add_header('Content-Disposition','attachment;filename=Vendor-Fulfilment' + ' - ' + date.today().isoformat() + '.xls')
119
    msg.attach(fileMsg)
120
 
121
    mailServer.login(SENDER, PASSWORD)
122
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
123
 
124
def main():
125
    workbook = Workbook()
126
 
127
    timeNow = datetime.datetime.now()
128
    toDate = timeNow.strftime('%Y-%m-%d %H:%M:%S')
129
    fromDate = (timeNow - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
130
    data = getProductSaleData(fromDate, toDate)
131
    createXlsReport(workbook, data, 1)
132
 
133
    fromDate = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, 1, 0, 0, 0, 0)
134
    data = getProductSaleData(str(fromDate), str(toDate))
135
    createXlsReport(workbook, data, 2)
136
 
137
    sendmail()
138
 
139
if __name__ == '__main__':
140
    main()