Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
14305 amit.gupta 1
from bson.objectid import ObjectId
2
from datetime import datetime, timedelta
3
from dtr.config import PythonPropertyReader
16546 kshitij.so 4
from dtr.dao import FeaturedDeals, AppTransactions
14037 kshitij.so 5
from dtr.storage import DataService
6
from dtr.storage.DataService import price_preferences, brand_preferences, \
16546 kshitij.so 7
    user_actions, Brands, app_offers
16304 amit.gupta 8
from dtr.storage.MemCache import MemCache
16560 amit.gupta 9
from dtr.utils.FetchLivePrices import returnLatestPrice
16546 kshitij.so 10
from dtr.utils.utils import to_java_date, CB_PENDING, CB_APPROVED, CB_INIT
14305 amit.gupta 11
from elixir import *
12
from operator import itemgetter
13
import pymongo
16398 amit.gupta 14
import random
14322 kshitij.so 15
import re
14791 kshitij.so 16
import traceback
13572 kshitij.so 17
 
18
con = None
19
 
14037 kshitij.so 20
DataService.initialize(db_hostname="localhost")
16304 amit.gupta 21
mc = MemCache("127.0.0.1")
14037 kshitij.so 22
 
16406 kshitij.so 23
SOURCE_MAP = {1:'AMAZON',2:'FLIPKART',3:'SNAPDEAL',4:'SAHOLIC',5:"SHOPCLUES.COM",6:"PAYTM.COM"}
14482 kshitij.so 24
 
15853 kshitij.so 25
COLLECTION_MAP = {
26
                  'ExceptionalNlc':'skuBundleId',
27
                  'SkuDealerPrices':'skuBundleId',
28
                  'SkuDiscountInfo':'skuBundleId',
29
                  'SkuSchemeDetails':'skuBundleId',
16488 kshitij.so 30
                  'DealPoints':'skuBundleId'
15853 kshitij.so 31
                  }
32
 
13572 kshitij.so 33
def get_mongo_connection(host='localhost', port=27017):
34
    global con
35
    if con is None:
36
        print "Establishing connection %s host and port %d" %(host,port)
37
        try:
38
            con = pymongo.MongoClient(host, port)
39
        except Exception, e:
40
            print e
41
            return None
42
    return con
43
 
13907 kshitij.so 44
def populateCashBack():
13921 kshitij.so 45
    print "Populating cashback"
46
    cashBackMap = {}
47
    itemCashBackMap = {}
13907 kshitij.so 48
    cashBack = list(get_mongo_connection().Catalog.CategoryCashBack.find())
49
    for row in cashBack:
13970 kshitij.so 50
        temp_map = {}
51
        temp_list = []
13907 kshitij.so 52
        if cashBackMap.has_key(row['source_id']):
53
            arr = cashBackMap.get(row['source_id'])
54
            for val in arr:
55
                temp_list.append(val)
56
            temp_map[row['category_id']] = row
57
            temp_list.append(temp_map)
58
            cashBackMap[row['source_id']] = temp_list 
59
        else:
60
            temp_map[row['category_id']] = row
61
            temp_list.append(temp_map)
62
            cashBackMap[row['source_id']] = temp_list
13921 kshitij.so 63
    itemCashBack = list(get_mongo_connection().Catalog.ItemCashBack.find())
64
    for row in itemCashBack:
65
        if not itemCashBackMap.has_key(row['skuId']):
66
            itemCashBackMap[row['skuId']] = row
14761 kshitij.so 67
    mc.set("item_cash_back", itemCashBackMap, 24 * 60 * 60)
68
    mc.set("category_cash_back", cashBackMap, 24 * 60 * 60)
13907 kshitij.so 69
 
13572 kshitij.so 70
def addCategoryDiscount(data):
13970 kshitij.so 71
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 72
    query = []
73
    data['brand'] = data['brand'].strip().upper()
13970 kshitij.so 74
    data['discountType'] = data['discountType'].upper().strip()
13572 kshitij.so 75
    query.append({"brand":data['brand']})
76
    query.append({"category_id":data['category_id']})
77
    r = collection.find({"$and":query})
78
    if r.count() > 0:
13639 kshitij.so 79
        return {0:"Brand & Category info already present."}
13572 kshitij.so 80
    else:
81
        collection.insert(data)
13970 kshitij.so 82
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 83
        return {1:"Data added successfully"}
13572 kshitij.so 84
 
13970 kshitij.so 85
def updateCategoryDiscount(data,_id):
86
    try:
87
        collection = get_mongo_connection().Catalog.CategoryDiscount
88
        collection.update({'_id':ObjectId(_id)},{"$set":{'min_discount':data['min_discount'],'max_discount':data['max_discount'],'discountType':data['discountType'].upper().strip()}},upsert=False, multi = False)
89
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
90
        return {1:"Data updated successfully"}
91
    except:
92
        return {0:"Data not updated."}
93
 
94
 
13572 kshitij.so 95
def getAllCategoryDiscount():
96
    data = []
13970 kshitij.so 97
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 98
    cursor = collection.find()
99
    for val in cursor:
100
        data.append(val)
101
    return data
102
 
14553 kshitij.so 103
def __getBundledSkusfromSku(sku):
104
    masterData =  get_mongo_connection().Catalog.MasterData.find_one({"_id":sku},{"skuBundleId":1})
105
    if masterData is not None:
106
        return list(get_mongo_connection().Catalog.MasterData.find({"skuBundleId":masterData.get('skuBundleId')},{'_id':1,'skuBundleId':1}))
107
    else:
108
        return []
13572 kshitij.so 109
 
15853 kshitij.so 110
def addSchemeDetailsForSku(data):
111
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
112
    result = collection.find_one({'skuBundleId':data['skuBundleId']})
113
    if result is None:
14553 kshitij.so 114
        collection.insert(data)
15853 kshitij.so 115
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14553 kshitij.so 116
        return {1:"Data added successfully"}
15853 kshitij.so 117
    return {1:"BundleId info already present"}
118
 
14069 kshitij.so 119
def getAllSkuWiseSchemeDetails(offset, limit):
13572 kshitij.so 120
    data = []
13970 kshitij.so 121
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
14071 kshitij.so 122
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 123
    for val in cursor:
15853 kshitij.so 124
        master = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':val['skuBundleId']})
125
        if master is not None:
126
            val['brand'] = master['brand']
127
            val['source_product_name'] = master['source_product_name']
14069 kshitij.so 128
        else:
129
            val['brand'] = ""
130
            val['source_product_name'] = ""
13572 kshitij.so 131
        data.append(val)
132
    return data
133
 
15853 kshitij.so 134
def addSkuDiscountInfo(data):
135
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
136
    cursor = collection.find_one({"skuBundleId":data['skuBundleId']})
137
    if cursor is not None:
138
        return {0:"BundleId information already present."}
13572 kshitij.so 139
    else:
15853 kshitij.so 140
        collection.insert(data)
141
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 142
        return {1:"Data added successfully"}
13572 kshitij.so 143
 
13970 kshitij.so 144
def getallSkuDiscountInfo(offset, limit):
13572 kshitij.so 145
    data = []
13970 kshitij.so 146
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
147
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 148
    for val in cursor:
15853 kshitij.so 149
        master = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':val['skuBundleId']})
150
        if master is not None:
151
            val['brand'] = master['brand']
152
            val['source_product_name'] = master['source_product_name']
13970 kshitij.so 153
        else:
154
            val['brand'] = ""
155
            val['source_product_name'] = ""
13572 kshitij.so 156
        data.append(val)
157
    return data
158
 
13970 kshitij.so 159
def updateSkuDiscount(data,_id):
160
    try:
161
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
162
        collection.update({'_id':ObjectId(_id)},{"$set":{'min_discount':data['min_discount'],'max_discount':data['max_discount'],'discountType':data['discountType'].upper().strip()}},upsert=False, multi = False)
