Subversion Repositories SmartDukaan

Rev

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