Subversion Repositories SmartDukaan

Rev

Rev 17151 | Rev 17153 | Go to most recent revision | Details | Compare with Previous | 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):
17139 naman 33
    if storeId in (1,2,4,5,6,7):
17137 naman 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()            
17138 naman 66
        db=client.Dtr
17137 naman 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'); 
17146 amit.gupta 76
                ''')
17137 naman 77
 
17145 amit.gupta 78
        query = """INSERT INTO allorder 
79
                    (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) 
80
                    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)
81
                """        
17137 naman 82
        for result in results:
83
            morder = db.merchantOrder.find_one({"orderId":result[0]})
84
            if morder is not None:
85
                subOrders = morder.get("subOrders")
86
                if subOrders is not None:
87
                    for  subOrder in subOrders:
88
                        user_id = result[1]
89
                        user_name= result[7]
90
                        order_id =  result[0]
91
                        created_on =result[6]
92
                        store_id = sourceMap.get(result[2])
93
                        merchant_order_id = morder.get("merchantOrderId")
94
                        status = subOrder.get("status")
95
                        detailed_status = subOrder.get("detailedStatus")
96
                        product_title= subOrder.get("productTitle")
97
                        referrer =  result[9]
98
                        if int(subOrder.get("quantity")) > 0:
99
                            amount_paid = int(subOrder.get("amountPaid"))/int(subOrder.get("quantity"))
100
                        skuData = getSkuData(morder.get("storeId"), subOrder.get("productCode"))
101
                        if morder.get("storeId") in (1,2,4,5):
102
                            skuData = db1.MasterData.find_one({'identifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
103
                        elif morder.get("storeId") == 3:
104
                            skuData = db1.MasterData.find_one({'secondaryIdentifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
105
                        if skuData is not None:
106
                            catalog_id = skuData.get("skuBundleId")
107
                            brand= skuData.get("brand")
108
                            model = skuData.get("model_name")
109
                            category = skuData.get("category")
110
                            deal_rank = subOrder.get("dealRank")
111
                            max_nlc = subOrder.get("maxNlc")
112
                            min_nlc = subOrder.get("minNlc")
17145 amit.gupta 113
                            dp = subOrder.get("db")
114
                            item_status = utils.statusMap.get(subOrder.get("itemStatus"))
17137 naman 115
                        else:
116
                            catalog_id = 'None'
117
                            brand= 'None'
118
                            model = 'None'
119
                            category = 'None'
120
                            deal_rank = 'None'
121
                            max_nlc = 'None'
122
                            min_nlc = 'None'
123
                            dp = 'None'
124
                            item_status = 'None'
125
                        merchant_suborder_id = subOrder.get("merchantSubOrderId")
126
                        cashback_status = subOrder.get("cashBackStatus")
127
                        cashback_amount = subOrder.get("cashBackAmount")
128
                        city = result[10]
129
                        state = result[11]
130
                        pincode = result[12]
131
 
132
                        print user_id
17148 amit.gupta 133
                        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)
134
                        cur.execute(query,values)     
17137 naman 135
                        con.commit()
136
    except _mysql.Error, e:
137
 
138
        print "Error %d: %s" % (e.args[0], e.args[1])
139
        sys.exit(1)
140
 
141
    finally:
142
 
143
        if con:
144
            con.close()
145
 
146
 
147
def summaryByBrandAndStore():
148
    con = mdb.connect('localhost','root','shop2020','dtr')
149
    try:
150
        cur = con.cursor()            
151
        book = xlwt.Workbook()
152
        sheet1 = book.add_sheet("data_by_brand")
153
        sheet2 = book.add_sheet("data_by_store")
154
        sheet1.write(0,0,"Brand")
155
        sheet1.write(0,1,"Amount")
156
        sheet1.write(0,2,"Quantity")
157
        sheet1.write(0,3,"No. of order")
158
 
159
        sheet2.write(0,0,"Store")
160
        sheet2.write(0,1,"Amount")
161
        sheet2.write(0,2,"Quantity")
162
        sheet2.write(0,3,"No. of order")
163
        sheet2.write(0,4,"MTD Amount")
164
        sheet2.write(0,5,"MTD Quantity")
165
        sheet2.write(0,6,"MTD No. of order")
166
 
167
 
168
            # ----Data by brand---
169
        tbody = []
170
        rowtemplate_brand="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>"
171
        mailBodyTemplate_brand="""
172
                <html>
173
                    <body>
174
                    <table cellspacing="0" border="1" style="text-align:right">
175
                        <thead>
176
                            <tr>
177
                                <th colspan='4' style="text-align:center">Summary by Brand</th>
178
                            </tr>
179
                            <tr>
180
                                <th style="text-align:center">Brand</th>
181
                                <th  style="text-align:center">Amount</th>
182
                                <th  style="text-align:center">Quantity</th>
183
                                <th  style="text-align:center">Number of Order</th>
184
                            </tr>
185
                        </thead>
186
                        <tbody>
187
                            {0}
188
                        </tbody>
189
                    </table><br><br>
190
                    </body>
191
                </html>
192
            """
193
 
17149 amit.gupta 194
        cur.execute('''select brand ,sum(amount_paid) amount,count(brand) quantity, count(distinct order_id) no_of_orders  
17150 amit.gupta 195
                    from allorder where created_on >= CURDATE() -  interval 1 day and created_on < CURDATE() group by brand order by count(brand) desc limit 10