15853 kshitij.so 163
        get_mongo_connection().Catalog.MasterData.update({'_id':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 164
        return {1:"Data updated successfully"}
165
    except:
166
        return {0:"Data not updated."}
167
 
168
 
15853 kshitij.so 169
def addExceptionalNlc(data):
170
    collection = get_mongo_connection().Catalog.ExceptionalNlc
171
    cursor = collection.find_one({"skuBundleId":data['skuBundleId']})
172
    if cursor is not None:
173
        return {0:"BundleId information already present."}
13572 kshitij.so 174
    else:
15853 kshitij.so 175
        collection.insert(data)
176
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 177
        return {1:"Data added successfully"}
13572 kshitij.so 178
 
13970 kshitij.so 179
def getAllExceptionlNlcItems(offset, limit):
13572 kshitij.so 180
    data = []
13970 kshitij.so 181
    collection = get_mongo_connection().Catalog.ExceptionalNlc
14071 kshitij.so 182
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 183
    for val in cursor:
15853 kshitij.so 184
        master = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':val['skuBundleId']})
185
        if master is not None:
186
            val['brand'] = master['brand']
187
            val['source_product_name'] = master['source_product_name']
13970 kshitij.so 188
        else:
189
            val['brand'] = ""
190
            val['source_product_name'] = ""
13572 kshitij.so 191
        data.append(val)
192
    return data
193
 
14005 amit.gupta 194
def getMerchantOrdersByUser(userId, page=1, window=50, searchMap={}):
195
    if searchMap is None:
196
        searchMap = {}
13603 amit.gupta 197
    if page==None:
198
        page = 1
199
 
200
    if window==None:
201
        window = 50
202
    result = {}
13582 amit.gupta 203
    skip = (page-1)*window
14005 amit.gupta 204
 
14353 amit.gupta 205
    if userId is not None:
206
        searchMap['userId'] = userId
13603 amit.gupta 207
    collection = get_mongo_connection().Dtr.merchantOrder
14609 amit.gupta 208
    cursor = collection.find(searchMap).sort("orderId",-1)
13603 amit.gupta 209
    total_count = cursor.count()
210
    pages = total_count/window + (0 if total_count%window==0 else 1)  
211
    print "total_count", total_count
212
    if total_count > skip:
13999 amit.gupta 213
        cursor = cursor.skip(skip).limit(window)
13603 amit.gupta 214
        orders = []
215
        for order in cursor:
14002 amit.gupta 216
            del(order["_id"])
217
            orders.append(order)
13603 amit.gupta 218
        result['data'] = orders
219
        result['window'] = window
220
        result['totalCount'] = total_count 
221
        result['currCount'] = cursor.count()
222
        result['totalPages'] = pages
223
        result['currPage'] = page    
224
        return result
225
    else:
226
        return result
13630 kshitij.so 227
 
13927 amit.gupta 228
def getRefunds(userId, page=1, window=10):
229
    if page==None:
230
        page = 1
231
 
232
    if window==None:
13995 amit.gupta 233
        window = 10
13927 amit.gupta 234
    result = {}
235
    skip = (page-1)*window
236
    collection = get_mongo_connection().Dtr.refund
237
    cursor = collection.find({"userId":userId})
238
    total_count = cursor.count()
239
    pages = total_count/window + (0 if total_count%window==0 else 1)  
240
    print "total_count", total_count
241
    if total_count > skip:
14668 amit.gupta 242
        cursor = cursor.skip(skip).limit(window).sort([('batch',-1)])
13927 amit.gupta 243
        refunds = []
244
        for refund in cursor:
245
            del(refund["_id"])
246
            refunds.append(refund)
247
        result['data'] = refunds
248
        result['window'] = window
249
        result['totalCount'] = total_count 
250
        result['currCount'] = cursor.count()
251
        result['totalPages'] = pages
252
        result['currPage'] = page    
253
        return result
254
    else:
255
        return result
256
 
257
def getPendingRefunds(userId):
13991 amit.gupta 258
    print type(userId)
13927 amit.gupta 259
    result = get_mongo_connection().Dtr.merchantOrder\
260
        .aggregate([
16398 amit.gupta 261
                    {'$match':{'subOrders.cashBackStatus':CB_APPROVED, 'userId':userId}},
13927 amit.gupta 262
                    {'$unwind':"$subOrders"},
16398 amit.gupta 263
                    {'$match':{'subOrders.cashBackStatus':CB_APPROVED}},
13927 amit.gupta 264
                    { 
265
                     '$group':{
266
                               '_id':None,
267
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
268
                               }
269
                     }
13987 amit.gupta 270
                ])['result']
271
 
272
    if len(result)>0:
273
        result = result[0]        
274
        result.pop("_id")
275
    else:
276
        result={}
277
        result['amount'] = 0.0
14305 amit.gupta 278
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), int(PythonPropertyReader.getConfig('CREDIT_DAY_OF_WEEK'))),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 279
    return result
14037 kshitij.so 280
 
14671 amit.gupta 281
def getPendingCashbacks(userId):
282
    result = get_mongo_connection().Dtr.merchantOrder\
283
        .aggregate([
16398 amit.gupta 284
                    {'$match':{'subOrders.cashBackStatus':CB_PENDING, 'userId':userId}},
14671 amit.gupta 285
                    {'$unwind':"$subOrders"},
16398 amit.gupta 286
                    {'$match':{'subOrders.cashBackStatus':CB_PENDING}},
14671 amit.gupta 287
                    { 
288
                     '$group':{
289
                               '_id':None,
290
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
291
                               }
292
                     }
293
                ])['result']
294
 
295
    if len(result)>0:
296
        result = result[0]        
297
        result.pop("_id")
298
    else:
299
        result={}
300
        result['amount'] = 0.0
301
    return result
302
 
14037 kshitij.so 303
def __populateCache(userId):
304
    print "Populating memcache for userId",userId
305
    outer_query = []
16067 kshitij.so 306
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
14037 kshitij.so 307
    query = {}
16170 kshitij.so 308
    query['$gt'] = -100
14037 kshitij.so 309
    outer_query.append({'totalPoints':query})
310
    brandPrefMap = {}
311
    pricePrefMap = {}
312
    actionsMap = {}
313
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
314
    for x in brand_p:
315
        pricePrefMap[x.category_id] = [x.min_price,x.max_price]
316
    for x in session.query(brand_preferences).filter_by(user_id=userId).all():
317
        temp_map = {}
318
        if brandPrefMap.has_key((x.brand).strip().upper()):
319
            val = brandPrefMap.get((x.brand).strip().upper())
320
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
321
            val.append(temp_map)
322
        else:
323
            temp = []
324
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
325
            temp.append(temp_map)
326
            brandPrefMap[(x.brand).strip().upper()] = temp
327
 
328
    for x in session.query(user_actions).filter_by(user_id=userId).all():
329
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
16458 kshitij.so 330
    all_deals = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query},{'_id':1,'category_id':1,'brand':1,'totalPoints':1,'bestSellerPoints':1,'nlcPoints':1,'rank':1,'available_price':1,'dealType':1,'source_id':1,'brand_id':1,'skuBundleId':1,'dp':1, 'showDp':1}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
14037 kshitij.so 331
    all_category_deals = []
332
    mobile_deals = []
333
    tablet_deals = []
334
    for deal in all_deals:
335
        if actionsMap.get(deal['_id']) == 0:
336
            fav_weight =.25
337
        elif actionsMap.get(deal['_id']) == 1:
338
            fav_weight = 1.5
339
        else:
340
            fav_weight = 1
341
 
342
        if brandPrefMap.get(deal['brand'].strip().upper()) is not None:
343
            brand_weight = 1
344
            for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):
345
                if brandInfo.get(deal['category_id']) is not None:
346
                    if brandInfo.get(deal['category_id']) == 1:
14055 kshitij.so 347
                        brand_weight = 2.0
14037 kshitij.so 348
        else:
349
            brand_weight = 1
350
 
351
        if pricePrefMap.get(deal['category_id']) is not None:
352
 
353
            if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:
354
                asp_weight = 1.5
355
            elif  deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] - 0.5 * pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1] + 0.5 * pricePrefMap.get(deal['category_id'])[1]:
356
                asp_weight = 1.2
357
            else:
358
                asp_weight = 1
359
        else:
360
            asp_weight = 1
361
 
362
        persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weight
363
        deal['persPoints'] = persPoints
364
 
365
        if deal['category_id'] ==3:
366
            mobile_deals.append(deal)
367
        elif deal['category_id'] ==5:
368
            tablet_deals.append(deal)
369
        else:
370
            continue
371
        all_category_deals.append(deal)
372
 
14144 kshitij.so 373
    session.close()
14037 kshitij.so 374
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 0:all_deals}
375
    mc.set(str(userId), mem_cache_val)
376
 
377
 
14531 kshitij.so 378
def __populateFeaturedDeals():
379
    all_category_fd = []
