Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
14450 amit.gupta 1
'''
2
Created on Mar 13, 2015
3
 
4
@author: amit
5
'''
6
from datetime import date, datetime, timedelta
14632 amit.gupta 7
from dtr.main import Store, sourceMap
14650 amit.gupta 8
from dtr.reports.amazonreco import generateAmazonReco
14613 amit.gupta 9
from dtr.storage import Mysql
10
from dtr.storage.Mysql import getOrdersAfterDate, getOrdersByTag
14450 amit.gupta 11
from email import encoders
12
from email.mime.base import MIMEBase
13
from email.mime.multipart import MIMEMultipart
14
from email.mime.text import MIMEText
15
from pymongo.mongo_client import MongoClient
14460 amit.gupta 16
from xlrd import open_workbook
14524 amit.gupta 17
from xlutils.copy import copy
14460 amit.gupta 18
from xlwt.Workbook import Workbook
14450 amit.gupta 19
import MySQLdb
20
import smtplib
21
import time
22
import xlwt
14988 amit.gupta 23
from dtr.utils.utils import fromTimeStamp
14460 amit.gupta 24
#from xlwt import 
14450 amit.gupta 25
 
26
client = MongoClient('mongodb://localhost:27017/')
27
 
28
SENDER = "cnc.center@shop2020.in"
29
PASSWORD = "5h0p2o2o"
30
SUBJECT = "DTR User Segmentation report for " + date.today().isoformat()
31
SMTP_SERVER = "smtp.gmail.com"
32
SMTP_PORT = 587    
33
 
14647 amit.gupta 34
XLS_FILENAME = "snapdealaffiliatereco.xls"
14632 amit.gupta 35
XLS_O_FILENAME = "allorders.xls"
14647 amit.gupta 36
XLS_F_FILENAME = "flipkartaffiliatereco.xls"
14650 amit.gupta 37
XLS_A_FILENAME = "amazonaffiliatereco.xls"
14460 amit.gupta 38
boldStyle = xlwt.XFStyle()
39
f = xlwt.Font()
40
f.bold = True
41
boldStyle.font = f
42
i = -1
14616 amit.gupta 43
 
44
datetime_format = xlwt.XFStyle()
45
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
46
 
14450 amit.gupta 47
def generateFlipkartReco():
14508 amit.gupta 48
    global i
49
    i = -1
14460 amit.gupta 50
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=30), 2)
51
    db = client.Dtr
14647 amit.gupta 52
    wb = xlwt.Workbook()
53
    #rb = open_workbook(XLS_F_FILENAME)
54
    #wb = copy(rb)
14460 amit.gupta 55
    #wb = xlwt.Workbook()
56
    row = 0
14647 amit.gupta 57
    row2 = 0
58
    row3 = 0
59
    row4 = 0
60
    worksheet = wb.add_sheet("All Orders")
61
    worksheet1 = wb.add_sheet("Orders Reconciled")
62
    worksheet2 = wb.add_sheet("Orders not Reconciled")
63
    worksheet3 = wb.add_sheet("Aff not Reconciled")
14460 amit.gupta 64
    worksheet.write(row, inc(), 'Order Id', boldStyle)
14647 amit.gupta 65
    worksheet1.write(row, i, 'Order Id', boldStyle)
66
    worksheet2.write(row, i, 'Order Id', boldStyle)
14460 amit.gupta 67
    worksheet.write(row, inc(), 'User Id', boldStyle)
14647 amit.gupta 68
    worksheet1.write(row, i, 'User Id', boldStyle)
69
    worksheet2.write(row, i, 'User Id', boldStyle)
14474 amit.gupta 70
    worksheet.write(row, inc(), 'Username', boldStyle)
14647 amit.gupta 71
    worksheet1.write(row, i, 'Username', boldStyle)
72
    worksheet2.write(row, i, 'Username', boldStyle)
14771 amit.gupta 73
    worksheet.write(row, inc(), 'Version code', boldStyle)
74
    worksheet1.write(row, i, 'Version code', boldStyle)
75
    worksheet2.write(row, i, 'Version code', boldStyle)
76
    worksheet.write(row, inc(), 'Device', boldStyle)
77
    worksheet1.write(row, i, 'Device', boldStyle)
78
    worksheet2.write(row, i, 'Device', boldStyle)
14460 amit.gupta 79
    worksheet.write(row, inc(), 'Merchant Order Id', boldStyle)
14647 amit.gupta 80
    worksheet1.write(row, i, 'Merchant Order Id', boldStyle)
81
    worksheet2.write(row, i, 'Merchant Order Id', boldStyle)
14460 amit.gupta 82
    worksheet.write(row, inc(), 'Product Title', boldStyle)
14647 amit.gupta 83
    worksheet1.write(row, i, 'Product Title', boldStyle)
84
    worksheet2.write(row, i, 'Product Title', boldStyle)
14460 amit.gupta 85
    worksheet.write(row, inc(), 'Price', boldStyle)
14647 amit.gupta 86
    worksheet1.write(row, i, 'Price', boldStyle)
87
    worksheet2.write(row, i, 'Price', boldStyle)
14460 amit.gupta 88
    worksheet.write(row, inc(), 'Quantity', boldStyle)
14647 amit.gupta 89
    worksheet1.write(row, i, 'Quantity', boldStyle)
90
    worksheet2.write(row, i, 'Quantity', boldStyle)
14460 amit.gupta 91
    worksheet.write(row, inc(), 'Status', boldStyle)
14647 amit.gupta 92
    worksheet1.write(row, i, 'Status', boldStyle)
93
    worksheet2.write(row, i, 'Status', boldStyle)
14460 amit.gupta 94
    worksheet.write(row, inc(), 'Detailed Status', boldStyle)
