Subversion Repositories SmartDukaan

Rev

Rev 17012 | Rev 17014 | 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
15932 amit.gupta 10
from dtr.storage.DataService import Users, Clicks, FlipkartOrders,\
11
    All_user_addresses
14613 amit.gupta 12
from dtr.storage.Mysql import getOrdersAfterDate, getOrdersByTag
16947 amit.gupta 13
from dtr.utils import utils
15423 amit.gupta 14
from elixir import *
15440 amit.gupta 15
from sqlalchemy.sql.expression import func, func, or_
14450 amit.gupta 16
from email import encoders
17
from email.mime.base import MIMEBase
18
from email.mime.multipart import MIMEMultipart
19
from email.mime.text import MIMEText
20
from pymongo.mongo_client import MongoClient
14460 amit.gupta 21
from xlrd import open_workbook
14524 amit.gupta 22
from xlutils.copy import copy
14460 amit.gupta 23
from xlwt.Workbook import Workbook
14450 amit.gupta 24
import MySQLdb
25
import smtplib
26
import time
27
import xlwt
16317 amit.gupta 28
from dtr.utils import utils
17001 amit.gupta 29
from dtr.utils.utils import toTimeStamp
14460 amit.gupta 30
#from xlwt import 
14450 amit.gupta 31
 
15445 amit.gupta 32
DataService.initialize()
14450 amit.gupta 33
client = MongoClient('mongodb://localhost:27017/')
34
 
35
SENDER = "cnc.center@shop2020.in"
36
PASSWORD = "5h0p2o2o"
37
SUBJECT = "DTR User Segmentation report for " + date.today().isoformat()
38
SMTP_SERVER = "smtp.gmail.com"
39
SMTP_PORT = 587    
40
 
14647 amit.gupta 41
XLS_FILENAME = "snapdealaffiliatereco.xls"
14632 amit.gupta 42
XLS_O_FILENAME = "allorders.xls"
14647 amit.gupta 43
XLS_F_FILENAME = "flipkartaffiliatereco.xls"
14650 amit.gupta 44
XLS_A_FILENAME = "amazonaffiliatereco.xls"
15791 manish.sha 45
XLS_SC_FILENAME = "shopcluesaffiliatereco.xls"
17013 manish.sha 46
XLS_HS_FILENAME = "homeshopaffiliatereco.xls"
14460 amit.gupta 47
boldStyle = xlwt.XFStyle()
48
f = xlwt.Font()
49
f.bold = True
50
boldStyle.font = f
51
i = -1
14616 amit.gupta 52
 
53
datetime_format = xlwt.XFStyle()
54
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
15540 amit.gupta 55
categoryMap = {3:"Mobiles", 5:"Tablets"}
14450 amit.gupta 56
def generateFlipkartReco():
14508 amit.gupta 57
    global i
58
    i = -1
14460 amit.gupta 59
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=30), 2)
60
    db = client.Dtr
14647 amit.gupta 61
    wb = xlwt.Workbook()
62
    #rb = open_workbook(XLS_F_FILENAME)
63
    #wb = copy(rb)
14460 amit.gupta 64
    #wb = xlwt.Workbook()
65
    row = 0
14647 amit.gupta 66
    row2 = 0
67
    row3 = 0
68
    row4 = 0
69
    worksheet = wb.add_sheet("All Orders")
70
    worksheet1 = wb.add_sheet("Orders Reconciled")
71
    worksheet2 = wb.add_sheet("Orders not Reconciled")
72
    worksheet3 = wb.add_sheet("Aff not Reconciled")
14460 amit.gupta 73
    worksheet.write(row, inc(), 'Order Id', boldStyle)
14647 amit.gupta 74
    worksheet1.write(row, i, 'Order Id', boldStyle)
75
    worksheet2.write(row, i, 'Order Id', boldStyle)
14460 amit.gupta 76
    worksheet.write(row, inc(), 'User Id', boldStyle)
14647 amit.gupta 77
    worksheet1.write(row, i, 'User Id', boldStyle)
78
    worksheet2.write(row, i, 'User Id', boldStyle)
14474 amit.gupta 79
    worksheet.write(row, inc(), 'Username', boldStyle)
14647 amit.gupta 80
    worksheet1.write(row, i, 'Username', boldStyle)
81
    worksheet2.write(row, i, 'Username', boldStyle)
14771 amit.gupta 82
    worksheet.write(row, inc(), 'Version code', boldStyle)
83
    worksheet1.write(row, i, 'Version code', boldStyle)
84
    worksheet2.write(row, i, 'Version code', boldStyle)
85
    worksheet.write(row, inc(), 'Device', boldStyle)
86
    worksheet1.write(row, i, 'Device', boldStyle)
87
    worksheet2.write(row, i, 'Device', boldStyle)
14460 amit.gupta 88
    worksheet.write(row, inc(), 'Merchant Order Id', boldStyle)
14647 amit.gupta 89
    worksheet1.write(row, i, 'Merchant Order Id', boldStyle)
90
    worksheet2.write(row, i, 'Merchant Order Id', boldStyle)
14460 amit.gupta 91
    worksheet.write(row, inc(), 'Product Title', boldStyle)
14647 amit.gupta 92
    worksheet1.write(row, i, 'Product Title', boldStyle)
93
    worksheet2.write(row, i, 'Product Title', boldStyle)
14460 amit.gupta 94
    worksheet.write(row, inc(), 'Price', boldStyle)
14647 amit.gupta 95
    worksheet1.write(row, i, 'Price', boldStyle)
96
    worksheet2.write(row, i, 'Price', boldStyle)
14460 amit.gupta 97
    worksheet.write(row, inc(), 'Quantity', boldStyle)
14647 amit.gupta 98
    worksheet1.write(row, i, 'Quantity', boldStyle)
99
    worksheet2.write(row, i, 'Quantity', boldStyle)
14460 amit.gupta 100
    worksheet.write(row, inc(), 'Status', boldStyle)
14647 amit.gupta 101
    worksheet1.write(row, i, 'Status', boldStyle)
102
    worksheet2.write(row, i, 'Status', boldStyle)
14460 amit.gupta 103
    worksheet.write(row, inc(), 'Detailed Status', boldStyle)
14647 amit.gupta 104
    worksheet1.write(row, i, 'Detailed Status', boldStyle)
105
    worksheet2.write(row, i, 'Detailed Status', boldStyle)
14460 amit.gupta 106
    worksheet.write(row, inc(), 'Cashback Status', boldStyle)
14647 amit.gupta 107
    worksheet1.write(row, i, 'Cashback Status', boldStyle)
108
    worksheet2.write(row, i, 'Cashback Status', boldStyle)
14460 amit.gupta 109
    worksheet.write(row, inc(), 'Our CashBack', boldStyle)
14647 amit.gupta 110
    worksheet1.write(row, i, 'Our CashBack', boldStyle)
111
    worksheet2.write(row, i, 'Our CashBack', boldStyle)
112
    worksheet.write(row, inc(), 'Sale Date', boldStyle) 
113
    worksheet1.write(row, i, 'Sale Date', boldStyle)
114
    worksheet2.write(row, i, 'Sale Date', boldStyle)
14460 amit.gupta 115
    worksheet.write(row, inc(), 'SubtagId', boldStyle)
14647 amit.gupta 116
    worksheet1.write(row, i, 'SubtagId', boldStyle)
117
    worksheet2.write(row, i, 'SubtagId', boldStyle)
14460 amit.gupta 118
    worksheet.write(row, inc(), 'Category', boldStyle)
14647 amit.gupta 119
    worksheet1.write(row, i, 'Category', boldStyle)
14460 amit.gupta 120
    worksheet.write(row, inc(), 'Aff PayOut', boldStyle)
14647 amit.gupta 121
    worksheet1.write(row, i, 'Aff PayOut', boldStyle)
14460 amit.gupta 122
    worksheet.write(row, inc(), 'Aff Sale Amount', boldStyle)
14647 amit.gupta 123
    worksheet1.write(row, i, 'Aff Sale Amount', boldStyle)
14460 amit.gupta 124
    worksheet.write(row, inc(), 'Aff Sale Date', boldStyle)
14647 amit.gupta 125
    worksheet1.write(row, i, 'Aff Sale Date', boldStyle)
14460 amit.gupta 126
    for row1 in curs:
127
        orderId = row1[0]
128
        order = db.merchantOrder.find_one({"orderId":orderId})
129
        if order is None:
130
            continue
131
        saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%d %B, %Y %I:%M %p").replace(hour=0, minute=0, second=0, microsecond=0).timetuple()))
132
        #saleTime1 = int(time.mktime((datetime.strptime(order['placedOn'], "%b %d, %Y %I:%M %p") + timedelta(seconds=-60)).timetuple()))
14647 amit.gupta 133
        reconciled_affiliates = []
14460 amit.gupta 134
        for subOrder in order['subOrders']: 
14647 amit.gupta 135
            affs = list(db.flipkartOrderAffiliateInfo.find({"productCode":subOrder.get("productCode"), "saleDateInt":saleTime}))
14460 amit.gupta 136
            row += 1
137
            i=-1
138
            worksheet.write(row, inc(), orderId)
139
            worksheet.write(row, inc(), row1[1])
14474 amit.gupta 140
            worksheet.write(row, inc(), row1[-1])
14771 amit.gupta 141
            worksheet.write(row, inc(), row1[-2])
142
            worksheet.write(row, inc(), row1[-3])
14460 amit.gupta 143
            worksheet.write(row, inc(), order['merchantOrderId'])
144
            worksheet.write(row, inc(), subOrder['productTitle'])
145
            worksheet.write(row, inc(), subOrder['amountPaid'])
146
            worksheet.write(row, inc(), subOrder['quantity'])
147
            worksheet.write(row, inc(), subOrder['status'])
148
            worksheet.write(row, inc(), subOrder['detailedStatus'])
149
            worksheet.write(row, inc(), subOrder['cashBackStatus'])
150
            worksheet.write(row, inc(), subOrder['cashBackAmount'])
151
            worksheet.write(row, inc(), subOrder['placedOn'])
152
            worksheet.write(row, inc(), order['subTagId'])
153
            for aff in affs:
14647 amit.gupta 154
                if aff["_id"] not in reconciled_affiliates and aff['subTagId']== order['subTagId']:
155
                    reconciled_affiliates.append(aff["_id"])