380
    mobile_fd = []
381
    tablet_fd = []
14550 kshitij.so 382
    activeFeaturedDeals = get_mongo_connection().Catalog.FeaturedDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}).sort({'rank':pymongo.ASCENDING})
14531 kshitij.so 383
    for activeFeaturedDeal in activeFeaturedDeals:
384
        for k,v in activeFeaturedDeal['rankDetails']:
385
            featuredDeal = FeaturedDeals(activeFeaturedDeal['sku'], int(k), activeFeaturedDeal['thresholdPrice'], int(v))
386
            if featuredDeal.category_id == 0:
387
                all_category_fd.append(featuredDeal)
388
            elif featuredDeal.category_id == 3:
389
                mobile_fd.append(featuredDeal)
390
            elif featuredDeal.category_id == 5:
391
                tablet_fd.append(featuredDeal)
392
            else:
393
                continue
14550 kshitij.so 394
    mc.set("featured_deals_category_"+str(0), all_category_fd, 3600)
395
    mc.set("featured_deals_category_"+str(3), mobile_fd, 3600)
396
    mc.set("featured_deals_category_"+str(5), tablet_fd, 3600)
14037 kshitij.so 397
 
14791 kshitij.so 398
def getNewDeals(userId, category_id, offset, limit, sort, direction, filterData=None):
14761 kshitij.so 399
    if not bool(mc.get("category_cash_back")):
13921 kshitij.so 400
        populateCashBack()
14037 kshitij.so 401
 
14550 kshitij.so 402
    try:
403
        if mc.get("featured_deals_category_"+str(category_id)) is None:
404
            __populateFeaturedDeals()
405
    except:
406
        pass 
14531 kshitij.so 407
 
13771 kshitij.so 408
    rank = 1
16079 kshitij.so 409
    dealsListMap = []
14037 kshitij.so 410
    user_specific_deals = mc.get(str(userId))
411
    if user_specific_deals is None:
412
        __populateCache(userId)
413
        user_specific_deals = mc.get(str(userId))
14038 kshitij.so 414
    else:
415
        print "Getting user deals from cache"
14037 kshitij.so 416
    category_specific_deals = user_specific_deals.get(category_id)
417
 
418
    if sort is None or direction is None:
419
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
420
    else:
421
        if sort == "bestSellerPoints":
422
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
423
        else:
424
            if direction == -1:
425
                rev = True
426
            else:
427
                rev = False
428
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
429
 
14791 kshitij.so 430
 
431
    print "============================"
432
    if filterData is not None:
433
        try:
434
            sorted_deals = filterDeals(sorted_deals, filterData)
435
        except:
16067 kshitij.so 436
            traceback.print_exc()
14791 kshitij.so 437
 
16067 kshitij.so 438
 
439
    sortedMap = {}
440
    rankMap = {}
441
    rank = 0
442
    for sorted_deal in sorted_deals:
443
        if sortedMap.get(sorted_deal['skuBundleId']) is None:
444
            sortedMap[sorted_deal['skuBundleId']] = {rank:[sorted_deal]}
445
            rankMap[rank] = (sortedMap[sorted_deal['skuBundleId']].values())[0]
446
            rank = rank +1
447
        else:
448
            for temp_list in sortedMap.get(sorted_deal['skuBundleId']).itervalues():
449
                temp_list.append(sorted_deal)
16079 kshitij.so 450
            rankMap[(sortedMap.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
16067 kshitij.so 451
 
452
    for dealList in [rankMap.get(k, []) for k in range(offset, offset+limit)]:
16079 kshitij.so 453
        temp = []
16067 kshitij.so 454
        for d in dealList:
455
            item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
16320 kshitij.so 456
            if len(item) ==0:
457
                continue
16079 kshitij.so 458
            item[0]['persPoints'] = d['persPoints']
459
            if d['dealType'] == 1 and d['source_id'] ==1:
16511 kshitij.so 460
                try:
461
                    manualDeal = list(get_mongo_connection().Catalog.ManualDeals.find({'sku':d['_id'],'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}))
462
                    item[0]['marketPlaceUrl'] = manualDeal[0]['dealUrl'].strip()
463
                except:
464
                    pass
16079 kshitij.so 465
            elif d['source_id'] ==3:
466
                item[0]['marketPlaceUrl'] = item[0]['marketPlaceUrl']+'?supc='+item[0].get('identifier')
467
            else:
468
                pass 
469
            try:
470
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
471
                if not cashBack or cashBack.get('cash_back_status')!=1:
14037 kshitij.so 472
                    item[0]['cash_back_type'] = 0
473
                    item[0]['cash_back'] = 0
16079 kshitij.so 474
                else:
475
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
476
                    item[0]['cash_back'] = cashBack['cash_back']
477
            except:
478
                print "Error in adding cashback to deals"
479
                item[0]['cash_back_type'] = 0
480
                item[0]['cash_back'] = 0
16252 kshitij.so 481
            try:
482
                item[0]['dp'] = d['dp']
483
                item[0]['showDp'] = d['showDp']
484
            except:
485
                item[0]['dp'] = 0.0
486
                item[0]['showDp'] = 0
16483 kshitij.so 487
            try:
488
                item[0]['thumbnail'] = item[0]['thumbnail'].strip()
489
            except:
490
                pass 
16079 kshitij.so 491
            temp.append(item[0])
16125 kshitij.so 492
        if len(temp) > 1:
16126 kshitij.so 493
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
16079 kshitij.so 494
        dealsListMap.append(temp)
495
    return dealsListMap
14037 kshitij.so 496
 
14791 kshitij.so 497
def filterDeals(deals, filterData):
498
    dealFiltered = []
499
    brandsFiltered = []
500
    filterArray = filterData.split('|')
501
    for data in filterArray:
502
        try:
503
            filter, info = data.split(':')
504
        except Exception as ex:
505
            traceback.print_exc()
506
            continue
507
        if filter == 'dealFilter':
508
            toFilter = info.split('^')
509
            print "deal filter ",toFilter
510
            if 'deals' in toFilter:
511
                dealFiltered = deals
512
                continue
513
            for filterVal in toFilter:
514
                if filterVal == 'dod':
515
                    for deal in deals:
516
                        if deal['dealType'] == 1:
517
                            dealFiltered.append(deal)
518
        elif filter == 'brandFilter':
519
            toFilter = info.split('^')
520
            print "brand filter ",toFilter
521
            if len(toFilter) == 0 or (len(toFilter)==1 and toFilter[0]==''):
522
                brandsFiltered = deals
523
            for deal in deals:
15151 kshitij.so 524
                if str(int(deal['brand_id'])) in toFilter:
14791 kshitij.so 525
                    brandsFiltered.append(deal)
15040 kshitij.so 526
    if len(dealFiltered) == 0:
527
        return brandsFiltered
14791 kshitij.so 528
    return [i for i in dealFiltered for j in brandsFiltered if i['_id']==j['_id']]
529
 
530
 
14037 kshitij.so 531
def getDeals(userId, category_id, offset, limit, sort, direction):
14761 kshitij.so 532
    if not bool(mc.get("category_cash_back")):
14037 kshitij.so 533
        populateCashBack()
534
    rank = 1
13771 kshitij.so 535
    deals = {}
13910 kshitij.so 536
    outer_query = []
537
    outer_query.append({"showDeal":1})
538
    query = {}
539
    query['$gt'] = 0
540
    outer_query.append({'totalPoints':query})
541
    if category_id in (3,5):
542
        outer_query.append({'category_id':category_id})
13803 kshitij.so 543
    if sort is None or direction is None:
544
        direct = -1
13910 kshitij.so 545
        print outer_query
546
        data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('totalPoints',direct),('bestSellerPoints',direct),('nlcPoints',direct),('rank',direct)]).skip(offset).limit(limit))
13795 kshitij.so 547
    else:
13910 kshitij.so 548
        print outer_query
13803 kshitij.so 549
        direct = direction
13910 kshitij.so 550
        if sort == "bestSellerPoints":
551
            print "yes,sorting by bestSellerPoints"
552
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
553
        else:
554
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 555
    for d in data:
556
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
557
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 558
            item[0]['dealRank'] = rank
559
            try:
14761 kshitij.so 560
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
13921 kshitij.so 561
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 562
                    item[0]['cash_back_type'] = 0
563
                    item[0]['cash_back'] = 0
13921 kshitij.so 564
                else:
14766 kshitij.so 565
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
13928 kshitij.so 566
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 567
            except:
568
                print "Error in adding cashback to deals"
13928 kshitij.so 569
                item[0]['cash_back_type'] = 0
570
                item[0]['cash_back'] = 0
13771 kshitij.so 571
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 572
 
13771 kshitij.so 573
            rank +=1
13785 kshitij.so 574
    return sorted(deals.values(), key=itemgetter('dealRank'))
575
 
16222 kshitij.so 576
def getItem(skuId,showDp=None):
16224 kshitij.so 577
    temp = []
14761 kshitij.so 578
    if not bool(mc.get("category_cash_back")):
14113 kshitij.so 579
        populateCashBack()
13795 kshitij.so 580
    try:
16222 kshitij.so 581
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'_id':int(skuId)})
582
        if skuData is None:
