Subversion Repositories SmartDukaan

Rev

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

Rev 19435 Rev 19441
Line 352... Line 352...
352
def __constructDummyDealObject(skuBundleId):
352
def __constructDummyDealObject(skuBundleId):
353
    temp =[]
353
    temp =[]
354
    deals = get_mongo_connection().Catalog.Deals.find({"skuBundleId":skuBundleId,"$or":[{"showDeal":1}, {"prepaidDeal":1}]},{'_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, 'gross_price':1,'subCategoryId':1,'netPriceAfterCashBack':1})
354
    deals = get_mongo_connection().Catalog.Deals.find({"skuBundleId":skuBundleId,"$or":[{"showDeal":1}, {"prepaidDeal":1}]},{'_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, 'gross_price':1,'subCategoryId':1,'netPriceAfterCashBack':1})
355
    for d in deals:
355
    for d in deals:
356
        d['persPoints'] = 0
356
        d['persPoints'] = 0
-
 
357
        d['internalRank'] = 999999
357
        temp.append(d)
358
        temp.append(d)
358
    return temp
359
    return temp
359
    
360
    
360
    
361
    
361
 
362
 
Line 367... Line 368...
367
            
368
            
368
    except Exception as e:
369
    except Exception as e:
369
        print traceback.print_exc()
370
        print traceback.print_exc()
370
        featuredDeals = {3:{},5:{},6:{}}
371
        featuredDeals = {3:{},5:{},6:{}}
371
    
372
    
-
 
373
    
-
 
374
    #Not taking into account accessories
-
 
375
    featuredDeals.pop(6,None)
-
 
376
    
372
    fd_bundles = []
377
    fd_bundles = []
373
    
378
    
374
    for catMap in featuredDeals.itervalues():
379
    for catMap in featuredDeals.itervalues():
375
        for fd_map in catMap.itervalues():
380
        for fd_map in catMap.itervalues():
376
            if not fd_map.get('skuBundleId') in fd_bundles:
381
            if not fd_map.get('skuBundleId') in fd_bundles:
Line 380... Line 385...
380
    outer_query = []
385
    outer_query = []
381
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
386
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
382
    query = {}
387
    query = {}
383
    query['$gt'] = -100
388
    query['$gt'] = -100
384
    outer_query.append({'totalPoints':query})
389
    outer_query.append({'totalPoints':query})
-
 
390
    outer_query.append({'category_id':{"$in":[3,5]}})
385
    brandPrefMap = {}
391
    brandPrefMap = {}
386
    pricePrefMap = {}
392
    pricePrefMap = {}
387
    actionsMap = {}
393
    actionsMap = {}
388
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
394
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
389
    for x in brand_p:
395
    for x in brand_p:
Line 403... Line 409...
403
    for x in session.query(user_actions).filter_by(user_id=userId).all():
409
    for x in session.query(user_actions).filter_by(user_id=userId).all():
404
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
410
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
405
    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, 'gross_price':1, 'subCategoryId':1,'netPriceAfterCashBack':1}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
411
    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, 'gross_price':1, 'subCategoryId':1,'netPriceAfterCashBack':1}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
406
    mobile_deals = []
412
    mobile_deals = []
407
    tablet_deals = []
413
    tablet_deals = []
408
    accessories_deals = []
414
    #accessories_deals = []
409
    for deal in all_deals:
415
    for deal in all_deals:
410
 
416
 
411
        try:
417
        try:
412
            fd_bundles.remove(deal.get('skuBundleId'))
418
            fd_bundles.remove(deal.get('skuBundleId'))
413
        except:
419
        except:
Line 446... Line 452...
446
        
452
        
447
        if deal['category_id'] ==3:
453
        if deal['category_id'] ==3:
448
            mobile_deals.append(deal)
454
            mobile_deals.append(deal)
449
        elif deal['category_id'] ==5:
455
        elif deal['category_id'] ==5:
450
            tablet_deals.append(deal)
456
            tablet_deals.append(deal)
451
        elif deal['category_id'] ==6:
457
        #elif deal['category_id'] ==6:
452
            accessories_deals.append(deal)
458
        #    accessories_deals.append(deal)
453
        else:
459
        else:
454
            continue
460
            continue
455
    
461
    
456
    session.close()
462
    session.close()
457
    
463
    
458
    mobile_deals = sorted(mobile_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
464
    mobile_deals = sorted(mobile_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
459
    tablet_deals = sorted(tablet_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
465
    tablet_deals = sorted(tablet_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
460
    accessories_deals = sorted(accessories_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
466
    #accessories_deals = sorted(accessories_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
461
    
467
    
462
    
468
    
463
    if len(fd_bundles) > 0:
469
    if len(fd_bundles) > 0:
464
        print "There is still bundle in feature deals with points less than -100.Lets add info"
470
        print "There is still bundle in feature deals with points less than -100.Lets add info"
465
        for skuBundleId in fd_bundles:
471
        for skuBundleId in fd_bundles:
Line 467... Line 473...
467
            for dummyDealObj in dummyDealObjList:
473
            for dummyDealObj in dummyDealObjList:
468
                if dummyDealObj['category_id'] ==3:
474
                if dummyDealObj['category_id'] ==3:
469
                    mobile_deals.append(dummyDealObj)
475
                    mobile_deals.append(dummyDealObj)
470
                elif dummyDealObj['category_id'] ==5:
476
                elif dummyDealObj['category_id'] ==5:
471
                    tablet_deals.append(dummyDealObj)
477
                    tablet_deals.append(dummyDealObj)
472
                elif dummyDealObj['category_id'] ==6:
478
                #elif dummyDealObj['category_id'] ==6:
473
                    accessories_deals.append(dummyDealObj)
479
                #    accessories_deals.append(dummyDealObj)
474
                else:
480
                else:
475
                    pass
481
                    pass
476
    
482
    
477
    for super_category, categoryFeaturedDeals in featuredDeals.iteritems():
483
    for super_category, categoryFeaturedDeals in featuredDeals.iteritems():
478
        for val in categoryFeaturedDeals.itervalues():
484
        for val in categoryFeaturedDeals.itervalues():
Line 483... Line 489...
483
                
489
                
484
                if super_category ==3:
490
                if super_category ==3:
485
                    mobile_deals.append(dummyDealObj)
491
                    mobile_deals.append(dummyDealObj)
486
                elif super_category ==5:
492
                elif super_category ==5:
487
                    tablet_deals.append(dummyDealObj)
493
                    tablet_deals.append(dummyDealObj)
488
                elif super_category ==6:
494
                #elif super_category ==6:
489
                    accessories_deals.append(dummyDealObj)
495
                #    accessories_deals.append(dummyDealObj)
490
                else:
496
                else:
491
                    pass
497
                    pass
492
 
498
 
493
    sortedMapMobiles = {}
499
    sortedMapMobiles = {}
494
    rankMapMobiles = {}
500
    rankMapMobiles = {}
Line 577... Line 583...
577
    for rank in blockedRanksTablets:
583
    for rank in blockedRanksTablets:
578
        if blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId')) is not None:
584
        if blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId')) is not None:
579
            rankMapTablets[rank] = blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId'))
585
            rankMapTablets[rank] = blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId'))
580
            
586
            
581
    
587
    
-
 
588
#     sortedMapAccessories = {}
-
 
589
#     rankMapAccessories = {}
-
 
590
#     rankAccessories = 0
-
 
591
#     
-
 
592
#     blockedRanksAccessories = []
-
 
593
#     blockedSkuBundlesAccessories = []
-
 
594
#     blockedInfoAccessories = {}
-
 
595
#     
-
 
596
#     featuredDealsAccessories = featuredDeals.get(6)
-
 
597
#     
-
 
598
#     for k, v in featuredDealsAccessories.iteritems():
-
 
599
#         blockedRanksAccessories.append(k-1)
-
 
600
#         blockedSkuBundlesAccessories.append(v.get('skuBundleId'))
-
 
601
#     
-
 
602
#     
-
 
603
#     for sorted_deal in accessories_deals:
-
 
604
#        
-
 
605
#         while(True):
-
 
606
#             if rankAccessories in blockedRanksAccessories:
-
 
607
#                 rankAccessories = rankAccessories +1
-
 
608
#             else:
-
 
609
#                 break
-
 
610
#              
-
 
611
#         if sorted_deal['skuBundleId'] in blockedSkuBundlesAccessories:
-
 
612
#             if blockedInfoAccessories.has_key(sorted_deal['skuBundleId']):
-
 
613
#                 blockedInfoAccessories.get(sorted_deal['skuBundleId']).append(sorted_deal)
-
 
614
#             else:
-
 
615
#                 blockedInfoAccessories[sorted_deal['skuBundleId']] = [sorted_deal]
-
 
616
#             continue
-
 
617
#          
-
 
618
#         if sortedMapAccessories.get(sorted_deal['skuBundleId']) is None:
-
 
619
#             sortedMapAccessories[sorted_deal['skuBundleId']] = {rankAccessories:[sorted_deal]}
-
 
620
#             rankMapAccessories[rankAccessories] = (sortedMapAccessories[sorted_deal['skuBundleId']].values())[0]
-
 
621
#             rankAccessories = rankAccessories +1
-
 
622
#         else:
-
 
623
#             for temp_list in sortedMapAccessories.get(sorted_deal['skuBundleId']).itervalues():
-
 
624
#                 temp_list.append(sorted_deal)
-
 
625
#             rankMapAccessories[(sortedMapAccessories.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
-
 
626
#     
-
 
627
#             
-
 
628
#     for rank in blockedRanksAccessories:
-
 
629
#         if blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId')) is not None:
-
 
630
#             rankMapAccessories[rank] = blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId'))
-
 
631
#     
-
 
632
    specialOffer = None
-
 
633
    promoOffer = get_mongo_connection().Catalog.PromoOffer.find_one({'user_id':userId})
-
 
634
    try:
-
 
635
        if promoOffer is not None:
-
 
636
            offer = get_mongo_connection().Catalog.Promotions.find_one({'_id':promoOffer.get('offer_id')})
-
 
637
            if offer is None:
-
 
638
                raise
-
 
639
            promo = Promotion(offer.get('_id'),offer.get('offer_name'),offer.get('offer_description') , offer.get('categories_applicable'), offer.get('sub_categories_not_applicable'),
-
 
640
                     offer.get('startDate'), offer.get('endDate'), promoOffer.get('target1'), promoOffer.get('target1_cash_back_percetage'), promoOffer.get('target2'), promoOffer.get('target2_cash_back_percetage'), promoOffer.get('maxCashBack'),offer.get('url'),
-
 
641
                     promoOffer.get('pending_order_value'), promoOffer.get('delivered_order_value'), promoOffer.get('last_run_timestamp'))
-
 
642
    
-
 
643
            specialOffer = promo
-
 
644
    except:
-
 
645
        traceback.print_exc()
-
 
646
    
-
 
647
    
-
 
648
    mem_cache_val = {3:mobile_deals, 5:tablet_deals,"3_rankMap": rankMapMobiles,"5_rankMap": rankMapTablets, "specialOffer":specialOffer }
-
 
649
    mc.set(str(userId), mem_cache_val)
-
 
650
    
-
 
651
def __populateCacheForAccessories(userId):
-
 
652
    try:
-
 
653
        if mc.get("featured_deals") is None:
-
 
654
            __populateFeaturedDeals()
-
 
655
        featuredDeals = mc.get("featured_deals")
-
 
656
            
-
 
657
    except Exception as e:
-
 
658
        print traceback.print_exc()
-
 
659
        featuredDeals = {3:{},5:{},6:{}}
-
 
660
    
-
 
661
    
-
 
662
    #Not taking into account mobiles, tablets
-
 
663
    featuredDeals.pop(3,None)
-
 
664
    featuredDeals.pop(5,None)
-
 
665
    
-
 
666
    fd_bundles = []
-
 
667
    
-
 
668
    for catMap in featuredDeals.itervalues():
-
 
669
        for fd_map in catMap.itervalues():
-
 
670
            if not fd_map.get('skuBundleId') in fd_bundles:
-
 
671
                fd_bundles.append(fd_map.get('skuBundleId'))
-
 
672
    
-
 
673
    print "Populating accessory memcache for userId",userId
-
 
674
    outer_query = []
-
 
675
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
-
 
676
    query = {}
-
 
677
    query['$gte'] = 0
-
 
678
    outer_query.append({'internalRank':query})
-
 
679
    outer_query.append({'category_id':{"$in":[6]}})
-
 
680
 
-
 
681
    accessories_deals = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query},{'_id':1,'category_id':1,'brand':1,'bestSellerPoints':1,'nlcPoints':1,'totalPoints':1,'internalRank':1,'available_price':1,'dealType':1,'source_id':1,'brand_id':1,'skuBundleId':1,'dp':1, 'showDp':1, 'gross_price':1, 'subCategoryId':1,'netPriceAfterCashBack':1}).sort([('internalRank',pymongo.ASCENDING),('bestSellerPoints',pymongo.DESCENDING)]))
-
 
682
    
-
 
683
    actionsMap = {}
-
 
684
    
-
 
685
    actionRank = 3
-
 
686
    for x in session.query(user_actions).filter_by(user_id=userId).order_by(asc(user_actions.created)).all():
-
 
687
        #actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
-
 
688
        action = 1 if x.action == 'like' else 0
-
 
689
        if action==1:
-
 
690
            actionsMap[x.store_product_id] = {'action':action,'rank':actionRank}
-
 
691
            actionRank = actionRank+3
-
 
692
        else:
-
 
693
            actionsMap[x.store_product_id] = {'action':action,'rank':None}
-
 
694
    
-
 
695
    session.close()
-
 
696
    
-
 
697
    psuedo_count = 1
-
 
698
 
-
 
699
    if actionsMap:
-
 
700
        for k,v in actionsMap.iteritems():
-
 
701
            if v['action'] == 0:
-
 
702
                tmp_deal = get_mongo_connection().Catalog.Deals.find_one({'_id':k})
-
 
703
                if tmp_deal is None:
-
 
704
                    v['rank'] = 999999
-
 
705
                    continue
-
 
706
                max_rank = list(get_mongo_connection().Catalog.Deals.find({'subCategoryId':tmp_deal.get('subCategoryId')}).sort([('internalRank',pymongo.DESCENDING)]).limit(1))
-
 
707
                if len(max_rank) == 0 or max_rank[0].get('internalRank') is None:
-
 
708
                    v['rank'] = 999999
-
 
709
                    continue
-
 
710
                v['rank'] = max_rank[0]['internalRank'] + 1
-
 
711
                 
-
 
712
    for deal in accessories_deals:
-
 
713
 
-
 
714
        try:
-
 
715
            fd_bundles.remove(deal.get('skuBundleId'))
-
 
716
        except:
-
 
717
            pass
-
 
718
        if actionsMap and actionsMap.get(deal['_id'])!=None:
-
 
719
            if actionsMap.get(deal['_id']).get('action') ==1:
-
 
720
                actionRank = actionsMap.get(deal['_id']).get('rank')
-
 
721
                if actionRank < psuedo_count:
-
 
722
                    deal['internalRank'] = actionRank
-
 
723
                
-
 
724
            elif actionsMap.get(deal['_id']).get('action') ==0:
-
 
725
                actionRank = actionsMap.get(deal['_id']).get('rank')
-
 
726
                deal['internalRank'] = actionRank
-
 
727
            else:
-
 
728
                pass
-
 
729
        psuedo_count = psuedo_count+1
-
 
730
    
-
 
731
    if actionsMap:
-
 
732
        accessories_deals = sorted(accessories_deals, key = lambda x: (-x['internalRank'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints']),reverse=True)
-
 
733
    
-
 
734
    if len(fd_bundles) > 0:
-
 
735
        print "There is still bundle in feature deals.Lets add info"
-
 
736
        for skuBundleId in fd_bundles:
-
 
737
            dummyDealObjList = __constructDummyDealObject(skuBundleId)
-
 
738
            for dummyDealObj in dummyDealObjList:
-
 
739
                if dummyDealObj['category_id'] ==6:
-
 
740
                    accessories_deals.append(dummyDealObj)
-
 
741
    
-
 
742
    for super_category, categoryFeaturedDeals in featuredDeals.iteritems():
-
 
743
        for val in categoryFeaturedDeals.itervalues():
-
 
744
            dummyDealObjList = __constructDummyDealObject(val.get('skuBundleId'))
-
 
745
            for dummyDealObj in dummyDealObjList:
-
 
746
                if super_category == dummyDealObj['category_id']:
-
 
747
                    continue  
-
 
748
                if super_category ==6:
-
 
749
                    accessories_deals.append(dummyDealObj)
-
 
750
 
-
 
751
    
582
    sortedMapAccessories = {}
752
    sortedMapAccessories = {}
583
    rankMapAccessories = {}
753
    rankMapAccessories = {}
584
    rankAccessories = 0
754
    rankAccessories = 0
585
    
755
     
586
    blockedRanksAccessories = []
756
    blockedRanksAccessories = []
587
    blockedSkuBundlesAccessories = []
757
    blockedSkuBundlesAccessories = []
588
    blockedInfoAccessories = {}
758
    blockedInfoAccessories = {}
589
    
759
     
590
    featuredDealsAccessories = featuredDeals.get(6)
760
    featuredDealsAccessories = featuredDeals.get(6)
591
    
761
     
592
    for k, v in featuredDealsAccessories.iteritems():
762
    for k, v in featuredDealsAccessories.iteritems():
593
        blockedRanksAccessories.append(k-1)
763
        blockedRanksAccessories.append(k-1)
594
        blockedSkuBundlesAccessories.append(v.get('skuBundleId'))
764
        blockedSkuBundlesAccessories.append(v.get('skuBundleId'))
595
    
765
     
596
    
766
     
597
    for sorted_deal in accessories_deals:
767
    for sorted_deal in accessories_deals:
598
       
768
        
599
        while(True):
769
        while(True):
600
            if rankAccessories in blockedRanksAccessories:
770
            if rankAccessories in blockedRanksAccessories:
601
                rankAccessories = rankAccessories +1
771
                rankAccessories = rankAccessories +1
602
            else:
772
            else:
603
                break
773
                break
604
             
774
              
605
        if sorted_deal['skuBundleId'] in blockedSkuBundlesAccessories:
775
        if sorted_deal['skuBundleId'] in blockedSkuBundlesAccessories:
606
            if blockedInfoAccessories.has_key(sorted_deal['skuBundleId']):
776
            if blockedInfoAccessories.has_key(sorted_deal['skuBundleId']):
607
                blockedInfoAccessories.get(sorted_deal['skuBundleId']).append(sorted_deal)
777
                blockedInfoAccessories.get(sorted_deal['skuBundleId']).append(sorted_deal)
608
            else:
778
            else:
609
                blockedInfoAccessories[sorted_deal['skuBundleId']] = [sorted_deal]
779
                blockedInfoAccessories[sorted_deal['skuBundleId']] = [sorted_deal]
610
            continue
780
            continue
611
         
781
          
612
        if sortedMapAccessories.get(sorted_deal['skuBundleId']) is None:
782
        if sortedMapAccessories.get(sorted_deal['skuBundleId']) is None:
613
            sortedMapAccessories[sorted_deal['skuBundleId']] = {rankAccessories:[sorted_deal]}
783
            sortedMapAccessories[sorted_deal['skuBundleId']] = {rankAccessories:[sorted_deal]}
614
            rankMapAccessories[rankAccessories] = (sortedMapAccessories[sorted_deal['skuBundleId']].values())[0]
784
            rankMapAccessories[rankAccessories] = (sortedMapAccessories[sorted_deal['skuBundleId']].values())[0]
615
            rankAccessories = rankAccessories +1
785
            rankAccessories = rankAccessories +1
616
        else:
786
        else:
617
            for temp_list in sortedMapAccessories.get(sorted_deal['skuBundleId']).itervalues():
787
            for temp_list in sortedMapAccessories.get(sorted_deal['skuBundleId']).itervalues():
618
                temp_list.append(sorted_deal)
788
                temp_list.append(sorted_deal)
619
            rankMapAccessories[(sortedMapAccessories.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
789
            rankMapAccessories[(sortedMapAccessories.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
620
    
790
     
621
            
791
             
622
    for rank in blockedRanksAccessories:
792
    for rank in blockedRanksAccessories:
623
        if blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId')) is not None:
793
        if blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId')) is not None:
624
            rankMapAccessories[rank] = blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId'))
794
            rankMapAccessories[rank] = blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId'))
625
    
795
     
626
    specialOffer = None
796
    specialOffer = None
627
    promoOffer = get_mongo_connection().Catalog.PromoOffer.find_one({'user_id':userId})
797
    promoOffer = get_mongo_connection().Catalog.PromoOffer.find_one({'user_id':userId})
628
    try:
798
    try:
629
        if promoOffer is not None:
799
        if promoOffer is not None:
630
            offer = get_mongo_connection().Catalog.Promotions.find_one({'_id':promoOffer.get('offer_id')})
800
            offer = get_mongo_connection().Catalog.Promotions.find_one({'_id':promoOffer.get('offer_id')})
Line 637... Line 807...
637
            specialOffer = promo
807
            specialOffer = promo
638
    except:
808
    except:
639
        traceback.print_exc()
809
        traceback.print_exc()
640
    
810
    
641
    
811
    
642
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 6: accessories_deals,"3_rankMap": rankMapMobiles,"5_rankMap": rankMapTablets,"6_rankMap": rankMapAccessories, "specialOffer":specialOffer }
812
    mem_cache_val = {6:accessories_deals,"6_rankMap": rankMapAccessories, "specialOffer":specialOffer }
643
    mc.set(str(userId), mem_cache_val)
813
    mc.set(str(userId)+'_acc', mem_cache_val)
-
 
814
 
644
    
815
    
645
 
816
 
646
def __populateFeaturedDeals():
817
def __populateFeaturedDeals():
647
    print "Populating featured deals....."
818
    print "Populating featured deals....."
648
    featuredDealsMobiles = {}
819
    featuredDealsMobiles = {}
Line 927... Line 1098...
927
                elif item[0]['cash_back_type'] ==2:
1098
                elif item[0]['cash_back_type'] ==2:
928
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(item[0]['cash_back'])
1099
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(item[0]['cash_back'])
929
                else:
1100
                else:
930
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price']
1101
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price']
931
            
1102
            
-
 
1103
            temp.append(item[0])
-
 
1104
        if len(temp) > 1:
-
 
1105
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
-
 
1106
        dealsListMap.append(temp)
-
 
1107
    return dealsListMap
-
 
1108
 
-
 
1109
 
-
 
1110
def getAccesoryDeals(userId, category_id, offset, limit, sort, direction, filterData=None):
-
 
1111
    if mc.get("category_cash_back") is None or not bool(mc.get("category_cash_back")):
-
 
1112
        populateCashBack()
-
 
1113
    
-
 
1114
    dealsListMap = []
-
 
1115
    user_specific_deals = mc.get(str(userId)+'_acc')
-
 
1116
    if user_specific_deals is None:
-
 
1117
        __populateCacheForAccessories(userId)
-
 
1118
        user_specific_deals = mc.get(str(userId)+'_acc')
-
 
1119
    else:
-
 
1120
        print "Getting user deals from accessory cache"
-
 
1121
    category_specific_deals = user_specific_deals.get(category_id)
-
 
1122
    
-
 
1123
    insert_featured_deals = False
-
 
1124
    if sort is None or direction is None:
-
 
1125
        insert_featured_deals = True
-
 
1126
        rankMap = user_specific_deals.get(str(category_id)+"_rankMap")
-
 
1127
    else:
-
 
1128
        if sort == "bestSellerPoints":
-
 
1129
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['internalRank'], x['nlcPoints']),reverse=True)
-
 
1130
        else:
-
 
1131
            if direction == -1:
-
 
1132
                rev = True
-
 
1133
            else:
-
 
1134
                rev = False
-
 
1135
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
-
 
1136
    
-
 
1137
    
-
 
1138
    filtered_deals = []
-
 
1139
    dataExist = True
-
 
1140
    if filterData is not None:
-
 
1141
        try:
-
 
1142
            filtered_deals = filterDeals(category_specific_deals, filterData)
-
 
1143
            if len(filtered_deals)==0:
-
 
1144
                dataExist = False
-
 
1145
        except:
-
 
1146
            traceback.print_exc()
-
 
1147
    if dataExist:
-
 
1148
    
-
 
1149
        if not insert_featured_deals:
-
 
1150
            sortedMap = {}
-
 
1151
            rankMap = {}
-
 
1152
            rank = 0
-
 
1153
            for sorted_deal in sorted_deals:
-
 
1154
                
-
 
1155
                if len(filtered_deals) > 0 and  sorted_deal['skuBundleId'] not in filtered_deals:
-
 
1156
                    continue
-
 
1157
                
-
 
1158
                if sortedMap.get(sorted_deal['skuBundleId']) is None:
-
 
1159
                    sortedMap[sorted_deal['skuBundleId']] = {rank:[sorted_deal]}
-
 
1160
                    rankMap[rank] = (sortedMap[sorted_deal['skuBundleId']].values())[0]
-
 
1161
                    rank = rank +1
-
 
1162
                else:
-
 
1163
                    for temp_list in sortedMap.get(sorted_deal['skuBundleId']).itervalues():
-
 
1164
                        temp_list.append(sorted_deal)
-
 
1165
                    rankMap[(sortedMap.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
-
 
1166
        else:
-
 
1167
            filterMap = {}
-
 
1168
            rank = 0
-
 
1169
            if len(filtered_deals) > 0:
-
 
1170
                try:
-
 
1171
                    od = collections.OrderedDict(sorted(rankMap.items()))
-
 
1172
                except:
-
 
1173
                    od = ordereddict.OrderedDict(sorted(rankMap.items()))
-
 
1174
                for k, v in od.iteritems():
-
 
1175
                    if v[0].get('skuBundleId') in filtered_deals:
-
 
1176
                        filterMap[rank] = v
-
 
1177
                        rank =rank+1
-
 
1178
                rankMap = filterMap
-
 
1179
        
-
 
1180
        rankCounter = offset
-
 
1181
        if filterData is None:
-
 
1182
            if mc.get("featured_deals_deal_object") is None or not bool(mc.get("featured_deals_deal_object")):
-
 
1183
                try:
-
 
1184
                    __populateFeaturedDealsForDealObject()
-
 
1185
                    fd_dealObject = mc.get("featured_deals_deal_object")
-
 
1186
                except:
-
 
1187
                    fd_dealObject = {3:{},5:{},6:{}}
-
 
1188
            else:
-
 
1189
                fd_dealObject = mc.get("featured_deals_deal_object")
-
 
1190
        
-
 
1191
    else:
-
 
1192
        rankMap = {}
-
 
1193
    
-
 
1194
    
-
 
1195
    specialOffer = user_specific_deals.get('specialOffer')
-
 
1196
    
-
 
1197
    for dealList in [rankMap.get(k, []) for k in range(offset, offset+limit)]:
-
 
1198
        if filterData is None:
-
 
1199
            while(True):
-
 
1200
                
-
 
1201
                rankCounter = rankCounter+1
-
 
1202
                if (fd_dealObject.get(category_id).get(rankCounter)) is not None:
-
 
1203
                    if (fd_dealObject.get(category_id).get(rankCounter).get('offer_id') !=0):
-
 
1204
                        #Check whether user can see offer
-
 
1205
                        if specialOffer is None or specialOffer.endDate < to_java_date(datetime.now()):
-
 
1206
                            continue
-
 
1207
                    deal_object_temp = []
-
 
1208
                    deal_object_temp.append(fd_dealObject.get(category_id).get(rankCounter).get('object'))
-
 
1209
                    dealsListMap.append(deal_object_temp)
-
 
1210
                else:
-
 
1211
                    break
-
 
1212
            
-
 
1213
        temp = []
-
 
1214
        if dealList is None or len(dealList)==0:
-
 
1215
            continue
-
 
1216
        for d in dealList:
-
 
1217
            item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
-
 
1218
            if len(item) ==0:
-
 
1219
                continue
-
 
1220
            if d['dealType'] == 1 and d['source_id'] ==1:
-
 
1221
                try:
-
 
1222
                    manualDeal = list(get_mongo_connection().Catalog.ManualDeals.find({'sku':d['_id'],'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}))
-
 
1223
                    item[0]['marketPlaceUrl'] = manualDeal[0]['dealUrl'].strip()
-
 
1224
                except:
-
 
1225
                    pass
-
 
1226
            elif d['source_id'] ==3:
-
 
1227
                item[0]['marketPlaceUrl'] = item[0]['marketPlaceUrl']+'?supc='+item[0].get('identifier')
-
 
1228
            else:
-
 
1229
                pass 
-
 
1230
            try:
-
 
1231
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
-
 
1232
                if not cashBack or cashBack.get('cash_back_status')!=1:
-
 
1233
                    item[0]['cash_back_type'] = 0
-
 
1234
                    item[0]['cash_back'] = 0
-
 
1235
                else:
-
 
1236
                    if cashBack.get('maxCashBack') is not None:
-
 
1237
                        
-
 
1238
                        if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*item[0]['available_price'])/100 > cashBack.get('maxCashBack'):
-
 
1239
                            cashBack['cash_back_type'] = 2
-
 
1240
                            cashBack['cash_back'] = cashBack['maxCashBack']
-
 
1241
                        elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):
-
 
1242
                            cashBack['cash_back'] = cashBack['maxCashBack']
-
 
1243
                    
-
 
1244
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
-
 
1245
                    item[0]['cash_back'] = cashBack['cash_back']
-
 
1246
            except:
-
 
1247
                print "Error in adding cashback to deals"
-
 
1248
                item[0]['cash_back_type'] = 0
-
 
1249
                item[0]['cash_back'] = 0
-
 
1250
            try:
-
 
1251
                item[0]['dp'] = d['dp']
-
 
1252
                item[0]['showDp'] = d['showDp']
-
 
1253
            except:
-
 
1254
                item[0]['dp'] = 0.0
-
 
1255
                item[0]['showDp'] = 0
-
 
1256
            try:
-
 
1257
                item[0]['thumbnail'] = item[0]['thumbnail'].strip()
-
 
1258
            except:
-
 
1259
                pass
-
 
1260
            
-
 
1261
            try:
-
 
1262
                if item[0]['showVideo']==0:
-
 
1263
                    item[0]['videoLink'] =""
-
 
1264
            except:
-
 
1265
                item[0]['videoLink'] =""
-
 
1266
            try:
-
 
1267
                if item[0]['quantity'] >1:
-
 
1268
                    ppq = float(item[0]['available_price'])/item[0]['quantity']
-
 
1269
                     
-
 
1270
                    if ppq == round(ppq):
-
 
1271
                        item[0]['ppq'] = int(ppq)
-
 
1272
                    else:
-
 
1273
                        item[0]['ppq'] = round(ppq,2)
-
 
1274
                else:
-
 
1275
                    item[0]['ppq'] = 0
-
 
1276
            except:
-
 
1277
                item[0]['ppq'] = 0
-
 
1278
            if filterData is None:
-
 
1279
                if item[0]['category_id']!=6:
-
 
1280
                    try:
-
 
1281
                        item[0]['filterLinkBrand'] = '/category/'+str(int(item[0]['category_id']))+'?searchFor='+urllib.quote(item[0]['brand'])+'&filter=brand&brands='+str(int(item[0]['brand_id']))
-
 
1282
                        item[0]['filterTextBrand'] = (item[0]['brand'])
-
 
1283
                    except:
-
 
1284
                        pass
-
 
1285
                else:
-
 
1286
                    try:
-
 
1287
                        if item[0]['subCategory']=='' or item[0]['subCategory'] is None or item[0]['subCategoryId']==0:
-
 
1288
                            raise
-
 
1289
                        item[0]['filterLinkSubCategory'] = '/category/'+str(int(item[0]['category_id']))+'?searchFor='+urllib.quote(item[0]['subCategory'])+'&filter=subcategory&subcategories='+str(int(item[0]['subCategoryId']))
-
 
1290
                        item[0]['filterTextSubCategory'] = (item[0]['subCategory'])
-
 
1291
                        item[0]['filterLinkBrand'] = '/category/'+str(int(item[0]['category_id']))+'?searchFor='+urllib.quote(item[0]['brand'])+'&filter=brand&brands='+str(int(item[0]['brand_id']))
-
 
1292
                        item[0]['filterTextBrand'] = (item[0]['brand'])
-
 
1293
                    except:
-
 
1294
                        pass
-
 
1295
            try:
-
 
1296
                if item[0]['source_id']==4:
-
 
1297
                    item_availability_info = mc.get("item_availability_"+str(item[0]['identifier']).strip())
-
 
1298
                    if item_availability_info is None or len(item_availability_info)==0:
-
 
1299
                        item[0]['availabilityInfo'] = [{}]
-
 
1300
                    else:
-
 
1301
                        item[0]['availabilityInfo'] = item_availability_info
-
 
1302
            except:
-
 
1303
                item[0]['availabilityInfo'] = [{}]
-
 
1304
            
-
 
1305
            if item[0]['source_id']==4:
-
 
1306
                for av_info in item[0]['availabilityInfo']:
-
 
1307
                    if not av_info:
-
 
1308
                        continue
-
 
1309
                    av_info['cash_back'] = item[0]['cash_back']
-
 
1310
                    av_info['cash_back_type'] = item[0]['cash_back_type']
-
 
1311
                    netPriceAfterCashBack = av_info['sellingPrice'] 
-
 
1312
                    if av_info['cash_back_type'] ==1:
-
 
1313
                        netPriceAfterCashBack = av_info['sellingPrice'] - math.floor(float(av_info['sellingPrice'])*av_info['cash_back']/100)
-
 
1314
                    elif av_info['cash_back_type'] ==2:
-
 
1315
                        netPriceAfterCashBack = av_info['sellingPrice'] - math.floor(av_info['cash_back'])
-
 
1316
                    else:
-
 
1317
                        pass
-
 
1318
                    av_info['netPriceAfterCashBack'] = netPriceAfterCashBack
-
 
1319
                
-
 
1320
            #item[0]['netPriceAfterCashBack'] = d['netPriceAfterCashBack']
-
 
1321
            
-
 
1322
            if item[0]['source_id'] != SOURCE_MAP.get("PAYTM.COM"):
-
 
1323
                if item[0]['codAvailable'] ==1:
-
 
1324
                    paytmPrice = item[0]['available_price']
-
 
1325
                else:
-
 
1326
                    paytmPrice = item[0]['gross_price']
-
 
1327
                  
-
 
1328
                if item[0]['cash_back_type'] ==1:
-
 
1329
                    item[0]['netPriceAfterCashBack'] = paytmPrice -  math.floor(float(paytmPrice)*item[0]['cash_back']/100)
-
 
1330
                elif item[0]['cash_back_type'] ==2:
-
 
1331
                    item[0]['netPriceAfterCashBack'] = paytmPrice -  math.floor(item[0]['cash_back'])
-
 
1332
                else:
-
 
1333
                    item[0]['netPriceAfterCashBack'] = paytmPrice
-
 
1334
                
-
 
1335
            else:
-
 
1336
                if item[0]['cash_back_type'] ==1:
-
 
1337
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(float(item[0]['available_price'])*item[0]['cash_back']/100)
-
 
1338
                elif item[0]['cash_back_type'] ==2:
-
 
1339
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(item[0]['cash_back'])
-
 
1340
                else:
-
 
1341
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price']
-
 
1342
            
932
#             if specialOffer is not None and item[0]['source_id']==4:
1343
#             if specialOffer is not None and item[0]['source_id']==4:
933
#                 if item[0]['category_id'] in specialOffer.categories_applicable and item[0]['subCategoryId'] not in specialOffer.sub_categories_not_applicable:
1344
#                 if item[0]['category_id'] in specialOffer.categories_applicable and item[0]['subCategoryId'] not in specialOffer.sub_categories_not_applicable:
934
#                     item[0]['specialOffer'] = specialOffer.__dict__
1345
#                     item[0]['specialOffer'] = specialOffer.__dict__
935
#             else:
1346
#             else:
936
#                 item[0]['specialOffer'] = {}
1347
#                 item[0]['specialOffer'] = {}
Line 939... Line 1350...
939
        if len(temp) > 1:
1350
        if len(temp) > 1:
940
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
1351
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
941
        dealsListMap.append(temp)
1352
        dealsListMap.append(temp)
942
    return dealsListMap
1353
    return dealsListMap
943
 
1354
 
-
 
1355
 
944
def filterDeals(deals, filterData):
1356
def filterDeals(deals, filterData):
945
    print "Filter data ", filterData
1357
    print "Filter data ", filterData
946
    brandsFiltered = []
1358
    brandsFiltered = []
947
    subCategoryFiltered = []
1359
    subCategoryFiltered = []
948
    filterArray = filterData.split('|')
1360
    filterArray = filterData.split('|')
Line 1235... Line 1647...
1235
        return {0:"Data not updated."}
1647
        return {0:"Data not updated."}
1236
 
1648
 
1237
def resetCache(userId):
1649
def resetCache(userId):
1238
    try:
1650
    try:
1239
        mc.delete(userId)
1651
        mc.delete(userId)
-
 
1652
        mc.delete(userId+'_acc')
1240
        return {1:'Cache cleared.'}
1653
        return {1:'Cache cleared.'}
1241
    except:
1654
    except:
1242
        return {0:'Unable to clear cache.'}
1655
        return {0:'Unable to clear cache.'}
1243
    
1656
    
1244
def updateCollection(data):
1657
def updateCollection(data):
Line 2788... Line 3201...
2788
        return {}
3201
        return {}
2789
 
3202
 
2790
            
3203
            
2791
def main():
3204
def main():
2792
    resetCache("47")
3205
    resetCache("47")
2793
    getNewDeals(47, 3, 0, 10, None, None, None)
3206
    getAccesoryDeals(47, 6, 0, 20, None, None, None)
2794
    
3207
    
2795
if __name__=='__main__':
3208
if __name__=='__main__':
2796
    main()
3209
    main()
2797
 
3210
 
2798
 
3211