Make sure the users have “View and Edit Converted Leads” permission.
Check this for more information on this permission.
Sample Code:
Trigger:
trigger LeadTrigger on Lead ( after update ) {
Map < Id, Id > mapOpptyIdLeadId = new Map < Id, Id >();
for ( Lead objLead : trigger.new ) {
/*
Once the Lead is converted, getting the Converted Opportunity Id
*/
if ( String.isNotBlank( objLead.ConvertedOpportunityId ) && String.isBlank( trigger.oldMap.get( objLead.Id ).ConvertedOpportunityId ) )
mapOpptyIdLeadId.put( objLead.ConvertedOpportunityId, objLead.Id );
}
if ( mapOpptyIdLeadId.size() > 0 ) {
/*
Calling the Queueable interface to transfer the tasks
*/
System.enqueueJob( new TransferActivities( mapOpptyIdLeadId ) );
}
}
Queueable Interface:
public class TransferActivities implements Queueable {
Map < Id, Id > mapOpptyIdLeadId = new Map < Id, Id >();
public TransferActivities( Map < Id, Id > mapOpptyIdLeadId ) {
this.mapOpptyIdLeadId = mapOpptyIdLeadId;
}
public void execute( QueueableContext qc ) {
List < Task > listTasks = [ SELECT Id, WhatId, WhoId FROM Task WHERE WhatId IN: mapOpptyIdLeadId.keySet() ];
for ( Task objTask : listTasks ) {
system.debug( 'Lead Id is ' + mapOpptyIdLeadId.get( objTask.WhatId ) );
objTask.WhoId = mapOpptyIdLeadId.get( objTask.WhatId );
/*
Setting WhatId to null since Task cannot be linked to Lead and Opportunity
*/
objTask.WhatId = null;
}
update listTasks;
}
}