583
            raise
584
        try:
585
            cashBack = getCashBack(skuData['_id'], skuData['source_id'], skuData['category_id'])
586
            if not cashBack or cashBack.get('cash_back_status')!=1:
587
                skuData['cash_back_type'] = 0
588
                skuData['cash_back'] = 0
589
            else:
590
                skuData['cash_back_type'] = cashBack['cash_back_type']
591
                skuData['cash_back'] = cashBack['cash_back']
592
        except:
593
            print "Error in adding cashback to deals"
594
            skuData['cash_back_type'] = 0
595
            skuData['cash_back'] = 0
596
        skuData['in_stock'] = int(skuData['in_stock'])
597
        skuData['is_shortage'] = int(skuData['is_shortage'])
598
        skuData['category_id'] = int(skuData['category_id'])
599
        skuData['status'] = int(skuData['status'])
16483 kshitij.so 600
        try:
601
            skuData['thumbnail'] = skuData['thumbnail'].strip()
602
        except:
603
            pass 
16222 kshitij.so 604
        if showDp is not None:
605
            dealerPrice = get_mongo_connection().Catalog.SkuDealerPrices.find_one({'skuBundleId':skuData['skuBundleId']})
606
            skuData['dp'] = 0.0
607
            skuData['showDp'] = 0
608
            if dealerPrice is not None:
609
                skuData['dp'] = dealerPrice['dp']
610
                skuData['showDp'] = dealerPrice['showDp']
16224 kshitij.so 611
        temp.append(skuData)
612
        return temp
13795 kshitij.so 613
    except:
16224 kshitij.so 614
        return []
13836 kshitij.so 615
 
14761 kshitij.so 616
def getCashBack(skuId, source_id, category_id):
617
    if not bool(mc.get("category_cash_back")):
618
        populateCashBack()
619
    itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 620
    itemCashBack = itemCashBackMap.get(skuId)
621
    if itemCashBack is not None:
622
        return itemCashBack
14761 kshitij.so 623
    cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 624
    sourceCashBack = cashBackMap.get(source_id)
625
    if sourceCashBack is not None and len(sourceCashBack) > 0:
626
        for cashBack in sourceCashBack:
627
            if cashBack.get(category_id) is None:
628
                continue
629
            else:
630
                return cashBack.get(category_id)
631
    else:
632
        return {}
16560 amit.gupta 633
 
634
def getBundleBySourceSku(source_id, identifier):
635
    returnResult=[]
636
    if source_id in (1,2,4,5):
637
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
638
    elif source_id == 3:
639
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
640
    else:
641
        return {}
642
 
643
    if not skuData:
644
        return {}
645
    else:
16564 amit.gupta 646
        bundleId = skuData[0]["skuBundleId"]
16577 amit.gupta 647
        itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bundleId, 'in_stock':1}))
16560 amit.gupta 648
        for item in itemIds:
16575 amit.gupta 649
            sourceid = item['source_id']
16560 amit.gupta 650
            item['dealFlag'] = 0
651
            item['dealType'] = 0
652
            item['dealUrl'] = ""
16575 amit.gupta 653
            if item['sourceid'] ==5 and item['rank'] == 0:
16560 amit.gupta 654
                continue
16575 amit.gupta 655
            if item['sourceid'] ==3:
16560 amit.gupta 656
                item['marketPlaceUrl'] = item['marketPlaceUrl']+'?supc='+item.get('identifier')
16576 amit.gupta 657
            manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':sourceid, 'sku':item['_id']}))
16560 amit.gupta 658
            if len(manualDeals) > 0:
659
                item['dealFlag'] = 1
660
                item['dealType'] =manualDeals[0]['dealType']
661
                item['dealUrl'] = manualDeals[0]['dealUrl']
16575 amit.gupta 662
            info = returnLatestPrice(item, sourceid)
16577 amit.gupta 663
            if info:
664
                returnResult.append(info)
16560 amit.gupta 665
 
666
        return {'products':returnResult}
667
 
668
 
13921 kshitij.so 669
 
15129 kshitij.so 670
def getDealRank(identifier, source_id, userId):
16406 kshitij.so 671
    if source_id in (1,2,4,5,6):
15129 kshitij.so 672
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
673
    elif source_id == 3:
674
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
675
    else:
16282 amit.gupta 676
        return {'rank':0, 'description':'Source not valid','maxNlc':None, 'minNlc':None,'status':None,'dp':None}
15349 kshitij.so 677
    if len(skuData) == 0:
16282 amit.gupta 678
        return {'rank':0, 'description':'No matching product identifier found','maxNlc':None, 'minNlc':None,'status':None,'dp':None}
15129 kshitij.so 679
    user_specific_deals = mc.get(str(userId))
680
    if user_specific_deals is None:
681
        __populateCache(userId)
682
        user_specific_deals = mc.get(str(userId))
683
    else:
684
        print "Getting user deals from cache"
685
    category_id = skuData[0]['category_id']
686
    category_specific_deals = user_specific_deals.get(category_id)
16280 kshitij.so 687
 
688
    dealsData = get_mongo_connection().Catalog.Deals.find_one({'skuBundleId':skuData[0]['skuBundleId']})
689
    if dealsData is None:
690
        dealsData = {}
691
 
15129 kshitij.so 692
    if category_specific_deals is None or len(category_specific_deals) ==0:
16280 kshitij.so 693
        return {'rank':0,'description':'Category specific deals is empty','maxNlc':dealsData.get('maxNlc'),'minNlc':dealsData.get('minNlc'),'status':dealsData.get('status'),'dp':dealsData.get('dp')}
15129 kshitij.so 694
    sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
16168 kshitij.so 695
    sortedMap = {}
696
    rankMap = {}
697
    rank = 0
15129 kshitij.so 698
    for sorted_deal in sorted_deals:
16168 kshitij.so 699
        if sortedMap.get(sorted_deal['skuBundleId']) is None:
700
            sortedMap[sorted_deal['skuBundleId']] = {rank:[sorted_deal]}
701
            rankMap[rank] = (sortedMap[sorted_deal['skuBundleId']].values())[0]
702
            rank = rank +1
703
        else:
704
            for temp_list in sortedMap.get(sorted_deal['skuBundleId']).itervalues():
705
                temp_list.append(sorted_deal)
