Subversion Repositories SmartDukaan

Rev

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

Rev 19511 Rev 19512
Line 7... Line 7...
7
    user_actions, Brands, app_offers, approved_app_transactions, user_app_cashbacks, \
7
    user_actions, Brands, app_offers, approved_app_transactions, user_app_cashbacks, \
8
    user_app_installs, appmasters, notification_campaigns
8
    user_app_installs, appmasters, notification_campaigns
9
from dtr.storage.MemCache import MemCache
9
from dtr.storage.MemCache import MemCache
10
from dtr.utils.MailSender import Email
10
from dtr.utils.MailSender import Email
11
from dtr.utils.utils import to_java_date, CB_PENDING, CB_APPROVED, CB_INIT, \
11
from dtr.utils.utils import to_java_date, CB_PENDING, CB_APPROVED, CB_INIT, \
12
    to_py_date, CB_REJECTED, SUB_CATEGORY_MAP,CREDIT_TYPE_REFUND,CREDIT_TYPE_OFFER,CREDIT_TYPE_ADJUSTMENT,REFUND_ADJUSTMENT_MAP
12
    to_py_date, CB_REJECTED, SUB_CATEGORY_MAP,CREDIT_TYPE_REFUND,CREDIT_TYPE_OFFER,CREDIT_TYPE_ADJUSTMENT,REFUND_ADJUSTMENT_MAP, todict
13
from sqlalchemy.sql.expression import func, func, or_, desc, asc, case
13
from sqlalchemy.sql.expression import func, func, or_, desc, asc, case
14
from elixir import *
14
from elixir import *
15
from operator import itemgetter
15
from operator import itemgetter
16
from pymongo.command_cursor import CommandCursor
16
from pymongo.command_cursor import CommandCursor
17
import pymongo
17
import pymongo
Line 364... Line 364...
364
def __constructDummyDealObject(skuBundleId):
364
def __constructDummyDealObject(skuBundleId):
365
    temp =[]
365
    temp =[]
366
    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})
366
    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})
367
    for d in deals:
367
    for d in deals:
368
        d['persPoints'] = 0
368
        d['persPoints'] = 0
369
        d['internalRank'] = 999999
-
 
370
        temp.append(d)
369
        temp.append(d)
371
    return temp
370
    return temp
372
    
371
    
373
    
372
    
374
 
373
 
Line 380... Line 379...
380
            
379
            
381
    except Exception as e:
380
    except Exception as e:
382
        print traceback.print_exc()
381
        print traceback.print_exc()
383
        featuredDeals = {3:{},5:{},6:{}}
382
        featuredDeals = {3:{},5:{},6:{}}
384
    
383
    
385
    
-
 
386
    #Not taking into account accessories
-
 
387
    featuredDeals.pop(6,None)
-
 
388
    
-
 
389
    fd_bundles = []
384
    fd_bundles = []
390
    
385
    
391
    for catMap in featuredDeals.itervalues():
386
    for catMap in featuredDeals.itervalues():
392
        for fd_map in catMap.itervalues():
387
        for fd_map in catMap.itervalues():
393
            if not fd_map.get('skuBundleId') in fd_bundles:
388
            if not fd_map.get('skuBundleId') in fd_bundles:
Line 397... Line 392...
397
    outer_query = []
392
    outer_query = []
398
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
393
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
399
    query = {}
394
    query = {}
400
    query['$gt'] = -100
395
    query['$gt'] = -100
401
    outer_query.append({'totalPoints':query})
396
    outer_query.append({'totalPoints':query})
402
    outer_query.append({'category_id':{"$in":[3,5]}})
-
 
403
    brandPrefMap = {}
397
    brandPrefMap = {}
404
    pricePrefMap = {}
398
    pricePrefMap = {}
405
    actionsMap = {}
399
    actionsMap = {}
406
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
400
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
407
    for x in brand_p:
401
    for x in brand_p:
Line 421... Line 415...
421
    for x in session.query(user_actions).filter_by(user_id=userId).all():
415
    for x in session.query(user_actions).filter_by(user_id=userId).all():
422
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
416
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
423
    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)]))
417
    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)]))
424
    mobile_deals = []
418
    mobile_deals = []
425
    tablet_deals = []
419
    tablet_deals = []
426
    #accessories_deals = []
420
    accessories_deals = []
427
    for deal in all_deals:
421
    for deal in all_deals:
428
 
422
 
429
        try:
423
        try:
430
            fd_bundles.remove(deal.get('skuBundleId'))
424
            fd_bundles.remove(deal.get('skuBundleId'))
431
        except:
425
        except:
Line 464... Line 458...
464
        
458
        
465
        if deal['category_id'] ==3:
459
        if deal['category_id'] ==3:
466
            mobile_deals.append(deal)
460
            mobile_deals.append(deal)
467
        elif deal['category_id'] ==5:
461
        elif deal['category_id'] ==5:
468
            tablet_deals.append(deal)
462
            tablet_deals.append(deal)
469
        #elif deal['category_id'] ==6:
463
        elif deal['category_id'] ==6:
470
        #    accessories_deals.append(deal)
464
            accessories_deals.append(deal)
471
        else:
465
        else:
472
            continue
466
            continue
473
    
467
    
474
    session.close()
468
    session.close()
475
    
469
    