156
                    row2 += 1
157
                    i = -1 
158
                    worksheet1.write(row2, inc(), orderId)
159
                    worksheet1.write(row2, inc(), row1[1])
160
                    worksheet1.write(row2, inc(), row1[-1])
14771 amit.gupta 161
                    worksheet1.write(row2, inc(), row1[-2])
162
                    worksheet1.write(row2, inc(), row1[-3])
14647 amit.gupta 163
                    worksheet1.write(row2, inc(), order['merchantOrderId'])
164
                    worksheet1.write(row2, inc(), subOrder['productTitle'])
165
                    worksheet1.write(row2, inc(), subOrder['amountPaid'])
166
                    worksheet1.write(row2, inc(), subOrder['quantity'])
167
                    worksheet1.write(row2, inc(), subOrder['status'])
168
                    worksheet1.write(row2, inc(), subOrder['detailedStatus'])
169
                    worksheet1.write(row2, inc(), subOrder['cashBackStatus'])
170
                    worksheet1.write(row2, inc(), subOrder['cashBackAmount'])
171
                    worksheet1.write(row2, inc(), subOrder['placedOn'])
172
                    worksheet1.write(row2, inc(), order['subTagId'])
173
                    db.flipkartOrderAffiliateInfo.update(
174
                        {"productCode":subOrder.get("productCode"), "saleDateInt":saleTime, "subTagId":aff['subTagId']}, 
175
                        {"$set":{"reconciled":True}})
176
                    db.merchantOrder.update({"merchantOrderId":order["merchantOrderId"]}, 
177
                                            {"$set":{"reconciled":True}})
14460 amit.gupta 178
                    worksheet.write(row, inc(), aff['category'])
14647 amit.gupta 179
                    worksheet1.write(row2, i, aff['category'])
14460 amit.gupta 180
                    worksheet.write(row, inc(), aff['payOut'])
14647 amit.gupta 181
                    worksheet1.write(row2, i, aff['payOut'])
14460 amit.gupta 182
                    worksheet.write(row, inc(), aff['saleAmount'])
14647 amit.gupta 183
                    worksheet1.write(row2, i, aff['saleAmount'])
14460 amit.gupta 184
                    worksheet.write(row, inc(), aff['saleDate'])
14647 amit.gupta 185
                    worksheet1.write(row2, i, aff['saleDate'])
14460 amit.gupta 186
                    break
14647 amit.gupta 187
            row3 += 1
188
            i=-1
189
            worksheet2.write(row3, inc(), orderId)
190
            worksheet2.write(row3, inc(), row1[1])
191
            worksheet2.write(row3, inc(), row1[-1])
14771 amit.gupta 192
            worksheet2.write(row3, inc(), row1[-2])
193
            worksheet2.write(row3, inc(), row1[-3])
14647 amit.gupta 194
            worksheet2.write(row3, inc(), order['merchantOrderId'])
195
            worksheet2.write(row3, inc(), subOrder['productTitle'])
196
            worksheet2.write(row3, inc(), subOrder['amountPaid'])
197
            worksheet2.write(row3, inc(), subOrder['quantity'])
198
            worksheet2.write(row3, inc(), subOrder['status'])
199
            worksheet2.write(row3, inc(), subOrder['detailedStatus'])
200
            worksheet2.write(row3, inc(), subOrder['cashBackStatus'])
201
            worksheet2.write(row3, inc(), subOrder['cashBackAmount'])
202
            worksheet2.write(row3, inc(), subOrder['placedOn'])
203
            worksheet2.write(row3, inc(), order['subTagId'])
204
 
205
    i=-1
206
    worksheet3.write(0, inc(), "category",boldStyle)    
207
    worksheet3.write(0, inc(), "conversionStatus",boldStyle)    
208
    worksheet3.write(0, inc(), "Product Title",boldStyle)    
209
    worksheet3.write(0, inc(), "price",boldStyle)    
210
    worksheet3.write(0, inc(), "quantity",boldStyle)    
211
    worksheet3.write(0, inc(), "payOut",boldStyle)    
212
    worksheet3.write(0, inc(), "saleDate",boldStyle)    
213
    worksheet3.write(0, inc(), "subTagId",boldStyle)
214
    for aff in db.flipkartOrderAffiliateInfo.find({"reconciled":{"$exists":False}}):
215
        row4 += 1
216
        i =-1
217
        worksheet3.write(row4, inc(), aff["category"])    
218
        worksheet3.write(row4, inc(), aff["conversionStatus"])    
219
        skuData = getSkuData(2, aff["productCode"])
220
        if skuData is None:    
221
            worksheet3.write(row4, inc(), aff["productTitle"])
222
        else:
223
            worksheet3.write(row4, inc(), skuData["product_name"])
224
        worksheet3.write(row4, inc(), aff['price'])    
225
        worksheet3.write(row4, inc(), aff['quantity'])    
226
        worksheet3.write(row4, inc(), aff['payOut'])    
227
        worksheet3.write(row4, inc(), aff['saleDate'])    
228
        worksheet3.write(row4, inc(), aff['subTagId'])    
229
 
230
 
231
 
232
    wb.save(XLS_F_FILENAME)
14450 amit.gupta 233
def generateSnapDealReco():
14524 amit.gupta 234
    global i
14460 amit.gupta 235
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=30), 3)
14450 amit.gupta 236
    db = client.Dtr
14524 amit.gupta 237
    notReconciled = {}
14487 amit.gupta 238
    matchedList = []
14450 amit.gupta 239
    workbook = xlwt.Workbook()
14501 amit.gupta 240
    worksheet = workbook.add_sheet("Snapdeal Reconciled")
241
    worksheet1 = workbook.add_sheet("Snapdeal Reconciled All")
14508 amit.gupta 242
    worksheet2 = workbook.add_sheet("Snapdeal Orders not reconciled")
16947 amit.gupta 243
    worksheet3 = workbook.add_sheet("DateWise Sale Summary")
14508 amit.gupta 244
    affNotReconciledSheet = workbook.add_sheet("Snapdeal Aff not reconciled")
16947 amit.gupta 245
    setHeaders(worksheet, worksheet1, worksheet2, affNotReconciledSheet, worksheet3)
14450 amit.gupta 246
    row = 0
14501 amit.gupta 247
    anotherrow = 0
15577 amit.gupta 248
    row5=0
16947 amit.gupta 249
    datemap={}
14450 amit.gupta 250
    for row1 in curs:
251
        orderId = row1[0]
252
        order = db.merchantOrder.find_one({"orderId":orderId})
253
        if order is None:
254
            continue
14496 amit.gupta 255
        #saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))
16949 amit.gupta 256
        try:
16951 amit.gupta 257
            saleTime = datetime.strptime(order['placedOn'], "%a, %d %b, %Y").strftime("%Y-%m-%d")
16949 amit.gupta 258
        except:
17001 amit.gupta 259
            saleTime = datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").strftime("%Y-%m-%d")    
16947 amit.gupta 260
 
14450 amit.gupta 261
        aff = list(db.snapdealOrderAffiliateInfo.find({"subTagId":order["subTagId"]}))
16718 amit.gupta 262
        if len(aff) > 1:
263
            aff = [f for f in aff if f.get("payOut")>0]
14501 amit.gupta 264
        anotherrow += 1
14988 amit.gupta 265
        try:
266
            formattedTimestamp = order['placedOn']
267
            timestamp1 = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))
268
        except:
269
            timestamp1 = int(time.mktime(row1[-4].timetuple()))
16947 amit.gupta 270
            formattedTimestamp = datetime.strftime(utils.fromTimeStamp(timestamp1), "%b %d, %Y, %I:%M %p")
16718 amit.gupta 271
        if len(aff) > 0 and order["subTagId"] not in matchedList and int(order["paidAmount"])==int(aff[0]["saleAmount"]):
272
 
14501 amit.gupta 273
            matchedList.append(order["subTagId"])
14610 amit.gupta 274
            db.snapdealOrderAffiliateInfo.update({"adId":aff[0].get("adId")}, {"$set":{"reconciled":True, "orderId":orderId}}, multi=True)
14501 amit.gupta 275
            order['reconciled'] = True
14610 amit.gupta 276
            order['adId'] = aff[0].get("adId")
14501 amit.gupta 277
            db.merchantOrder.save(order)
278
            row += 1
279
            i=-1 
280
            worksheet.write(row, inc(), orderId)
281
            worksheet1.write(anotherrow, i, orderId)
282
            worksheet.write(row, inc(), row1[1])
283
            worksheet1.write(anotherrow, i, row1[1])
14850 amit.gupta 284
            worksheet.write(row, inc(), row1[-1])
285
            worksheet1.write(anotherrow, i, row1[-1])
286
            worksheet.write(row, inc(), row1[-2])
287
            worksheet1.write(anotherrow, i, row1[-2])
14771 amit.gupta 288
            worksheet.write(row, inc(), row1[-3])
289
            worksheet1.write(anotherrow, i, row1[-3])
14501 amit.gupta 290
            worksheet.write(row, inc(), order['merchantOrderId'])
291
            worksheet1.write(anotherrow, i, order['merchantOrderId'])
292
            worksheet.write(row, inc(), order['subTagId'])
293
            worksheet1.write(anotherrow, i, order['subTagId'])
294
            worksheet.write(row, inc(), order['placedOn'])
295
            worksheet1.write(anotherrow, i, order['placedOn'])
14988 amit.gupta 296
            worksheet.write(row, inc(), formattedTimestamp)
297
            worksheet1.write(anotherrow, i, formattedTimestamp)
14501 amit.gupta 298
            worksheet.write(row, inc(), int(order['paidAmount']))
299
            worksheet1.write(anotherrow, i, int(order['paidAmount']))
14524 amit.gupta 300
            worksheet.write(row, inc(), aff[0]['saleDate'])
301
            worksheet1.write(anotherrow, i, aff[0]['saleDate'])
302
            worksheet.write(row, inc(), aff[0]['saleAmount'])
303
            worksheet1.write(anotherrow, i, aff[0]['saleAmount'])
304
            worksheet.write(row, inc(), aff[0]['payOut'])
305
            worksheet1.write(anotherrow, i, aff[0]['payOut'])
14601 amit.gupta 306
            worksheet.write(row, inc(), aff[0]['ip'])
307
            worksheet1.write(anotherrow, i, aff[0]['ip'])