17149 amit.gupta 196
                    ''')
17137 naman 197
        rows = cur.fetchall()
198
        row = 1
199
        alldata =''
200
        for data in rows:
201
            sheet1.write(row,0,data[0])
202
            sheet1.write(row,1,data[1])
203
            sheet1.write(row,2,data[2])
204
            sheet1.write(row,3,data[3])
205
            row +=1
206
            if len(alldata)>0:
207
                alldata = alldata + ",'"+ data[0]+"'"
208
            else:
209
                alldata = "'"+data[0]+"'"
210
            tbody.append(rowtemplate_brand.format(data[0],data[1],data[2],data[3]))
211
 
212
        print alldata
17152 amit.gupta 213
        cur.execute("select sum(amount_paid) amount,count(*) quantity,count(distinct order_id) from allorder where created_on >= CURDATE() -  interval 1 day and created_on < CURDATE() and brand not in("+alldata+")")
17137 naman 214
        row_other = cur.fetchall()
215
        print row_other
216
        for data in row_other:
217
            sheet1.write(row,0,'Other')
218
            sheet1.write(row,1,data[0])
219
            sheet1.write(row,2,data[1])
220
            sheet1.write(row,3,data[2])
221
            tbody.append(rowtemplate_brand.format('Other',data[0],data[1],data[2]))
222
        tbody.append(rowtemplate_brand.format('','','',''))
223
        tbody.append(rowtemplate_brand.format('','<b>MTD Amount</b>','<b>MTD Quantity</b>','<b>MTD No. of Order</b>'))
224
 
225
        # Brand by MTD
17150 amit.gupta 226
        cur.execute('''select brand ,sum(amount_paid) amount,count(brand) quantity, count(distinct order_id) no_of_orders  
227
                    from allorder where created_on >= CURDATE() -  interval DAY(CURDATE()-INTERVAL 1 day) day and 
228
                                        created_on < CURDATE() group by brand order by count(brand) desc limit 10''')
17137 naman 229
        rows = cur.fetchall()
230
        row += 2
231
        alldata =''
232
        sheet1.write(row,0,"Brands")
233
        sheet1.write(row,1,"MTD Amount")
234
        sheet1.write(row,2,"MTD Quantity")
235
        sheet1.write(row,3,"MTD No. of order")
236
        row +=1
237
 
238
        for data in rows:
239
            sheet1.write(row,0,data[0])
240
            sheet1.write(row,1,data[1])
241
            sheet1.write(row,2,data[2])
242
            sheet1.write(row,3,data[3])
243
            row +=1
244
            if len(alldata)>0:
245
                alldata = alldata + ",'"+ data[0]+"'"
246
            else:
247
                alldata = "'"+data[0]+"'"
248
            tbody.append(rowtemplate_brand.format(data[0],data[1],data[2],data[3]))
249
 
250
        print alldata
17152 amit.gupta 251
        cur.execute("select sum(amount_paid) amount,count(*) quantity,count(distinct order_id) from allorder where created_on >= CURDATE() -  interval DAY(CURDATE()-INTERVAL 1 day) day and created_on < CURDATE() AND brand not in("+alldata+")")
17137 naman 252
        mtd_row_other = cur.fetchall()
253
        print row_other
254
        for data in mtd_row_other:
255
            sheet1.write(row,0,'Other')
256
            sheet1.write(row,1,data[0])
257
            sheet1.write(row,2,data[1])
258
            sheet1.write(row,3,data[2])
259
            tbody.append(rowtemplate_brand.format('Other',data[0],data[1],data[2]))
260
 
261
        message_by_brand = mailBodyTemplate_brand.format("".join(tbody))
262
#         sendmail(["naman.kumar@shop2020.in"] ,message_by_brand, "Summary by brand","")
263
        # Data by Store
264
        # 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;")
265
        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;")
266
        rows = cur.fetchall()
267
        new_row = 1
268
        tbody =[]
269
        rowtemplate="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td></tr>"
270
        for data in rows:
271
            print data[0]
272
            sheet2.write(new_row,0,data[4])
273
            sheet2.write(new_row,1,data[1])
274
            sheet2.write(new_row,2,data[2])
275
            sheet2.write(new_row,3,data[3])
276
            sheet2.write(new_row,4,data[5])
277
            sheet2.write(new_row,5,data[6])
278
            sheet2.write(new_row,6,data[7])
279
            new_row +=1
280
            tbody.append(rowtemplate.format(data[4],data[1],data[2],data[3],data[5],data[6],data[7]))
281
 
282
        # book.save("/home/manish/Desktop/Summary.xls")
283
 
284
        mailBodyTemplate="""
285
                <html>
286
                    <body>
287
                    <table cellspacing="0" border="1" style="text-align:right">
288
                        <thead>
289
                            <tr>
290
                                <th colspan='7' style="text-align:center">Summary by Store</th>
291
                            </tr>
292
                            <tr>
293
                                <th style="text-align:center">Brand</th>
294
                                <th  style="text-align:center">Amount</th>
295
                                <th  style="text-align:center">Quantity</th>
296
                                <th  style="text-align:center">Number of Order</th>
297
                                <th  style="text-align:center">MTD Amount</th>
298
                                <th  style="text-align:center">MTD Quantity</th>
299
                                <th  style="text-align:center">MTD Number of Order</th>
300
                            </tr>
301
                        </thead>
302
                        <tbody>
303
                            {0}
304
                        </tbody>
305
                    </table><br><br>
306
                    </body>
307
                </html>
308
            """
309
        message = mailBodyTemplate.format("".join(tbody))
310
        return message+message_by_brand
311
    except _mysql.Error, e:
312
 
313
        print "Error %d: %s" % (e.args[0], e.args[1])
314
        sys.exit(1)
315
 
316
    finally:
317
 
318
        if con:
319
            con.close()               
320
 
321
if __name__ == '__main__':
322
    addToAllOrders(date(2015,1,1))
323
    #summaryByBrandAndStore()