Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
17137 naman 1
'''
2
Created on 24-Sep-2015
3
 
4
@author: manish
5
'''
6
import _mysql
7
from datetime import date, datetime, timedelta
8
from email.mime.multipart import MIMEMultipart
9
from email.mime.text import MIMEText
10
from pymongo import MongoClient
11
import smtplib
12
import sys
13
import xlwt
14
 
15
import MySQLdb as mdb
16
from dtr.main import Store, sourceMap
17
from dtr.storage import Mysql
18
from dtr.utils import utils
19
import dtr.utils
20
 
21
 
22
# DataService.initialize()
23
# client = MongoClient('mongodb://localhost:27017/')
24
SENDER = "cnc.center@shop2020.in"
25
PASSWORD = "5h0p2o2o"
26
SUBJECT = "Summary"
27
SMTP_SERVER = "smtp.gmail.com"
28
SMTP_PORT = 587
29
client = MongoClient()
30
con = mdb.connect('localhost','root','shop2020','dtr')
31
 
32
def getSkuData(storeId, identifier):
33
    if storeId in (1,2,4,5):
34
        skuData = client.Catalog.MasterData.find_one({'identifier':identifier, 'source_id':storeId})
35
    elif storeId == 3:
36
        skuData = client.Catalog.MasterData.find_one({'secondaryIdentifier':identifier, 'source_id':storeId})
37
    return skuData
38
 
39
def sendmail(email, message, title, *varargs):
40
    if email == "":
41
        return
42
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
43
    mailServer.ehlo()
44
    mailServer.starttls()
45
    mailServer.ehlo()
46
 
47
    # Create the container (outer) email message.
48
    msg = MIMEMultipart()
49
    msg['Subject'] = title
50
    msg.preamble = title
51
    html_msg = MIMEText(message, 'html')
52
    msg.attach(html_msg)
53
 
54
#     email.append('amit.gupta@shop2020.in')
55
    MAILTO = email 
56
    mailServer.login(SENDER, PASSWORD)
57
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
58
 
59
def addToAllOrders(start_date, end_date=None):
60
    if not end_date:
61
        end_date = datetime.now()
62
    else:
63
        end_date = end_date + timedelta(days=1) 
64
    try:
65
        cur = con.cursor()            
66
        db=client.dump
67
        db1 = client.Catalog
68
        cur.execute("delete from allorder where created_on >= %s and created_on < %s", (start_date, end_date))
69
        con.commit()
70
        results = Mysql.fetchResult('''
71
                select ow.*, u.username, crm1.order_count, u.referrer, aua.city,aua.state,aua.pincode from order_view ow 
72
                left join users u on u.id = ow.user_id 
73
                left join (select user_id, count(*) as order_count from order_view where status in ('ORDER_CREATED','DETAIL_CREATED')  group by user_id)as crm1 on ow.user_id = crm1.user_id
74
                left join (select * from (select * from all_user_addresses order by source) s group by user_id)aua on aua.user_id=u.id 
75
                where (lower(u.referrer) not like 'emp%' or u.utm_campaign is not null) and u.activated = 1 and ow.status in ('ORDER_CREATED','DETAIL_CREATED'); 
76
                ''',)
77
 