706
            rankMap[(sortedMap.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
707
 
16187 kshitij.so 708
    for dealRank ,dealList in rankMap.iteritems():
16168 kshitij.so 709
        for d in dealList:
16186 kshitij.so 710
            if d['skuBundleId'] == skuData[0]['skuBundleId']:
16280 kshitij.so 711
                return {'rank':dealRank+1,'description':'Rank found','maxNlc':dealsData.get('maxNlc'),'minNlc':dealsData.get('minNlc'),'status':dealsData.get('status'),'dp':dealsData.get('dp')}
16168 kshitij.so 712
 
16280 kshitij.so 713
    return {'rank':0,'description':'Rank not found','maxNlc':dealsData.get('maxNlc'),'minNlc':dealsData.get('minNlc'),'status':dealsData.get('status'),'dp':dealsData.get('dp')}
15129 kshitij.so 714
 
715
 
13836 kshitij.so 716
def getCashBackDetails(identifier, source_id):
14761 kshitij.so 717
    if not bool(mc.get("category_cash_back")):
13921 kshitij.so 718
        populateCashBack()
13771 kshitij.so 719
 
16406 kshitij.so 720
    if source_id in (1,2,4,5,6):
13839 kshitij.so 721
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 722
    elif source_id == 3:
13839 kshitij.so 723
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 724
    else:
725
        return {}
13836 kshitij.so 726
    if len(skuData) > 0:
14761 kshitij.so 727
        itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 728
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
729
        if itemCashBack is not None:
730
            return itemCashBack
14761 kshitij.so 731
        cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 732
        sourceCashBack = cashBackMap.get(source_id)
733
        if sourceCashBack is not None and len(sourceCashBack) > 0:
734
            for cashBack in sourceCashBack:
735
                if cashBack.get(skuData[0]['category_id']) is None:
736
                    continue
737
                else:
738
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 739
        else:
740
            return {} 
741
    else:
742
        return {}
13986 amit.gupta 743
 
14398 amit.gupta 744
def getImgSrc(identifier, source_id):
745
    skuData = None
16406 kshitij.so 746
    if source_id in (1,2,4,5,6):
14414 amit.gupta 747
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 748
    elif source_id == 3:
14414 amit.gupta 749
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 750
    if skuData is None:
751
        return {}
752
    else:
16483 kshitij.so 753
        try:
754
            return {'thumbnail':skuData.get('thumbnail').strip()}
755
        except:
756
            return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 757
 
758
def next_weekday(d, weekday):
759
    days_ahead = weekday - d.weekday()
760
    if days_ahead <= 0: # Target day already happened this week
761
        days_ahead += 7
762
    return d + timedelta(days_ahead)
763
 
13771 kshitij.so 764
 
13970 kshitij.so 765
def getAllDealerPrices(offset, limit):
766
    data = []
767
    collection = get_mongo_connection().Catalog.SkuDealerPrices
768
    cursor = collection.find().skip(offset).limit(limit)
769
    for val in cursor:
15853 kshitij.so 770
        master = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':val['skuBundleId']})
771
        if master is not None:
772
            val['brand'] = master['brand']
773
            val['source_product_name'] = master['source_product_name']
13970 kshitij.so 774
        else:
775
            val['brand'] = ""
776
            val['source_product_name'] = ""
16231 kshitij.so 777
        val['showDp'] = int(val['showDp'])
13970 kshitij.so 778
        data.append(val)
779
    return data
780
 
15853 kshitij.so 781
def addSkuDealerPrice(data):
782
    collection = get_mongo_connection().Catalog.SkuDealerPrices
783
    cursor = collection.find_one({"skuBundleId":data['skuBundleId']})
784
    if cursor is not None:
785
        return {0:"BundleId information already present."}
13970 kshitij.so 786
    else:
15853 kshitij.so 787
        collection.insert(data)
788
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 789
        return {1:"Data added successfully"}
790
 
791
def updateSkuDealerPrice(data, _id):
792
    try:
793
        collection = get_mongo_connection().Catalog.SkuDealerPrices
794
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
15853 kshitij.so 795
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 796
        return {1:"Data updated successfully"}
797
    except:
798
        return {0:"Data not updated."}
799
 
800
def updateExceptionalNlc(data, _id):
801
    try:
802
        collection = get_mongo_connection().Catalog.ExceptionalNlc
803
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
15853 kshitij.so 804
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 805
        return {1:"Data updated successfully"}
806
    except:
807
        return {0:"Data not updated."}
808
 
14041 kshitij.so 809
def resetCache(userId):
14043 kshitij.so 810
    try:
811
        mc.delete(userId)
812
        return {1:'Cache cleared.'}
813
    except:
814
        return {0:'Unable to clear cache.'}
815
 
15853 kshitij.so 816
def updateCollection(data):
14083 kshitij.so 817
    print data
15853 kshitij.so 818
    try:
819
        collection = get_mongo_connection().Catalog[data['class']]
820
        class_name = data.pop('class')
821
        _id = data.pop('oid')
822
        result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
823
        if class_name != "Notifications":
824
            record = list(collection.find({'_id':ObjectId(_id)}))
825
            if class_name !="CategoryDiscount":
826
                if record[0].has_key('sku'):
827
                    field = '_id'
828
                    val = record[0]['sku']
14852 kshitij.so 829
                else:
15853 kshitij.so 830
                    field = 'skuBundleId'
831
                    val = record[0]['skuBundleId']
832
                get_mongo_connection().Catalog.MasterData.update({field:val},{"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False, multi = True)
833
            else:
834
                get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
835
                                                                 {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
16233 kshitij.so 836
        if class_name =='SkuDealerPrices':
16237 kshitij.so 837
            get_mongo_connection().Catalog.Deals.update({'skuBundleId':val},{"$set":data},upsert=False, multi=True)
15853 kshitij.so 838
        return {1:"Data updated successfully"}
839
    except Exception as e:
840
        print e
841
        return {0:"Data not updated."}
14575 kshitij.so 842
 
14076 kshitij.so 843
 
14553 kshitij.so 844
def addNegativeDeals(data, multi):
845
    if multi !=1: 
846
        collection = get_mongo_connection().Catalog.NegativeDeals
847
        cursor = collection.find({"sku":data['sku']})
848
        if cursor.count() > 0:
849
            return {0:"Sku information already present."}
850
        else:
851
            collection.insert(data)
852
            return {1:"Data added successfully"}
14481 kshitij.so 853
    else:
14553 kshitij.so 854
        skuIds = __getBundledSkusfromSku(data['sku'])
855
        for sku in skuIds:
856
            data['sku'] = sku.get('_id')
857
            collection = get_mongo_connection().Catalog.NegativeDeals
858
            cursor = collection.find({"sku":data['sku']})
859
            if cursor.count() > 0:
860
                continue
861
            else:
14558 kshitij.so 862
                data.pop('_id',None)
14553 kshitij.so 863
                collection.insert(data)
14481 kshitij.so 864
        return {1:"Data added successfully"}
865
 
866
def getAllNegativeDeals(offset, limit):
867
    data = []
868
    collection = get_mongo_connection().Catalog.NegativeDeals
869
    cursor = collection.find().skip(offset).limit(limit)
870
    for val in cursor:
871
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
872
        if len(master) > 0:
873
            val['brand'] = master[0]['brand']
874
            val['source_product_name'] = master[0]['source_product_name']
875
            val['skuBundleId'] = master[0]['skuBundleId']
876
        else:
877
            val['brand'] = ""
878
            val['source_product_name'] = ""
879
            val['skuBundleId'] = ""
880
        data.append(val)
881
    return data
882
 
883
def getAllManualDeals(offset, limit):
884
    data = []
885
    collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 886
    cursor = collection.find().skip(offset).limit(limit)
14481 kshitij.so 887
    for val in cursor:
888
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
889
        if len(master) > 0:
890
            val['brand'] = master[0]['brand']
891
            val['source_product_name'] = master[0]['source_product_name']
892
            val['skuBundleId'] = master[0]['skuBundleId']
893
        else:
894
            val['brand'] = ""
895
            val['source_product_name'] = ""
896
            val['skuBundleId'] = ""
897
        data.append(val)
898
    return data
14076 kshitij.so 899
 
14553 kshitij.so 900
def addManualDeal(data, multi):
901
    if multi !=1:
902
        collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 903
        cursor = collection.find({'sku':data['sku']})
14553 kshitij.so 904
        if cursor.count() > 0:
905
            return {0:"Sku information already present."}
906
        else:
907
            collection.insert(data)
908
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
909
            return {1:"Data added successfully"}
14481 kshitij.so 910
    else:
14553 kshitij.so 911
        skuIds = __getBundledSkusfromSku(data['sku'])
912
        for sku in skuIds:
913
            data['sku'] = sku.get('_id')
914
            collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 915
            cursor = collection.find({'sku':data['sku']})
14553 kshitij.so 916
            if cursor.count() > 0:
917
                continue
918
            else:
14558 kshitij.so 919
                data.pop('_id',None)
14553 kshitij.so 920
                collection.insert(data)
921
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14481 kshitij.so 922
        return {1:"Data added successfully"}
14553 kshitij.so 923
 
14481 kshitij.so 924
def deleteDocument(data):
15853 kshitij.so 925
    print "inside detete document"
14481 kshitij.so 926
    print data
927
    try:
928
        collection = get_mongo_connection().Catalog[data['class']]
929
        class_name = data.pop('class')
930
        _id = data.pop('oid')
931
        record = list(collection.find({'_id':ObjectId(_id)}))
932
        collection.remove({'_id':ObjectId(_id)})
15075 kshitij.so 933
        if class_name != "Notifications":
934
            if class_name !="CategoryDiscount":
15853 kshitij.so 935
                print record[0]
936
                if record[0].has_key('sku'):
937
                    field = '_id'
938
                    val = record[0]['sku']
939
                else:
940
                    field = 'skuBundleId'
941
                    val = record[0]['skuBundleId']
942
                print "Updating master"
943
                print field
944
                print val
945
                get_mongo_connection().Catalog.MasterData.update({field:val},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
15075 kshitij.so 946
            else:
947
                get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
948
                                                                 {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14481 kshitij.so 949
        return {1:"Document deleted successfully"}
950
    except Exception as e:
951
        print e
952
        return {0:"Document not deleted."}
13970 kshitij.so 953
 
14482 kshitij.so 954
def searchMaster(offset, limit, search_term):
955
    data = []
14531 kshitij.so 956
    if search_term is not None:
14551 kshitij.so 957
        terms = search_term.split(' ')
958
        outer_query = []
959
        for term in terms:
960
            outer_query.append({"source_product_name":re.compile(term, re.IGNORECASE)})
14531 kshitij.so 961
        try:
14551 kshitij.so 962
            collection = get_mongo_connection().Catalog.MasterData.find({"$and":outer_query,'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14531 kshitij.so 963
            for record in collection:
964
                data.append(record)
965
        except:
966
            pass
967
    else:
968
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 969
        for record in collection:
970
            data.append(record)
971
    return data
14481 kshitij.so 972
 
14495 kshitij.so 973
def getAllFeaturedDeals(offset, limit):
974
    data = []
975
    collection = get_mongo_connection().Catalog.FeaturedDeals
976
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
977
    for val in cursor:
978
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
979
        if len(master) > 0:
980
            val['brand'] = master[0]['brand']
981
            val['source_product_name'] = master[0]['source_product_name']
982
            val['skuBundleId'] = master[0]['skuBundleId']
983
        else:
984
            val['brand'] = ""
985
            val['source_product_name'] = ""
986
            val['skuBundleId'] = ""
987
        data.append(val)
988
    return data
989
 
14553 kshitij.so 990
def addFeaturedDeal(data, multi):
991
    if multi !=1:
992
        collection = get_mongo_connection().Catalog.FeaturedDeals
993
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
994
        if cursor.count() > 0:
995
            return {0:"Sku information already present."}
996
        else:
997
            collection.insert(data)
998
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
999
            return {1:"Data added successfully"}
14495 kshitij.so 1000
    else:
14553 kshitij.so 1001
        skuIds = __getBundledSkusfromSku(data['sku'])
1002
        for sku in skuIds:
1003
            data['sku'] = sku.get('_id')
1004
            collection = get_mongo_connection().Catalog.FeaturedDeals
1005
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
1006
            if cursor.count() > 0:
1007
                continue
1008
            else:
14558 kshitij.so 1009
                data.pop('_id',None)
14553 kshitij.so 1010
                collection.insert(data)
1011
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14495 kshitij.so 1012
        return {1:"Data added successfully"}
1013
 
14499 kshitij.so 1014
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 1015
    data = []
1016
    collection = get_mongo_connection().Catalog[class_name]
15076 kshitij.so 1017
    if class_name == "Notifications":
1018
        cursor = collection.find({'skuBundleId':skuBundleId})
1019
        for val in cursor:
1020
            master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
1021
            if len(master) > 0:
1022
                val['brand'] = master[0]['brand']
1023
                val['model_name'] = master[0]['model_name']
1024
                val['skuBundleId'] = master[0]['skuBundleId']
1025
            else:
1026
                val['brand'] = ""
1027
                val['model_name'] = ""
1028
                val['skuBundleId'] = val['skuBundleId']
1029
            data.append(val)
15095 kshitij.so 1030
        return data
15853 kshitij.so 1031
    master = None
14499 kshitij.so 1032
    if sku is not None:
15853 kshitij.so 1033
        if COLLECTION_MAP.has_key(class_name):
1034
            master = get_mongo_connection().Catalog.MasterData.find_one({'_id':sku})
1035
            cursor = collection.find({'skuBundleId':master['skuBundleId']})
1036
        else:
1037
            cursor = collection.find({'sku':sku})
14499 kshitij.so 1038
        for val in cursor:
15853 kshitij.so 1039
            if master is None:
1040
                master = get_mongo_connection().Catalog.MasterData.find_one({'_id':val['sku']})
1041
            if master is not None:
1042
                val['brand'] = master['brand']
1043
                val['source_product_name'] = master['source_product_name']
1044
                val['skuBundleId'] = master['skuBundleId']
14499 kshitij.so 1045
            else:
1046
                val['brand'] = ""
1047
                val['source_product_name'] = ""
1048
                val['skuBundleId'] = ""
1049
            data.append(val)
1050
        return data
1051
    else:
15853 kshitij.so 1052
        if not COLLECTION_MAP.has_key(class_name):
1053
            skuIds = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
1054
            for sku in skuIds:
1055
                cursor = collection.find({'sku':sku})
1056
                for val in cursor:
1057
                    master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
1058
                    if len(master) > 0:
1059
                        val['brand'] = master[0]['brand']
1060
                        val['source_product_name'] = master[0]['source_product_name']
1061
                        val['skuBundleId'] = master[0]['skuBundleId']
1062
                    else:
1063
                        val['brand'] = ""
1064
                        val['source_product_name'] = ""
1065
                        val['skuBundleId'] = ""
1066
                    data.append(val)
1067
            return data
1068
        else:
1069
            cursor = collection.find({'skuBundleId':skuBundleId})
14499 kshitij.so 1070
            for val in cursor:
15853 kshitij.so 1071
                master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
14499 kshitij.so 1072
                if len(master) > 0:
1073
                    val['brand'] = master[0]['brand']
1074
                    val['source_product_name'] = master[0]['source_product_name']
1075
                else:
1076
                    val['brand'] = ""
1077
                    val['source_product_name'] = ""
1078
                data.append(val)
15853 kshitij.so 1079
            return data
14495 kshitij.so 1080
 
15074 kshitij.so 1081
def __getBrandIdForBrand(brandName, category_id):
1082
    brandInfo = Brands.query.filter(Brands.category_id==category_id).filter(Brands.name == brandName).all()
1083
    if brandInfo is None or len(brandInfo)!=1:
1084
        raise
1085
    else:
1086
        return brandInfo[0].id
1087
 
14588 kshitij.so 1088
def addNewItem(data):
14594 kshitij.so 1089
    try:
1090
        data['updatedOn'] = to_java_date(datetime.now())
1091
        data['addedOn'] = to_java_date(datetime.now())
1092
        data['priceUpdatedOn'] = to_java_date(datetime.now())
1093
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
1094
        max_bundle = list(get_mongo_connection().Catalog.MasterData.find().sort([('skuBundleId',pymongo.DESCENDING)]).limit(1))
1095
        data['_id'] = max_id[0]['_id'] + 1
1096
        data['skuBundleId'] = max_bundle[0]['skuBundleId'] + 1
1097
        data['identifier'] = str(data['identifier'])
1098
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
15074 kshitij.so 1099
        data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
14594 kshitij.so 1100
        get_mongo_connection().Catalog.MasterData.insert(data)
1101
        return {1:'Data added successfully'}
1102
    except Exception as e:
1103
        print e
1104
        return {0:'Unable to add data.'}
15130 kshitij.so 1105
    finally:
1106
        session.close()
14588 kshitij.so 1107
 
1108
def addItemToExistingBundle(data):
1109
    try:
1110
        data['updatedOn'] = to_java_date(datetime.now())
1111
        data['addedOn'] = to_java_date(datetime.now())
1112
        data['priceUpdatedOn'] = to_java_date(datetime.now())
14593 kshitij.so 1113
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
14590 kshitij.so 1114
        data['_id'] = max_id[0]['_id'] + 1
14594 kshitij.so 1115
        data['identifier'] = str(data['identifier'])
1116
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
15074 kshitij.so 1117
        data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
14588 kshitij.so 1118
        get_mongo_connection().Catalog.MasterData.insert(data)
1119
        return {1:'Data added successfully.'}
14594 kshitij.so 1120
    except Exception as e:
1121
        print e
14588 kshitij.so 1122
        return {0:'Unable to add data.'}
15130 kshitij.so 1123
    finally:
1124
        session.close()
14588 kshitij.so 1125
 
1126
def updateMaster(data, multi):
15130 kshitij.so 1127
    try:
1128
        print data
1129
        if multi != 1:
1130
            _id = data.pop('_id')
1131
            skuBundleId = data.pop('skuBundleId')
1132
            data['updatedOn'] = to_java_date(datetime.now())
1133
            data['identifier'] = str(data['identifier'])
1134
            data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
1135
            data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
1136
            get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1137
            return {1:'Data updated successfully.'}
1138
        else:
1139
            _id = data.pop('_id')
1140
            skuBundleId = data.pop('skuBundleId')
1141
            data['updatedOn'] = to_java_date(datetime.now())
1142
            data['identifier'] = str(data['identifier'])
1143
            data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
1144
            data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
1145
            get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1146
            similarItems = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId})
1147
            for item in similarItems:
1148
                if item['_id'] == _id:
1149
                    continue
1150
                item['updatedOn'] = to_java_date(datetime.now())
1151
                item['thumbnail'] = data['thumbnail']
1152
                item['category'] = data['category']
1153
                item['category_id'] = data['category_id']
1154
                item['tagline'] = data['tagline']
1155
                item['is_shortage'] = data['is_shortage']
1156
                item['mrp'] = data['mrp']
1157
                item['status'] = data['status']
1158
                item['maxPrice'] = data['maxPrice']
1159
                item['brand_id'] = data['brand_id']
1160
                similar_item_id = item.pop('_id')
1161
                get_mongo_connection().Catalog.MasterData.update({'_id':similar_item_id},{"$set":item},upsert=False)
1162
            return {1:'Data updated successfully.'}
1163
    finally:
1164
        session.close()
14619 kshitij.so 1165
 
1166
def getLiveCricScore():
1167
    return mc.get('liveScore')
14852 kshitij.so 1168
 
1169
def addBundleToNotification(data):
1170
    try:
15069 kshitij.so 1171
        collection = get_mongo_connection().Catalog.Notifications
14852 kshitij.so 1172
        cursor = collection.find({'skuBundleId':data['skuBundleId']})
1173
        if cursor.count() > 0:
1174
            return {0:"SkuBundleId information already present."}
1175
        else:
1176
            collection.insert(data)
1177
            return {1:'Data updated successfully.'}
1178
    except:
1179
        return {0:'Unable to add data.'}
1180
 
1181
def getAllNotifications(offset, limit):
1182
    data = []
15069 kshitij.so 1183
    collection = get_mongo_connection().Catalog.Notifications
16450 kshitij.so 1184
    cursor = collection.find().sort([('endDate',pymongo.DESCENDING)]).skip(offset).limit(limit)
14852 kshitij.so 1185
    for val in cursor:
15072 kshitij.so 1186
        master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
14852 kshitij.so 1187
        if len(master) > 0:
1188
            val['brand'] = master[0]['brand']
15071 kshitij.so 1189
            val['model_name'] = master[0]['model_name']
14852 kshitij.so 1190
            val['skuBundleId'] = master[0]['skuBundleId']
1191
        else:
1192
            val['brand'] = ""
15071 kshitij.so 1193
            val['model_name'] = ""
1194
            val['skuBundleId'] = val['skuBundleId']
14852 kshitij.so 1195
        data.append(val)
1196
    return data
14997 kshitij.so 1197
 
1198
def getBrandsForFilter(category_id):
1199
    if mc.get("brandFilter") is None:
15095 kshitij.so 1200
        print "Populating brand data for category_id %d" %(category_id)
14997 kshitij.so 1201
        tabData, mobData = [], []
1202
        mobileDeals = get_mongo_connection().Catalog.Deals.aggregate([
16170 kshitij.so 1203
                                                                      {"$match":{"category_id":3,"showDeal":1,"totalPoints":{"$gt":-100}}
14997 kshitij.so 1204
                                                                    },
1205
                                                                 {"$group" : 
1206
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1207
                                                                  }
1208
                                                                ])
14588 kshitij.so 1209
 
14997 kshitij.so 1210
        tabletDeals = get_mongo_connection().Catalog.Deals.aggregate([
16170 kshitij.so 1211
                                                                      {"$match":{"category_id":5,"showDeal":1,"totalPoints":{"$gt":-100}}
14997 kshitij.so 1212
                                                                    },
1213
                                                                 {"$group" : 
1214
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1215
                                                                  }
1216
                                                                ])
1217
 
1218
        allDeals = get_mongo_connection().Catalog.Deals.aggregate([
16170 kshitij.so 1219
                                                                   {"$match":{"showDeal":1,"totalPoints":{"$gt":-100}}
14997 kshitij.so 1220
                                                                    },
1221
                                                                 {"$group" : 
1222
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1223
                                                                  }
1224
                                                                ])
1225
        #print mobileDeals
1226
        #print "==========Mobile data ends=========="
1227
 
1228
        #print tabletDeals
1229
        #print "==========Tablet data ends=========="
1230
 
1231
        #print allDeals
1232
        #print "==========All deal data ends========="
1233
 
1234
        for mobileDeal in mobileDeals['result']:
1235
            if mobileDeal.get('_id').get('brand_id') != 0:
1236
                tempMap = {}
1237
                tempMap['brand'] = mobileDeal.get('_id').get('brand')
1238
                tempMap['brand_id'] = mobileDeal.get('_id').get('brand_id')
1239
                tempMap['count'] = mobileDeal.get('count')
1240
                mobData.append(tempMap)
1241
 
1242
        for tabletDeal in tabletDeals['result']:
1243
            if tabletDeal.get('_id').get('brand_id') != 0:
1244
                tempMap = {}
1245
                tempMap['brand'] = tabletDeal.get('_id').get('brand')
1246
                tempMap['brand_id'] = tabletDeal.get('_id').get('brand_id')
1247
                tempMap['count'] = tabletDeal.get('count')
1248
                tabData.append(tempMap)
1249
 
1250
 
1251
        brandMap = {}
1252
        for allDeal in allDeals['result']:
1253
            if allDeal.get('_id').get('brand_id') != 0:
1254
                if brandMap.has_key(allDeal.get('_id').get('brand')):
15002 kshitij.so 1255
                    brand_ids = brandMap.get(allDeal.get('_id').get('brand')).get('brand_ids')
14997 kshitij.so 1256
                    brand_ids.append(allDeal.get('_id').get('brand_id'))
15003 kshitij.so 1257
                    brandMap[allDeal.get('_id').get('brand')] = {'brand_ids':brand_ids,'count':brandMap.get(allDeal.get('_id').get('brand')).get('count') + allDeal.get('count')}
14997 kshitij.so 1258
                else:
1259
                    temp = []
1260
                    temp.append(allDeal.get('_id').get('brand_id'))
15002 kshitij.so 1261
                    brandMap[allDeal.get('_id').get('brand')] = {'brand_ids':temp,'count':allDeal.get('count')}
14997 kshitij.so 1262
 
1263
        mc.set("brandFilter",{0:brandMap, 3:mobData, 5:tabData}, 600)  
1264
 
15062 kshitij.so 1265
    return sorted(mc.get("brandFilter").get(category_id), key = lambda x: (-x['count'], x['brand']))
15375 kshitij.so 1266
 
15459 kshitij.so 1267
def getStaticDeals(offset, limit, category_id, direction):
15375 kshitij.so 1268
    user_specific_deals = mc.get("staticDeals")
1269
    if user_specific_deals is None:
1270
        __populateStaticDeals()
1271
        user_specific_deals = mc.get("staticDeals")
15459 kshitij.so 1272
    rev = False
1273
    if direction is None or direction == -1:
1274
        rev=True
1275
    return sorted((user_specific_deals.get(category_id))[offset:offset+limit],reverse=rev)
15375 kshitij.so 1276
 
1277
def __populateStaticDeals():
1278
    print "Populating memcache for static deals"
1279
    outer_query = []
1280
    outer_query.append({"showDeal":1})
1281
    query = {}
16170 kshitij.so 1282
    query['$gt'] = -100
15375 kshitij.so 1283
    outer_query.append({'totalPoints':query})
1284
    all_deals = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query},{'_id':1,'category_id':1,'brand':1,'totalPoints':1,'bestSellerPoints':1,'nlcPoints':1,'rank':1,'available_price':1,'dealType':1,'source_id':1,'brand_id':1,'skuBundleId':1}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
1285
    mobile_deals = []
1286
    tablet_deals = []
1287
    for deal in all_deals:
1288
        item = get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']})
1289
        if deal['category_id'] ==3:
1290
            mobile_deals.append(getItemObjForStaticDeals(item[0]))
1291
        elif deal['category_id'] ==5:
1292
            tablet_deals.append(getItemObjForStaticDeals(item[0]))
1293
        else:
1294
            continue
1295
 
1296
    random.shuffle(mobile_deals,random.random)
1297
    random.shuffle(tablet_deals,random.random)
1298
 
1299
    mem_cache_val = {3:mobile_deals, 5:tablet_deals}
1300
    mc.set("staticDeals", mem_cache_val, 3600)
1301
 
1302
def getItemObjForStaticDeals(item):
15379 kshitij.so 1303
    return {'marketPlaceUrl':item.get('marketPlaceUrl'),'available_price':item.get('available_price'),'source_product_name':item.get('source_product_name'),'thumbnail':item.get('thumbnail'),'source_id':int(item.get('source_id'))}
16300 manas 1304
 
1305
def getItemByMerchantIdentifier(identifier, source_id):
1306
    skuData = None
16406 kshitij.so 1307
    if source_id in (1,2,4,5,6):
16300 manas 1308
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
1309
    elif source_id == 3:
1310
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
1311
    if skuData is None:
1312
        return {}
1313
    else:
1314
        return skuData
15375 kshitij.so 1315
 
16364 kshitij.so 1316
def getDealsForNotification(skuBundleIds):
1317
    bundles= [int(skuBundleId) for skuBundleId in skuBundleIds.split(',')]
1318
    print bundles
16406 kshitij.so 1319
    dealsList = []
16364 kshitij.so 1320
    dealsListMap = []
16406 kshitij.so 1321
    for bundleId in bundles:
1322
        outer_query = []
1323
        outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
1324
        outer_query.append({'skuBundleId':bundleId})
1325
        deals = get_mongo_connection().Catalog.Deals.find({"$and":outer_query})
1326
        for deal in deals:
1327
            dealsList.append(deal)
16364 kshitij.so 1328
    sortedMap = {}
1329
    rankMap = {}
1330
    rank = 0
16406 kshitij.so 1331
    for sorted_deal in dealsList:
16364 kshitij.so 1332
        if sortedMap.get(sorted_deal['skuBundleId']) is None:
1333
            sortedMap[sorted_deal['skuBundleId']] = {rank:[sorted_deal]}
1334
            rankMap[rank] = (sortedMap[sorted_deal['skuBundleId']].values())[0]
1335
            rank = rank +1
1336
        else:
1337
            for temp_list in sortedMap.get(sorted_deal['skuBundleId']).itervalues():
1338
                temp_list.append(sorted_deal)
1339
            rankMap[(sortedMap.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
1340
 
16367 kshitij.so 1341
    for dealList in [rankMap.get(k, []) for k in range(0, len(bundles))]:
16364 kshitij.so 1342
        temp = []
1343
        for d in dealList:
1344
            item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
1345
            if len(item) ==0:
1346
                continue
1347
            if d['dealType'] == 1 and d['source_id'] ==1:
1348
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip())
1349
            elif d['source_id'] ==3:
1350
                item[0]['marketPlaceUrl'] = item[0]['marketPlaceUrl']+'?supc='+item[0].get('identifier')
1351
            else:
1352
                pass 
1353
            try:
1354
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
1355
                if not cashBack or cashBack.get('cash_back_status')!=1:
1356
                    item[0]['cash_back_type'] = 0
1357
                    item[0]['cash_back'] = 0
1358
                else:
1359
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
1360
                    item[0]['cash_back'] = cashBack['cash_back']
1361
            except:
1362
                print "Error in adding cashback to deals"
1363
                item[0]['cash_back_type'] = 0
1364
                item[0]['cash_back'] = 0
1365
            try:
1366
                item[0]['dp'] = d['dp']
1367
                item[0]['showDp'] = d['showDp']
1368
            except:
1369
                item[0]['dp'] = 0.0
1370
                item[0]['showDp'] = 0
1371
            temp.append(item[0])
1372
        if len(temp) > 1:
1373
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
1374
        dealsListMap.append(temp)
1375
    return dealsListMap
1376
 
16373 manas 1377
def getSkuBrandData(sku):
1378
    if sku is None:
1379
        return {}
1380
    else:
1381
        orders = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':sku})
1382
        if orders is None:
1383
            return {}
1384
        return orders
16488 kshitij.so 1385
 
1386
def addDealPoints(data):
1387
    collection = get_mongo_connection().Catalog.DealPoints
1388
    cursor = collection.find({'skuBundleId':data['skuBundleId']})
1389
    if cursor.count() > 0:
1390
        return {0:"Sku information already present."}
1391
    else:
1392
        collection.insert(data)
1393
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
1394
        return {1:"Data added successfully"}
1395
 
1396
def getAllBundlesWithDealPoints(offset, limit):
1397
    data = []
1398
    collection = get_mongo_connection().Catalog.DealPoints
1399
    cursor = collection.find().sort([('endDate',pymongo.DESCENDING)]).skip(offset).limit(limit)
1400
    for val in cursor:
1401
        master = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':val.get('skuBundleId')})
1402
        if master is not None:
1403
            val['brand'] = master['brand']
1404
            val['source_product_name'] = master['product_name']
1405
        else:
1406
            val['brand'] = ""
1407
            val['source_product_name'] = ""
1408
        data.append(val)
1409
    return data
16546 kshitij.so 1410
 
1411
def generateRedirectUrl(retailer_id, app_id):
1412
    try:
1413
        d_app_offer = app_offers.get_by(id=app_id)
1414
    finally:
1415
        session.close()
1416
    if d_app_offer is None:
1417
        return {'url':"","message":"App id doesn't exist"}
16364 kshitij.so 1418
 
16553 kshitij.so 1419
    appTransactions = AppTransactions(app_id, retailer_id, to_java_date(datetime.now()), None, 1, CB_INIT, 1, CB_INIT, None, None, d_app_offer.offer_price, d_app_offer.overriden_payout, d_app_offer.override_payout, d_app_offer.user_payout)
16546 kshitij.so 1420
 
1421
    get_mongo_connection().AppOrder.AppTransaction.insert(appTransactions.__dict__)
1422
    embedd = str((appTransactions.__dict__).get('_id'))
16548 kshitij.so 1423
    try:
1424
        index = d_app_offer.link.index(".freeb.co.in")
1425
    except:
1426
        return {'url':"","message":"Substring not found"}
1427
    redirect_url = d_app_offer.link[0:index]+"."+embedd+d_app_offer.link[index:]
16546 kshitij.so 1428
    get_mongo_connection().AppOrder.AppTransaction.update({'_id':ObjectId(embedd)},{"$set":{'redirect_url':redirect_url}})
16548 kshitij.so 1429
    return {'url':redirect_url,"message":"Success"}
16556 kshitij.so 1430
 
1431
def addPayout(payout, transaction_id):
1432
    try:
1433
        transaction = list(get_mongo_connection().AppOrder.AppTransaction.find({'_id':ObjectId(transaction_id)}))
1434
        if len(transaction) > 0:
1435
            if (transaction[0])['payout_status'] ==1:
1436
                get_mongo_connection().AppOrder.AppTransaction.update({'_id':ObjectId(transaction_id)},{"$set":{'payout_amount':float(payout), 'payout_description': CB_APPROVED,'payout_status':2}})
1437
                return {'status':'ok','message':'Payout updated'}
1438
            elif (transaction[0])['payout_status'] ==2:
1439
                return {'status':'ok','message':'Payout already processed'}
1440
            else:
1441
                return {'status':'fail','message':'Something is wrong'}
1442
        else:
1443
            return {'status':'fail','message':'transaction_id not found'}
1444
    except:
16559 kshitij.so 1445
        return  {'status':'fail','message':'Something is wrong'}
16556 kshitij.so 1446
 
16546 kshitij.so 1447
 
1448
 
1449
 
13572 kshitij.so 1450
def main():
16556 kshitij.so 1451
    #generateRedirectUrl(101,1
1452
    print addPayout("10", "55db82c0bcabd7fc59e0a71")
13811 kshitij.so 1453
 
13921 kshitij.so 1454
 
15375 kshitij.so 1455
 
13572 kshitij.so 1456
if __name__=='__main__':
13932 amit.gupta 1457
    main()