476
    mobile_deals = sorted(mobile_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
470
    mobile_deals = sorted(mobile_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
477
    tablet_deals = sorted(tablet_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
471
    tablet_deals = sorted(tablet_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
478
    #accessories_deals = sorted(accessories_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
472
    accessories_deals = sorted(accessories_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
479
    
473
    
480
    
474
    
481
    if len(fd_bundles) > 0:
475
    if len(fd_bundles) > 0:
482
        print "There is still bundle in feature deals with points less than -100.Lets add info"
476
        print "There is still bundle in feature deals with points less than -100.Lets add info"
483
        for skuBundleId in fd_bundles:
477
        for skuBundleId in fd_bundles:
Line 485... Line 479...
485
            for dummyDealObj in dummyDealObjList:
479
            for dummyDealObj in dummyDealObjList:
486
                if dummyDealObj['category_id'] ==3:
480
                if dummyDealObj['category_id'] ==3:
487
                    mobile_deals.append(dummyDealObj)
481
                    mobile_deals.append(dummyDealObj)
488
                elif dummyDealObj['category_id'] ==5:
482
                elif dummyDealObj['category_id'] ==5:
489
                    tablet_deals.append(dummyDealObj)
483
                    tablet_deals.append(dummyDealObj)
490
                #elif dummyDealObj['category_id'] ==6:
484
                elif dummyDealObj['category_id'] ==6:
491
                #    accessories_deals.append(dummyDealObj)
485
                    accessories_deals.append(dummyDealObj)
492
                else:
486
                else:
493
                    pass
487
                    pass
494
    
488
    
495
    for super_category, categoryFeaturedDeals in featuredDeals.iteritems():
489
    for super_category, categoryFeaturedDeals in featuredDeals.iteritems():
496
        for val in categoryFeaturedDeals.itervalues():
490
        for val in categoryFeaturedDeals.itervalues():
Line 501... Line 495...
501
                
495
                
502
                if super_category ==3:
496
                if super_category ==3:
503
                    mobile_deals.append(dummyDealObj)
497
                    mobile_deals.append(dummyDealObj)
504
                elif super_category ==5:
498
                elif super_category ==5:
505
                    tablet_deals.append(dummyDealObj)
499
                    tablet_deals.append(dummyDealObj)
506
                #elif super_category ==6:
500
                elif super_category ==6:
507
                #    accessories_deals.append(dummyDealObj)
501
                    accessories_deals.append(dummyDealObj)
508
                else:
502
                else:
509
                    pass
503
                    pass
510
 
504
 
511
    sortedMapMobiles = {}
505
    sortedMapMobiles = {}
512
    rankMapMobiles = {}
506
    rankMapMobiles = {}
Line 595... Line 589...
595
    for rank in blockedRanksTablets:
589
    for rank in blockedRanksTablets:
596
        if blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId')) is not None:
590
        if blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId')) is not None:
597
            rankMapTablets[rank] = blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId'))
591
            rankMapTablets[rank] = blockedInfoTablets.get((featuredDealsTablets.get(rank+1)).get('skuBundleId'))
598
            
592
            
599
    
593
    
600
#     sortedMapAccessories = {}
-
 
601
#     rankMapAccessories = {}
-
 
602
#     rankAccessories = 0
-
 
603
#     
-
 
604
#     blockedRanksAccessories = []
-
 
605
#     blockedSkuBundlesAccessories = []
-
 
606
#     blockedInfoAccessories = {}
-
 
607
#     
-
 
608
#     featuredDealsAccessories = featuredDeals.get(6)
-
 
609
#     
-
 
610
#     for k, v in featuredDealsAccessories.iteritems():
-
 
611
#         blockedRanksAccessories.append(k-1)
-
 
612
#         blockedSkuBundlesAccessories.append(v.get('skuBundleId'))
-
 
613
#     
-
 
614
#     
-
 
615
#     for sorted_deal in accessories_deals:
-
 
616
#        
-
 
617
#         while(True):
-
 
618
#             if rankAccessories in blockedRanksAccessories:
-
 
619
#                 rankAccessories = rankAccessories +1
-
 
620
#             else:
-
 
621
#                 break
-
 
622
#              
-
 
623
#         if sorted_deal['skuBundleId'] in blockedSkuBundlesAccessories:
-
 
624
#             if blockedInfoAccessories.has_key(sorted_deal['skuBundleId']):
-
 
625
#                 blockedInfoAccessories.get(sorted_deal['skuBundleId']).append(sorted_deal)
-
 
626
#             else:
-
 
627
#                 blockedInfoAccessories[sorted_deal['skuBundleId']] = [sorted_deal]
-
 
628
#             continue
-
 
629
#          
-
 
630
#         if sortedMapAccessories.get(sorted_deal['skuBundleId']) is None:
-
 
631
#             sortedMapAccessories[sorted_deal['skuBundleId']] = {rankAccessories:[sorted_deal]}
-
 
632
#             rankMapAccessories[rankAccessories] = (sortedMapAccessories[sorted_deal['skuBundleId']].values())[0]
-
 
633
#             rankAccessories = rankAccessories +1
-
 
634
#         else:
-
 
635
#             for temp_list in sortedMapAccessories.get(sorted_deal['skuBundleId']).itervalues():
-
 
636
#                 temp_list.append(sorted_deal)
-
 
637
#             rankMapAccessories[(sortedMapAccessories.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
-
 
638
#     
-
 
639
#             
-
 
640
#     for rank in blockedRanksAccessories:
-
 
641
#         if blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId')) is not None:
-
 
642
#             rankMapAccessories[rank] = blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId'))
-
 
643
#     
-
 
644
    specialOffer = None
-
 
645
    promoOffer = get_mongo_connection().Catalog.PromoOffer.find_one({'user_id':userId})
-
 
646
    try:
-
 
647
        if promoOffer is not None:
-
 
648
            offer = get_mongo_connection().Catalog.Promotions.find_one({'_id':promoOffer.get('offer_id')})
-
 
649
            if offer is None:
-
 
650
                raise
-
 
651
            promo = Promotion(offer.get('_id'),offer.get('offer_name'),offer.get('offer_description') , offer.get('categories_applicable'), offer.get('sub_categories_not_applicable'),
-
 
652
                     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'),
-
 
653
                     promoOffer.get('pending_order_value'), promoOffer.get('delivered_order_value'), promoOffer.get('last_run_timestamp'))
-
 
654
    
-
 
655
            specialOffer = promo
-
 
656
    except:
-
 
657
        traceback.print_exc()
-
 
658
    
-
 
659
    
-
 
660
    mem_cache_val = {3:mobile_deals, 5:tablet_deals,"3_rankMap": rankMapMobiles,"5_rankMap": rankMapTablets, "specialOffer":specialOffer }
-
 
661
    mc.set(str(userId), mem_cache_val)
-
 
662
    
-
 
663
def __populateCacheForAccessories(userId):
-
 
664
    try:
-
 
665
        if mc.get("featured_deals") is None:
-
 
666
            __populateFeaturedDeals()
-
 
667
        featuredDeals = mc.get("featured_deals")
-
 
668
            
-
 
669
    except Exception as e:
-
 
670
        print traceback.print_exc()
-
 
671
        featuredDeals = {3:{},5:{},6:{}}
-
 
672
    
-
 
673
    
-
 
674
    #Not taking into account mobiles, tablets
-
 
675
    featuredDeals.pop(3,None)
-
 
676
    featuredDeals.pop(5,None)
-
 
677
    
-
 
678
    fd_bundles = []
-
 
679
    
-
 
680
    for catMap in featuredDeals.itervalues():
-
 
681
        for fd_map in catMap.itervalues():
-
 
682
            if not fd_map.get('skuBundleId') in fd_bundles:
-
 
683
                fd_bundles.append(fd_map.get('skuBundleId'))
-
 
684
    
-
 
685
    print "Populating accessory memcache for userId",userId
-
 
686
    outer_query = []
-
 
687
    outer_query.append({ "$or": [ { "showDeal": 1} , { "prepaidDeal": 1 } ] })
-
 
688
    query = {}
-
 
689
    query['$gte'] = 0
-
 
690
    outer_query.append({'internalRank':query})
-
 
691
    outer_query.append({'category_id':{"$in":[6]}})
-
 
692
 
-
 
693
    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)]))
-
 
694
    
-
 
695
    actionsMap = {}
-
 
696
    
-
 
697
    actionRank = 3
-
 
698
    for x in session.query(user_actions).filter_by(user_id=userId).order_by(asc(user_actions.created)).all():
-
 
699
        #actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
-
 
700
        action = 1 if x.action == 'like' else 0
-
 
701
        if action==1:
-
 
702
            actionsMap[x.store_product_id] = {'action':action,'rank':actionRank}
-
 
703
            actionRank = actionRank+3
-
 
704
        else:
-
 
705
            actionsMap[x.store_product_id] = {'action':action,'rank':None}
-
 
706
    
-
 
707
    session.close()
-
 
708
    
-
 
709
    psuedo_count = 1
-
 
710
 
-
 
711
    if actionsMap:
-
 
712
        for k,v in actionsMap.iteritems():
-
 
713
            if v['action'] == 0:
-
 
714
                tmp_deal = get_mongo_connection().Catalog.Deals.find_one({'_id':k})
-
 
715
                if tmp_deal is None:
-
 
716
                    v['rank'] = 999999
-
 
717
                    continue
-
 
718
                max_rank = list(get_mongo_connection().Catalog.Deals.find({'subCategoryId':tmp_deal.get('subCategoryId')}).sort([('internalRank',pymongo.DESCENDING)]).limit(1))
-
 
719
                if len(max_rank) == 0 or max_rank[0].get('internalRank') is None:
-
 
720
                    v['rank'] = 999999
-
 
721
                    continue
-
 
722
                v['rank'] = max_rank[0]['internalRank'] + 1
-
 
723
                 
-
 
724
    for deal in accessories_deals:
-
 
725
 
-
 
726
        try:
-
 
727
            fd_bundles.remove(deal.get('skuBundleId'))
-
 
728
        except:
-
 
729
            pass
-
 
730
        if actionsMap and actionsMap.get(deal['_id'])!=None:
-
 
731
            if actionsMap.get(deal['_id']).get('action') ==1:
-
 
732
                actionRank = actionsMap.get(deal['_id']).get('rank')
-
 
733
                if actionRank < psuedo_count:
-
 
734
                    deal['internalRank'] = actionRank
-
 
735
                
-
 
736
            elif actionsMap.get(deal['_id']).get('action') ==0:
-
 
737
                actionRank = actionsMap.get(deal['_id']).get('rank')
-
 
738
                deal['internalRank'] = actionRank
-
 
739
            else:
-
 
740
                pass
-
 
741
        psuedo_count = psuedo_count+1
-
 
742
    
-
 
743
    if actionsMap:
-
 
744
        accessories_deals = sorted(accessories_deals, key = lambda x: (-x['internalRank'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints']),reverse=True)
-
 
745
    
-
 
746
    if len(fd_bundles) > 0:
-
 
747
        print "There is still bundle in feature deals.Lets add info"
-
 
748
        for skuBundleId in fd_bundles:
-
 
749
            dummyDealObjList = __constructDummyDealObject(skuBundleId)
-
 
750
            for dummyDealObj in dummyDealObjList:
-
 
751
                if dummyDealObj['category_id'] ==6:
-
 
752
                    accessories_deals.append(dummyDealObj)
-
 
753
    
-
 
754
    for super_category, categoryFeaturedDeals in featuredDeals.iteritems():
-
 
755
        for val in categoryFeaturedDeals.itervalues():
-
 
756
            dummyDealObjList = __constructDummyDealObject(val.get('skuBundleId'))
-
 
757
            for dummyDealObj in dummyDealObjList:
-
 
758
                if super_category == dummyDealObj['category_id']:
-
 
759
                    continue  
-
 
760
                if super_category ==6:
-
 
761
                    accessories_deals.append(dummyDealObj)
-
 
762
 
-
 
763
    
-
 
764
    sortedMapAccessories = {}
594
    sortedMapAccessories = {}
765
    rankMapAccessories = {}
595
    rankMapAccessories = {}
766
    rankAccessories = 0
596
    rankAccessories = 0
767
     
597
    
768
    blockedRanksAccessories = []
598
    blockedRanksAccessories = []
769
    blockedSkuBundlesAccessories = []
599
    blockedSkuBundlesAccessories = []
770
    blockedInfoAccessories = {}
600
    blockedInfoAccessories = {}
771
     
601
    
772
    featuredDealsAccessories = featuredDeals.get(6)
602
    featuredDealsAccessories = featuredDeals.get(6)
773
     
603
    
774
    for k, v in featuredDealsAccessories.iteritems():
604
    for k, v in featuredDealsAccessories.iteritems():
775
        blockedRanksAccessories.append(k-1)
605
        blockedRanksAccessories.append(k-1)
776
        blockedSkuBundlesAccessories.append(v.get('skuBundleId'))
606
        blockedSkuBundlesAccessories.append(v.get('skuBundleId'))
777
     
607
    
778
     
608
    
779
    for sorted_deal in accessories_deals:
609
    for sorted_deal in accessories_deals:
780
        
610
       
781
        while(True):
611
        while(True):
782
            if rankAccessories in blockedRanksAccessories:
612
            if rankAccessories in blockedRanksAccessories:
783
                rankAccessories = rankAccessories +1
613
                rankAccessories = rankAccessories +1
784
            else:
614
            else:
785
                break
615
                break
786
              
616
             
787
        if sorted_deal['skuBundleId'] in blockedSkuBundlesAccessories:
617
        if sorted_deal['skuBundleId'] in blockedSkuBundlesAccessories:
788
            if blockedInfoAccessories.has_key(sorted_deal['skuBundleId']):
618
            if blockedInfoAccessories.has_key(sorted_deal['skuBundleId']):
789
                blockedInfoAccessories.get(sorted_deal['skuBundleId']).append(sorted_deal)
619
                blockedInfoAccessories.get(sorted_deal['skuBundleId']).append(sorted_deal)
790
            else:
620
            else:
791
                blockedInfoAccessories[sorted_deal['skuBundleId']] = [sorted_deal]
621
                blockedInfoAccessories[sorted_deal['skuBundleId']] = [sorted_deal]
792
            continue
622
            continue
793
          
623
         
794
        if sortedMapAccessories.get(sorted_deal['skuBundleId']) is None:
624
        if sortedMapAccessories.get(sorted_deal['skuBundleId']) is None:
795
            sortedMapAccessories[sorted_deal['skuBundleId']] = {rankAccessories:[sorted_deal]}
625
            sortedMapAccessories[sorted_deal['skuBundleId']] = {rankAccessories:[sorted_deal]}
796
            rankMapAccessories[rankAccessories] = (sortedMapAccessories[sorted_deal['skuBundleId']].values())[0]
626
            rankMapAccessories[rankAccessories] = (sortedMapAccessories[sorted_deal['skuBundleId']].values())[0]
797
            rankAccessories = rankAccessories +1
627
            rankAccessories = rankAccessories +1
798
        else:
628
        else:
799
            for temp_list in sortedMapAccessories.get(sorted_deal['skuBundleId']).itervalues():
629
            for temp_list in sortedMapAccessories.get(sorted_deal['skuBundleId']).itervalues():
800
                temp_list.append(sorted_deal)
630
                temp_list.append(sorted_deal)
801
            rankMapAccessories[(sortedMapAccessories.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
631
            rankMapAccessories[(sortedMapAccessories.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
802
     
632
    
803
             
633
            
804
    for rank in blockedRanksAccessories:
634
    for rank in blockedRanksAccessories:
805
        if blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId')) is not None:
635
        if blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId')) is not None:
806
            rankMapAccessories[rank] = blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId'))
636
            rankMapAccessories[rank] = blockedInfoAccessories.get((featuredDealsAccessories.get(rank+1)).get('skuBundleId'))
807
     
637
    
808
    specialOffer = None
638
    specialOffer = None
809
    promoOffer = get_mongo_connection().Catalog.PromoOffer.find_one({'user_id':userId})
639
    promoOffer = get_mongo_connection().Catalog.PromoOffer.find_one({'user_id':userId})
810
    try:
640
    try:
811
        if promoOffer is not None:
641
        if promoOffer is not None:
812
            offer = get_mongo_connection().Catalog.Promotions.find_one({'_id':promoOffer.get('offer_id')})
642
            offer = get_mongo_connection().Catalog.Promotions.find_one({'_id':promoOffer.get('offer_id')})
Line 816... Line 646...
816
                     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'),
646
                     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'),
817
                     promoOffer.get('pending_order_value'), promoOffer.get('delivered_order_value'), promoOffer.get('last_run_timestamp'))
647
                     promoOffer.get('pending_order_value'), promoOffer.get('delivered_order_value'), promoOffer.get('last_run_timestamp'))
818
    
648
    
819
            specialOffer = promo
649
            specialOffer = promo
820
    except:
650
    except:
821
        traceback.print_exc()
651
        pass
822
    
652
    
823
    
653
    
824
    mem_cache_val = {6:accessories_deals,"6_rankMap": rankMapAccessories, "specialOffer":specialOffer }
654
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 6: accessories_deals,"3_rankMap": rankMapMobiles,"5_rankMap": rankMapTablets,"6_rankMap": rankMapAccessories, "specialOffer":specialOffer }
825
    mc.set(str(userId)+'_acc', mem_cache_val)
655
    mc.set(str(userId), mem_cache_val)
826
 
-
 
827
    
656
    
828
 
657
 
829
def __populateFeaturedDeals():
658
def __populateFeaturedDeals():
830
    print "Populating featured deals....."
659
    print "Populating featured deals....."
831
    featuredDealsMobiles = {}
660
    featuredDealsMobiles = {}
Line 971... Line 800...
971
                
800
                
972
                rankCounter = rankCounter+1
801
                rankCounter = rankCounter+1
973
                if (fd_dealObject.get(category_id).get(rankCounter)) is not None:
802
                if (fd_dealObject.get(category_id).get(rankCounter)) is not None:
974
                    if (fd_dealObject.get(category_id).get(rankCounter).get('offer_id') !=0):
803
                    if (fd_dealObject.get(category_id).get(rankCounter).get('offer_id') !=0):
975
                        #Check whether user can see offer
804
                        #Check whether user can see offer
976
                        if specialOffer is None or specialOffer.endDate < to_java_date(datetime.now()):
805
                        if specialOffer is None or specialOffer.endDate > to_java_date(datetime.now()):
977
                            continue
806
                            continue
978
                    deal_object_temp = []
807
                    deal_object_temp = []
979
                    deal_object_temp.append(fd_dealObject.get(category_id).get(rankCounter).get('object'))
808
                    deal_object_temp.append(fd_dealObject.get(category_id).get(rankCounter).get('object'))
980
                    dealsListMap.append(deal_object_temp)
809
                    dealsListMap.append(deal_object_temp)
981
                else:
810
                else:
Line 1110... Line 939...
1110
                elif item[0]['cash_back_type'] ==2:
939
                elif item[0]['cash_back_type'] ==2:
1111
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(item[0]['cash_back'])
940
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(item[0]['cash_back'])
1112
                else:
941
                else:
1113
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price']
942
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price']
1114
            
943
            
1115
            temp.append(item[0])
-
 
1116
        if len(temp) > 1:
-
 
1117
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
-
 
1118
        dealsListMap.append(temp)
-
 
1119
    return dealsListMap
-
 
1120
 
-
 
1121
 
-
 
1122
def getAccesoryDeals(userId, category_id, offset, limit, sort, direction, filterData=None):
-
 
1123
    if mc.get("category_cash_back") is None or not bool(mc.get("category_cash_back")):
-
 
1124
        populateCashBack()
-
 
1125
    
-
 
1126
    dealsListMap = []
-
 
1127
    user_specific_deals = mc.get(str(userId)+'_acc')
-
 
1128
    if user_specific_deals is None:
-
 
1129
        __populateCacheForAccessories(userId)
-
 
1130
        user_specific_deals = mc.get(str(userId)+'_acc')
-
 
1131
    else:
-
 
1132
        print "Getting user deals from accessory cache"
-
 
1133
    category_specific_deals = user_specific_deals.get(category_id)
-
 
1134
    
-
 
1135
    insert_featured_deals = False
-
 
1136
    if sort is None or direction is None:
-
 
1137
        insert_featured_deals = True
-
 
1138
        rankMap = user_specific_deals.get(str(category_id)+"_rankMap")
-
 
1139
    else:
-
 
1140
        if sort == "bestSellerPoints":
-
 
1141
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['internalRank'], x['nlcPoints']),reverse=True)
-
 
1142
        else:
-
 
1143
            if direction == -1:
-
 
1144
                rev = True
-
 
1145
            else:
-
 
1146
                rev = False
-
 
1147
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
-
 
1148
    
-
 
1149
    
-
 
1150
    filtered_deals = []
-
 
1151
    dataExist = True
-
 
1152
    if filterData is not None:
-
 
1153
        try:
-
 
1154
            filtered_deals = filterDeals(category_specific_deals, filterData)
-
 
1155
            if len(filtered_deals)==0:
-
 
1156
                dataExist = False
-
 
1157
        except:
-
 
1158
            traceback.print_exc()
-
 
1159
    if dataExist:
-
 
1160
    
-
 
1161
        if not insert_featured_deals:
-
 
1162
            sortedMap = {}
-
 
1163
            rankMap = {}
-
 
1164
            rank = 0
-
 
1165
            for sorted_deal in sorted_deals:
-
 
1166
                
-
 
1167
                if len(filtered_deals) > 0 and  sorted_deal['skuBundleId'] not in filtered_deals:
-
 
1168
                    continue
-
 
1169
                
-
 
1170
                if sortedMap.get(sorted_deal['skuBundleId']) is None:
-
 
1171
                    sortedMap[sorted_deal['skuBundleId']] = {rank:[sorted_deal]}
-
 
1172
                    rankMap[rank] = (sortedMap[sorted_deal['skuBundleId']].values())[0]
-
 
1173
                    rank = rank +1
-
 
1174
                else:
-
 
1175
                    for temp_list in sortedMap.get(sorted_deal['skuBundleId']).itervalues():
-
 
1176
                        temp_list.append(sorted_deal)
-
 
1177
                    rankMap[(sortedMap.get(sorted_deal['skuBundleId']).keys())[0]] = temp_list
-
 
1178
        else:
-
 
1179
            filterMap = {}
-
 
1180
            rank = 0
-
 
1181
            if len(filtered_deals) > 0:
-
 
1182
                try:
-
 
1183
                    od = collections.OrderedDict(sorted(rankMap.items()))
-
 
1184
                except:
-
 
1185
                    od = ordereddict.OrderedDict(sorted(rankMap.items()))
-
 
1186
                for k, v in od.iteritems():
-
 
1187
                    if v[0].get('skuBundleId') in filtered_deals:
-
 
1188
                        filterMap[rank] = v
-
 
1189
                        rank =rank+1
-
 
1190
                rankMap = filterMap
-
 
1191
        
-
 
1192
        rankCounter = offset
-
 
1193
        if filterData is None:
-
 
1194
            if mc.get("featured_deals_deal_object") is None or not bool(mc.get("featured_deals_deal_object")):
-
 
1195
                try:
-
 
1196
                    __populateFeaturedDealsForDealObject()
-
 
1197
                    fd_dealObject = mc.get("featured_deals_deal_object")
-
 
1198
                except:
-
 
1199
                    fd_dealObject = {3:{},5:{},6:{}}
-
 
1200
            else:
-
 
1201
                fd_dealObject = mc.get("featured_deals_deal_object")
-
 
1202
        
-
 
1203
    else:
-
 
1204
        rankMap = {}
-
 
1205
    
-
 
1206
    
-
 
1207
    specialOffer = user_specific_deals.get('specialOffer')
-
 
1208
    
-
 
1209
    for dealList in [rankMap.get(k, []) for k in range(offset, offset+limit)]:
-
 
1210
        if filterData is None:
-
 
1211
            while(True):
-
 
1212
                
-
 
1213
                rankCounter = rankCounter+1
-
 
1214
                if (fd_dealObject.get(category_id).get(rankCounter)) is not None:
-
 
1215
                    if (fd_dealObject.get(category_id).get(rankCounter).get('offer_id') !=0):
-
 
1216
                        #Check whether user can see offer
-
 
1217
                        if specialOffer is None or specialOffer.endDate < to_java_date(datetime.now()):
-
 
1218
                            continue
-
 
1219
                    deal_object_temp = []
-
 
1220
                    deal_object_temp.append(fd_dealObject.get(category_id).get(rankCounter).get('object'))
-
 
1221
                    dealsListMap.append(deal_object_temp)
-
 
1222
                else:
-
 
1223
                    break
-
 
1224
            
-
 
1225
        temp = []
-
 
1226
        if dealList is None or len(dealList)==0:
-
 
1227
            continue
-
 
1228
        for d in dealList:
-
 
1229
            item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
-
 
1230
            if len(item) ==0:
-
 
1231
                continue
-
 
1232
            if d['dealType'] == 1 and d['source_id'] ==1:
-
 
1233
                try:
-
 
1234
                    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())}}))
