Subversion Repositories SmartDukaan

Rev

Rev 16187 | Rev 16222 | 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
13927 amit.gupta 4
from dtr.main import Store
14531 kshitij.so 5
from dtr.dao import FeaturedDeals
14037 kshitij.so 6
from dtr.storage import DataService
7
from dtr.storage.DataService import price_preferences, brand_preferences, \
15074 kshitij.so 8
    user_actions, Brands
14037 kshitij.so 9
from dtr.storage.MemCache import MemCache
14305 amit.gupta 10
from dtr.utils.utils import to_java_date
11
from elixir import *
12
from operator import itemgetter
13
import pymongo
14322 kshitij.so 14
import re
14791 kshitij.so 15
import traceback
15375 kshitij.so 16
import random
13572 kshitij.so 17
 
18
con = None
19
 
14037 kshitij.so 20
DataService.initialize(db_hostname="localhost")
21
mc = MemCache("127.0.0.1")
22
 
15908 kshitij.so 23
SOURCE_MAP = {1:'AMAZON',2:'FLIPKART',3:'SNAPDEAL',4:'SAHOLIC',5:"SHOPCLUES.COM"}
14482 kshitij.so 24
 
15853 kshitij.so 25
COLLECTION_MAP = {
26
                  'ExceptionalNlc':'skuBundleId',
27
                  'SkuDealerPrices':'skuBundleId',
28
                  'SkuDiscountInfo':'skuBundleId',
29
                  'SkuSchemeDetails':'skuBundleId',
30
 
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([
261
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
262
                    {'$unwind':"$subOrders"},
14670 amit.gupta 263
                    {'$match':{'subOrders.cashBackStatus':Store.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([
284
                    {'$match':{'subOrders.cashBackStatus':Store.CB_PENDING, 'userId':userId}},
285
                    {'$unwind':"$subOrders"},
286
                    {'$match':{'subOrders.cashBackStatus':Store.CB_PENDING}},
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
15345 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}).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']}))
16079 kshitij.so 456
            item[0]['persPoints'] = d['persPoints']
457
            if d['dealType'] == 1 and d['source_id'] ==1:
458
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip())
459
            elif d['source_id'] ==3:
460
                item[0]['marketPlaceUrl'] = item[0]['marketPlaceUrl']+'?supc='+item[0].get('identifier')
461
            else:
462
                pass 
463
            try:
464
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
465
                if not cashBack or cashBack.get('cash_back_status')!=1:
14037 kshitij.so 466
                    item[0]['cash_back_type'] = 0
467
                    item[0]['cash_back'] = 0
16079 kshitij.so 468
                else:
469
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
470
                    item[0]['cash_back'] = cashBack['cash_back']
471
            except:
472
                print "Error in adding cashback to deals"
473
                item[0]['cash_back_type'] = 0
474
                item[0]['cash_back'] = 0
475
            temp.append(item[0])
16125 kshitij.so 476
        if len(temp) > 1:
16126 kshitij.so 477
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
16079 kshitij.so 478
        dealsListMap.append(temp)
479
    return dealsListMap
14037 kshitij.so 480
 
14791 kshitij.so 481
def filterDeals(deals, filterData):
482
    dealFiltered = []
483
    brandsFiltered = []
484
    filterArray = filterData.split('|')
485
    for data in filterArray:
486
        try:
487
            filter, info = data.split(':')
488
        except Exception as ex:
489
            traceback.print_exc()
490
            continue
491
        if filter == 'dealFilter':
492
            toFilter = info.split('^')
493
            print "deal filter ",toFilter
494
            if 'deals' in toFilter:
495
                dealFiltered = deals
496
                continue
497
            for filterVal in toFilter:
498
                if filterVal == 'dod':
499
                    for deal in deals:
500
                        if deal['dealType'] == 1:
501
                            dealFiltered.append(deal)
502
        elif filter == 'brandFilter':
503
            toFilter = info.split('^')
504
            print "brand filter ",toFilter
505
            if len(toFilter) == 0 or (len(toFilter)==1 and toFilter[0]==''):
506
                brandsFiltered = deals
507
            for deal in deals:
15151 kshitij.so 508
                if str(int(deal['brand_id'])) in toFilter:
14791 kshitij.so 509
                    brandsFiltered.append(deal)
15040 kshitij.so 510
    if len(dealFiltered) == 0:
511
        return brandsFiltered
14791 kshitij.so 512
    return [i for i in dealFiltered for j in brandsFiltered if i['_id']==j['_id']]
513
 
514
 
14037 kshitij.so 515
def getDeals(userId, category_id, offset, limit, sort, direction):
14761 kshitij.so 516
    if not bool(mc.get("category_cash_back")):
14037 kshitij.so 517
        populateCashBack()
518
    rank = 1
13771 kshitij.so 519
    deals = {}
13910 kshitij.so 520
    outer_query = []
521
    outer_query.append({"showDeal":1})
522
    query = {}
523
    query['$gt'] = 0
524
    outer_query.append({'totalPoints':query})
525
    if category_id in (3,5):
526
        outer_query.append({'category_id':category_id})
13803 kshitij.so 527
    if sort is None or direction is None:
528
        direct = -1
13910 kshitij.so 529
        print outer_query
530
        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 531
    else:
13910 kshitij.so 532
        print outer_query
13803 kshitij.so 533
        direct = direction
13910 kshitij.so 534
        if sort == "bestSellerPoints":
535
            print "yes,sorting by bestSellerPoints"
536
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
537
        else:
538
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 539
    for d in data:
540
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
541
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 542
            item[0]['dealRank'] = rank
543
            try:
14761 kshitij.so 544
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
13921 kshitij.so 545
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 546
                    item[0]['cash_back_type'] = 0
547
                    item[0]['cash_back'] = 0
13921 kshitij.so 548
                else:
14766 kshitij.so 549
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
13928 kshitij.so 550
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 551
            except:
552
                print "Error in adding cashback to deals"
13928 kshitij.so 553
                item[0]['cash_back_type'] = 0
554
                item[0]['cash_back'] = 0
13771 kshitij.so 555
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 556
 
13771 kshitij.so 557
            rank +=1
13785 kshitij.so 558
    return sorted(deals.values(), key=itemgetter('dealRank'))
559
 
560
def getItem(skuId):
14761 kshitij.so 561
    if not bool(mc.get("category_cash_back")):
14113 kshitij.so 562
        populateCashBack()
13795 kshitij.so 563
    try:
564
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 565
        for sku in skuData:
566
            try:
14761 kshitij.so 567
                cashBack = getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
14107 kshitij.so 568
                if not cashBack or cashBack.get('cash_back_status')!=1:
569
                    sku['cash_back_type'] = 0
570
                    sku['cash_back'] = 0
571
                else:
572
                    sku['cash_back_type'] = cashBack['cash_back_type']
573
                    sku['cash_back'] = cashBack['cash_back']
574
            except:
575
                print "Error in adding cashback to deals"
576
                sku['cash_back_type'] = 0
577
                sku['cash_back'] = 0
14629 kshitij.so 578
            sku['in_stock'] = int(sku['in_stock'])
579
            sku['is_shortage'] = int(sku['is_shortage'])
580
            sku['category_id'] = int(sku['category_id'])
581
            sku['status'] = int(sku['status'])
13785 kshitij.so 582
        return skuData
13795 kshitij.so 583
    except:
584
        return [{}]
13836 kshitij.so 585
 
14761 kshitij.so 586
def getCashBack(skuId, source_id, category_id):
587
    if not bool(mc.get("category_cash_back")):
588
        populateCashBack()
589
    itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 590
    itemCashBack = itemCashBackMap.get(skuId)
591
    if itemCashBack is not None:
592
        return itemCashBack
14761 kshitij.so 593
    cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 594
    sourceCashBack = cashBackMap.get(source_id)
595
    if sourceCashBack is not None and len(sourceCashBack) > 0:
596
        for cashBack in sourceCashBack:
597
            if cashBack.get(category_id) is None:
598
                continue
599
            else:
600
                return cashBack.get(category_id)
601
    else:
602
        return {}
603
 
15129 kshitij.so 604
def getDealRank(identifier, source_id, userId):
605
    if source_id in (1,2,4,5):
606
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
607
    elif source_id == 3:
608
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
609
    else:
15349 kshitij.so 610
        return {'rank':0, 'description':'Source not valid'}
611
    if len(skuData) == 0:
612
        return {'rank':0, 'description':'No matching product identifier found'}
15129 kshitij.so 613
    user_specific_deals = mc.get(str(userId))
614
    if user_specific_deals is None:
615
        __populateCache(userId)
616
        user_specific_deals = mc.get(str(userId))
617
    else:
618
        print "Getting user deals from cache"
619
    category_id = skuData[0]['category_id']
620
    category_specific_deals = user_specific_deals.get(category_id)
621
    if category_specific_deals is None or len(category_specific_deals) ==0:
15347 amit.gupta 622
        return {'rank':0,'description':'Category specific deals is empty'}
15129 kshitij.so 623
    sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
16168 kshitij.so 624
    sortedMap = {}
625
    rankMap = {}
626
    rank = 0
15129 kshitij.so 627
    for sorted_deal in sorted_deals:
16168 kshitij.so 628
        if sortedMap.get(sorted_deal['skuBundleId']) is None:
629
            sortedMap[sorted_deal['skuBundleId']] = {rank:[sorted_deal]}
630
            rankMap[rank] = (sortedMap[sorted_deal['skuBundleId']].values())[0]
631
            rank = rank +1
632
        else:
633
            for temp_list in sortedMap.get(sorted_deal['skuBundleId']).itervalues():
634
                temp_list.append(sorted_deal)
635
            rankMap[(sortedMap.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
636
 
16187 kshitij.so 637
    for dealRank ,dealList in rankMap.iteritems():
16168 kshitij.so 638
        for d in dealList:
16186 kshitij.so 639
            if d['skuBundleId'] == skuData[0]['skuBundleId']:
16188 kshitij.so 640
                return {'rank':dealRank+1,'description':'Rank found'}
16168 kshitij.so 641
 
15347 amit.gupta 642
    return {'rank':0,'description':'Rank not found'}
15129 kshitij.so 643
 
644
 
13836 kshitij.so 645
def getCashBackDetails(identifier, source_id):
14761 kshitij.so 646
    if not bool(mc.get("category_cash_back")):
13921 kshitij.so 647
        populateCashBack()
13771 kshitij.so 648
 
13921 kshitij.so 649
    if source_id in (1,2,4,5):
13839 kshitij.so 650
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 651
    elif source_id == 3:
13839 kshitij.so 652
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 653
    else:
654
        return {}
13836 kshitij.so 655
    if len(skuData) > 0:
14761 kshitij.so 656
        itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 657
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
658
        if itemCashBack is not None:
659
            return itemCashBack
14761 kshitij.so 660
        cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 661
        sourceCashBack = cashBackMap.get(source_id)
662
        if sourceCashBack is not None and len(sourceCashBack) > 0:
663
            for cashBack in sourceCashBack:
664
                if cashBack.get(skuData[0]['category_id']) is None:
665
                    continue
666
                else:
667
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 668
        else:
669
            return {} 
670
    else:
671
        return {}
13986 amit.gupta 672
 
14398 amit.gupta 673
def getImgSrc(identifier, source_id):
674
    skuData = None
675
    if source_id in (1,2,4,5):
14414 amit.gupta 676
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 677
    elif source_id == 3:
14414 amit.gupta 678
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 679
    if skuData is None:
680
        return {}
681
    else:
682
        return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 683
 
684
def next_weekday(d, weekday):
685
    days_ahead = weekday - d.weekday()
686
    if days_ahead <= 0: # Target day already happened this week
687
        days_ahead += 7
688
    return d + timedelta(days_ahead)
689
 
13771 kshitij.so 690
 
13970 kshitij.so 691
def getAllDealerPrices(offset, limit):
692
    data = []
693
    collection = get_mongo_connection().Catalog.SkuDealerPrices
694
    cursor = collection.find().skip(offset).limit(limit)
695
    for val in cursor:
15853 kshitij.so 696
        master = get_mongo_connection().Catalog.MasterData.find_one({'skuBundleId':val['skuBundleId']})
697
        if master is not None:
698
            val['brand'] = master['brand']
699
            val['source_product_name'] = master['source_product_name']
13970 kshitij.so 700
        else:
701
            val['brand'] = ""
702
            val['source_product_name'] = ""
703
        data.append(val)
704
    return data
705
 
15853 kshitij.so 706
def addSkuDealerPrice(data):
707
    collection = get_mongo_connection().Catalog.SkuDealerPrices
708
    cursor = collection.find_one({"skuBundleId":data['skuBundleId']})
709
    if cursor is not None:
710
        return {0:"BundleId information already present."}
13970 kshitij.so 711
    else:
15853 kshitij.so 712
        collection.insert(data)
713
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 714
        return {1:"Data added successfully"}
715
 
716
def updateSkuDealerPrice(data, _id):
717
    try:
718
        collection = get_mongo_connection().Catalog.SkuDealerPrices
719
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
15853 kshitij.so 720
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 721
        return {1:"Data updated successfully"}
722
    except:
723
        return {0:"Data not updated."}
724
 
725
def updateExceptionalNlc(data, _id):
726
    try:
727
        collection = get_mongo_connection().Catalog.ExceptionalNlc
728
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
15853 kshitij.so 729
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':data['skuBundleId']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 730
        return {1:"Data updated successfully"}
731
    except:
732
        return {0:"Data not updated."}
733
 
14041 kshitij.so 734
def resetCache(userId):
14043 kshitij.so 735
    try:
736
        mc.delete(userId)
737
        return {1:'Cache cleared.'}
738
    except:
739
        return {0:'Unable to clear cache.'}
740
 
15853 kshitij.so 741
def updateCollection(data):
14083 kshitij.so 742
    print data
15853 kshitij.so 743
    try:
744
        collection = get_mongo_connection().Catalog[data['class']]
745
        class_name = data.pop('class')
746
        _id = data.pop('oid')
747
        result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
748
        if class_name != "Notifications":
749
            record = list(collection.find({'_id':ObjectId(_id)}))
750
            if class_name !="CategoryDiscount":
751
                if record[0].has_key('sku'):
752
                    field = '_id'
753
                    val = record[0]['sku']
14852 kshitij.so 754
                else:
15853 kshitij.so 755
                    field = 'skuBundleId'
756
                    val = record[0]['skuBundleId']
757
                get_mongo_connection().Catalog.MasterData.update({field:val},{"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False, multi = True)
758
            else:
759
                get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
760
                                                                 {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
761
        return {1:"Data updated successfully"}
762
    except Exception as e:
763
        print e
764
        return {0:"Data not updated."}
14575 kshitij.so 765
 
14076 kshitij.so 766
 
14553 kshitij.so 767
def addNegativeDeals(data, multi):
768
    if multi !=1: 
769
        collection = get_mongo_connection().Catalog.NegativeDeals
770
        cursor = collection.find({"sku":data['sku']})
771
        if cursor.count() > 0:
772
            return {0:"Sku information already present."}
773
        else:
774
            collection.insert(data)
775
            return {1:"Data added successfully"}
14481 kshitij.so 776
    else:
14553 kshitij.so 777
        skuIds = __getBundledSkusfromSku(data['sku'])
778
        for sku in skuIds:
779
            data['sku'] = sku.get('_id')
780
            collection = get_mongo_connection().Catalog.NegativeDeals
781
            cursor = collection.find({"sku":data['sku']})
782
            if cursor.count() > 0:
783
                continue
784
            else:
14558 kshitij.so 785
                data.pop('_id',None)
14553 kshitij.so 786
                collection.insert(data)
14481 kshitij.so 787
        return {1:"Data added successfully"}
788
 
789
def getAllNegativeDeals(offset, limit):
790
    data = []
791
    collection = get_mongo_connection().Catalog.NegativeDeals
792
    cursor = collection.find().skip(offset).limit(limit)
793
    for val in cursor:
794
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
795
        if len(master) > 0:
796
            val['brand'] = master[0]['brand']
797
            val['source_product_name'] = master[0]['source_product_name']
798
            val['skuBundleId'] = master[0]['skuBundleId']
799
        else:
800
            val['brand'] = ""
801
            val['source_product_name'] = ""
802
            val['skuBundleId'] = ""
803
        data.append(val)
804
    return data
805
 
806
def getAllManualDeals(offset, limit):
807
    data = []
808
    collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 809
    cursor = collection.find().skip(offset).limit(limit)
14481 kshitij.so 810
    for val in cursor:
811
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
812
        if len(master) > 0:
813
            val['brand'] = master[0]['brand']
814
            val['source_product_name'] = master[0]['source_product_name']
815
            val['skuBundleId'] = master[0]['skuBundleId']
816
        else:
817
            val['brand'] = ""
818
            val['source_product_name'] = ""
819
            val['skuBundleId'] = ""
820
        data.append(val)
821
    return data
14076 kshitij.so 822
 
14553 kshitij.so 823
def addManualDeal(data, multi):
824
    if multi !=1:
825
        collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 826
        cursor = collection.find({'sku':data['sku']})
14553 kshitij.so 827
        if cursor.count() > 0:
828
            return {0:"Sku information already present."}
829
        else:
830
            collection.insert(data)
831
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
832
            return {1:"Data added successfully"}
14481 kshitij.so 833
    else:
14553 kshitij.so 834
        skuIds = __getBundledSkusfromSku(data['sku'])
835
        for sku in skuIds:
836
            data['sku'] = sku.get('_id')
837
            collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 838
            cursor = collection.find({'sku':data['sku']})
14553 kshitij.so 839
            if cursor.count() > 0:
840
                continue
841
            else:
14558 kshitij.so 842
                data.pop('_id',None)
14553 kshitij.so 843
                collection.insert(data)
844
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14481 kshitij.so 845
        return {1:"Data added successfully"}
14553 kshitij.so 846
 
14481 kshitij.so 847
def deleteDocument(data):
15853 kshitij.so 848
    print "inside detete document"
14481 kshitij.so 849
    print data
850
    try:
851
        collection = get_mongo_connection().Catalog[data['class']]
852
        class_name = data.pop('class')
853
        _id = data.pop('oid')
854
        record = list(collection.find({'_id':ObjectId(_id)}))
855
        collection.remove({'_id':ObjectId(_id)})
15075 kshitij.so 856
        if class_name != "Notifications":
857
            if class_name !="CategoryDiscount":
15853 kshitij.so 858
                print record[0]
859
                if record[0].has_key('sku'):
860
                    field = '_id'
861
                    val = record[0]['sku']
862
                else:
863
                    field = 'skuBundleId'
864
                    val = record[0]['skuBundleId']
865
                print "Updating master"
866
                print field
867
                print val
868
                get_mongo_connection().Catalog.MasterData.update({field:val},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
15075 kshitij.so 869
            else:
870
                get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
871
                                                                 {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14481 kshitij.so 872
        return {1:"Document deleted successfully"}
873
    except Exception as e:
874
        print e
875
        return {0:"Document not deleted."}
13970 kshitij.so 876
 
14482 kshitij.so 877
def searchMaster(offset, limit, search_term):
878
    data = []
14531 kshitij.so 879
    if search_term is not None:
14551 kshitij.so 880
        terms = search_term.split(' ')
881
        outer_query = []
882
        for term in terms:
883
            outer_query.append({"source_product_name":re.compile(term, re.IGNORECASE)})
14531 kshitij.so 884
        try:
14551 kshitij.so 885
            collection = get_mongo_connection().Catalog.MasterData.find({"$and":outer_query,'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14531 kshitij.so 886
            for record in collection:
887
                data.append(record)
888
        except:
889
            pass
890
    else:
891
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 892
        for record in collection:
893
            data.append(record)
894
    return data
14481 kshitij.so 895
 
14495 kshitij.so 896
def getAllFeaturedDeals(offset, limit):
897
    data = []
898
    collection = get_mongo_connection().Catalog.FeaturedDeals
899
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
900
    for val in cursor:
901
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
902
        if len(master) > 0:
903
            val['brand'] = master[0]['brand']
904
            val['source_product_name'] = master[0]['source_product_name']
905
            val['skuBundleId'] = master[0]['skuBundleId']
906
        else:
907
            val['brand'] = ""
908
            val['source_product_name'] = ""
909
            val['skuBundleId'] = ""
910
        data.append(val)
911
    return data
912
 
14553 kshitij.so 913
def addFeaturedDeal(data, multi):
914
    if multi !=1:
915
        collection = get_mongo_connection().Catalog.FeaturedDeals
916
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
917
        if cursor.count() > 0:
918
            return {0:"Sku information already present."}
919
        else:
920
            collection.insert(data)
921
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
922
            return {1:"Data added successfully"}
14495 kshitij.so 923
    else:
14553 kshitij.so 924
        skuIds = __getBundledSkusfromSku(data['sku'])
925
        for sku in skuIds:
926
            data['sku'] = sku.get('_id')
927
            collection = get_mongo_connection().Catalog.FeaturedDeals
928
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
929
            if cursor.count() > 0:
930
                continue
931
            else:
14558 kshitij.so 932
                data.pop('_id',None)
14553 kshitij.so 933
                collection.insert(data)
934
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14495 kshitij.so 935
        return {1:"Data added successfully"}
936
 
14499 kshitij.so 937
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 938
    data = []
939
    collection = get_mongo_connection().Catalog[class_name]
15076 kshitij.so 940
    if class_name == "Notifications":
941
        cursor = collection.find({'skuBundleId':skuBundleId})
942
        for val in cursor:
943
            master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
944
            if len(master) > 0:
945
                val['brand'] = master[0]['brand']
946
                val['model_name'] = master[0]['model_name']
947
                val['skuBundleId'] = master[0]['skuBundleId']
948
            else:
949
                val['brand'] = ""
950
                val['model_name'] = ""
951
                val['skuBundleId'] = val['skuBundleId']
952
            data.append(val)
15095 kshitij.so 953
        return data
15853 kshitij.so 954
    master = None
14499 kshitij.so 955
    if sku is not None:
15853 kshitij.so 956
        if COLLECTION_MAP.has_key(class_name):
957
            master = get_mongo_connection().Catalog.MasterData.find_one({'_id':sku})
958
            cursor = collection.find({'skuBundleId':master['skuBundleId']})
959
        else:
960
            cursor = collection.find({'sku':sku})
14499 kshitij.so 961
        for val in cursor:
15853 kshitij.so 962
            if master is None:
963
                master = get_mongo_connection().Catalog.MasterData.find_one({'_id':val['sku']})
964
            if master is not None:
965
                val['brand'] = master['brand']
966
                val['source_product_name'] = master['source_product_name']
967
                val['skuBundleId'] = master['skuBundleId']
14499 kshitij.so 968
            else:
969
                val['brand'] = ""
970
                val['source_product_name'] = ""
971
                val['skuBundleId'] = ""
972
            data.append(val)
973
        return data
974
    else:
15853 kshitij.so 975
        if not COLLECTION_MAP.has_key(class_name):
976
            skuIds = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
977
            for sku in skuIds:
978
                cursor = collection.find({'sku':sku})
979
                for val in cursor:
980
                    master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
981
                    if len(master) > 0:
982
                        val['brand'] = master[0]['brand']
983
                        val['source_product_name'] = master[0]['source_product_name']
984
                        val['skuBundleId'] = master[0]['skuBundleId']
985
                    else:
986
                        val['brand'] = ""
987
                        val['source_product_name'] = ""
988
                        val['skuBundleId'] = ""
989
                    data.append(val)
990
            return data
991
        else:
992
            cursor = collection.find({'skuBundleId':skuBundleId})
14499 kshitij.so 993
            for val in cursor:
15853 kshitij.so 994
                master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
14499 kshitij.so 995
                if len(master) > 0:
996
                    val['brand'] = master[0]['brand']
997
                    val['source_product_name'] = master[0]['source_product_name']
998
                else:
999
                    val['brand'] = ""
1000
                    val['source_product_name'] = ""
1001
                data.append(val)
15853 kshitij.so 1002
            return data
14495 kshitij.so 1003
 
15074 kshitij.so 1004
def __getBrandIdForBrand(brandName, category_id):
1005
    brandInfo = Brands.query.filter(Brands.category_id==category_id).filter(Brands.name == brandName).all()
1006
    if brandInfo is None or len(brandInfo)!=1:
1007
        raise
1008
    else:
1009
        return brandInfo[0].id
1010
 
14588 kshitij.so 1011
def addNewItem(data):
14594 kshitij.so 1012
    try:
1013
        data['updatedOn'] = to_java_date(datetime.now())
1014
        data['addedOn'] = to_java_date(datetime.now())
1015
        data['priceUpdatedOn'] = to_java_date(datetime.now())
1016
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
1017
        max_bundle = list(get_mongo_connection().Catalog.MasterData.find().sort([('skuBundleId',pymongo.DESCENDING)]).limit(1))
1018
        data['_id'] = max_id[0]['_id'] + 1
1019
        data['skuBundleId'] = max_bundle[0]['skuBundleId'] + 1
1020
        data['identifier'] = str(data['identifier'])
1021
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
15074 kshitij.so 1022
        data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
14594 kshitij.so 1023
        get_mongo_connection().Catalog.MasterData.insert(data)
1024
        return {1:'Data added successfully'}
1025
    except Exception as e:
1026
        print e
1027
        return {0:'Unable to add data.'}
15130 kshitij.so 1028
    finally:
1029
        session.close()
14588 kshitij.so 1030
 
1031
def addItemToExistingBundle(data):
1032
    try:
1033
        data['updatedOn'] = to_java_date(datetime.now())
1034
        data['addedOn'] = to_java_date(datetime.now())
1035
        data['priceUpdatedOn'] = to_java_date(datetime.now())
14593 kshitij.so 1036
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
14590 kshitij.so 1037
        data['_id'] = max_id[0]['_id'] + 1
14594 kshitij.so 1038
        data['identifier'] = str(data['identifier'])
1039
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
15074 kshitij.so 1040
        data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
14588 kshitij.so 1041
        get_mongo_connection().Catalog.MasterData.insert(data)
1042
        return {1:'Data added successfully.'}
14594 kshitij.so 1043
    except Exception as e:
1044
        print e
14588 kshitij.so 1045
        return {0:'Unable to add data.'}
15130 kshitij.so 1046
    finally:
1047
        session.close()
14588 kshitij.so 1048
 
1049
def updateMaster(data, multi):
15130 kshitij.so 1050
    try:
1051
        print data
1052
        if multi != 1:
1053
            _id = data.pop('_id')
1054
            skuBundleId = data.pop('skuBundleId')
1055
            data['updatedOn'] = to_java_date(datetime.now())
1056
            data['identifier'] = str(data['identifier'])
1057
            data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
1058
            data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
1059
            get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1060
            return {1:'Data updated successfully.'}
1061
        else:
1062
            _id = data.pop('_id')
1063
            skuBundleId = data.pop('skuBundleId')
1064
            data['updatedOn'] = to_java_date(datetime.now())
1065
            data['identifier'] = str(data['identifier'])
1066
            data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
1067
            data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
1068
            get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1069
            similarItems = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId})
1070
            for item in similarItems:
1071
                if item['_id'] == _id:
1072
                    continue
1073
                item['updatedOn'] = to_java_date(datetime.now())
1074
                item['thumbnail'] = data['thumbnail']
1075
                item['category'] = data['category']
1076
                item['category_id'] = data['category_id']
1077
                item['tagline'] = data['tagline']
1078
                item['is_shortage'] = data['is_shortage']
1079
                item['mrp'] = data['mrp']
1080
                item['status'] = data['status']
1081
                item['maxPrice'] = data['maxPrice']
1082
                item['brand_id'] = data['brand_id']
1083
                similar_item_id = item.pop('_id')
1084
                get_mongo_connection().Catalog.MasterData.update({'_id':similar_item_id},{"$set":item},upsert=False)
1085
            return {1:'Data updated successfully.'}
1086
    finally:
1087
        session.close()
14619 kshitij.so 1088
 
1089
def getLiveCricScore():
1090
    return mc.get('liveScore')
14852 kshitij.so 1091
 
1092
def addBundleToNotification(data):
1093
    try:
15069 kshitij.so 1094
        collection = get_mongo_connection().Catalog.Notifications
14852 kshitij.so 1095
        cursor = collection.find({'skuBundleId':data['skuBundleId']})
1096
        if cursor.count() > 0:
1097
            return {0:"SkuBundleId information already present."}
1098
        else:
1099
            collection.insert(data)
1100
            return {1:'Data updated successfully.'}
1101
    except:
1102
        return {0:'Unable to add data.'}
1103
 
1104
def getAllNotifications(offset, limit):
1105
    data = []
15069 kshitij.so 1106
    collection = get_mongo_connection().Catalog.Notifications
14852 kshitij.so 1107
    cursor = collection.find().skip(offset).limit(limit)
1108
    for val in cursor:
15072 kshitij.so 1109
        master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
14852 kshitij.so 1110
        if len(master) > 0:
1111
            val['brand'] = master[0]['brand']
15071 kshitij.so 1112
            val['model_name'] = master[0]['model_name']
14852 kshitij.so 1113
            val['skuBundleId'] = master[0]['skuBundleId']
1114
        else:
1115
            val['brand'] = ""
15071 kshitij.so 1116
            val['model_name'] = ""
1117
            val['skuBundleId'] = val['skuBundleId']
14852 kshitij.so 1118
        data.append(val)
1119
    return data
14997 kshitij.so 1120
 
1121
def getBrandsForFilter(category_id):
1122
    if mc.get("brandFilter") is None:
15095 kshitij.so 1123
        print "Populating brand data for category_id %d" %(category_id)
14997 kshitij.so 1124
        tabData, mobData = [], []
1125
        mobileDeals = get_mongo_connection().Catalog.Deals.aggregate([
16170 kshitij.so 1126
                                                                      {"$match":{"category_id":3,"showDeal":1,"totalPoints":{"$gt":-100}}
14997 kshitij.so 1127
                                                                    },
1128
                                                                 {"$group" : 
1129
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1130
                                                                  }
1131
                                                                ])
14588 kshitij.so 1132
 
14997 kshitij.so 1133
        tabletDeals = get_mongo_connection().Catalog.Deals.aggregate([
16170 kshitij.so 1134
                                                                      {"$match":{"category_id":5,"showDeal":1,"totalPoints":{"$gt":-100}}
14997 kshitij.so 1135
                                                                    },
1136
                                                                 {"$group" : 
1137
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1138
                                                                  }
1139
                                                                ])
1140
 
1141
        allDeals = get_mongo_connection().Catalog.Deals.aggregate([
16170 kshitij.so 1142
                                                                   {"$match":{"showDeal":1,"totalPoints":{"$gt":-100}}
14997 kshitij.so 1143
                                                                    },
1144
                                                                 {"$group" : 
1145
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1146
                                                                  }
1147
                                                                ])
1148
        #print mobileDeals
1149
        #print "==========Mobile data ends=========="
1150
 
1151
        #print tabletDeals
1152
        #print "==========Tablet data ends=========="
1153
 
1154
        #print allDeals
1155
        #print "==========All deal data ends========="
1156
 
1157
        for mobileDeal in mobileDeals['result']:
1158
            if mobileDeal.get('_id').get('brand_id') != 0:
1159
                tempMap = {}
1160
                tempMap['brand'] = mobileDeal.get('_id').get('brand')
1161
                tempMap['brand_id'] = mobileDeal.get('_id').get('brand_id')
1162
                tempMap['count'] = mobileDeal.get('count')
1163
                mobData.append(tempMap)
1164
 
1165
        for tabletDeal in tabletDeals['result']:
1166
            if tabletDeal.get('_id').get('brand_id') != 0:
1167
                tempMap = {}
1168
                tempMap['brand'] = tabletDeal.get('_id').get('brand')
1169
                tempMap['brand_id'] = tabletDeal.get('_id').get('brand_id')
1170
                tempMap['count'] = tabletDeal.get('count')
1171
                tabData.append(tempMap)
1172
 
1173
 
1174
        brandMap = {}
1175
        for allDeal in allDeals['result']:
1176
            if allDeal.get('_id').get('brand_id') != 0:
1177
                if brandMap.has_key(allDeal.get('_id').get('brand')):
15002 kshitij.so 1178
                    brand_ids = brandMap.get(allDeal.get('_id').get('brand')).get('brand_ids')
14997 kshitij.so 1179
                    brand_ids.append(allDeal.get('_id').get('brand_id'))
15003 kshitij.so 1180
                    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 1181
                else:
1182
                    temp = []
1183
                    temp.append(allDeal.get('_id').get('brand_id'))
15002 kshitij.so 1184
                    brandMap[allDeal.get('_id').get('brand')] = {'brand_ids':temp,'count':allDeal.get('count')}
14997 kshitij.so 1185
 
1186
        mc.set("brandFilter",{0:brandMap, 3:mobData, 5:tabData}, 600)  
1187
 
15062 kshitij.so 1188
    return sorted(mc.get("brandFilter").get(category_id), key = lambda x: (-x['count'], x['brand']))
15375 kshitij.so 1189
 
15459 kshitij.so 1190
def getStaticDeals(offset, limit, category_id, direction):
15375 kshitij.so 1191
    user_specific_deals = mc.get("staticDeals")
1192
    if user_specific_deals is None:
1193
        __populateStaticDeals()
1194
        user_specific_deals = mc.get("staticDeals")
15459 kshitij.so 1195
    rev = False
1196
    if direction is None or direction == -1:
1197
        rev=True
1198
    return sorted((user_specific_deals.get(category_id))[offset:offset+limit],reverse=rev)
15375 kshitij.so 1199
 
1200
def __populateStaticDeals():
1201
    print "Populating memcache for static deals"
1202
    outer_query = []
1203
    outer_query.append({"showDeal":1})
1204
    query = {}
16170 kshitij.so 1205
    query['$gt'] = -100
15375 kshitij.so 1206
    outer_query.append({'totalPoints':query})
1207
    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)]))
1208
    mobile_deals = []
1209
    tablet_deals = []
1210
    for deal in all_deals:
1211
        item = get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']})
1212
        if deal['category_id'] ==3:
1213
            mobile_deals.append(getItemObjForStaticDeals(item[0]))
1214
        elif deal['category_id'] ==5:
1215
            tablet_deals.append(getItemObjForStaticDeals(item[0]))
1216
        else:
1217
            continue
1218
 
1219
    random.shuffle(mobile_deals,random.random)
1220
    random.shuffle(tablet_deals,random.random)
1221
 
1222
    mem_cache_val = {3:mobile_deals, 5:tablet_deals}
1223
    mc.set("staticDeals", mem_cache_val, 3600)
1224
 
1225
def getItemObjForStaticDeals(item):
15379 kshitij.so 1226
    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'))}
15375 kshitij.so 1227
 
13572 kshitij.so 1228
def main():
16186 kshitij.so 1229
    pass
13811 kshitij.so 1230
 
13921 kshitij.so 1231
 
15375 kshitij.so 1232
 
13572 kshitij.so 1233
if __name__=='__main__':
13932 amit.gupta 1234
    main()