14647 amit.gupta 95
    worksheet1.write(row, i, 'Detailed Status', boldStyle)
96
    worksheet2.write(row, i, 'Detailed Status', boldStyle)
14460 amit.gupta 97
    worksheet.write(row, inc(), 'Cashback Status', boldStyle)
14647 amit.gupta 98
    worksheet1.write(row, i, 'Cashback Status', boldStyle)
99
    worksheet2.write(row, i, 'Cashback Status', boldStyle)
14460 amit.gupta 100
    worksheet.write(row, inc(), 'Our CashBack', boldStyle)
14647 amit.gupta 101
    worksheet1.write(row, i, 'Our CashBack', boldStyle)
102
    worksheet2.write(row, i, 'Our CashBack', boldStyle)
103
    worksheet.write(row, inc(), 'Sale Date', boldStyle) 
104
    worksheet1.write(row, i, 'Sale Date', boldStyle)
105
    worksheet2.write(row, i, 'Sale Date', boldStyle)
14460 amit.gupta 106
    worksheet.write(row, inc(), 'SubtagId', boldStyle)
14647 amit.gupta 107
    worksheet1.write(row, i, 'SubtagId', boldStyle)
108
    worksheet2.write(row, i, 'SubtagId', boldStyle)
14460 amit.gupta 109
    worksheet.write(row, inc(), 'Category', boldStyle)
14647 amit.gupta 110
    worksheet1.write(row, i, 'Category', boldStyle)
14460 amit.gupta 111
    worksheet.write(row, inc(), 'Aff PayOut', boldStyle)
14647 amit.gupta 112
    worksheet1.write(row, i, 'Aff PayOut', boldStyle)
14460 amit.gupta 113
    worksheet.write(row, inc(), 'Aff Sale Amount', boldStyle)
14647 amit.gupta 114
    worksheet1.write(row, i, 'Aff Sale Amount', boldStyle)
14460 amit.gupta 115
    worksheet.write(row, inc(), 'Aff Sale Date', boldStyle)
14647 amit.gupta 116
    worksheet1.write(row, i, 'Aff Sale Date', boldStyle)
14460 amit.gupta 117
    for row1 in curs:
118
        orderId = row1[0]
119
        order = db.merchantOrder.find_one({"orderId":orderId})
120
        if order is None:
121
            continue
122
        saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%d %B, %Y %I:%M %p").replace(hour=0, minute=0, second=0, microsecond=0).timetuple()))
123
        #saleTime1 = int(time.mktime((datetime.strptime(order['placedOn'], "%b %d, %Y %I:%M %p") + timedelta(seconds=-60)).timetuple()))
14647 amit.gupta 124
        reconciled_affiliates = []
14460 amit.gupta 125
        for subOrder in order['subOrders']: 
14647 amit.gupta 126
            affs = list(db.flipkartOrderAffiliateInfo.find({"productCode":subOrder.get("productCode"), "saleDateInt":saleTime}))
14460 amit.gupta 127
            row += 1
128
            i=-1
129
            worksheet.write(row, inc(), orderId)
130
            worksheet.write(row, inc(), row1[1])
14474 amit.gupta 131
            worksheet.write(row, inc(), row1[-1])
14771 amit.gupta 132
            worksheet.write(row, inc(), row1[-2])
133
            worksheet.write(row, inc(), row1[-3])
14460 amit.gupta 134
            worksheet.write(row, inc(), order['merchantOrderId'])
135
            worksheet.write(row, inc(), subOrder['productTitle'])
136
            worksheet.write(row, inc(), subOrder['amountPaid'])
137
            worksheet.write(row, inc(), subOrder['quantity'])
138
            worksheet.write(row, inc(), subOrder['status'])
139
            worksheet.write(row, inc(), subOrder['detailedStatus'])
140
            worksheet.write(row, inc(), subOrder['cashBackStatus'])
141
            worksheet.write(row, inc(), subOrder['cashBackAmount'])
142
            worksheet.write(row, inc(), subOrder['placedOn'])
143
            worksheet.write(row, inc(), order['subTagId'])
144
            for aff in affs:
14647 amit.gupta 145
                if aff["_id"] not in reconciled_affiliates and aff['subTagId']== order['subTagId']:
146
                    reconciled_affiliates.append(aff["_id"])
147
                    row2 += 1
148
                    i = -1 
149
                    worksheet1.write(row2, inc(), orderId)
150
                    worksheet1.write(row2, inc(), row1[1])
151
                    worksheet1.write(row2, inc(), row1[-1])
14771 amit.gupta 152
                    worksheet1.write(row2, inc(), row1[-2])
153
                    worksheet1.write(row2, inc(), row1[-3])
14647 amit.gupta 154
                    worksheet1.write(row2, inc(), order['merchantOrderId'])
155
                    worksheet1.write(row2, inc(), subOrder['productTitle'])
156
                    worksheet1.write(row2, inc(), subOrder['amountPaid'])
157
                    worksheet1.write(row2, inc(), subOrder['quantity'])
158
                    worksheet1.write(row2, inc(), subOrder['status'])
159
                    worksheet1.write(row2, inc(), subOrder['detailedStatus'])
160
                    worksheet1.write(row2, inc(), subOrder['cashBackStatus'])
161
                    worksheet1.write(row2, inc(), subOrder['cashBackAmount'])
162
                    worksheet1.write(row2, inc(), subOrder['placedOn'])
163
                    worksheet1.write(row2, inc(), order['subTagId'])
164
                    db.flipkartOrderAffiliateInfo.update(
165
                        {"productCode":subOrder.get("productCode"), "saleDateInt":saleTime, "subTagId":aff['subTagId']}, 
166
                        {"$set":{"reconciled":True}})
167
                    db.merchantOrder.update({"merchantOrderId":order["merchantOrderId"]}, 
168
                                            {"$set":{"reconciled":True}})