-
 
1235
                    item[0]['marketPlaceUrl'] = manualDeal[0]['dealUrl'].strip()
-
 
1236
                except:
-
 
1237
                    pass
-
 
1238
            elif d['source_id'] ==3:
-
 
1239
                item[0]['marketPlaceUrl'] = item[0]['marketPlaceUrl']+'?supc='+item[0].get('identifier')
-
 
1240
            else:
-
 
1241
                pass 
-
 
1242
            try:
-
 
1243
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
-
 
1244
                if not cashBack or cashBack.get('cash_back_status')!=1:
-
 
1245
                    item[0]['cash_back_type'] = 0
-
 
1246
                    item[0]['cash_back'] = 0
-
 
1247
                else:
-
 
1248
                    if cashBack.get('maxCashBack') is not None:
-
 
1249
                        
-
 
1250
                        if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*item[0]['available_price'])/100 > cashBack.get('maxCashBack'):
-
 
1251
                            cashBack['cash_back_type'] = 2
-
 
1252
                            cashBack['cash_back'] = cashBack['maxCashBack']
-
 
1253
                        elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):
-
 
1254
                            cashBack['cash_back'] = cashBack['maxCashBack']
-
 
1255
                    
-
 
1256
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
-
 
1257
                    item[0]['cash_back'] = cashBack['cash_back']
