Step 1: Created an Invocable Apex class
public class UpdateSharingByUser {
@invocableMethod
public static void SharingAcc(list<id> sharingAccIDList)
{
system.debug('sharingAccIDList : '+sharingAccIDList);
list<Sharing_Acc__c> sharingAccList = [select id, user__c, Product_Type__c, Region__c, Access_level__c from Sharing_Acc__c where id=:sharingAccIDList ];
list<id>UserIdList= new list<id>();
list<string>prodType= new list<string>();
list<string>regionlist= new list<string>();
for(Sharing_Acc__c sa: sharingAccList)
{
UserIdList.add(sa.user__c);
prodType.add(sa.Product_Type__c);
regionlist.addall(sa.Region__c.split(';'));
}
system.debug('Product type list: '+prodType);
system.debug('Region Type list: '+regionlist);
system.debug('user id: '+UserIdList);
list<AccountShare> oldshare = [select id,accountId,AccountAccessLevel from AccountShare where UserOrGroupId=:UserIdList and RowCause = 'Manual'];
system.debug('OldShare rcord: '+oldshare);
if(oldshare.size()>0){delete oldshare;} // deleting old sharing record
List<AccountShare> shares = new List <AccountShare>();
// fatching all the account record based on Product type and record type
list<account>acclist=[select id,name, RecordType.Name, Products_Serviced_by__c from account where Products_Serviced_by__c=:prodType AND RecordType.Name =:regionlist];
system.debug('accList: '+acclist);
if(acclist!=null)
{
for( account a: acclist)
{
for(Sharing_Acc__c u : sharingAccList )
{
if(u.Region__c!=null && u.Product_Type__c!=null && u.User__c!=null)
{
// assigning to set for exact matching of product type and region
Set<string> regionset = new Set<string>(u.Region__c.split(';'));
Set<string> Prodset = new Set<string>(a.Products_Serviced_by__c.split(';'));
if(Prodset.contains(u.Product_Type__c) && regionset.contains(a.RecordType.Name))
{
//create share record and assign user id
AccountShare share = new AccountShare();
share.AccountAccessLevel= u.Access_level__c;
share.CaseAccessLevel='None';
share.OpportunityAccessLevel='None';
share.AccountId= a.id;
share.UserOrGroupId=u.User__c;
shares.add(share);
system.debug('share access level: '+u.Access_level__c);
}
}
}
}
}
system.debug('Sharing Rec List: '+shares);
if(!shares.isEmpty())
{
try{
//inserting share record
Database.SaveResult[] accountInsertResult = Database.insert(shares,false);
for( Database.SaveResult s: accountInsertResult)
{
if(s.isSuccess())
{
System.debug('Saved');
}
list<database.Error> err= s.getErrors();
for(database.Error d: err)
{
system.debug('Error message is: '+ d.getmessage());
}
}
}
catch(Exception e)
{
system.debug('Exception: '+e);
}
}
}
}
**Note: Products_Serviced_by__c and Region__c are Multi select picklist
Step 2: Create a process builder and invoke the above class
No comments:
Post a Comment