Subversion Repositories SmartDukaan

Rev

Rev 14005 | Rev 14038 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 14005 Rev 14037
Line 1... Line 1...
1
import pymongo
1
import pymongo
-
 
2
from elixir import *
2
from datetime import datetime
3
from datetime import datetime
3
from datetime import timedelta
4
from datetime import timedelta
4
from dtr.main import Store
5
from dtr.main import Store
5
from dtr.utils.utils import to_java_date
6
from dtr.utils.utils import to_java_date
6
from operator import itemgetter
7
from operator import itemgetter
7
from bson.objectid import ObjectId
8
from bson.objectid import ObjectId
-
 
9
from dtr.storage import DataService
-
 
10
from dtr.storage.DataService import price_preferences, brand_preferences, \
-
 
11
user_actions
-
 
12
from dtr.storage.MemCache import MemCache
8
 
13
 
9
con = None
14
con = None
10
cashBackMap = {}
15
cashBackMap = {}
11
itemCashBackMap = {}
16
itemCashBackMap = {}
12
 
17
 
-
 
18
DataService.initialize(db_hostname="localhost")
-
 
19
mc = MemCache("127.0.0.1")
-
 
20
 
13
def get_mongo_connection(host='localhost', port=27017):
21
def get_mongo_connection(host='localhost', port=27017):
14
    global con
22
    global con
15
    if con is None:
23
    if con is None:
16
        print "Establishing connection %s host and port %d" %(host,port)
24
        print "Establishing connection %s host and port %d" %(host,port)
17
        try:
25
        try:
Line 240... Line 248...
240
    else:
248
    else:
241
        result={}
249
        result={}
242
        result['amount'] = 0.0
250
        result['amount'] = 0.0
243
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
251
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
244
    return result
252
    return result
-
 
253
 
-
 
254
def __populateCache(userId):
-
 
255
    print "Populating memcache for userId",userId
-
 
256
    outer_query = []
-
 
257
    outer_query.append({"showDeal":1})
-
 
258
    query = {}
-
 
259
    query['$gt'] = 0
-
 
260
    outer_query.append({'totalPoints':query})
-
 
261
    brandPrefMap = {}
-
 
262
    pricePrefMap = {}
-
 
263
    actionsMap = {}
-
 
264
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
-
 
265
    for x in brand_p:
-
 
266
        pricePrefMap[x.category_id] = [x.min_price,x.max_price]
-
 
267
    for x in session.query(brand_preferences).filter_by(user_id=userId).all():
-
 
268
        temp_map = {}
-
 
269
        if brandPrefMap.has_key((x.brand).strip().upper()):
-
 
270
            val = brandPrefMap.get((x.brand).strip().upper())
-
 
271
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
-
 
272
            val.append(temp_map)
-
 
273
        else:
-
 
274
            temp = []
-
 
275
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
-
 
276
            temp.append(temp_map)
-
 
277
            brandPrefMap[(x.brand).strip().upper()] = temp
-
 
278
        
-
 
279
    for x in session.query(user_actions).filter_by(user_id=userId).all():
-
 
280
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
245
def getDeals(category_id, offset, limit, sort, direction):
281
    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}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
-
 
282
    all_category_deals = []
-
 
283
    mobile_deals = []
-
 
284
    tablet_deals = []
-
 
285
    for deal in all_deals:
-
 
286
        if actionsMap.get(deal['_id']) == 0:
-
 
287
            fav_weight =.25
-
 
288
        elif actionsMap.get(deal['_id']) == 1:
-
 
289
            fav_weight = 1.5
-
 
290
        else:
-
 
291
            fav_weight = 1
-
 
292
        
-
 
293
        if brandPrefMap.get(deal['brand'].strip().upper()) is not None:
-
 
294
            brand_weight = 1
-
 
295
            for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):
-
 
296
                if brandInfo.get(deal['category_id']) is not None:
-
 
297
                    if brandInfo.get(deal['category_id']) == 1:
-
 
298
                        brand_weight = 1.5
-
 
299
        else:
-
 
300
            brand_weight = 1
-
 
301
        
-
 
302
        if pricePrefMap.get(deal['category_id']) is not None:
-
 
303
        
-
 
304
            if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:
-
 
305
                asp_weight = 1.5
-
 
306
            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]:
-
 
307
                asp_weight = 1.2
-
 
308
            else:
-
 
309
                asp_weight = 1
-
 
310
        else:
-
 
311
            asp_weight = 1
-
 
312
        
-
 
313
        persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weight
-
 
314
        deal['persPoints'] = persPoints
-
 
315
        
-
 
316
        if deal['category_id'] ==3:
-
 
317
            mobile_deals.append(deal)
-
 
318
        elif deal['category_id'] ==5:
-
 
319
            tablet_deals.append(deal)
-
 
320
        else:
-
 
321
            continue
-
 
322
        all_category_deals.append(deal)
-
 
323
    
-
 
324
        
-
 
325
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 0:all_deals}
-
 
326
    mc.set(str(userId), mem_cache_val)
-
 
327
    
-
 
328
 
-
 
329
 
-
 
330
def getNewDeals(userId, category_id, offset, limit, sort, direction):
-
 
331
    if not bool(cashBackMap):
-
 
332
        populateCashBack()
-
 
333
    
-
 
334
    rank = 1
-
 
335
    dealsMap = {}
-
 
336
    user_specific_deals = mc.get(str(userId))
-
 
337
    if user_specific_deals is None:
-
 
338
        __populateCache(userId)
-
 
339
        user_specific_deals = mc.get(str(userId))
-
 
340
    category_specific_deals = user_specific_deals.get(category_id)
-
 
341
    
-
 
342
    if sort is None or direction is None:
-
 
343
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
-
 
344
    else:
-
 
345
        if sort == "bestSellerPoints":
-
 
346
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
-
 
347
        else:
-
 
348
            if direction == -1:
-
 
349
                rev = True
-
 
350
            else:
-
 
351
                rev = False
-
 
352
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
-
 
353
    
-
 
354
    for d in sorted_deals[offset:offset+limit]:
-
 
355
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
-
 
356
        if not dealsMap.has_key(item[0]['identifier']):
-
 
357
            item[0]['dealRank'] = rank
-
 
358
            item[0]['persPoints'] = d['persPoints']
-
 
359
            try:
-
 
360
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
-
 
361
                if not cashBack or cashBack.get('cash_back_status')!=1:
-
 
362
                    item[0]['cash_back_type'] = 0
-
 
363
                    item[0]['cash_back'] = 0
-
 
364
                else:
-
 
365
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
-
 
366
                    item[0]['cash_back'] = cashBack['cash_back']
-
 
367
            except:
-
 
368
                print "Error in adding cashback to deals"
-
 
369
                item[0]['cash_back_type'] = 0
-
 
370
                item[0]['cash_back'] = 0
-
 
371
            dealsMap[item[0]['identifier']] = item[0]
-
 
372
            
-
 
373
            rank +=1
-
 
374
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
-
 
375
        
-
 
376
 
-
 
377
def getDeals(userId, category_id, offset, limit, sort, direction):
246
    if not bool(cashBackMap):
378
    if not bool(cashBackMap):
247
        populateCashBack()
379
        populateCashBack()
248
    rank = 1
380
    rank = 1
249
    deals = {}
381
    deals = {}
250
    outer_query = []
382
    outer_query = []
Line 392... Line 524...
392
    except:
524
    except:
393
        return {0:"Data not updated."}
525
        return {0:"Data not updated."}
394
 
526
 
395
 
527
 
396
def main():
528
def main():
-
 
529
    x = getNewDeals(1, 0, 0, 30, None, None)
-
 
530
    for i in x:
-
 
531
        print i['_id'],
-
 
532
        print '\t',
397
    print getPendingRefunds(15) 
533
        print i['persPoints']
398
    
534
    
399
    
535
    
400
if __name__=='__main__':
536
if __name__=='__main__':
401
    main()
537
    main()