-
 
1258
            except:
-
 
1259
                print "Error in adding cashback to deals"
-
 
1260
                item[0]['cash_back_type'] = 0
-
 
1261
                item[0]['cash_back'] = 0
-
 
1262
            try:
-
 
1263
                item[0]['dp'] = d['dp']
-
 
1264
                item[0]['showDp'] = d['showDp']
-
 
1265
            except:
-
 
1266
                item[0]['dp'] = 0.0
-
 
1267
                item[0]['showDp'] = 0
-
 
1268
            try:
-
 
1269
                item[0]['thumbnail'] = item[0]['thumbnail'].strip()
-
 
1270
            except:
-
 
1271
                pass
-
 
1272
            
-
 
1273
            try:
-
 
1274
                if item[0]['showVideo']==0:
-
 
1275
                    item[0]['videoLink'] =""
-
 
1276
            except:
-
 
1277
                item[0]['videoLink'] =""
-
 
1278
            try:
-
 
1279
                if item[0]['quantity'] >1:
-
 
1280
                    ppq = float(item[0]['available_price'])/item[0]['quantity']
-
 
1281
                     
-
 
1282
                    if ppq == round(ppq):
-
 
1283
                        item[0]['ppq'] = int(ppq)
-
 
1284
                    else:
-
 