14460 amit.gupta 169
                    worksheet.write(row, inc(), aff['category'])
14647 amit.gupta 170
                    worksheet1.write(row2, i, aff['category'])
14460 amit.gupta 171
                    worksheet.write(row, inc(), aff['payOut'])
14647 amit.gupta 172
                    worksheet1.write(row2, i, aff['payOut'])
14460 amit.gupta 173
                    worksheet.write(row, inc(), aff['saleAmount'])
14647 amit.gupta 174
                    worksheet1.write(row2, i, aff['saleAmount'])
14460 amit.gupta 175
                    worksheet.write(row, inc(), aff['saleDate'])
14647 amit.gupta 176
                    worksheet1.write(row2, i, aff['saleDate'])
14460 amit.gupta 177
                    break
14647 amit.gupta 178
            row3 += 1
179
            i=-1
180
            worksheet2.write(row3, inc(), orderId)
181
            worksheet2.write(row3, inc(), row1[1])
182
            worksheet2.write(row3, inc(), row1[-1])
14771 amit.gupta 183
            worksheet2.write(row3, inc(), row1[-2])
184
            worksheet2.write(row3, inc(), row1[-3])
14647 amit.gupta 185
            worksheet2.write(row3, inc(), order['merchantOrderId'])
186
            worksheet2.write(row3, inc(), subOrder['productTitle'])
187
            worksheet2.write(row3, inc(), subOrder['amountPaid'])
188
            worksheet2.write(row3, inc(), subOrder['quantity'])
189
            worksheet2.write(row3, inc(), subOrder['status'])
190
            worksheet2.write(row3, inc(), subOrder['detailedStatus'])
191
            worksheet2.write(row3, inc(), subOrder['cashBackStatus'])
192
            worksheet2.write(row3, inc(), subOrder['cashBackAmount'])
193
            worksheet2.write(row3, inc(), subOrder['placedOn'])
194
            worksheet2.write(row3, inc(), order['subTagId'])
195
 
196
    i=-1
197
    worksheet3.write(0, inc(), "category",boldStyle)    
198
    worksheet3.write(0, inc(), "conversionStatus",boldStyle)    
199
    worksheet3.write(0, inc(), "Product Title",boldStyle)    
200
    worksheet3.write(0, inc(), "price",boldStyle)    
201
    worksheet3.write(0, inc(), "quantity",boldStyle)    
202
    worksheet3.write(0, inc(), "payOut",boldStyle)    
203
    worksheet3.write(0, inc(), "saleDate",boldStyle)    
204
    worksheet3.write(0, inc(), "subTagId",boldStyle)
205
    for aff in db.flipkartOrderAffiliateInfo.find({"reconciled":{"$exists":False}}):
206
        row4 += 1
207
        i =-1
208
        worksheet3.write(row4, inc(), aff["category"])    
209
        worksheet3.write(row4, inc(), aff["conversionStatus"])    
210
        skuData = getSkuData(2, aff["productCode"])
211
        if skuData is None:    
212
            worksheet3.write(row4, inc(), aff["productTitle"])
213
        else:
214
            worksheet3.write(row4, inc(), skuData["product_name"])
215
        worksheet3.write(row4, inc(), aff['price'])    
216
        worksheet3.write(row4, inc(), aff['quantity'])    
217
        worksheet3.write(row4, inc(), aff['payOut'])    
218
        worksheet3.write(row4, inc(), aff['saleDate'])    
219
        worksheet3.write(row4, inc(), aff['subTagId'])    
220
 
221
 
222
 
223
    wb.save(XLS_F_FILENAME)
14450 amit.gupta 224
def generateSnapDealReco():
14524 amit.gupta 225
    global i
14460 amit.gupta 226
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=30), 3)
14450 amit.gupta 227
    db = client.Dtr
14524 amit.gupta 228
    notReconciled = {}
14487 amit.gupta 229
    matchedList = []
14450 amit.gupta 230
    workbook = xlwt.Workbook()
14501 amit.gupta 231
    worksheet = workbook.add_sheet("Snapdeal Reconciled")
232
    worksheet1 = workbook.add_sheet("Snapdeal Reconciled All")
14508 amit.gupta 233
    worksheet2 = workbook.add_sheet("Snapdeal Orders not reconciled")
234
    affNotReconciledSheet = workbook.add_sheet("Snapdeal Aff not reconciled")
235
    setHeaders(worksheet, worksheet1, worksheet2, affNotReconciledSheet)
14450 amit.gupta 236
    row = 0
14501 amit.gupta 237
    anotherrow = 0
14508 amit.gupta 238
    row2 = 0
14450 amit.gupta 239
    for row1 in curs:
240
        orderId = row1[0]
241
        order = db.merchantOrder.find_one({"orderId":orderId})
242
        if order is None:
243
            continue
14496 amit.gupta 244
        #saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))
14450 amit.gupta 245
        aff = list(db.snapdealOrderAffiliateInfo.find({"subTagId":order["subTagId"]}))
14501 amit.gupta 246
        anotherrow += 1
14988 amit.gupta 247
        try:
248
            formattedTimestamp = order['placedOn']
249
            timestamp1 = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))
250
        except:
251
            timestamp1 = int(time.mktime(row1[-4].timetuple()))
252
            formattedTimestamp = datetime.strftime(fromTimeStamp(timestamp1), "%b %d, %Y, %I:%M %p")
14524 amit.gupta 253
        if len(aff) > 0 and order["subTagId"] not in matchedList and int(order["paidAmount"])==int(aff[0]["saleAmount"]): 
14501 amit.gupta 254
            matchedList.append(order["subTagId"])
14610 amit.gupta 255
            db.snapdealOrderAffiliateInfo.update({"adId":aff[0].get("adId")}, {"$set":{"reconciled":True, "orderId":orderId}}, multi=True)