78
        query = """INSERT INTO allorder (user_id, user_name, order_id, created_on, store_id, merchant_order_id, status, detailed_status, product_title, referrer, amount_paid, catalog_id, brand, model,category, deal_rank, max_nlc, min_nlc, dp, item_status, city, state, pincode, merchant_suborder_id,cashback_status,cashback_amount) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""        
79
        for result in results:
80
            morder = db.merchantOrder.find_one({"orderId":result[0]})
81
            if morder is not None:
82
                subOrders = morder.get("subOrders")
83
                if subOrders is not None:
84
                    for  subOrder in subOrders:
85
                        user_id = result[1]
86
                        user_name= result[7]
87
                        order_id =  result[0]
88
                        created_on =result[6]
89
                        store_id = sourceMap.get(result[2])
90
                        merchant_order_id = morder.get("merchantOrderId")
91
                        status = subOrder.get("status")
92
                        detailed_status = subOrder.get("detailedStatus")
93
                        product_title= subOrder.get("productTitle")
94
                        referrer =  result[9]
95
                        if int(subOrder.get("quantity")) > 0:
96
                            amount_paid = int(subOrder.get("amountPaid"))/int(subOrder.get("quantity"))
97
                        skuData = getSkuData(morder.get("storeId"), subOrder.get("productCode"))
98
                        if morder.get("storeId") in (1,2,4,5):
99
                            skuData = db1.MasterData.find_one({'identifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
100
                        elif morder.get("storeId") == 3:
101
                            skuData = db1.MasterData.find_one({'secondaryIdentifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
102
                        if skuData is not None:
103
                            catalog_id = skuData.get("skuBundleId")
104
                            brand= skuData.get("brand")
105
                            model = skuData.get("model_name")
106
                            category = skuData.get("category")
107
                            deal_rank = subOrder.get("dealRank")
108
                            max_nlc = subOrder.get("maxNlc")
109
                            min_nlc = subOrder.get("minNlc")
110
                            dp = utils.statusMap.get(subOrder.get("db"))
111
                            item_status = subOrder.get("itemStatus")
112
                        else:
113
                            catalog_id = 'None'
114
                            brand= 'None'
115
                            model = 'None'
116
                            category = 'None'
117
                            deal_rank = 'None'
118
                            max_nlc = 'None'
119
                            min_nlc = 'None'
120
                            dp = 'None'
121
                            item_status = 'None'
122
                        merchant_suborder_id = subOrder.get("merchantSubOrderId")
123
                        cashback_status = subOrder.get("cashBackStatus")
124
                        cashback_amount = subOrder.get("cashBackAmount")
125
                        city = result[10]
126
                        state = result[11]
127
                        pincode = result[12]
128
 
129
                        print user_id
130
                        values = (user_id, user_name, order_id, created_on, store_id, merchant_order_id, status, detailed_status, product_title, referrer, amount_paid, catalog_id, brand, model,category, deal_rank, max_nlc, min_nlc, dp, item_status, city, state, pincode,merchant_suborder_id,cashback_status,cashback_amount)
131
                        cur.execute(query,values)     
132
                        con.commit()
133
    except _mysql.Error, e:
134
 
135
        print "Error %d: %s" % (e.args[0], e.args[1])
136
        sys.exit(1)
137
 
138
    finally:
139
 
140
        if con:
141
            con.close()
142
 
143
 
144
def summaryByBrandAndStore():
145
    con = mdb.connect('localhost','root','shop2020','dtr')
146
    try:
147
        cur = con.cursor()            
148
        book = xlwt.Workbook()
149
        sheet1 = book.add_sheet("data_by_brand")
150
        sheet2 = book.add_sheet("data_by_store")
151
        sheet1.write(0,0,"Brand")
152
        sheet1.write(0,1,"Amount")
153
        sheet1.write(0,2,"Quantity")
154
        sheet1.write(0,3,"No. of order")
155
 
156
        sheet2.write(0,0,"Store")
157
        sheet2.write(0,1,"Amount")
158
        sheet2.write(0,2,"Quantity")
159
        sheet2.write(0,3,"No. of order")
160
        sheet2.write(0,4,"MTD Amount")
161
        sheet2.write(0,5,"MTD Quantity")
162
        sheet2.write(0,6,"MTD No. of order")
163
 
164
 
165
            # ----Data by brand---
166
        tbody = []
167
        rowtemplate_brand="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>"
168
        mailBodyTemplate_brand="""
169
                <html>
170
                    <body>
171
                    <table cellspacing="0" border="1" style="text-align:right">
172
                        <thead>
173
                            <tr>
174
                                <th colspan='4' style="text-align:center">Summary by Brand</th>
175
                            </tr>
176
                            <tr>
177
                                <th style="text-align:center">Brand</th>
178
                                <th  style="text-align:center">Amount</th>
179
                                <th  style="text-align:center">Quantity</th>
180
                                <th  style="text-align:center">Number of Order</th>
181
                            </tr>
182
                        </thead>
183
                        <tbody>
184
                            {0}
185
                        </tbody>
186
                    </table><br><br>
187
                    </body>
188
                </html>