1285
                        item[0]['ppq'] = round(ppq,2)
-
 
1286
                else:
-
 
1287
                    item[0]['ppq'] = 0
-
 
1288
            except:
-
 
1289
                item[0]['ppq'] = 0
-
 
1290
            if filterData is None:
-
 
1291
                if item[0]['category_id']!=6:
-
 
1292
                    try:
-
 
1293
                        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']))
-
 
1294
                        item[0]['filterTextBrand'] = (item[0]['brand'])
-
 
1295
                    except:
-
 
1296
                        pass
-
 
1297
                else:
-
 
1298
                    try:
-
 
1299
                        if item[0]['subCategory']=='' or item[0]['subCategory'] is None or item[0]['subCategoryId']==0:
-
 
1300
                            raise
-
 
1301
                        item[0]['filterLinkSubCategory'] = '/category/'+str(int(item[0]['category_id']))+'?searchFor='+urllib.quote(item[0]['subCategory'])+'&filter=subcategory&subcategories='+str(int(item[0]['subCategoryId']))
-
 
1302
                        item[0]['filterTextSubCategory'] = (item[0]['subCategory'])
-
 
1303
                        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']))
-
 
1304
                        item[0]['filterTextBrand'] = (item[0]['brand'])
-
 
1305
                    except:
-
 
1306
                        pass
-
 
1307
            try:
-
 
1308
                if item[0]['source_id']==4:
-
 
1309
                    item_availability_info = mc.get("item_availability_"+str(item[0]['identifier']).strip())
-
 
1310
                    if item_availability_info is None or len(item_availability_info)==0:
-
 
1311
                        item[0]['availabilityInfo'] = [{}]
-
 
1312
                    else:
-
 
1313
                        item[0]['availabilityInfo'] = item_availability_info
-
 
1314
            except:
-
 
1315
                item[0]['availabilityInfo'] = [{}]
-
 
1316
            
-
 
1317
            if item[0]['source_id']==4:
-
 
1318
                for av_info in item[0]['availabilityInfo']:
-
 
1319
                    if not av_info:
-
 
1320
                        continue
-
 
1321
                    av_info['cash_back'] = item[0]['cash_back']
-
 
1322
                    av_info['cash_back_type'] = item[0]['cash_back_type']
-
 
1323
                    netPriceAfterCashBack = av_info['sellingPrice'] 
-
 
1324
                    if av_info['cash_back_type'] ==1:
-
 
1325
                        netPriceAfterCashBack = av_info['sellingPrice'] - math.floor(float(av_info['sellingPrice'])*av_info['cash_back']/100)