16718 amit.gupta 308
            worksheet.write(row, inc(), aff[0]['conversionStatus'])
309
            worksheet1.write(anotherrow, i, aff[0]['conversionStatus'])
14501 amit.gupta 310
            k = i
14504 amit.gupta 311
            row -= 1
312
            anotherrow -= 1
14501 amit.gupta 313
            for subOrder in order['subOrders']:
314
                i = k
14503 amit.gupta 315
                row += 1
316
                anotherrow += 1
14501 amit.gupta 317
                worksheet.write(row, inc(), subOrder['productTitle'])
318
                worksheet1.write(anotherrow, i, subOrder['productTitle'])
319
                worksheet.write(row, inc(), subOrder['amountPaid'])
320
                worksheet1.write(anotherrow, i, subOrder['amountPaid'])
321
                worksheet.write(row, inc(), subOrder['quantity'])
322
                worksheet1.write(anotherrow, i, subOrder['quantity'])
323
                worksheet.write(row, inc(), subOrder['status'])
324
                worksheet1.write(anotherrow, i, subOrder['status'])
325
                worksheet.write(row, inc(), subOrder['cashBackStatus'])
326
                worksheet1.write(anotherrow, i, subOrder['cashBackStatus'])
327
                worksheet.write(row, inc(), subOrder['cashBackAmount'])
328
                worksheet1.write(anotherrow, i, subOrder['cashBackAmount'])
14504 amit.gupta 329
 
14501 amit.gupta 330
        else:
14524 amit.gupta 331
            i=-1
14501 amit.gupta 332
            worksheet1.write(anotherrow, inc(), orderId)
333
            worksheet1.write(anotherrow, inc(), row1[1])
14850 amit.gupta 334
            worksheet1.write(anotherrow, inc(), row1[-1])
335
            worksheet1.write(anotherrow, inc(), row1[-2])
14771 amit.gupta 336
            worksheet1.write(anotherrow, inc(), row1[-3])
14501 amit.gupta 337
            worksheet1.write(anotherrow, inc(), order['merchantOrderId'])
338
            worksheet1.write(anotherrow, inc(), order['subTagId'])
339
            worksheet1.write(anotherrow, inc(), order['placedOn'])
15576 amit.gupta 340
            worksheet1.write(anotherrow, inc(), formattedTimestamp)
14501 amit.gupta 341
            worksheet1.write(anotherrow, inc(), int(order['paidAmount']))
14873 amit.gupta 342
 
14524 amit.gupta 343
            notReconciled[orderId] = (anotherrow, i, int(order['paidAmount']), timestamp1, order["subTagId"]) 
344
            inc()
345
            inc()
346
            inc()
14771 amit.gupta 347
            inc()
16718 amit.gupta 348
            inc()
14501 amit.gupta 349
            k = i
14504 amit.gupta 350
            anotherrow -= 1
14501 amit.gupta 351
            for subOrder in order['subOrders']:
14503 amit.gupta 352
                anotherrow += 1
14501 amit.gupta 353
                i = k
14505 amit.gupta 354
                worksheet1.write(anotherrow, inc(), subOrder['productTitle'])
355
                worksheet1.write(anotherrow, inc(), subOrder['amountPaid'])
356
                worksheet1.write(anotherrow, inc(), subOrder['quantity'])
357
                worksheet1.write(anotherrow, inc(), subOrder['status'])
358
                worksheet1.write(anotherrow, inc(), subOrder['cashBackStatus'])
359
                worksheet1.write(anotherrow, inc(), subOrder['cashBackAmount'])
15577 amit.gupta 360
            row5 += 1
361
            i=-1
362
            worksheet2.write(row5, inc(), order["orderId"])
363
            worksheet2.write(row5, inc(), row1[1])
364
            worksheet2.write(row5, inc(), row1[-1])
365
            worksheet2.write(row5, inc(), row1[-2])
366
            worksheet2.write(row5, inc(), row1[-3])
367
            worksheet2.write(row5, inc(), order['merchantOrderId'])
368
            worksheet2.write(row5, inc(), order['subTagId'])
369
            worksheet2.write(row5, inc(), order['placedOn'])
370
            worksheet2.write(row5, inc(), formattedTimestamp)
371
            worksheet2.write(row5, inc(), int(order['paidAmount']))
372
            row5 -=1
373
            k=i
374
            for subOrder in order['subOrders']:
375
                i = k
15578 amit.gupta 376
                row5 += 1
15577 amit.gupta 377
                worksheet2.write(row5, inc(), subOrder['productTitle'])
378
                worksheet2.write(row5, inc(), subOrder['amountPaid'])
379
                worksheet2.write(row5, inc(), subOrder['quantity'])
380
                worksheet2.write(row5, inc(), subOrder['status'])
381
                worksheet2.write(row5, inc(), subOrder['cashBackStatus'])
15578 amit.gupta 382
                worksheet2.write(row5, inc(), subOrder['cashBackAmount'])
14524 amit.gupta 383
 
384
    last30Days =  date.today() - timedelta(days=30)
385
    int(time.mktime(last30Days.timetuple()))
386
    row = 0
387
    for offer in db.snapdealOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
388
                                                     "saleTime":{"$gt":int(time.mktime(last30Days.timetuple())),
16953 amit.gupta 389
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}}, timeout=False ):
14524 amit.gupta 390
        subTagId = offer.get("subTagId")
391
        saleTime = offer.get("saleTime")
392
        orders = getOrdersByTag(subTagId, 3)
393
        for order in orders:
394
            if notReconciled.has_key(order[0]):
395
                (roww, column, paidAmount, timestamp1, oSubTagId) = notReconciled[order[0]]
396
                if paidAmount==int(offer.get("saleAmount")) and timestamp1 <= saleTime and timestamp1 + 120 >= saleTime:
397
                    i = column
14570 amit.gupta 398
                    worksheet1.write(roww, inc(), offer.get("saleDate"))        
14527 amit.gupta 399
                    worksheet1.write(roww, inc(), offer.get("saleAmount"))        
400
                    worksheet1.write(roww, inc(), offer.get("payOut"))
401
                    del notReconciled[order[0]]
14530 amit.gupta 402
                    print "found match for user", order[1]
14610 amit.gupta 403
                    db.snapdealOrderAffiliateInfo.update({"adId":offer.get("adId")}, {"$set":{"reconciled":True, "orderId":order[0]}}, multi=True)
404
                    db.merchantOrder.update({"orderId":order[0]}, {"$set":{"reconciled":True, "adId":offer.get("adId")}}, multi=True)
14570 amit.gupta 405
                    break
17010 amit.gupta 406
 
14570 amit.gupta 407
 
408
 
409
    for offer in db.snapdealOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
410
                                                     "saleTime":{"$gt":int(time.mktime(last30Days.timetuple())),
411
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
412
        row += 1
413
        i=-1
414
        affNotReconciledSheet.write(row, inc(), offer.get("adId")) 
415
        affNotReconciledSheet.write(row, inc(), offer.get("subTagId")) 
416
        affNotReconciledSheet.write(row, inc(), offer.get("saleDate")) 
417
        affNotReconciledSheet.write(row, inc(), offer.get("saleAmount")) 
418
        affNotReconciledSheet.write(row, inc(), offer.get("payOut")) 
419
        affNotReconciledSheet.write(row, inc(), offer.get("conversionStatus"))
14601 amit.gupta 420
        affNotReconciledSheet.write(row, inc(), offer.get("ip"))
16947 amit.gupta 421
 
17010 amit.gupta 422
    mailBodyTemplate="""
423
        <html>
424
            <body>
425
            <table cellspacing="0" border="1" style="text-align:right">
426
                <thead>
427
                    <tr>
428
                        <th style="text-align:center">Date</th>
429
                        <th  style="text-align:center">Sale</th>
430
                        <th  style="text-align:center">Approved</th>
431
                        <th  style="text-align:center">Approved %</th>
432
                        <th  style="text-align:center">Rejected</th>
433
                        <th  style="text-align:center">Rejected %</th>
434
                    </tr>
435
                </thead>
436
                <tbody>
437
                    {0}
438
                </tbody>
439
            </table>
440
            </body>
441
        </html>
442
    """
443
    tbody=[]
444
    rowtemplate="<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>"
445
    for offer in db.flSaleSnapshot.find().limit(61).sort("_id",-1):
446
        approved = offer.get("approvedAmount")
447
        rejected = offer.get("rejectedAmount")
448
        total = approved + rejected
449
        if total ==0:
450
            continue
451
        tbody.append(rowtemplate.format(offer.get("_id"), offer.get("paidAmount"), approved, int((approved*100/total)), rejected, int((rejected*100/total))))
452
    message = mailBodyTemplate.format("".join(tbody))
15540 amit.gupta 453
    workbook.save(XLS_FILENAME)
17013 manish.sha 454
 
455
def generateHomeShopReco():
456
    global i
457
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=30), 7)
458
    db = client.Dtr
459
    notReconciled = {}
460
    matchedList = []
461
    workbook = xlwt.Workbook()
462
    worksheet = workbook.add_sheet("HomeShop18 Reconciled")
463
    worksheet1 = workbook.add_sheet("HomeShop18 Reconciled All")
464
    worksheet2 = workbook.add_sheet("HomeShop18 Orders not reconciled")
465
    affNotReconciledSheet = workbook.add_sheet("HomeShop18 Aff not reconciled")
466
    setHeaders(worksheet, worksheet1, worksheet2, affNotReconciledSheet)
467
    row = 0
468
    anotherrow = 0
469
    row2 = 0
470
    row5=0
471
 
472
    for row1 in curs:
473
        orderId = row1[0]
474
        order = db.merchantOrder.find_one({"orderId":orderId})
475
        if order is None:
476
            continue
477
        #saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))  26 May 2015 02:12 PM
478
        aff = list(db.shopcluesOrderAffiliateInfo.find({"merchantOrderId":order["merchantOrderId"]}))
479
        anotherrow += 1
480
        try:
481
            formattedTimestamp = order['placedOn']
482
            timestamp1 = int(time.mktime(datetime.strptime(order['placedOn'], "%d %b %Y %I:%M %p").timetuple()))
483
        except:
484
            timestamp1 = int(time.mktime(row1[-4].timetuple()))
485
            formattedTimestamp = datetime.strftime(utils.fromTimeStamp(timestamp1), "%d %b %Y %I:%M %p")