14501 amit.gupta 256
            order['reconciled'] = True
14610 amit.gupta 257
            order['adId'] = aff[0].get("adId")
14501 amit.gupta 258
            db.merchantOrder.save(order)
259
            row += 1
260
            i=-1 
261
            worksheet.write(row, inc(), orderId)
262
            worksheet1.write(anotherrow, i, orderId)
263
            worksheet.write(row, inc(), row1[1])
264
            worksheet1.write(anotherrow, i, row1[1])
14850 amit.gupta 265
            worksheet.write(row, inc(), row1[-1])
266
            worksheet1.write(anotherrow, i, row1[-1])
267
            worksheet.write(row, inc(), row1[-2])
268
            worksheet1.write(anotherrow, i, row1[-2])
14771 amit.gupta 269
            worksheet.write(row, inc(), row1[-3])
270
            worksheet1.write(anotherrow, i, row1[-3])
14501 amit.gupta 271
            worksheet.write(row, inc(), order['merchantOrderId'])
272
            worksheet1.write(anotherrow, i, order['merchantOrderId'])
273
            worksheet.write(row, inc(), order['subTagId'])
274
            worksheet1.write(anotherrow, i, order['subTagId'])
275
            worksheet.write(row, inc(), order['placedOn'])
276
            worksheet1.write(anotherrow, i, order['placedOn'])
14988 amit.gupta 277
            worksheet.write(row, inc(), formattedTimestamp)
278
            worksheet1.write(anotherrow, i, formattedTimestamp)
14501 amit.gupta 279
            worksheet.write(row, inc(), int(order['paidAmount']))
280
            worksheet1.write(anotherrow, i, int(order['paidAmount']))
14524 amit.gupta 281
            worksheet.write(row, inc(), aff[0]['saleDate'])
282
            worksheet1.write(anotherrow, i, aff[0]['saleDate'])
283
            worksheet.write(row, inc(), aff[0]['saleAmount'])
284
            worksheet1.write(anotherrow, i, aff[0]['saleAmount'])
285
            worksheet.write(row, inc(), aff[0]['payOut'])
286
            worksheet1.write(anotherrow, i, aff[0]['payOut'])
14601 amit.gupta 287
            worksheet.write(row, inc(), aff[0]['ip'])
288
            worksheet1.write(anotherrow, i, aff[0]['ip'])
14501 amit.gupta 289
            k = i
14504 amit.gupta 290
            row -= 1
291
            anotherrow -= 1
14501 amit.gupta 292
            for subOrder in order['subOrders']:
293
                i = k
14503 amit.gupta 294
                row += 1
295
                anotherrow += 1
14501 amit.gupta 296
                worksheet.write(row, inc(), subOrder['productTitle'])
297
                worksheet1.write(anotherrow, i, subOrder['productTitle'])
298
                worksheet.write(row, inc(), subOrder['amountPaid'])
299
                worksheet1.write(anotherrow, i, subOrder['amountPaid'])
300
                worksheet.write(row, inc(), subOrder['quantity'])
301
                worksheet1.write(anotherrow, i, subOrder['quantity'])
302
                worksheet.write(row, inc(), subOrder['status'])
303
                worksheet1.write(anotherrow, i, subOrder['status'])
304
                worksheet.write(row, inc(), subOrder['cashBackStatus'])
305
                worksheet1.write(anotherrow, i, subOrder['cashBackStatus'])
306
                worksheet.write(row, inc(), subOrder['cashBackAmount'])
307
                worksheet1.write(anotherrow, i, subOrder['cashBackAmount'])
14504 amit.gupta 308
 
14501 amit.gupta 309
        else:
14524 amit.gupta 310
            i=-1
14501 amit.gupta 311
            worksheet1.write(anotherrow, inc(), orderId)
312
            worksheet1.write(anotherrow, inc(), row1[1])
14850 amit.gupta 313
            worksheet1.write(anotherrow, inc(), row1[-1])
314
            worksheet1.write(anotherrow, inc(), row1[-2])
14771 amit.gupta 315
            worksheet1.write(anotherrow, inc(), row1[-3])
14501 amit.gupta 316
            worksheet1.write(anotherrow, inc(), order['merchantOrderId'])
317
            worksheet1.write(anotherrow, inc(), order['subTagId'])
318
            worksheet1.write(anotherrow, inc(), order['placedOn'])
319
            worksheet1.write(anotherrow, inc(), int(order['paidAmount']))
14873 amit.gupta 320
 
14524 amit.gupta 321
            notReconciled[orderId] = (anotherrow, i, int(order['paidAmount']), timestamp1, order["subTagId"]) 
322
            inc()
323
            inc()
324
            inc()
14771 amit.gupta 325
            inc()
14501 amit.gupta 326
            k = i
14504 amit.gupta 327
            anotherrow -= 1
14501 amit.gupta 328
            for subOrder in order['subOrders']:
14503 amit.gupta 329
                anotherrow += 1
14501 amit.gupta 330
                i = k
14505 amit.gupta 331
                worksheet1.write(anotherrow, inc(), subOrder['productTitle'])
332
                worksheet1.write(anotherrow, inc(), subOrder['amountPaid'])
333
                worksheet1.write(anotherrow, inc(), subOrder['quantity'])
334
                worksheet1.write(anotherrow, inc(), subOrder['status'])
335
                worksheet1.write(anotherrow, inc(), subOrder['cashBackStatus'])
336
                worksheet1.write(anotherrow, inc(), subOrder['cashBackAmount'])
14570 amit.gupta 337
 
14524 amit.gupta 338
 
339
    last30Days =  date.today() - timedelta(days=30)
340
    int(time.mktime(last30Days.timetuple()))