-
 
1326
                    elif av_info['cash_back_type'] ==2:
-
 
1327
                        netPriceAfterCashBack = av_info['sellingPrice'] - math.floor(av_info['cash_back'])
-
 
1328
                    else:
-
 
1329
                        pass
-
 
1330
                    av_info['netPriceAfterCashBack'] = netPriceAfterCashBack
-
 
1331
                
-
 
1332
            #item[0]['netPriceAfterCashBack'] = d['netPriceAfterCashBack']
-
 
1333
            
-
 
1334
            if item[0]['source_id'] != SOURCE_MAP.get("PAYTM.COM"):
-
 
1335
                if item[0]['codAvailable'] ==1:
-
 
1336
                    paytmPrice = item[0]['available_price']
-
 
1337
                else:
-
 
1338
                    paytmPrice = item[0]['gross_price']
-
 
1339
                  
-
 
1340
                if item[0]['cash_back_type'] ==1:
-
 
1341
                    item[0]['netPriceAfterCashBack'] = paytmPrice -  math.floor(float(paytmPrice)*item[0]['cash_back']/100)
-
 
1342
                elif item[0]['cash_back_type'] ==2:
-
 
1343
                    item[0]['netPriceAfterCashBack'] = paytmPrice -  math.floor(item[0]['cash_back'])
