Subversion Repositories SmartDukaan

Rev

Rev 17145 | Rev 17148 | 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
17146 amit.gupta 133
                        cur.execute(query,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)     
17137 naman 134
                        con.commit()
135
    except _mysql.Error, e:
136
 
137
        print "Error %d: %s" % (e.args[0], e.args[1])
138
        sys.exit(1)
139
 
140
    finally:
141
 
142
        if con:
143
            con.close()
144
 
145
 
146
def summaryByBrandAndStore():
147
    con = mdb.connect('localhost','root','shop2020','dtr')
148
    try:
149
        cur = con.cursor()            
150
        book = xlwt.Workbook()
151
        sheet1 = book.add_sheet("data_by_brand")
152
        sheet2 = book.add_sheet("data_by_store")
153
        sheet1.write(0,0,"Brand")
154
        sheet1.write(0,1,"Amount")
155
        sheet1.write(0,2,"Quantity")
156
        sheet1.write(0,3,"No. of order")
157
 
158
        sheet2.write(0,0,"Store")
159
        sheet2.write(0,1,"Amount")
160
        sheet2.write(0,2,"Quantity")
161
        sheet2.write(0,3,"No. of order")
162
        sheet2.write(0,4,"MTD Amount")
163
        sheet2.write(0,5,"MTD Quantity")
164
        sheet2.write(0,6,"MTD No. of order")
165
 
166
 
167
            # ----Data by brand---
168
        tbody = []
169
        rowtemplate_brand="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>"
170
        mailBodyTemplate_brand="""
171
                <html>
172
                    <body>
173
                    <table cellspacing="0" border="1" style="text-align:right">
174
                        <thead>
175
                            <tr>
176
                                <th colspan='4' style="text-align:center">Summary by Brand</th>
177
                            </tr>
178
                            <tr>
179
                                <th style="text-align:center">Brand</th>
180
                                <th  style="text-align:center">Amount</th>
181
                                <th  style="text-align:center">Quantity</th>
182
                                <th  style="text-align:center">Number of Order</th>
183
                            </tr>
184
                        </thead>
185
                        <tbody>
186
                            {0}
187
                        </tbody>
188
                    </table><br><br>
189
                    </body>
190
                </html>
191
            """
192
 
193
        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;")
194
        rows = cur.fetchall()
195
        row = 1
196
        alldata =''
197
        for data in rows:
198
            sheet1.write(row,0,data[0])
199
            sheet1.write(row,1,data[1])
200
            sheet1.write(row,2,data[2])
201
            sheet1.write(row,3,data[3])
202
            row +=1
203
            if len(alldata)>0:
204
                alldata = alldata + ",'"+ data[0]+"'"
205
            else:
206
                alldata = "'"+data[0]+"'"
207
            tbody.append(rowtemplate_brand.format(data[0],data[1],data[2],data[3]))
208
 
209
        print alldata
210
        cur.execute("select sum(amount_paid) amount,count(*) quantity,count(distinct order_id) from allorder where brand not in("+alldata+");")
211
        row_other = cur.fetchall()
212
        print row_other
213
        for data in row_other:
214
            sheet1.write(row,0,'Other')
215
            sheet1.write(row,1,data[0])
216
            sheet1.write(row,2,data[1])
217
            sheet1.write(row,3,data[2])
218
            tbody.append(rowtemplate_brand.format('Other',data[0],data[1],data[2]))
219
        tbody.append(rowtemplate_brand.format('','','',''))
220
        tbody.append(rowtemplate_brand.format('','<b>MTD Amount</b>','<b>MTD Quantity</b>','<b>MTD No. of Order</b>'))
221
 
222
        # Brand by MTD
223
        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;")
224
        rows = cur.fetchall()
225
        row += 2
226
        alldata =''
227
        sheet1.write(row,0,"Brands")
228
        sheet1.write(row,1,"MTD Amount")
229
        sheet1.write(row,2,"MTD Quantity")
230
        sheet1.write(row,3,"MTD No. of order")
231
        row +=1
232
 
233
        for data in rows:
234
            sheet1.write(row,0,data[0])
235
            sheet1.write(row,1,data[1])
236
            sheet1.write(row,2,data[2])
237
            sheet1.write(row,3,data[3])
238
            row +=1
239
            if len(alldata)>0:
240
                alldata = alldata + ",'"+ data[0]+"'"
241
            else:
242
                alldata = "'"+data[0]+"'"
243
            tbody.append(rowtemplate_brand.format(data[0],data[1],data[2],data[3]))
244
 
245
        print alldata
246
        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+");")
247
        mtd_row_other = cur.fetchall()
248
        print row_other
249
        for data in mtd_row_other:
250
            sheet1.write(row,0,'Other')
251
            sheet1.write(row,1,data[0])
252
            sheet1.write(row,2,data[1])
253
            sheet1.write(row,3,data[2])
254
            tbody.append(rowtemplate_brand.format('Other',data[0],data[1],data[2]))
255
 
256
        message_by_brand = mailBodyTemplate_brand.format("".join(tbody))
257
#         sendmail(["naman.kumar@shop2020.in"] ,message_by_brand, "Summary by brand","")
258
        # Data by Store
259
        # 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;")
260
        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;")
261
        rows = cur.fetchall()
262
        new_row = 1
263
        tbody =[]
264
        rowtemplate="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td></tr>"
265
        for data in rows:
266
            print data[0]
267
            sheet2.write(new_row,0,data[4])
268
            sheet2.write(new_row,1,data[1])
269
            sheet2.write(new_row,2,data[2])
270
            sheet2.write(new_row,3,data[3])
271
            sheet2.write(new_row,4,data[5])
272
            sheet2.write(new_row,5,data[6])
273
            sheet2.write(new_row,6,data[7])
274
            new_row +=1
275
            tbody.append(rowtemplate.format(data[4],data[1],data[2],data[3],data[5],data[6],data[7]))
276
 
277
        # book.save("/home/manish/Desktop/Summary.xls")
278
 
279
        mailBodyTemplate="""
280
                <html>
281
                    <body>
282
                    <table cellspacing="0" border="1" style="text-align:right">
283
                        <thead>
284
                            <tr>
285
                                <th colspan='7' style="text-align:center">Summary by Store</th>
286
                            </tr>
287
                            <tr>
288
                                <th style="text-align:center">Brand</th>
289
                                <th  style="text-align:center">Amount</th>
290
                                <th  style="text-align:center">Quantity</th>
291
                                <th  style="text-align:center">Number of Order</th>
292
                                <th  style="text-align:center">MTD Amount</th>
293
                                <th  style="text-align:center">MTD Quantity</th>
294
                                <th  style="text-align:center">MTD Number of Order</th>
295
                            </tr>
296
                        </thead>
297
                        <tbody>
298
                            {0}
299
                        </tbody>
300
                    </table><br><br>
301
                    </body>
302
                </html>
303
            """
304
        message = mailBodyTemplate.format("".join(tbody))
305
        return message+message_by_brand
306
    except _mysql.Error, e:
307
 
308
        print "Error %d: %s" % (e.args[0], e.args[1])
309
        sys.exit(1)
310
 
311
    finally:
312
 
313
        if con:
314
            con.close()               
315
 
316
if __name__ == '__main__':
317
    addToAllOrders(date(2015,1,1))
318
    #summaryByBrandAndStore()