341
    row = 0
342
    for offer in db.snapdealOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
343
                                                     "saleTime":{"$gt":int(time.mktime(last30Days.timetuple())),
344
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
345
        subTagId = offer.get("subTagId")
346
        saleTime = offer.get("saleTime")
347
        orders = getOrdersByTag(subTagId, 3)
348
        for order in orders:
349
            if notReconciled.has_key(order[0]):
350
                (roww, column, paidAmount, timestamp1, oSubTagId) = notReconciled[order[0]]
351
                if paidAmount==int(offer.get("saleAmount")) and timestamp1 <= saleTime and timestamp1 + 120 >= saleTime:
352
                    i = column
14570 amit.gupta 353
                    worksheet1.write(roww, inc(), offer.get("saleDate"))        
14527 amit.gupta 354
                    worksheet1.write(roww, inc(), offer.get("saleAmount"))        
355
                    worksheet1.write(roww, inc(), offer.get("payOut"))
356
                    del notReconciled[order[0]]
14530 amit.gupta 357
                    print "found match for user", order[1]
14610 amit.gupta 358
                    db.snapdealOrderAffiliateInfo.update({"adId":offer.get("adId")}, {"$set":{"reconciled":True, "orderId":order[0]}}, multi=True)
359
                    db.merchantOrder.update({"orderId":order[0]}, {"$set":{"reconciled":True, "adId":offer.get("adId")}}, multi=True)
14570 amit.gupta 360
                    break
14530 amit.gupta 361
 
14570 amit.gupta 362
    unreconciledOrders = notReconciled.keys()
363
    row2=0
364
    for row1 in curs:
365
        if row1[0] in unreconciledOrders:
366
            for order in db.merchantOrder.find({"orderId":row1[0]}):
367
                row2 += 1
368
                i=-1
369
                worksheet2.write(row2, inc(), order["orderId"])
370
                worksheet2.write(row2, inc(), row1[1])
14850 amit.gupta 371
                worksheet2.write(row2, inc(), row1[-1])
372
                worksheet2.write(row2, inc(), row1[-2])
14771 amit.gupta 373
                worksheet2.write(row2, inc(), row1[-3])
14570 amit.gupta 374
                worksheet2.write(row2, inc(), order['merchantOrderId'])
375
                worksheet2.write(row2, inc(), order['subTagId'])
376
                worksheet2.write(row2, inc(), order['placedOn'])
14988 amit.gupta 377
                worksheet2.write(row2, inc(), formattedTimestamp)
14570 amit.gupta 378
                worksheet2.write(row2, inc(), int(order['paidAmount']))
379
                row2 -=1
380
                k=i
381
                for subOrder in order['subOrders']:
382
                    i = k
383
                    row2 += 1
384
                    worksheet2.write(row2, inc(), subOrder['productTitle'])
385
                    worksheet2.write(row2, inc(), subOrder['amountPaid'])
386
                    worksheet2.write(row2, inc(), subOrder['quantity'])
387
                    worksheet2.write(row2, inc(), subOrder['status'])
388
                    worksheet2.write(row2, inc(), subOrder['cashBackStatus'])
389
                    worksheet2.write(row2, inc(), subOrder['cashBackAmount'])
390
 
391
 
392
    for offer in db.snapdealOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
393
                                                     "saleTime":{"$gt":int(time.mktime(last30Days.timetuple())),
394
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
395
        row += 1
396
        i=-1
397
        affNotReconciledSheet.write(row, inc(), offer.get("adId")) 
398
        affNotReconciledSheet.write(row, inc(), offer.get("subTagId")) 
399
        affNotReconciledSheet.write(row, inc(), offer.get("saleDate")) 
400
        affNotReconciledSheet.write(row, inc(), offer.get("saleAmount")) 
401
        affNotReconciledSheet.write(row, inc(), offer.get("payOut")) 
402
        affNotReconciledSheet.write(row, inc(), offer.get("conversionStatus"))
14601 amit.gupta 403
        affNotReconciledSheet.write(row, inc(), offer.get("ip"))
14570 amit.gupta 404
 
14460 amit.gupta 405
        workbook.save(XLS_FILENAME)
14450 amit.gupta 406
 
14647 amit.gupta 407
def sendmail(email, message, title, *varargs):
14450 amit.gupta 408
    if email == "":
409
        return
410
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
411
    mailServer.ehlo()
412
    mailServer.starttls()
413
    mailServer.ehlo()
414
 
415
    # Create the container (outer) email message.
416
    msg = MIMEMultipart()
417
    msg['Subject'] = title
418
    msg.preamble = title
419
    html_msg = MIMEText(message, 'html')
420
    msg.attach(html_msg)
421
 
422
    #snapdeal more to be added here
14647 amit.gupta 423
    for fileName in varargs:
424
        snapdeal = MIMEBase('application', 'vnd.ms-excel')
425
        snapdeal.set_payload(file(fileName).read())
426
        encoders.encode_base64(snapdeal)
427
        snapdeal.add_header('Content-Disposition', 'attachment;filename=' + fileName)
428
        msg.attach(snapdeal)
14450 amit.gupta 429
 
430
 
431
    email.append('amit.gupta@shop2020.in')
432
    MAILTO = email 
433
    mailServer.login(SENDER, PASSWORD)
434
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
435
 
14508 amit.gupta 436
def setHeaders(worksheet, worksheet1, worksheet2, affNotReconciledSheet):
14505 amit.gupta 437
    boldStyle = xlwt.XFStyle()
438
    f = xlwt.Font()
439
    f.bold = True
440
    boldStyle.font = f
14501 amit.gupta 441
    row = 0
442
    global i
443
    i=-1    
444
    worksheet.write(row, inc(), 'Order Id', boldStyle)
445
    worksheet.write(row, inc(), 'User Id', boldStyle)
14850 amit.gupta 446
    worksheet.write(row, inc(), 'Username', boldStyle)
14601 amit.gupta 447
    worksheet.write(row, inc(), 'Version Code', boldStyle)
14771 amit.gupta 448
    worksheet.write(row, inc(), 'Device', boldStyle)
14501 amit.gupta 449
    worksheet.write(row, inc(), 'Merchant Order Id', boldStyle)
450
    worksheet.write(row, inc(), 'SubtagId', boldStyle)
451
    worksheet.write(row, inc(), 'Sale Date', boldStyle)
14988 amit.gupta 452
    worksheet.write(row, inc(), 'Dtr Sale Date', boldStyle)
14501 amit.gupta 453
    worksheet.write(row, inc(), 'Sale Amount', boldStyle)
454
    worksheet.write(row, inc(), 'Aff Sale Date', boldStyle)
455
    worksheet.write(row, inc(), 'Aff Sale Amt', boldStyle)
456
    worksheet.write(row, inc(), 'Aff PayOut', boldStyle)
14601 amit.gupta 457
    worksheet.write(row, inc(), 'IP', boldStyle)
14501 amit.gupta 458
    worksheet.write(row, inc(), 'Product Title', boldStyle)
459
    worksheet.write(row, inc(), 'Price', boldStyle)
460
    worksheet.write(row, inc(), 'Quantity', boldStyle)
461
    worksheet.write(row, inc(), 'Status', boldStyle)
462
    worksheet.write(row, inc(), 'Cashback Status', boldStyle)
463
    worksheet.write(row, inc(), 'CashBack', boldStyle)
464
 
14505 amit.gupta 465
    i = -1
14501 amit.gupta 466
    worksheet1.write(row, inc(), 'Order Id', boldStyle)
467
    worksheet1.write(row, inc(), 'User Id', boldStyle)
14850 amit.gupta 468
    worksheet1.write(row, inc(), 'Username', boldStyle)
14601 amit.gupta 469
    worksheet1.write(row, inc(), 'Version Code', boldStyle)
14771 amit.gupta 470
    worksheet1.write(row, inc(), 'Device', boldStyle)
14501 amit.gupta 471
    worksheet1.write(row, inc(), 'Merchant Order Id', boldStyle)
472
    worksheet1.write(row, inc(), 'SubtagId', boldStyle)
473
    worksheet1.write(row, inc(), 'Sale Date', boldStyle)
14988 amit.gupta 474
    worksheet1.write(row, inc(), 'Dtr Sale Date', boldStyle)
14501 amit.gupta 475
    worksheet1.write(row, inc(), 'Sale Amount', boldStyle)
476
    worksheet1.write(row, inc(), 'Aff Sale Date', boldStyle)
477
    worksheet1.write(row, inc(), 'Aff Sale Amt', boldStyle)
478
    worksheet1.write(row, inc(), 'Aff PayOut', boldStyle)
14601 amit.gupta 479
    worksheet1.write(row, inc(), 'IP', boldStyle)
14501 amit.gupta 480
    worksheet1.write(row, inc(), 'Product Title', boldStyle)
481
    worksheet1.write(row, inc(), 'Price', boldStyle)
482
    worksheet1.write(row, inc(), 'Quantity', boldStyle)
483
    worksheet1.write(row, inc(), 'Status', boldStyle)
484
    worksheet1.write(row, inc(), 'Cashback Status', boldStyle)
485
    worksheet1.write(row, inc(), 'CashBack', boldStyle) 
14508 amit.gupta 486
 
487
    i = -1
488
    worksheet2.write(row, inc(), 'Order Id', boldStyle)
489
    worksheet2.write(row, inc(), 'User Id', boldStyle)
14850 amit.gupta 490
    worksheet2.write(row, inc(), 'Username', boldStyle)
14605 amit.gupta 491
    worksheet2.write(row, inc(), 'Version Code', boldStyle)
14771 amit.gupta 492
    worksheet2.write(row, inc(), 'Device', boldStyle)
14508 amit.gupta 493
    worksheet2.write(row, inc(), 'Merchant Order Id', boldStyle)
494
    worksheet2.write(row, inc(), 'SubtagId', boldStyle)
495
    worksheet2.write(row, inc(), 'Sale Date', boldStyle)
14988 amit.gupta 496
    worksheet2.write(row, inc(), 'Dtr Sale Date', boldStyle)
14508 amit.gupta 497
    worksheet2.write(row, inc(), 'Sale Amount', boldStyle)
498
    worksheet2.write(row, inc(), 'Product Title', boldStyle)
499
    worksheet2.write(row, inc(), 'Price', boldStyle)
500
    worksheet2.write(row, inc(), 'Quantity', boldStyle)
501
    worksheet2.write(row, inc(), 'Status', boldStyle)
502
    worksheet2.write(row, inc(), 'Cashback Status', boldStyle)
503
    worksheet2.write(row, inc(), 'CashBack', boldStyle)
14450 amit.gupta 504
 
14508 amit.gupta 505
    i =-1
506
    affNotReconciledSheet.write(row, inc(), 'AdId', boldStyle) 
507
    affNotReconciledSheet.write(row, inc(), 'subTagId', boldStyle) 
508
    affNotReconciledSheet.write(row, inc(), 'Sale Date', boldStyle) 
509
    affNotReconciledSheet.write(row, inc(), 'Sale Amount', boldStyle) 
510
    affNotReconciledSheet.write(row, inc(), 'Pay Out', boldStyle) 
511
    affNotReconciledSheet.write(row, inc(), 'Status', boldStyle) 
14601 amit.gupta 512
    affNotReconciledSheet.write(row, inc(), 'IP', boldStyle)
14524 amit.gupta 513
 
514
def getUserAmountReconciled():
515
    pass
516
 
14613 amit.gupta 517
def getUserOrders():
518
    global i
519
    rb = open_workbook(XLS_FILENAME,formatting_info=True)
520
    wb = copy(rb)
521
    worksheet = wb.add_sheet("All Users")
522
    worksheet1 = wb.add_sheet("Suspected Users")
14632 amit.gupta 523
    workbook = xlwt.Workbook()
524
    sh1 = workbook.add_sheet("All Orders")
525
 
14613 amit.gupta 526
    db=client.Dtr
527
    results = Mysql.fetchResult('''
14771 amit.gupta 528
        select ow.*, u.username, crm1.order_count, u.referrer from order_view ow left join users u on u.id = ow.user_id left join (select user_id, count(*) as order_count from order_view where status = 'ORDER_CREATED'  group by user_id) as crm1 on ow.user_id = crm1.user_id where lower(u.referrer) not like 'emp%' or u.referrer is null; 
14613 amit.gupta 529
        ''',)
530
    row = 0
531
    i=-1
532
    worksheet.write(row, inc(), 'User Id', boldStyle)
533
    worksheet1.write(row, i, 'User Id', boldStyle)
534
    worksheet.write(row, inc(), 'User name', boldStyle)
535
    worksheet1.write(row, i, 'User name', boldStyle)
536
    worksheet.write(row, inc(), 'Order Id', boldStyle)
537
    worksheet1.write(row, i, 'Order Id', boldStyle)
538
    worksheet.write(row, inc(), 'Created On', boldStyle)
539
    worksheet1.write(row, i, 'Created On', boldStyle)
540
    worksheet.write(row, inc(), 'Store Id', boldStyle)
541
    worksheet1.write(row, i, 'Store Id', boldStyle)
542
    worksheet.write(row, inc(), 'Merchant Order Id', boldStyle)
543
    worksheet1.write(row, i, 'Merchant Order Id', boldStyle)
14616 amit.gupta 544
    worksheet.write(row, inc(), 'Product title', boldStyle)
545
    worksheet1.write(row, i, 'Product title', boldStyle)
14613 amit.gupta 546
    worksheet.write(row, inc(), 'Amount Paid', boldStyle)
547
    worksheet1.write(row, i, 'Amount Paid', boldStyle)
548
    worksheet.write(row, inc(), 'Cashback', boldStyle)
549
    worksheet1.write(row, i, 'Cashback', boldStyle)
550
    worksheet.write(row, inc(), 'Order Status', boldStyle)
551
    worksheet1.write(row, i, 'Order Status', boldStyle)
552
    worksheet.write(row, inc(), 'Detailed Status', boldStyle)
553
    worksheet1.write(row, i, 'Detailed Status', boldStyle)
554
    worksheet.write(row, inc(), 'Cashback Status', boldStyle)
555
    worksheet1.write(row, i, 'Cashback Status', boldStyle)
556
    worksheet.write(row, inc(), 'Reconciled', boldStyle)
557
    worksheet1.write(row, i, 'Reconciled', boldStyle)
558
    worksheet.write(row, inc(), 'IP', boldStyle)
559
    worksheet1.write(row, i, 'IP', boldStyle)
14693 amit.gupta 560
    i=-1
561
    sh1.write(row, inc(), 'User Id', boldStyle)
562
    sh1.write(row, inc(), 'User name', boldStyle)
563
    sh1.write(row, inc(), 'Order Id', boldStyle)
564
    sh1.write(row, inc(), 'Created On', boldStyle)
565
    sh1.write(row, inc(), 'Store Id', boldStyle)
566
    sh1.write(row, inc(), 'Merchant Order Id', boldStyle)
14771 amit.gupta 567
    sh1.write(row, inc(), 'Status', boldStyle)
14693 amit.gupta 568
    sh1.write(row, inc(), 'Product title', boldStyle)
569
    sh1.write(row, inc(), 'Referrer', boldStyle)
570
    sh1.write(row, inc(), 'Amount Paid', boldStyle)
14771 amit.gupta 571
    sh1.write(row, inc(), 'Catalog Id', boldStyle)
14693 amit.gupta 572
    sh1.write(row, inc(), 'Brand', boldStyle)
573
    sh1.write(row, inc(), 'Model', boldStyle)
574
    sh1.write(row, inc(), 'Category', boldStyle)
14613 amit.gupta 575
 
576
    row=0
577
    row2=0
14632 amit.gupta 578
    row3=0
579
    db1 = client.Catalog
14613 amit.gupta 580
    for result in results:
581
        morder = db.merchantOrder.find_one({"orderId":result[0]})
582
        if morder is not None:
583
            subOrders = morder.get("subOrders")
584
            if subOrders is not None:
585
                for  subOrder in subOrders:
14632 amit.gupta 586
                    row3+=1
587
                    i=-1
14699 amit.gupta 588
                    sh1.write(row3, inc(), result[1])
589
                    sh1.write(row3, inc(), result[-3])
14632 amit.gupta 590
                    sh1.write(row3, inc(), result[0])
591
                    sh1.write(row3, inc(), result[-4], datetime_format)
592
                    sh1.write(row3, inc(), sourceMap.get(result[2]))
593
                    sh1.write(row3, inc(), morder.get("merchantOrderId"))
14771 amit.gupta 594
                    sh1.write(row3, inc(), subOrder.get("status"))
14632 amit.gupta 595
                    sh1.write(row3, inc(), subOrder.get("productTitle"))
14693 amit.gupta 596
                    sh1.write(row3, inc(), result[-1])
14632 amit.gupta 597
                    inc()
598
                    if int(subOrder.get("quantity")) > 0:
599
                        sh1.write(row3, i, int(subOrder.get("amountPaid"))/int(subOrder.get("quantity")))
14647 amit.gupta 600
                    skuData = getSkuData(morder.get("storeId"), subOrder.get("productCode"))
601
                    if morder.get("storeId") in (1,2,4,5):
602
                        skuData = db1.MasterData.find_one({'identifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
603
                    elif morder.get("storeId") == 3:
604
                        skuData = db1.MasterData.find_one({'secondaryIdentifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
14634 amit.gupta 605
                    if skuData is not None:
14771 amit.gupta 606
                        sh1.write(row3, inc(), skuData.get("skuBundleId"))
14634 amit.gupta 607
                        sh1.write(row3, inc(), skuData.get("brand"))
608
                        sh1.write(row3, inc(), skuData.get("model_name"))
609
                        sh1.write(row3, inc(), skuData.get("category"))
14881 amit.gupta 610
                    #removed filter as requested by Rajneesh
611
                    #if subOrder.get("cashBackStatus") == Store.CB_APPROVED or subOrder.get("cashBackStatus") == Store.CB_PENDING:
612
                    row +=1
613
                    i=-1
614
                    worksheet.write(row, inc(), result[0])
615
                    worksheet.write(row, inc(), result[-3])
616
                    worksheet.write(row, inc(), result[1])
617
                    worksheet.write(row, inc(), result[-4], datetime_format)
618
                    worksheet.write(row, inc(), result[2])
619
                    worksheet.write(row, inc(), morder.get("merchantOrderId"))
620
                    worksheet.write(row, inc(), subOrder.get("productTitle"))
621
                    worksheet.write(row, inc(), subOrder.get("amountPaid"))
622
                    worksheet.write(row, inc(), subOrder.get("cashBackAmount"))
623
                    worksheet.write(row, inc(), subOrder.get("status"))
624
                    worksheet.write(row, inc(), subOrder.get("detailedStatus"))
625
                    worksheet.write(row, inc(), subOrder.get("cashBackStatus"))
626
                    worksheet.write(row, inc(), False if morder.get("reconciled") is None else True)
627
                    if morder.get("reconciled") and morder.get("storeId")==3:
628
                        try:
629
                            worksheet.write(row, inc(), db.snapdealOrderAffiliateInfo.find_one({"adId":morder.get("adId"), "reconciled":True}).get("ip"))
630
                        except:
631
                            print "Could not find", morder.get("adId"), "that is reconcired for order", morder.get("orderId")
632
                    if result[-2] >= 10:
633
                        row2 +=1 
14613 amit.gupta 634
                        i=-1
14881 amit.gupta 635
                        worksheet1.write(row2, inc(), result[0])
636
                        worksheet1.write(row2, inc(), result[-3])
637
                        worksheet1.write(row2, inc(), result[1])
638
                        worksheet1.write(row2, inc(), result[-4], datetime_format)
639
                        worksheet1.write(row2, inc(), result[2])
640
                        worksheet1.write(row2, inc(), morder.get("merchantOrderId"))
641
                        worksheet1.write(row2, inc(), subOrder.get("productTitle"))
642
                        worksheet1.write(row2, inc(), subOrder.get("amountPaid"))
643
                        worksheet1.write(row2, inc(), subOrder.get("cashBackAmount"))
644
                        worksheet1.write(row2, inc(), subOrder.get("status"))
645
                        worksheet1.write(row2, inc(), subOrder.get("detailedStatus"))
646
                        worksheet1.write(row2, inc(), subOrder.get("cashBackStatus"))
647
                        worksheet1.write(row2, inc(), False if morder.get("reconciled") is None else True)
14613 amit.gupta 648
                        if morder.get("reconciled") and morder.get("storeId")==3:
649
                            try:
14881 amit.gupta 650
                                worksheet1.write(row2, inc(), db.snapdealOrderAffiliateInfo.find_one({"adId":morder.get("adId"), "reconciled":True}).get("ip"))
14613 amit.gupta 651
                            except:
652
                                print "Could not find", morder.get("adId"), "that is reconcired for order", morder.get("orderId")
14632 amit.gupta 653
 
654
 
14613 amit.gupta 655
    wb.save(XLS_FILENAME)
14632 amit.gupta 656
    workbook.save(XLS_O_FILENAME)
14647 amit.gupta 657
 
658
def getSkuData(storeId, identifier):
659
    if storeId in (1,2,4,5):
660
        skuData = client.Catalog.MasterData.find_one({'identifier':identifier, 'source_id':storeId})
661
    elif storeId == 3:
662
        skuData = client.Catalog.MasterData.find_one({'secondaryIdentifier':identifier, 'source_id':storeId})
663
    return skuData
664
 
14460 amit.gupta 665
def inc():
666
    global i
667
    i+=1
668
    return i
669
 
14632 amit.gupta 670
def addHeaders(sheet):
671
    global i
672
    i = 0
673
    sheet.write(0, inc(), )
14450 amit.gupta 674
def main():
14647 amit.gupta 675
 
14450 amit.gupta 676
    generateSnapDealReco()
14647 amit.gupta 677
    generateFlipkartReco()
14650 amit.gupta 678
    generateAmazonReco(XLS_A_FILENAME)
14613 amit.gupta 679
    getUserOrders()
14774 amit.gupta 680
    sendmail(["amit.gupta@shop2020.in","rajneesh.arora@saholic.com"], "", "Affiliate Reco", XLS_FILENAME, XLS_F_FILENAME, XLS_A_FILENAME)
681
    sendmail(["amit.gupta@shop2020.in", "rajneesh.arora@saholic.com", "chaitnaya.vats@saholic.com", "manoj.kumar@saholic.com"], "", "All DTR Orders", XLS_O_FILENAME)
14450 amit.gupta 682
 
683
if __name__ == '__main__':
14460 amit.gupta 684
    main()
685