Subversion Repositories SmartDukaan

Rev

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