486
 
487
        if len(aff) > 0 and order["subTagId"] not in matchedList and long(order["paidAmount"])==long(float(aff[0]["transactionValue"])): 
488
            matchedList.append(order["subTagId"])
489
            db.shopcluesOrderAffiliateInfo.update({"merchantOrderId":aff[0].get("merchantOrderId")}, {"$set":{"reconciled":True, "orderId":orderId}}, multi=True)
490
            order['reconciled'] = True
491
            order['adId'] = aff[0].get("uniqueKey")
492
            db.merchantOrder.save(order)
493
            row += 1
494
            i=-1 
495
 
496
            worksheet.write(row, inc(), orderId)
497
            worksheet1.write(anotherrow, i, orderId)
498
            worksheet.write(row, inc(), row1[1])
499
            worksheet1.write(anotherrow, i, row1[1])
500
            worksheet.write(row, inc(), row1[-1])
501
            worksheet1.write(anotherrow, i, row1[-1])
502
            worksheet.write(row, inc(), row1[-2])
503
            worksheet1.write(anotherrow, i, row1[-2])
504
            worksheet.write(row, inc(), row1[-3])
505
            worksheet1.write(anotherrow, i, row1[-3])
506
            worksheet.write(row, inc(), order['merchantOrderId'])
507
            worksheet1.write(anotherrow, i, order['merchantOrderId'])
508
            worksheet.write(row, inc(), order['subTagId'])
509
            worksheet1.write(anotherrow, i, order['subTagId'])
510
            worksheet.write(row, inc(), order['placedOn'])
511
            worksheet1.write(anotherrow, i, order['placedOn'])
512
            worksheet.write(row, inc(), formattedTimestamp)
513
            worksheet1.write(anotherrow, i, formattedTimestamp)
514
            worksheet.write(row, inc(), int(order['paidAmount']))
515
            worksheet1.write(anotherrow, i, int(order['paidAmount']))
516
            worksheet.write(row, inc(), datetime.strftime(utils.fromTimeStamp(aff[0]['transactionTime']), "%d %b %Y %I:%M %p"))
517
            worksheet1.write(anotherrow, i, datetime.strftime(utils.fromTimeStamp(aff[0]['transactionTime']), "%d %b %Y %I:%M %p"))
518
            worksheet.write(row, inc(), aff[0]['transactionValue'])
519
            worksheet1.write(anotherrow, i, aff[0]['transactionValue'])
520
            worksheet.write(row, inc(), aff[0]['payOut'])
521
            worksheet1.write(anotherrow, i, aff[0]['payOut'])
522
            worksheet.write(row, inc(), "NA")
523
            worksheet1.write(anotherrow, i, "NA")
524
            k = i
525
            row -= 1
526
            anotherrow -= 1
527
            for subOrder in order['subOrders']:
528
                i = k
529
                row += 1
530
                anotherrow += 1
531
                worksheet.write(row, inc(), subOrder['productTitle'])
532
                worksheet1.write(anotherrow, i, subOrder['productTitle'])
533
                worksheet.write(row, inc(), subOrder['amountPaid'])
534
                worksheet1.write(anotherrow, i, subOrder['amountPaid'])
535
                worksheet.write(row, inc(), subOrder['quantity'])
536
                worksheet1.write(anotherrow, i, subOrder['quantity'])
537
                worksheet.write(row, inc(), subOrder['status'])
538
                worksheet1.write(anotherrow, i, subOrder['status'])
539
                worksheet.write(row, inc(), subOrder['cashBackStatus'])
540
                worksheet1.write(anotherrow, i, subOrder['cashBackStatus'])
541
                worksheet.write(row, inc(), subOrder['cashBackAmount'])
542
                worksheet1.write(anotherrow, i, subOrder['cashBackAmount'])
543
 
544
        else:
545
            i=-1
546
            worksheet1.write(anotherrow, inc(), orderId)
547
            worksheet1.write(anotherrow, inc(), row1[1])
548
            worksheet1.write(anotherrow, inc(), row1[-1])
549
            worksheet1.write(anotherrow, inc(), row1[-2])
550
            worksheet1.write(anotherrow, inc(), row1[-3])
551
            worksheet1.write(anotherrow, inc(), order['merchantOrderId'])
552
            worksheet1.write(anotherrow, inc(), order['subTagId'])
553
            worksheet1.write(anotherrow, inc(), order['placedOn'])
554
            worksheet1.write(anotherrow, inc(), formattedTimestamp)
555
            worksheet1.write(anotherrow, inc(), int(order['paidAmount']))
556
 
557
            notReconciled[orderId] = (anotherrow, i, int(order['paidAmount']), timestamp1, order["subTagId"]) 
558
            inc()
559
            inc()
560
            inc()
561
            inc()
562
            k = i
563
            anotherrow -= 1
564
            for subOrder in order['subOrders']:
565
                anotherrow += 1
566
                i = k
567
                worksheet1.write(anotherrow, inc(), subOrder['productTitle'])
568
                worksheet1.write(anotherrow, inc(), subOrder['amountPaid'])
569
                worksheet1.write(anotherrow, inc(), subOrder['quantity'])
570
                worksheet1.write(anotherrow, inc(), subOrder['status'])
571
                worksheet1.write(anotherrow, inc(), subOrder['cashBackStatus'])
572
                worksheet1.write(anotherrow, inc(), subOrder['cashBackAmount'])
573
            row5 += 1
574
            i=-1
575
            worksheet2.write(row5, inc(), order["orderId"])
576
            worksheet2.write(row5, inc(), row1[1])
577
            worksheet2.write(row5, inc(), row1[-1])
578
            worksheet2.write(row5, inc(), row1[-2])
579
            worksheet2.write(row5, inc(), row1[-3])
580
            worksheet2.write(row5, inc(), order['merchantOrderId'])
581
            worksheet2.write(row5, inc(), order['subTagId'])
582
            worksheet2.write(row5, inc(), order['placedOn'])
583
            worksheet2.write(row5, inc(), formattedTimestamp)
584
            worksheet2.write(row5, inc(), int(order['paidAmount']))
585
            row5 -=1
586
            k=i
587
            for subOrder in order['subOrders']:
588
                i = k
589
                row5 += 1
590
                worksheet2.write(row5, inc(), subOrder['productTitle'])
591
                worksheet2.write(row5, inc(), subOrder['amountPaid'])
592
                worksheet2.write(row5, inc(), subOrder['quantity'])
593
                worksheet2.write(row5, inc(), subOrder['status'])
594
                worksheet2.write(row5, inc(), subOrder['cashBackStatus'])
595
                worksheet2.write(row5, inc(), subOrder['cashBackAmount'])
596
    last30Days =  date.today() - timedelta(days=30)
597
    int(time.mktime(last30Days.timetuple()))
598
    row = 0
599
    for offer in db.homeshopOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
600
                                                     "transactionTime":{"$gt":int(time.mktime(last30Days.timetuple())),
601
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
602
        subTagId = offer.get("subTagId")
603
        saleTime = offer.get("transactionTime")
604
        orders = getOrdersByTag(subTagId, 7)
605
        for order in orders:
606
            if notReconciled.has_key(order[0]):
607
                (roww, column, paidAmount, timestamp1, oSubTagId) = notReconciled[order[0]]
608
                if paidAmount==int(offer.get("transactionValue")) and timestamp1 <= saleTime and timestamp1 + 120 >= saleTime:
609
                    i = column
610
                    worksheet1.write(roww, inc(), datetime.strftime(utils.fromTimeStamp(offer.get("transactionTime")), "%d %b %Y %I:%M %p"))        
611
                    worksheet1.write(roww, inc(), offer.get("transactionValue"))        
612
                    worksheet1.write(roww, inc(), offer.get("payOut"))
613
                    del notReconciled[order[0]]
614
                    print "found match for user", order[1]
615
                    db.homeshopOrderAffiliateInfo.update({"transactionId":offer.get("transactionId")}, {"$set":{"reconciled":True, "orderId":order[0]}}, multi=True)
616
                    db.merchantOrder.update({"orderId":order[0]}, {"$set":{"reconciled":True, "adId":offer.get("uniqueKey")}}, multi=True)
617
                    break
618
 
619
    unreconciledOrders = notReconciled.keys()
620
 
621
    for offer in db.homeshopOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
622
                                                     "transactionTime":{"$gt":int(time.mktime(last30Days.timetuple())),
623
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
624
        row += 1
625
        i=-1
626
        affNotReconciledSheet.write(row, inc(), offer.get("uniqueKey")) 
627
        affNotReconciledSheet.write(row, inc(), offer.get("subTagId")) 
628
        affNotReconciledSheet.write(row, inc(), datetime.strftime(utils.fromTimeStamp(offer.get("transactionTime")), "%d %b %Y %I:%M %p")) 
629
        affNotReconciledSheet.write(row, inc(), offer.get("transactionValue")) 
630
        affNotReconciledSheet.write(row, inc(), offer.get("payOut")) 
631
        affNotReconciledSheet.write(row, inc(), offer.get("status"))
632
        affNotReconciledSheet.write(row, inc(), 'NA')
633
 
634
    workbook.save(XLS_HS_FILENAME)
635
 
16995 amit.gupta 636
    return message
637
 
17010 amit.gupta 638
 
15791 manish.sha 639
def generateShopcluesReco():
640
    global i
16238 manish.sha 641
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=30), 5)
15791 manish.sha 642
    db = client.Dtr
643
    notReconciled = {}
644
    matchedList = []
645
    workbook = xlwt.Workbook()
646
    worksheet = workbook.add_sheet("Shopclues Reconciled")
647
    worksheet1 = workbook.add_sheet("Shopclues Reconciled All")
648
    worksheet2 = workbook.add_sheet("Shopclues Orders not reconciled")
649
    affNotReconciledSheet = workbook.add_sheet("Shopclues Aff not reconciled")
650
    setHeaders(worksheet, worksheet1, worksheet2, affNotReconciledSheet)
651
    row = 0
652
    anotherrow = 0
653
    row2 = 0
654
    row5=0
655
 
656
    for row1 in curs:
657
        orderId = row1[0]
658
        order = db.merchantOrder.find_one({"orderId":orderId})
659
        if order is None:
660
            continue
661
        #saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))  26 May 2015 02:12 PM
