0

I have an apex code which identifies users who have subscribed to an Account( basically followed an Account for any chatter posts ).The code then subscribes these users to the related Opportunities of the Account.Below is the code that I wrote:

    List<EntitySubscription> lstSubsINS = new List<EntitySubscription>();
     Map<Id,List<Opportunity>> mapOpps = new Map<Id, List<Opportunity>>();
     Set<Id> setAccountIds = new Set<Id>();



     for(EntitySubscription obj:[select id,Parentid,SubscriberId,CreatedDate from EntitySubscription limit 1000 ]){

        String str = obj.ParentId;

        if(str.startsWith('001'))
          setAccountIds.add(str);   

     }

     for(Opportunity objOpp:[select id,name,AccountId from Opportunity where AccountId IN: setAccountIds]){

        if(mapOpps.get(objOpp.AccountId)==null){

            List<Opportunity> lst = new List<Opportunity>();
            lst.add(objOpp);

            mapOpps.put(objOpp.Accountid,lst);

        }

       else
          mapOpps.get(objOpp.Accountid).add(objOpp);    

     }

    for(EntitySubscription obj:[select id,Parentid,SubscriberId,CreatedDate from EntitySubscription limit 1000 ]){

       String str = obj.ParentId;

       if(str.startsWith('001') && mapOpps.get(str)!=null && mapOpps.get(str).size()>0 ){

         for(Opportunity objOpp:mapOpps.get(str)){

             EntitySubscription objSub = new EntitySubscription();
             objSub.ParentId = objOpp.id;
             objSub.SubscriberId = obj.SubscriberId;
             if(!(lstSubsINS.contains(objSub)))
             lstSubsINS.add(objSub);            

         }  

       }        

    }

if(!lstSubsINS.isEmpty())    
    insert lstSubsINS;

When I run this code in the developer console, I get the below error:

DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []

I tried to fix it by de-duplicating the list ( where i am inserting new subscriptions )but no luck.Any help will be much appreciated.

1 Answer 1

1

I was finally able to address the issue.The issue was the existing subscriptions.If the user is already subscribed to the opportunity, he/she can't be subscribed again.Placed a check in my code to verify if there is no existing subscription for the opportunity for the same user and I was able to fix this issue.Hope this helps someone who gets stuck in the same issue :)

if(mapExistingOppSubs.get(objOpp.id)==null || ( mapExistingOppSubs.get(objOpp.id)!= null && mapExistingOppSubs.get(objOpp.id).SubscriberId != obj.SubscriberId))

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .