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.