16204 manish.sha 662
        aff = list(db.shopcluesOrderAffiliateInfo.find({"merchantOrderId":order["merchantOrderId"]}))
15791 manish.sha 663
        anotherrow += 1
664
        try:
665
            formattedTimestamp = order['placedOn']
666
            timestamp1 = int(time.mktime(datetime.strptime(order['placedOn'], "%d %b %Y %I:%M %p").timetuple()))
667
        except:
668
            timestamp1 = int(time.mktime(row1[-4].timetuple()))
16947 amit.gupta 669
            formattedTimestamp = datetime.strftime(utils.fromTimeStamp(timestamp1), "%d %b %Y %I:%M %p")
15791 manish.sha 670
 
671
        if len(aff) > 0 and order["subTagId"] not in matchedList and long(order["paidAmount"])==long(float(aff[0]["transactionValue"])): 
672
            matchedList.append(order["subTagId"])
16204 manish.sha 673
            db.shopcluesOrderAffiliateInfo.update({"merchantOrderId":aff[0].get("merchantOrderId")}, {"$set":{"reconciled":True, "orderId":orderId}}, multi=True)
15791 manish.sha 674
            order['reconciled'] = True
675
            order['adId'] = aff[0].get("uniqueKey")
676
            db.merchantOrder.save(order)
677
            row += 1
678
            i=-1 
14450 amit.gupta 679
 
15791 manish.sha 680
            worksheet.write(row, inc(), orderId)
681
            worksheet1.write(anotherrow, i, orderId)
682
            worksheet.write(row, inc(), row1[1])
683
            worksheet1.write(anotherrow, i, row1[1])
684
            worksheet.write(row, inc(), row1[-1])
685
            worksheet1.write(anotherrow, i, row1[-1])
686
            worksheet.write(row, inc(), row1[-2])
687
            worksheet1.write(anotherrow, i, row1[-2])
688
            worksheet.write(row, inc(), row1[-3])
689
            worksheet1.write(anotherrow, i, row1[-3])
690
            worksheet.write(row, inc(), order['merchantOrderId'])
691
            worksheet1.write(anotherrow, i, order['merchantOrderId'])
692
            worksheet.write(row, inc(), order['subTagId'])
693
            worksheet1.write(anotherrow, i, order['subTagId'])
694
            worksheet.write(row, inc(), order['placedOn'])
695
            worksheet1.write(anotherrow, i, order['placedOn'])
696
            worksheet.write(row, inc(), formattedTimestamp)
697
            worksheet1.write(anotherrow, i, formattedTimestamp)
698
            worksheet.write(row, inc(), int(order['paidAmount']))
699
            worksheet1.write(anotherrow, i, int(order['paidAmount']))
16947 amit.gupta 700
            worksheet.write(row, inc(), datetime.strftime(utils.fromTimeStamp(aff[0]['transactionTime']), "%d %b %Y %I:%M %p"))
701
            worksheet1.write(anotherrow, i, datetime.strftime(utils.fromTimeStamp(aff[0]['transactionTime']), "%d %b %Y %I:%M %p"))
15791 manish.sha 702
            worksheet.write(row, inc(), aff[0]['transactionValue'])
703
            worksheet1.write(anotherrow, i, aff[0]['transactionValue'])
704
            worksheet.write(row, inc(), aff[0]['payOut'])
705
            worksheet1.write(anotherrow, i, aff[0]['payOut'])
16238 manish.sha 706
            worksheet.write(row, inc(), "NA")
707
            worksheet1.write(anotherrow, i, "NA")
15791 manish.sha 708
            k = i
709
            row -= 1
710
            anotherrow -= 1
711
            for subOrder in order['subOrders']:
712
                i = k
713
                row += 1
714
                anotherrow += 1
715
                worksheet.write(row, inc(), subOrder['productTitle'])
716
                worksheet1.write(anotherrow, i, subOrder['productTitle'])
717
                worksheet.write(row, inc(), subOrder['amountPaid'])
718
                worksheet1.write(anotherrow, i, subOrder['amountPaid'])
719
                worksheet.write(row, inc(), subOrder['quantity'])
720
                worksheet1.write(anotherrow, i, subOrder['quantity'])
721
                worksheet.write(row, inc(), subOrder['status'])
722
                worksheet1.write(anotherrow, i, subOrder['status'])
723
                worksheet.write(row, inc(), subOrder['cashBackStatus'])
724
                worksheet1.write(anotherrow, i, subOrder['cashBackStatus'])
725
                worksheet.write(row, inc(), subOrder['cashBackAmount'])
726
                worksheet1.write(anotherrow, i, subOrder['cashBackAmount'])
727
 
728
        else:
729
            i=-1
730
            worksheet1.write(anotherrow, inc(), orderId)
731
            worksheet1.write(anotherrow, inc(), row1[1])
732
            worksheet1.write(anotherrow, inc(), row1[-1])
733
            worksheet1.write(anotherrow, inc(), row1[-2])
734
            worksheet1.write(anotherrow, inc(), row1[-3])
735
            worksheet1.write(anotherrow, inc(), order['merchantOrderId'])
736
            worksheet1.write(anotherrow, inc(), order['subTagId'])
737
            worksheet1.write(anotherrow, inc(), order['placedOn'])
738
            worksheet1.write(anotherrow, inc(), formattedTimestamp)
739
            worksheet1.write(anotherrow, inc(), int(order['paidAmount']))
740
 
741
            notReconciled[orderId] = (anotherrow, i, int(order['paidAmount']), timestamp1, order["subTagId"]) 
742
            inc()
743
            inc()
744
            inc()
745
            inc()
746
            k = i
747
            anotherrow -= 1
748
            for subOrder in order['subOrders']:
749
                anotherrow += 1
750
                i = k
751
                worksheet1.write(anotherrow, inc(), subOrder['productTitle'])
752
                worksheet1.write(anotherrow, inc(), subOrder['amountPaid'])
753
                worksheet1.write(anotherrow, inc(), subOrder['quantity'])
754
                worksheet1.write(anotherrow, inc(), subOrder['status'])
755
                worksheet1.write(anotherrow, inc(), subOrder['cashBackStatus'])
756
                worksheet1.write(anotherrow, inc(), subOrder['cashBackAmount'])
757
            row5 += 1
758
            i=-1
759
            worksheet2.write(row5, inc(), order["orderId"])
760
            worksheet2.write(row5, inc(), row1[1])
761
            worksheet2.write(row5, inc(), row1[-1])
762
            worksheet2.write(row5, inc(), row1[-2])
763
            worksheet2.write(row5, inc(), row1[-3])
764
            worksheet2.write(row5, inc(), order['merchantOrderId'])
765
            worksheet2.write(row5, inc(), order['subTagId'])
766
            worksheet2.write(row5, inc(), order['placedOn'])
767
            worksheet2.write(row5, inc(), formattedTimestamp)
768
            worksheet2.write(row5, inc(), int(order['paidAmount']))
769
            row5 -=1
770
            k=i
771
            for subOrder in order['subOrders']:
772
                i = k
773
                row5 += 1
774
                worksheet2.write(row5, inc(), subOrder['productTitle'])
775
                worksheet2.write(row5, inc(), subOrder['amountPaid'])
776
                worksheet2.write(row5, inc(), subOrder['quantity'])
777
                worksheet2.write(row5, inc(), subOrder['status'])
778
                worksheet2.write(row5, inc(), subOrder['cashBackStatus'])
779
                worksheet2.write(row5, inc(), subOrder['cashBackAmount'])
780
 
781
    last30Days =  date.today() - timedelta(days=30)
782
    int(time.mktime(last30Days.timetuple()))
783
    row = 0
784
    for offer in db.shopcluesOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
785
                                                     "transactionTime":{"$gt":int(time.mktime(last30Days.timetuple())),
786
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
787
        subTagId = offer.get("subTagId")
788
        saleTime = offer.get("transactionTime")
15794 manish.sha 789
        orders = getOrdersByTag(subTagId, 5)
15791 manish.sha 790
        for order in orders:
791
            if notReconciled.has_key(order[0]):
792
                (roww, column, paidAmount, timestamp1, oSubTagId) = notReconciled[order[0]]
793
                if paidAmount==int(offer.get("transactionValue")) and timestamp1 <= saleTime and timestamp1 + 120 >= saleTime:
794
                    i = column
16947 amit.gupta 795
                    worksheet1.write(roww, inc(), datetime.strftime(utils.fromTimeStamp(offer.get("transactionTime")), "%d %b %Y %I:%M %p"))        
15791 manish.sha 796
                    worksheet1.write(roww, inc(), offer.get("transactionValue"))        
797
                    worksheet1.write(roww, inc(), offer.get("payOut"))
798
                    del notReconciled[order[0]]
799
                    print "found match for user", order[1]
800
                    db.shopcluesOrderAffiliateInfo.update({"transactionId":offer.get("transactionId")}, {"$set":{"reconciled":True, "orderId":order[0]}}, multi=True)
801
                    db.merchantOrder.update({"orderId":order[0]}, {"$set":{"reconciled":True, "adId":offer.get("uniqueKey")}}, multi=True)
802
                    break
803
 
804
    unreconciledOrders = notReconciled.keys()
805
 
806
    for offer in db.shopcluesOrderAffiliateInfo.find({"reconciled":{"$exists":False}, 
807
                                                     "transactionTime":{"$gt":int(time.mktime(last30Days.timetuple())),
808
                                                                 "$lt":int(time.mktime(date.today().timetuple()))}} ):
809
        row += 1
810
        i=-1
811
        affNotReconciledSheet.write(row, inc(), offer.get("uniqueKey")) 
812
        affNotReconciledSheet.write(row, inc(), offer.get("subTagId")) 
16947 amit.gupta 813
        affNotReconciledSheet.write(row, inc(), datetime.strftime(utils.fromTimeStamp(offer.get("transactionTime")), "%d %b %Y %I:%M %p")) 
15791 manish.sha 814
        affNotReconciledSheet.write(row, inc(), offer.get("transactionValue")) 
815
        affNotReconciledSheet.write(row, inc(), offer.get("payOut")) 
816
        affNotReconciledSheet.write(row, inc(), offer.get("status"))
817
        affNotReconciledSheet.write(row, inc(), 'NA')
818
 
819
    workbook.save(XLS_SC_FILENAME)
820
 
14647 amit.gupta 821
def sendmail(email, message, title, *varargs):
14450 amit.gupta 822
    if email == "":
823
        return
824
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
825
    mailServer.ehlo()
826
    mailServer.starttls()
827
    mailServer.ehlo()
828
 
829
    # Create the container (outer) email message.
830
    msg = MIMEMultipart()
831
    msg['Subject'] = title
832
    msg.preamble = title
833
    html_msg = MIMEText(message, 'html')
834
    msg.attach(html_msg)
835
 
836
    #snapdeal more to be added here
14647 amit.gupta 837
    for fileName in varargs:
838
        snapdeal = MIMEBase('application', 'vnd.ms-excel')
839
        snapdeal.set_payload(file(fileName).read())
840
        encoders.encode_base64(snapdeal)
841
        snapdeal.add_header('Content-Disposition', 'attachment;filename=' + fileName)
842
        msg.attach(snapdeal)
14450 amit.gupta 843
 
844
 
845
    email.append('amit.gupta@shop2020.in')
846
    MAILTO = email 
847
    mailServer.login(SENDER, PASSWORD)
848
    mailServer.sendmail(PASSWORD, MAILTO, msg.as_string())
849
 
16958 amit.gupta 850
def setHeaders(worksheet, worksheet1, worksheet2, affNotReconciledSheet, worksheet3=None):
14505 amit.gupta 851
    boldStyle = xlwt.XFStyle()
852
    f = xlwt.Font()
853
    f.bold = True
854
    boldStyle.font = f
14501 amit.gupta 855
    row = 0
856
    global i
857
    i=-1    
858
    worksheet.write(row, inc(), 'Order Id', boldStyle)
859
    worksheet.write(row, inc(), 'User Id', boldStyle)
14850 amit.gupta 860
    worksheet.write(row, inc(), 'Username', boldStyle)
14601 amit.gupta 861
    worksheet.write(row, inc(), 'Version Code', boldStyle)
14771 amit.gupta 862
    worksheet.write(row, inc(), 'Device', boldStyle)
14501 amit.gupta 863
    worksheet.write(row, inc(), 'Merchant Order Id', boldStyle)
864
    worksheet.write(row, inc(), 'SubtagId', boldStyle)
865
    worksheet.write(row, inc(), 'Sale Date', boldStyle)
14988 amit.gupta 866
    worksheet.write(row, inc(), 'Dtr Sale Date', boldStyle)
14501 amit.gupta 867
    worksheet.write(row, inc(), 'Sale Amount', boldStyle)
868
    worksheet.write(row, inc(), 'Aff Sale Date', boldStyle)
869
    worksheet.write(row, inc(), 'Aff Sale Amt', boldStyle)
870
    worksheet.write(row, inc(), 'Aff PayOut', boldStyle)
14601 amit.gupta 871
    worksheet.write(row, inc(), 'IP', boldStyle)
16718 amit.gupta 872
    worksheet.write(row, inc(), 'Aff Status', boldStyle)
14501 amit.gupta 873
    worksheet.write(row, inc(), 'Product Title', boldStyle)
874
    worksheet.write(row, inc(), 'Price', boldStyle)
875
    worksheet.write(row, inc(), 'Quantity', boldStyle)
876
    worksheet.write(row, inc(), 'Status', boldStyle)
877
    worksheet.write(row, inc(), 'Cashback Status', boldStyle)
878
    worksheet.write(row, inc(), 'CashBack', boldStyle)
879
 
14505 amit.gupta 880
    i = -1
14501 amit.gupta 881
    worksheet1.write(row, inc(), 'Order Id', boldStyle)
882
    worksheet1.write(row, inc(), 'User Id', boldStyle)
14850 amit.gupta 883
    worksheet1.write(row, inc(), 'Username', boldStyle)
14601 amit.gupta 884
    worksheet1.write(row, inc(), 'Version Code', boldStyle)
14771 amit.gupta 885
    worksheet1.write(row, inc(), 'Device', boldStyle)
14501 amit.gupta 886
    worksheet1.write(row, inc(), 'Merchant Order Id', boldStyle)
887
    worksheet1.write(row, inc(), 'SubtagId', boldStyle)
888
    worksheet1.write(row, inc(), 'Sale Date', boldStyle)
14988 amit.gupta 889
    worksheet1.write(row, inc(), 'Dtr Sale Date', boldStyle)
14501 amit.gupta 890
    worksheet1.write(row, inc(), 'Sale Amount', boldStyle)
891
    worksheet1.write(row, inc(), 'Aff Sale Date', boldStyle)
892
    worksheet1.write(row, inc(), 'Aff Sale Amt', boldStyle)
893
    worksheet1.write(row, inc(), 'Aff PayOut', boldStyle)
14601 amit.gupta 894
    worksheet1.write(row, inc(), 'IP', boldStyle)
16718 amit.gupta 895
    worksheet1.write(row, inc(), 'Aff Status', boldStyle)
14501 amit.gupta 896
    worksheet1.write(row, inc(), 'Product Title', boldStyle)
897
    worksheet1.write(row, inc(), 'Price', boldStyle)
898
    worksheet1.write(row, inc(), 'Quantity', boldStyle)
899
    worksheet1.write(row, inc(), 'Status', boldStyle)
900
    worksheet1.write(row, inc(), 'Cashback Status', boldStyle)
901
    worksheet1.write(row, inc(), 'CashBack', boldStyle) 
14508 amit.gupta 902
 
903
    i = -1
904
    worksheet2.write(row, inc(), 'Order Id', boldStyle)
905
    worksheet2.write(row, inc(), 'User Id', boldStyle)
14850 amit.gupta 906
    worksheet2.write(row, inc(), 'Username', boldStyle)
14605 amit.gupta 907
    worksheet2.write(row, inc(), 'Version Code', boldStyle)
14771 amit.gupta 908
    worksheet2.write(row, inc(), 'Device', boldStyle)
14508 amit.gupta 909
    worksheet2.write(row, inc(), 'Merchant Order Id', boldStyle)
910
    worksheet2.write(row, inc(), 'SubtagId', boldStyle)
911
    worksheet2.write(row, inc(), 'Sale Date', boldStyle)
14988 amit.gupta 912
    worksheet2.write(row, inc(), 'Dtr Sale Date', boldStyle)
14508 amit.gupta 913
    worksheet2.write(row, inc(), 'Sale Amount', boldStyle)
914
    worksheet2.write(row, inc(), 'Product Title', boldStyle)
915
    worksheet2.write(row, inc(), 'Price', boldStyle)
916
    worksheet2.write(row, inc(), 'Quantity', boldStyle)
917
    worksheet2.write(row, inc(), 'Status', boldStyle)
918
    worksheet2.write(row, inc(), 'Cashback Status', boldStyle)
919
    worksheet2.write(row, inc(), 'CashBack', boldStyle)
14450 amit.gupta 920
 
14508 amit.gupta 921
    i =-1
922
    affNotReconciledSheet.write(row, inc(), 'AdId', boldStyle) 
923
    affNotReconciledSheet.write(row, inc(), 'subTagId', boldStyle) 
924
    affNotReconciledSheet.write(row, inc(), 'Sale Date', boldStyle) 
925
    affNotReconciledSheet.write(row, inc(), 'Sale Amount', boldStyle) 
926
    affNotReconciledSheet.write(row, inc(), 'Pay Out', boldStyle) 
927
    affNotReconciledSheet.write(row, inc(), 'Status', boldStyle) 
14601 amit.gupta 928
    affNotReconciledSheet.write(row, inc(), 'IP', boldStyle)
14524 amit.gupta 929
 
16958 amit.gupta 930
    if worksheet3:
931
        i =-1
932
        worksheet3.write(row, inc(), 'Date', boldStyle) 
933
        worksheet3.write(row, inc(), 'Sale Amount', boldStyle) 
934
        worksheet3.write(row, inc(), 'Approved Sales', boldStyle) 
935
        worksheet3.write(row, inc(), 'Rejected Sales', boldStyle) 
16947 amit.gupta 936
 
14524 amit.gupta 937
def getUserAmountReconciled():
938
    pass
939
 
14613 amit.gupta 940
def getUserOrders():
941
    global i
942
    rb = open_workbook(XLS_FILENAME,formatting_info=True)
943
    wb = copy(rb)
944
    worksheet = wb.add_sheet("All Users")
16726 amit.gupta 945
    #worksheet1 = wb.add_sheet("Suspected Users")
17011 amit.gupta 946
    workbook = xlwt.Workbook("utf8")
14632 amit.gupta 947
    sh1 = workbook.add_sheet("All Orders")
15423 amit.gupta 948
    sh2 = workbook.add_sheet("Flipkart Orders")
14632 amit.gupta 949
 
14613 amit.gupta 950
    db=client.Dtr
951
    results = Mysql.fetchResult('''
15932 amit.gupta 952
        select ow.*, u.username, crm1.order_count, u.referrer, aua.city,aua.state,aua.pincode from order_view ow 
953
        left join users u on u.id = ow.user_id 
954
        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
955
        left join (select * from (select * from all_user_addresses order by source) s group by user_id)aua on aua.user_id=u.id 
956
        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'); 
14613 amit.gupta 957
        ''',)
958
    row = 0
959
    i=-1
960
    worksheet.write(row, inc(), 'User Id', boldStyle)
16726 amit.gupta 961
    #worksheet1.write(row, i, 'User Id', boldStyle)
14613 amit.gupta 962
    worksheet.write(row, inc(), 'User name', boldStyle)
16726 amit.gupta 963
    #worksheet1.write(row, i, 'User name', boldStyle)
14613 amit.gupta 964
    worksheet.write(row, inc(), 'Order Id', boldStyle)
16726 amit.gupta 965
    #worksheet1.write(row, i, 'Order Id', boldStyle)
14613 amit.gupta 966
    worksheet.write(row, inc(), 'Created On', boldStyle)
16726 amit.gupta 967
    #worksheet1.write(row, i, 'Created On', boldStyle)
14613 amit.gupta 968
    worksheet.write(row, inc(), 'Store Id', boldStyle)
16726 amit.gupta 969
    #worksheet1.write(row, i, 'Store Id', boldStyle)
14613 amit.gupta 970
    worksheet.write(row, inc(), 'Merchant Order Id', boldStyle)
16785 amit.gupta 971
    worksheet.write(row, inc(), 'SubOrder Id', boldStyle)
16726 amit.gupta 972
    #worksheet1.write(row, i, 'Merchant Order Id', boldStyle)
14616 amit.gupta 973
    worksheet.write(row, inc(), 'Product title', boldStyle)
16726 amit.gupta 974
    #worksheet1.write(row, i, 'Product title', boldStyle)
14613 amit.gupta 975
    worksheet.write(row, inc(), 'Amount Paid', boldStyle)
16726 amit.gupta 976
    #worksheet1.write(row, i, 'Amount Paid', boldStyle)
14613 amit.gupta 977
    worksheet.write(row, inc(), 'Cashback', boldStyle)
16726 amit.gupta 978
    #worksheet1.write(row, i, 'Cashback', boldStyle)
14613 amit.gupta 979
    worksheet.write(row, inc(), 'Order Status', boldStyle)
16726 amit.gupta 980
    #worksheet1.write(row, i, 'Order Status', boldStyle)
14613 amit.gupta 981
    worksheet.write(row, inc(), 'Detailed Status', boldStyle)
16726 amit.gupta 982
    #worksheet1.write(row, i, 'Detailed Status', boldStyle)
14613 amit.gupta 983
    worksheet.write(row, inc(), 'Cashback Status', boldStyle)
16726 amit.gupta 984
    #worksheet1.write(row, i, 'Cashback Status', boldStyle)
14613 amit.gupta 985
    worksheet.write(row, inc(), 'Reconciled', boldStyle)
16726 amit.gupta 986
    #worksheet1.write(row, i, 'Reconciled', boldStyle)
14613 amit.gupta 987
    worksheet.write(row, inc(), 'IP', boldStyle)
16726 amit.gupta 988
    #worksheet1.write(row, i, 'IP', boldStyle)
16718 amit.gupta 989
    worksheet.write(row, inc(), 'Aff Status', boldStyle)
16726 amit.gupta 990
    #worksheet1.write(row, i, 'Aff Status', boldStyle)
14693 amit.gupta 991
    i=-1
992
    sh1.write(row, inc(), 'User Id', boldStyle)
993
    sh1.write(row, inc(), 'User name', boldStyle)
994
    sh1.write(row, inc(), 'Order Id', boldStyle)
995
    sh1.write(row, inc(), 'Created On', boldStyle)
996
    sh1.write(row, inc(), 'Store Id', boldStyle)
997
    sh1.write(row, inc(), 'Merchant Order Id', boldStyle)
14771 amit.gupta 998
    sh1.write(row, inc(), 'Status', boldStyle)
15932 amit.gupta 999
    sh1.write(row, inc(), 'Detailed Status', boldStyle)
14693 amit.gupta 1000
    sh1.write(row, inc(), 'Product title', boldStyle)
1001
    sh1.write(row, inc(), 'Referrer', boldStyle)
1002
    sh1.write(row, inc(), 'Amount Paid', boldStyle)
14771 amit.gupta 1003
    sh1.write(row, inc(), 'Catalog Id', boldStyle)
14693 amit.gupta 1004
    sh1.write(row, inc(), 'Brand', boldStyle)
1005
    sh1.write(row, inc(), 'Model', boldStyle)
1006
    sh1.write(row, inc(), 'Category', boldStyle)
15932 amit.gupta 1007
    sh1.write(row, inc(), 'Deal Rank', boldStyle)
16286 amit.gupta 1008
    sh1.write(row, inc(), 'Max Nlc', boldStyle)
1009
    sh1.write(row, inc(), 'Min Nlc', boldStyle)
1010
    sh1.write(row, inc(), 'DP', boldStyle)
1011
    sh1.write(row, inc(), 'Item status', boldStyle)
15932 amit.gupta 1012
    sh1.write(row, inc(), 'City', boldStyle)
1013
    sh1.write(row, inc(), 'State', boldStyle)
1014
    sh1.write(row, inc(), 'Pincode', boldStyle)
15423 amit.gupta 1015
    i =-1
1016
    sh2.write(row, inc(), 'User Id', boldStyle)
1017
    sh2.write(row, inc(), 'User name', boldStyle)
1018
    sh2.write(row, inc(), 'Created On', boldStyle)
1019
    sh2.write(row, inc(), 'Store', boldStyle)
1020
    sh2.write(row, inc(), 'Status', boldStyle)
1021
    sh2.write(row, inc(), 'Product title', boldStyle)
1022
    sh2.write(row, inc(), 'Price', boldStyle)
1023
    sh2.write(row, inc(), 'Quantity', boldStyle)
1024
    sh2.write(row, inc(), 'Catalog Id', boldStyle)
1025
    sh2.write(row, inc(), 'Brand', boldStyle)
1026
    sh2.write(row, inc(), 'Model', boldStyle)
1027
    sh2.write(row, inc(), 'Category', boldStyle)
14613 amit.gupta 1028
 
1029
    row=0
1030
    row2=0
14632 amit.gupta 1031
    row3=0
1032
    db1 = client.Catalog
14613 amit.gupta 1033
    for result in results:
1034
        morder = db.merchantOrder.find_one({"orderId":result[0]})
1035
        if morder is not None:
1036
            subOrders = morder.get("subOrders")
1037
            if subOrders is not None:
1038
                for  subOrder in subOrders:
14632 amit.gupta 1039
                    row3+=1
1040
                    i=-1
14699 amit.gupta 1041
                    sh1.write(row3, inc(), result[1])
15932 amit.gupta 1042
                    sh1.write(row3, inc(), result[7])
14632 amit.gupta 1043
                    sh1.write(row3, inc(), result[0])
15932 amit.gupta 1044
                    sh1.write(row3, inc(), result[6], datetime_format)
14632 amit.gupta 1045
                    sh1.write(row3, inc(), sourceMap.get(result[2]))
1046
                    sh1.write(row3, inc(), morder.get("merchantOrderId"))
14771 amit.gupta 1047
                    sh1.write(row3, inc(), subOrder.get("status"))
15932 amit.gupta 1048
                    sh1.write(row3, inc(), subOrder.get("detailedStatus"))
14632 amit.gupta 1049
                    sh1.write(row3, inc(), subOrder.get("productTitle"))
15932 amit.gupta 1050
                    sh1.write(row3, inc(), result[9])
14632 amit.gupta 1051
                    inc()
1052
                    if int(subOrder.get("quantity")) > 0:
1053
                        sh1.write(row3, i, int(subOrder.get("amountPaid"))/int(subOrder.get("quantity")))
14647 amit.gupta 1054
                    skuData = getSkuData(morder.get("storeId"), subOrder.get("productCode"))
16492 amit.gupta 1055
                    if morder.get("storeId") in (1,2,4,5,6):
14647 amit.gupta 1056
                        skuData = db1.MasterData.find_one({'identifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
1057
                    elif morder.get("storeId") == 3:
1058
                        skuData = db1.MasterData.find_one({'secondaryIdentifier':subOrder.get("productCode").strip(), 'source_id':morder.get("storeId")})
14634 amit.gupta 1059
                    if skuData is not None:
14771 amit.gupta 1060
                        sh1.write(row3, inc(), skuData.get("skuBundleId"))
14634 amit.gupta 1061
                        sh1.write(row3, inc(), skuData.get("brand"))
1062
                        sh1.write(row3, inc(), skuData.get("model_name"))
1063
                        sh1.write(row3, inc(), skuData.get("category"))
16213 amit.gupta 1064
                        sh1.write(row3, inc(), subOrder.get("dealRank"))
16286 amit.gupta 1065
                        sh1.write(row3, inc(), subOrder.get("maxNlc"))
1066
                        sh1.write(row3, inc(), subOrder.get("minNlc"))
16317 amit.gupta 1067
                        sh1.write(row3, inc(), utils.statusMap.get(subOrder.get("db")))
1068
 
16286 amit.gupta 1069
                        sh1.write(row3, inc(), subOrder.get("itemStatus"))
15932 amit.gupta 1070
                    else:
1071
                        sh1.write(row3, inc(), None)
1072
                        sh1.write(row3, inc(), None)
1073
                        sh1.write(row3, inc(), None)
1074
                        sh1.write(row3, inc(), None)
1075
                        sh1.write(row3, inc(), None)
16286 amit.gupta 1076
                        sh1.write(row3, inc(), None)
1077
                        sh1.write(row3, inc(), None)
1078
                        sh1.write(row3, inc(), None)
1079
                        sh1.write(row3, inc(), None)
17012 amit.gupta 1080
                    print result[10]
1081
                    sh1.write(row3, inc(), unicode(result[10], errors='ignore'))
15932 amit.gupta 1082
                    sh1.write(row3, inc(), result[11])
1083
                    sh1.write(row3, inc(), result[12])
1084
 
14881 amit.gupta 1085
                    #removed filter as requested by Rajneesh
1086
                    #if subOrder.get("cashBackStatus") == Store.CB_APPROVED or subOrder.get("cashBackStatus") == Store.CB_PENDING:
1087
                    row +=1
1088
                    i=-1
1089
                    worksheet.write(row, inc(), result[0])
15932 amit.gupta 1090
                    worksheet.write(row, inc(), result[7])
14881 amit.gupta 1091
                    worksheet.write(row, inc(), result[1])
15932 amit.gupta 1092
                    worksheet.write(row, inc(), result[6], datetime_format)
14881 amit.gupta 1093
                    worksheet.write(row, inc(), result[2])
1094
                    worksheet.write(row, inc(), morder.get("merchantOrderId"))
16785 amit.gupta 1095
                    worksheet.write(row, inc(), subOrder.get("merchantSubOrderId"))                    
14881 amit.gupta 1096
                    worksheet.write(row, inc(), subOrder.get("productTitle"))
1097
                    worksheet.write(row, inc(), subOrder.get("amountPaid"))
1098
                    worksheet.write(row, inc(), subOrder.get("cashBackAmount"))
1099
                    worksheet.write(row, inc(), subOrder.get("status"))
1100
                    worksheet.write(row, inc(), subOrder.get("detailedStatus"))
1101
                    worksheet.write(row, inc(), subOrder.get("cashBackStatus"))
1102
                    worksheet.write(row, inc(), False if morder.get("reconciled") is None else True)
1103
                    if morder.get("reconciled") and morder.get("storeId")==3:
1104
                        try:
16718 amit.gupta 1105
                            snapdealafinfo = db.snapdealOrderAffiliateInfo.find_one({"adId":morder.get("adId"), "reconciled":True})
1106
                            worksheet.write(row, inc(), snapdealafinfo.get("ip"))
1107
                            worksheet.write(row, inc(), snapdealafinfo.get("conversionStatus"))
14881 amit.gupta 1108
                        except:
16718 amit.gupta 1109
                            print "Could not find", morder.get("adId"), "that is reconciled for order", morder.get("orderId")
16726 amit.gupta 1110
                    #if result[8] >= 10:
1111
                    #    row2 +=1 
1112
                    #    i=-1
1113
                        #worksheet1.write(row2, inc(), result[0])
1114
                        #worksheet1.write(row2, inc(), result[7])
1115
                        #worksheet1.write(row2, inc(), result[1])
1116
                        #worksheet1.write(row2, inc(), result[6], datetime_format)
1117
                        #worksheet1.write(row2, inc(), result[2])
1118
                        #worksheet1.write(row2, inc(), morder.get("merchantOrderId"))
1119
                        #worksheet1.write(row2, inc(), subOrder.get("productTitle"))
1120
                        #worksheet1.write(row2, inc(), subOrder.get("amountPaid"))
1121
                        #worksheet1.write(row2, inc(), subOrder.get("cashBackAmount"))
1122
                        #worksheet1.write(row2, inc(), subOrder.get("status"))
1123
                        #worksheet1.write(row2, inc(), subOrder.get("detailedStatus"))
1124
                        #worksheet1.write(row2, inc(), subOrder.get("cashBackStatus"))
1125
                        #worksheet1.write(row2, inc(), False if morder.get("reconciled") is None else True)
1126
                        #worksheet1.write(row2, inc(), )
1127
                        #if morder.get("reconciled") and morder.get("storeId")==3:
1128
                        #    try:
1129
                        #        snapdealafinfo = db.snapdealOrderAffiliateInfo.find_one({"adId":morder.get("adId"), "reconciled":True})
1130
                        #        worksheet1.write(row2, inc(), snapdealafinfo.get("ip"))
1131
                        #        worksheet1.write(row2, inc(), snapdealafinfo.get("conversionStatus"))
1132
                        #    except:
1133
                        #        print "Could not find", morder.get("adId"), "that is reconcired for order", morder.get("orderId")
15423 amit.gupta 1134
 
15542 amit.gupta 1135
    flipkartOrders = session.query(FlipkartOrders).order_by(FlipkartOrders.created.desc()).all()
15540 amit.gupta 1136
    flipkartOrders.reverse()
15423 amit.gupta 1137
    row3=0
15430 amit.gupta 1138
    #try:
15540 amit.gupta 1139
    for order in flipkartOrders:
15423 amit.gupta 1140
        row3 += 1
1141
        i=-1
15540 amit.gupta 1142
        sh2.write(row3, inc(), order.user_id)
1143
        sh2.write(row3, inc(), order.email)
1144
        sh2.write(row3, inc(), order.created, datetime_format)
15423 amit.gupta 1145
        sh2.write(row3, inc(), "Flipkart")
15540 amit.gupta 1146
        sh2.write(row3, inc(), order.status)
1147
        sh2.write(row3, inc(), order.title)
1148
        sh2.write(row3, inc(), order.price)
1149
        sh2.write(row3, inc(), order.quantity)
1150
        sh2.write(row3, inc(), order.catalogId)
1151
        sh2.write(row3, inc(), order.brand)
1152
        sh2.write(row3, inc(), order.model)
1153
        sh2.write(row3, inc(), order.category)
14632 amit.gupta 1154
 
14613 amit.gupta 1155
    wb.save(XLS_FILENAME)
14632 amit.gupta 1156
    workbook.save(XLS_O_FILENAME)
14647 amit.gupta 1157
 
1158
def getSkuData(storeId, identifier):
16492 amit.gupta 1159
    if storeId in (1,2,4,5,6):
14647 amit.gupta 1160
        skuData = client.Catalog.MasterData.find_one({'identifier':identifier, 'source_id':storeId})
1161
    elif storeId == 3:
1162
        skuData = client.Catalog.MasterData.find_one({'secondaryIdentifier':identifier, 'source_id':storeId})
1163
    return skuData
1164
 
14460 amit.gupta 1165
def inc():
1166
    global i
1167
    i+=1
1168
    return i
15540 amit.gupta 1169
 
1170
def migrateFlipkartOrders():
1171
    db = client.Dtr
1172
    info = reversed(list(db.flipkartOrderAffiliateInfo.find()))
1173
    #try:
1174
    for order in info:
1175
        userId = None
1176
        subTagId = None
1177
        email = None
1178
        subTagId = order.get("subTagId")
1179
        if subTagId:
1180
            click = session.query(Clicks).filter_by(tag = subTagId).first()
1181
            if click is not None:
1182
                userId= click.user_id 
1183
                user = session.query(Users.email).filter_by(id = userId).first()
1184
                if user is not None:
1185
                    email = user.email
1186
 
1187
        flipkartOrder = FlipkartOrders()
1188
        flipkartOrder.user_id = userId
1189
        flipkartOrder.identifier = order.get("identifier")
1190
        flipkartOrder.email = email
1191
        flipkartOrder.subtagId = order.get("subTagId")
1192
        flipkartOrder.created = datetime.strptime(order.get("saleDate"), "%Y-%m-%d")
1193
        flipkartOrder.status = order.get("conversionStatus")
1194
        flipkartOrder.title = order.get("productTitle")
1195
        flipkartOrder.price = order.get("price")
1196
        flipkartOrder.quantity = order.get("quantity")
1197
        flipkartOrder.productCode = order.get("productCode")
1198
        skuData = getSkuData(2, order.get("productCode"))
1199
        if skuData is not None:
1200
            flipkartOrder.catalogId = skuData.get("skuBundleId")
1201
            flipkartOrder.brand = skuData.get("brand")
1202
            flipkartOrder.model = skuData.get("model_name")
1203
            flipkartOrder.category =categoryMap.get(skuData.get("category_id"))
1204
            flipkartOrder.title =skuData.get("source_product_name")
1205
 
1206
    session.commit()
16947 amit.gupta 1207
 
1208
 
1209
def main1():
1210
    db = client.Dtr
1211
    for offer in db.snapdealOrderAffiliateInfo.find({}):
1212
        print offer.get("adId"), offer.get("saleAmount"), type(offer.get("saleAmount"))  
1213
        #obj = offer.get(saleTime)
1214
        #obj['paidAmount'] += order["paidAmount"]
14632 amit.gupta 1215
def addHeaders(sheet):
1216
    global i
1217
    i = 0
1218
    sheet.write(0, inc(), )
14450 amit.gupta 1219
def main():
14647 amit.gupta 1220
 
16995 amit.gupta 1221
    message = generateSnapDealReco()
14647 amit.gupta 1222
    generateFlipkartReco()
15791 manish.sha 1223
    generateShopcluesReco()
14650 amit.gupta 1224
    generateAmazonReco(XLS_A_FILENAME)
14613 amit.gupta 1225
    getUserOrders()
16995 amit.gupta 1226
    sendmail(["amit.gupta@shop2020.in","rajneesh.arora@saholic.com","manish.sharma@shop2020.in"], message, "Affiliate Reco", XLS_FILENAME, XLS_F_FILENAME, XLS_A_FILENAME, XLS_SC_FILENAME)
17001 amit.gupta 1227
    #sendmail(["amit.gupta@shop2020.in"], "", "Affiliate Reco", XLS_FILENAME, XLS_F_FILENAME, XLS_A_FILENAME, XLS_SC_FILENAME)
16266 manish.sha 1228
    sendmail(["amit.gupta@shop2020.in", "rajneesh.arora@saholic.com", "chaitnaya.vats@saholic.com", "manoj.kumar@saholic.com", "manish.sharma@shop2020.in"], "", "All DTR Orders", XLS_O_FILENAME)
17001 amit.gupta 1229
 
1230
 
1231
def main2():
1232
    db = client.Dtr
1233
    curs = getOrdersAfterDate(datetime.now() - timedelta(days=1), 3)
1234
    datemap={}
1235
    for row1 in curs:
1236
        orderId = row1[0]
1237
        order = db.merchantOrder.find_one({"orderId":orderId})
1238
        if order is None:
1239
            continue
1240
        #saleTime = int(time.mktime(datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").timetuple()))
1241
        try:
1242
            saleTime = datetime.strptime(order['placedOn'], "%a, %d %b, %Y").strftime("%Y-%m-%d")
1243
        except:
1244
            saleTime = datetime.strptime(order['placedOn'], "%b %d, %Y, %I:%M %p").strftime("%Y-%m-%d")
1245
        print "%s\t%s\t%s\t%s"%(orderId, order['placedOn'], saleTime, order['paidAmount'])
1246
        if not datemap.has_key(saleTime):
1247
            datemap[saleTime] = {"totalAmount":0, "paidAmount":0, "rejectedAmount":0, "approvedAmount":0, "count":0}
1248
 
1249
        obj = datemap.get(saleTime)
1250
        obj['paidAmount'] += order["paidAmount"]
1251
        obj['count'] += 1
1252
 
1253
    for offer in db.snapdealOrderAffiliateInfo1.find({"saleDate":{"$gte":toTimeStamp(datetime.now() - timedelta(days=1))}}):
1254
        saleTime =  utils.fromTimeStamp(offer.get('saleDate')).strftime("%Y-%m-%d")
1255
        obj = datemap.get(saleTime)
1256
        if obj is not None:
1257
            try:
1258
                if offer.get("payOut"):
1259
                    obj['approvedAmount'] += offer["saleAmount"]
1260
                else:
1261
                    obj['rejectedAmount'] += offer["saleAmount"]
1262
            except:
1263
                print "Exception for orderId" , offer.get("orderId")
1264
        else:
1265
            print "Could not find sale date", saleTime
1266
            continue
1267
 
1268
    for key,valmap in  datemap.iteritems():
1269
        valmap['_id'] = key
1270
        db.flSaleSnapshot.save(valmap)
14450 amit.gupta 1271
 
1272
if __name__ == '__main__':
17010 amit.gupta 1273
    main2()
17008 amit.gupta 1274
    main()
17010 amit.gupta 1275
 
14460 amit.gupta 1276