189
            """
190
 
191
        cur.execute("select brand ,sum(amount_paid) amount,count(brand) quantity, count(distinct order_id) no_of_orders  from allorder group by brand order by count(brand) desc limit 10;")
192
        rows = cur.fetchall()
193
        row = 1
194
        alldata =''
195
        for data in rows:
196
            sheet1.write(row,0,data[0])
197
            sheet1.write(row,1,data[1])
198
            sheet1.write(row,2,data[2])
199
            sheet1.write(row,3,data[3])
200
            row +=1
201
            if len(alldata)>0:
202
                alldata = alldata + ",'"+ data[0]+"'"
203
            else:
204
                alldata = "'"+data[0]+"'"
205
            tbody.append(rowtemplate_brand.format(data[0],data[1],data[2],data[3]))
206
 
207
        print alldata
208
        cur.execute("select sum(amount_paid) amount,count(*) quantity,count(distinct order_id) from allorder where brand not in("+alldata+");")
209
        row_other = cur.fetchall()
210
        print row_other
211
        for data in row_other:
212
            sheet1.write(row,0,'Other')
213
            sheet1.write(row,1,data[0])
214
            sheet1.write(row,2,data[1])
215
            sheet1.write(row,3,data[2])
216
            tbody.append(rowtemplate_brand.format('Other',data[0],data[1],data[2]))
217
        tbody.append(rowtemplate_brand.format('','','',''))
218
        tbody.append(rowtemplate_brand.format('','<b>MTD Amount</b>','<b>MTD Quantity</b>','<b>MTD No. of Order</b>'))
219
 
220
        # Brand by MTD
221
        cur.execute("select brand ,sum(amount_paid) amount,count(brand) quantity, count(distinct order_id) no_of_orders  from allorder where month(`created_on`) = 4 group by brand order by count(brand) desc limit 10;")
222
        rows = cur.fetchall()
223
        row += 2
224
        alldata =''
225
        sheet1.write(row,0,"Brands")
226
        sheet1.write(row,1,"MTD Amount")
227
        sheet1.write(row,2,"MTD Quantity")
228
        sheet1.write(row,3,"MTD No. of order")
229
        row +=1
230
 
231
        for data in rows:
232
            sheet1.write(row,0,data[0])
233
            sheet1.write(row,1,data[1])
234
            sheet1.write(row,2,data[2])
235
            sheet1.write(row,3,data[3])
236
            row +=1
237
            if len(alldata)>0:
238
                alldata = alldata + ",'"+ data[0]+"'"
239
            else:
240
                alldata = "'"+data[0]+"'"
241
            tbody.append(rowtemplate_brand.format(data[0],data[1],data[2],data[3]))
242
 
243
        print alldata
244
        cur.execute("select sum(amount_paid) amount,count(*) quantity,count(distinct order_id) from allorder where month(`created_on`) = 4 AND brand not in("+alldata+");")
245
        mtd_row_other = cur.fetchall()
246
        print row_other
247
        for data in mtd_row_other:
248
            sheet1.write(row,0,'Other')
249
            sheet1.write(row,1,data[0])
250
            sheet1.write(row,2,data[1])
251
            sheet1.write(row,3,data[2])
252
            tbody.append(rowtemplate_brand.format('Other',data[0],data[1],data[2]))
253
 
254
        message_by_brand = mailBodyTemplate_brand.format("".join(tbody))
255
#         sendmail(["naman.kumar@shop2020.in"] ,message_by_brand, "Summary by brand","")
256
        # Data by Store
257
        # cur.execute("select store_id store,sum(amount_paid) amount,count(store_id) quantity ,count(distinct order_id) from allorder group by store_id order by store_id ASC;")
258
        cur.execute("select x.*,a.store_id mtd_store,sum(a.amount_paid) mtd_amount,count(a.store_id) mtd_quantity, count(distinct a.order_id) mtd_num_of_order from allorder a left join (select store_id store,sum(amount_paid) amount,count(store_id) quantity,count(distinct order_id) num_of_orders from allorder where month(created_on) = 4 group by store_id ) as x on a.store_id=x.store  group by a.store_id order by store_id ASC;")
259
        rows = cur.fetchall()
260
        new_row = 1
261
        tbody =[]
262
        rowtemplate="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td></tr>"
263
        for data in rows:
264
            print data[0]
265
            sheet2.write(new_row,0,data[4])
266
            sheet2.write(new_row,1,data[1])
267
            sheet2.write(new_row,2,data[2])
268
            sheet2.write(new_row,3,data[3])
269
            sheet2.write(new_row,4,data[5])
270
            sheet2.write(new_row,5,data[6])
271
            sheet2.write(new_row,6,data[7])
272
            new_row +=1
273
            tbody.append(rowtemplate.format(data[4],data[1],data[2],data[3],data[5],data[6],data[7]))
274
 
275
        # book.save("/home/manish/Desktop/Summary.xls")
276
 
277
        mailBodyTemplate="""
278
                <html>
279
                    <body>
280
                    <table cellspacing="0" border="1" style="text-align:right">
281
                        <thead>
282
                            <tr>
283
                                <th colspan='7' style="text-align:center">Summary by Store</th>
284
                            </tr>
285
                            <tr>
286
                                <th style="text-align:center">Brand</th>
287
                                <th  style="text-align:center">Amount</th>
288
                                <th  style="text-align:center">Quantity</th>
289
                                <th  style="text-align:center">Number of Order</th>
290
                                <th  style="text-align:center">MTD Amount</th>
291
                                <th  style="text-align:center">MTD Quantity</th>
292
                                <th  style="text-align:center">MTD Number of Order</th>
293
                            </tr>
294
                        </thead>
295
                        <tbody>
296
                            {0}
297
                        </tbody>
298
                    </table><br><br>
299
                    </body>
300
                </html>
301
            """
302
        message = mailBodyTemplate.format("".join(tbody))
303
        return message+message_by_brand
304
    except _mysql.Error, e:
305
 
306
        print "Error %d: %s" % (e.args[0], e.args[1])
307
        sys.exit(1)
308
 
309
    finally:
310
 
311
        if con:
312
            con.close()               
313
 
314
if __name__ == '__main__':
315
    addToAllOrders(date(2015,1,1))
316
    #summaryByBrandAndStore()