-
 
1344
                else:
-
 
1345
                    item[0]['netPriceAfterCashBack'] = paytmPrice
-
 
1346
                
-
 
1347
            else:
-
 
1348
                if item[0]['cash_back_type'] ==1:
-
 
1349
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(float(item[0]['available_price'])*item[0]['cash_back']/100)
-
 
1350
                elif item[0]['cash_back_type'] ==2:
-
 
1351
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price'] -  math.floor(item[0]['cash_back'])
-
 
1352
                else:
-
 
1353
                    item[0]['netPriceAfterCashBack'] = item[0]['available_price']
-
 
1354
            
-
 
1355
#             if specialOffer is not None and item[0]['source_id']==4:
944
#             if specialOffer is not None and item[0]['source_id']==4:
1356
#                 if item[0]['category_id'] in specialOffer.categories_applicable and item[0]['subCategoryId'] not in specialOffer.sub_categories_not_applicable:
945
#                 if item[0]['category_id'] in specialOffer.categories_applicable and item[0]['subCategoryId'] not in specialOffer.sub_categories_not_applicable:
1357
#                     item[0]['specialOffer'] = specialOffer.__dict__
946
#                     item[0]['specialOffer'] = specialOffer.__dict__
1358
#             else:
947
#             else:
1359
#                 item[0]['specialOffer'] = {}
948
#                 item[0]['specialOffer'] = {}
Line 1362... Line 951...
1362
        if len(temp) > 1:
951
        if len(temp) > 1:
1363
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
952
            temp = sorted(temp, key = lambda x: (x['available_price']),reverse=False)
1364
        dealsListMap.append(temp)
953
        dealsListMap.append(temp)
1365
    return dealsListMap
954
    return dealsListMap
1366
 
955
 
1367
 
-
 
1368
def filterDeals(deals, filterData):
956
def filterDeals(deals, filterData):
1369
    print "Filter data ", filterData
957
    print "Filter data ", filterData
1370
    brandsFiltered = []
958
    brandsFiltered = []
1371
    subCategoryFiltered = []
959
    subCategoryFiltered = []
1372
    filterArray = filterData.split('|')
960
    filterArray = filterData.split('|')
Line 1659... Line 1247...
1659
        return {0:"Data not updated."}
1247
        return {0:"Data not updated."}
1660
 
1248
 
1661
def resetCache(userId):
1249
def resetCache(userId):
1662
    try:
1250
    try:
1663
        mc.delete(userId)
1251
        mc.delete(userId)
1664
        mc.delete(userId+'_acc')
-
 
1665
        return {1:'Cache cleared.'}
1252
        return {1:'Cache cleared.'}
1666
    except:
1253
    except:
1667
        return {0:'Unable to clear cache.'}
1254
        return {0:'Unable to clear cache.'}
1668
    
1255
    
1669
def updateCollection(data):
1256
def updateCollection(data):
Line 3245... Line 2832...
3245
 
2832
 
3246
def fetchCrmRefundByBatchId(batchId):
2833
def fetchCrmRefundByBatchId(batchId):
3247
    cursor = get_mongo_connection().Dtr.crmrefundwallet.find_one({"batchId":int(batchId)})
2834
    cursor = get_mongo_connection().Dtr.crmrefundwallet.find_one({"batchId":int(batchId)})
3248
    return cursor
2835
    return cursor
3249
 
2836
 
3250
def todict(obj, classkey=None):
-
 
3251
    if isinstance(obj, dict):
-
 
3252
        data = {}
-
 
3253
        for (k, v) in obj.items():
-
 
3254
            data[k] = todict(v, classkey)
-
 
3255
        return data
-
 
3256
    elif hasattr(obj, "_ast"):
-
 
3257
        return todict(obj._ast())
-
 
3258
    elif hasattr(obj, "__iter__"):
-
 
3259
        return [todict(v, classkey) for v in obj]
-
 
3260
    elif hasattr(obj, "__dict__"):
-
 
3261
        data = dict([(key, todict(value, classkey)) 
-
 
3262
            for key, value in obj.__dict__.iteritems() 
-
 
3263
            if not callable(value) and not key.startswith('_')])
-
 
3264
        if classkey is not None and hasattr(obj, "__class__"):
-
 
3265
            data[classkey] = obj.__class__.__name__
-
 
3266
        return data
-
 
3267
    else:
-
 
3268
        return obj
-
 
3269
 
2837
 
3270
def main():
2838
def main():
3271
    resetCache("47")
2839
    #getDealsForSearchText("20", 'Samsung', 0, 10)
-
 
2840
   
3272
    getAccesoryDeals(47, 6, 0, 20, None, None, None)
2841
    x = getBrandSubCategoryInfo(6,"15^17","subCategoryInfo")
-
 
2842
    print "==============="
-
 
2843
    print x
3273
    
2844
    
3274
if __name__=='__main__':
2845
if __name__=='__main__':
3275
    main()
-
 
3276
2846
    main()
-
 
2847
 
-
 
2848
 
-
 
2849