0

I am working a new project and when I moved it to the sandbox from my developer org I get this error creating leads, if I included an email address, or selected an agency type other than lender. If I check the assign using active assignment rule box I can create leads with out an issue. Why is this happening?

16:05:50.258 (291490092)|EXCEPTION_THROWN|[131]|System.DmlException: 
Upsert failed. First exception on row 0; first error: 
INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access 
rights on cross-reference id: a0G3900002v7qQJ: []
16:05:50.258 (291898427)|HEAP_ALLOCATE|[131]|Bytes:174
16:05:50.258 (291924042)|SYSTEM_MODE_EXIT|false
16:05:50.258 (291935858)|METHOD_EXIT|[213]|01p390000012GvI|ActionPlansBatchBuilderUtilities.generateActionPlans()
16:05:50.258 (292023273)|FATAL_ERROR|System.DmlException: Upsert 
failed. First exception on row 0; first error: 
INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access 
rights on cross-reference id: a0G3900002v7qQJ: []

 Class.ActionPlansBatchBuilderUtilities.generateActionPlans: line 131, 
column 1
Trigger.LeadTrigger: line 213, column 1
16:05:50.258 (292042358)|FATAL_ERROR|System.DmlException: Upsert 
 failed. First exception on row 0; first error: 
INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access 
rights on cross-reference id: a0G3900002v7qQJ: []

Class.ActionPlansBatchBuilderUtilities.generateActionPlans: line 131, 
column 1
Trigger.LeadTrigger: line 213, column 1
16:05:50.292 (292051486)|CUMULATIVE_LIMIT_USAGE
16:05:50.292 (292051486)|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 7 out of 100
Number of query rows: 3 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 4 out of 150
Number of DML rows: 4 out of 10000
Maximum CPU time: 0 out of 10000
Maximum heap size: 0 out of 6000000
Number of callouts: 0 out of 100
Number of Email Invocations: 0 out of 10
Number of future calls: 2 out of 50
Number of queueable jobs added to the queue: 0 out of 50
Number of Mobile Apex push calls: 0 out of 10

16:05:50.292 (292051486)|CUMULATIVE_LIMIT_USAGE_END

16:05:50.258 (293061789)|CODE_UNIT_FINISHED|LeadTrigger on Lead trigger 
event AfterUpdate for [00Q1F000000sMDu]

First trigger for lead creation:

trigger SendGridLeadCreation on Lead (after insert) {
   static List<Map<String, Object>> jsonMAP = new List<Map<String, 
Object>>();

//TriggerLogic
for(Lead lead : Trigger.new) {
   if (lead.email != null) {

  boolean sllead = lead.Simple_Listing__c;
  boolean eonly  = false;
  string  leadid = lead.Id;
  string  ecname = lead.Agency_Type__c;
  string  email  = lead.Email;
  string  fname  = lead.FirstName;
  string  lname  = lead.LastName;
  string  marea  = lead.Market_Area__c;


  if (lead.Phone == null && lead.MobilePhone == null)
    {
        eonly = true;
    }


  email_campaign__c Email_campagin = new Email_Campaign__c(email__c = 
email, first_name__c  = fname, last_name__c = lname, name='Marketing 
Campaign', lead__c=leadid, agency_type__c=ecname, Market_Area__c=marea, 
Simple_Listing__c =sllead, campaign_type__c='marketing', 
email_only__c=eonly);
             insert Email_campagin;
             string Email_campaginid = Email_campagin.id;
       system.debug(Email_campaginid);

}
}
}

Second Lead Trigger:

trigger LeadTrigger on Lead (after undelete, before delete, before 
update, before insert, after update, after insert) {

set<ID>         cIds    = new set<ID>();
List<String>    apIds   = new List<String>();
List<ActionPlan__c> deletePermantently_apIds= new List<ActionPlan__c>();

//Delete related action plans
if ( trigger.isdelete ){
    for( Lead l : trigger.old ){
        cIds.add( l.Id );
    }

    // GET Action Plans to delete from recycle bin 
    deletePermantently_apIds = [ select Id, Name , LastModifiedDate 
from ActionPlan__c where Lead__c in : cIds and isDeleted = true ALL ROWS ];

    if ( deletePermantently_apIds.size() >0 ){
        Database.emptyRecycleBin(deletePermantently_apIds);
    }

    List<ActionPlan__c> apList =  [ select Id from ActionPlan__c where Lead__c in : cIds ];
    for( ActionPlan__c ap : apList ){
        apIds.add( ap.Id );
    }

    if ( apIds.size() >0 ){
        ActionPlansBatchDelete aPBatch = new ActionPlansBatchDelete(apIds, Userinfo.getUserId());
        Database.ExecuteBatch( aPBatch );
    }
}

//Undelete related action plans
if ( trigger.isUnDelete ){
    for( Lead l : trigger.new ){
        cIds.add( l.Id );
    }
    list <ActionPlan__c> aPs = [ select Id from ActionPlan__c where Lead__c in : cIds ALL ROWS ];

    try{
        if(ActionPlanObjectTriggerTest.isTest){
            //throw dmlException
            insert new Contact();
        }
        //undelete aPs;
        Database.undelete( aPs,false);
    } catch ( Dmlexception e ){
        for (Lead l: trigger.new){
            l.addError('You can not undelete an action plan whose related object is deleted.');
        }
    }
}
if(trigger.isBefore && (trigger.isUpdate || trigger.isInsert)){
    Lead[] lcmap = new List<Lead>();
    for(Lead nl : Trigger.new){
        if(Trigger.isInsert && (nl.Email != null || nl.MobilePhone != null || nl.Phone != null)){
            lcmap.add(nl);
        } else if (Trigger.isUpdate){
            Lead ol = Trigger.oldMap.get(nl.Id);
            if(ol.email != nl.email || ol.phone != nl.phone || ol.MobilePhone != nl.MobilePhone){
                lcmap.add(nl);
            }
        }
    }
    if(!lcmap.isEmpty()){
        String[] phoneList = new List<String>();
        String[] emailList = new List<String>();
        for(Lead cl : lcmap){
            if(cl.email != null){
                emailList.add(cl.email);
            }
            if(cl.phone != null){
                phoneList.add(cl.phone);
            }
            if(cl.MobilePhone != null){
                phoneList.add(cl.MobilePhone);
            }
        }
        Contact[] cmatches = [SELECT Id,Email,Phone,MobilePhone,AccountId FROM Contact WHERE Email IN :emailList OR Phone IN :phoneList OR MobilePhone IN :phoneList];
        if(!cmatches.isEmpty()){
            Map<String,Id> cEmail = new Map<String,Id>();
            Map<String,Id> cMobile = new Map<String,Id>();
            Map<String,Id> cPhone = new Map<String,Id>();
            for(Contact mc : cmatches){
                if(mc.Email != null){
                    cEmail.put(mc.Email,mc.Id);
                }
                if(mc.Phone != null && mc.AccountId != null){
                    cPhone.put(mc.Phone,mc.AccountId);
                }
                if(mc.MobilePhone != null){
                    cMobile.put(mc.MobilePhone,mc.Id);
                }
            }
            for(Lead nl : Trigger.new){
                if(nl.Email != null && cEmail.containsKey(nl.Email)){
                    nl.Contact__c = cEmail.get(nl.Email);
                } else if(nl.MobilePhone != null && cMobile.containsKey(nl.MobilePhone)){
                    nl.Contact__c = cMobile.get(nl.MobilePhone);
                } else if(nl.Phone != null && nl.Account__c == null && cPhone.containsKey(nl.Phone)){
                    nl.Account__c = cPhone.get(nl.Phone);
                }
            }
        }
    }
}

if(trigger.isAfter && trigger.isUpdate){
    ID tempId;
    AP_Templates__c[] setting = AP_Templates__c.getAll().values();
    System.debug(setting.size());
    Integer count = 0;
    Boolean isChanged = true;
    for(Lead nl: trigger.new){
        System.debug(nl.CreatedDate);
        tempID = null;                             //clear this each time, to keep the value from being carried between iterations in the loop
        ActionPlan__c action = new ActionPlan__c();
        List<String> obtype = new List<String>();
        List<APTaskTemplate__c> permTasks = new List<APTaskTemplate__c>();
        if(count < trigger.old.size()){
            isChanged = (nl != trigger.old[count]);
        }

        //Determine if we can add an action plan to the lead.
        if((nl.OwnerId+'').substring(0,3) == '005' && isChanged){
            if(nl.Status != 'Disqualified' && nl.Status != 'Qualified' && nl.Agency_Type__c != null && nl.Last_Action_Plan__c == null){
                if(nl.Mobile__c != null || nl.Phone != null || nl.Email != null || nl.X2nd_Mobile__c != null || nl.X2nd_Phone__c != null){
                    //Selects the template
                    for(AP_Templates__c sett: setting){
                        if(sett.Active__c == False){
                            continue;
                        }
                        if((nl.Agency_Type__c+'') == sett.Required_Agency_Type__c && ((nl.Status+'') == sett.Required_Status__c || sett.Required_Status__c == null)){
                            if(sett.Phone_required__c){
                                if(!sett.Email_Required__c){
                                    if(nl.Phone != null || nl.Mobile__c != null || nl.X2nd_Mobile__c != null || nl.X2nd_Phone__c != null){
                                        if(nl.Email == null && nl.X2nd_Email__c == null){
                                            tempId = sett.Template_ID__c;
                                            continue;
                                        }
                                    }
                                }else{
                                    if((nl.Email != null || nl.X2nd_Email__c != null)){
                                        if(nl.Phone != null || nl.Mobile__c != null || nl.X2nd_Mobile__c != null || nl.X2nd_Phone__c != null){
                                            tempId = sett.Template_ID__c;
                                              continue;
                                        }
                                    }
                                }
                            }if(sett.Email_Required__c){
                                if(!sett.Phone_required__c){
                                    if(nl.Email != null || nl.X2nd_Email__c != null){
                                        if(nl.Phone == null && nl.Mobile__c == null && nl.X2nd_Mobile__c == null && nl.X2nd_Phone__c == null){
                                            tempId = sett.Template_ID__c;
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        //End of template selection.
        if(tempID != null){
            //Creates the action plan
            action.Action_Plan_Template__c = tempID;
            if(nl.Nurture_Start__c == null){
              action.StartDate__c = date.today();
            }else{
              action.StartDate__c = nl.Nurture_Start__c;
            }
            action.Lead__c = nl.Id;
            action.OwnerId = nl.OwnerId;
            Schema.SObjectType sobjectType = tempId.getSObjectType();
            String sobjectName = sobjectType.getDescribe().getName();
            try{
                SObject record = Database.query('Select Id, Name From ' + sobjectName + ' Where Id = :tempId');
                action.Name =  ((ActionPlanTemplate__c)record).Name;
            }catch(Exception e){
                action.Name = tempId;
            }
            obtype.add(nl.Lead_18_Digit_Id__c);
            //List of the tasks associated with the template.
            List<APTTaskTemplate__c> tasks = [ select a.Type__c, a.Subject__c, a.Priority__c, a.Dependent__c, a.Name, a.User__c, taskIndex__c,
                         a.User__r.Name, a.Id, a.DaysFromStart__c, a.CreatedById, a.Action_Plan_Template__c, a.APTTaskTemplate__c,
                         a.APTTaskTemplate__r.Subject__c, a.Reminder__c, a.SendEmail__c, a.Comments__c, a.Minutes_Reminder__c
                         From APTTaskTemplate__c a
                         where a.Action_Plan_Template__c =: tempID  order by taskIndex__c ASC ];
            for(APTTaskTemplate__c task: tasks){
                APTaskTemplate__c newTask = new APTaskTemplate__c();
                newTask.Type__c = task.Type__c;
                newTask.Subject__c = task.Subject__c;
                newTask.Priority__c = task.Priority__c;
                newTask.Dependent__c = task.Dependent__c;
                newTask.Name = task.Name;
                newTask.User__c = task.User__c;
                newTask.taskIndex__c = task.taskIndex__c;
                newTask.DaysFromStart__c = task.DaysFromStart__c;
                newTask.CreatedById = task.CreatedById;
                newTask.Action_Plan__c = action.Action_Plan__c;
                newTask.Reminder__c = task.Reminder__c;
                if(task.Minutes_Reminder__c == null){
                newTask.Minutes_Reminder__c = '480';
                }else{
                    newTask.Minutes_Reminder__c = task.Minutes_Reminder__c;
                }
                newTask.SendEmail__c = task.SendEmail__c;
                newTask.Comments__c = task.Comments__c;
                permTasks.add(newTask);
            }
            //creates and inserts tasks and inserts action plan.
            ActionPlansBatchBuilderUtilities taskbatch = new ActionPlansBatchBuilderUtilities(action,permTasks,'Lead',obtype);
            taskbatch.generateActionPlans();
        }

    }
}
if(trigger.isAfter && trigger.isInsert){
    //Custom setting initialization
    Default_Lead_Owner__c[] def_owners = Default_Lead_Owner__c.getAll().values();
    Default_Lead_Owner__c defa;
    for(Default_Lead_Owner__c def : def_owners){
        if(def.Name == 'Default'){
            defa = def;
            break;
        }
    }
    Integer count = 0;
    List<Id> forRequery = new List<Id>();
    List<Task> ts = new List<Task>();
    List<Id> dupids =  new List<Id>();
    Map<Lead,List<Lead>> Matches = new Map<Lead,List<Lead>>();
    Map<Id,List<Id>> forRemap = new Map<Id,List<Id>>();
    Map<Id,Lead> dups =  new Map<Id,Lead>();
    List<Lead> nls;
    map<Id,Lead> newleadmapping;
    Set<Lead> toBeUpd = new Set<Lead>();
    List<Lead> toBeUpdL = new List<Lead>();
    Boolean is_dup = false;
    for(Lead nl: trigger.new){
        //If the leads came from the Mailparser.
        if((nl.Created_via__c+'') == 'Mailparser'){
            System.debug('Lead to be checked');
            System.debug(nl);
            forRequery.add(nl.Id);
        }
    }
    if(forRequery.size() > 0){
        //requery Leads so they are not read only.
        nls = [SELECT Id, Created_via__c, Phone, CreatedDate, OwnerId FROM Lead where Id IN:forRequery];
        for(Lead ld : nls){
            ld.Created_via__c = null;
        }
        newleadmapping = new map<Id,Lead>(nls);
        forRequery.clear();
    }
    if(nls != null){
        //Check for duplicates by updating requeried leads.
        Database.SaveResult[] results = Database.update(nls,false);
        for(Database.SaveResult result : results){
            List<Id> dupListIds = new List<Id>();
            if(!forRemap.containsKey(trigger.new[count].Id)){
                forRemap.put(trigger.new[count].Id, dupListIds);
            }
            if(!result.isSuccess()){
                System.debug('We got some duplicates');
                for(Database.Error duplicateError: result.getErrors()){
                    try{
                        Datacloud.DuplicateResult duplicateResult = ((Database.DuplicateError)duplicateError).getDuplicateResult();
                        Datacloud.MatchResult[] du = duplicateResult.getMatchResults();
                        for(Datacloud.MatchResult mr: du){
                            for(Datacloud.MatchRecord ols: mr.getMatchRecords()){
                                System.debug('This matches');
                                Lead temp = (Lead)ols.getRecord();
                                System.debug(temp);
                                System.debug('----------');
                                forRemap.get(trigger.new[count].Id).add(temp.Id);
                                forRequery.add(temp.Id);
                                dups.put(trigger.new[count].Id,trigger.new[count]);
                                is_dup = true;
                            }
                        }
                    }catch(TypeException e){
                        System.debug('There was a type exception');
                        is_dup = false;
                    }
                }
            }else{
                is_dup = false;
                //Add task to lead if there are no duplicates.
                System.debug('No duplicates, add this task.');
                Task t = new task(
                    Subject = trigger.new[count].Agency_Type__c + ' Activity - ' + trigger.new[count].LeadSource +' - '+ trigger.new[count].Lead_Source_Detail__c,
                    Status = 'Completed',
                    ActivityDate = date.Today(),
                    WhoId = trigger.new[count].Id,
                    Description = trigger.new[count].Message__c
                );
                newleadmapping.get(trigger.new[count].Id).Task_Comment__c = t.Description;
                ts.add(t);
            }
            count += 1;
            if(is_dup){

            }
        }
        //Requery to get all fields in duplicate leads.
        if(forRequery.size() > 0){
            Map<Id, Lead> requery = new Map<Id,Lead>([SELECT Id, Email, Phone, MobilePhone, Mobile__c, Street, FirstName, LastName,
            LeadSource, Lead_Source_Detail__c, Status, OwnerId, Email_Owner__c  FROM Lead where Id IN:forRequery]);
            for(Id key: forRemap.keySet()){
                List<Id> currIds = forRemap.get(Key);
                List<Lead> currLeads = new list<Lead>();
                for(Id currId: currIds){
                    currLeads.add(requery.get(currId));
                }
                Matches.put(dups.get(key), currLeads);
                System.debug('to be processed');
                System.debug(dups.get(key));
                System.debug(currLeads);
                System.debug('-------!---------');
            }
            for(Lead key: Matches.keySet()){
                List<Lead> current = Matches.get(key);
                //Adds a new task with information from the duplicate lead.
                for(Lead match: current ){
                    Task t = new task(
                        Subject = key.Agency_Type__c + ' Activity - ' + key.LeadSource +' - '+ key.Lead_Source_Detail__c,
                        Status = 'Completed',
                        ActivityDate = date.Today(),
                        WhoId = match.Id,
                        Description = key.Message__c
                    );
                    //Updates old lead with information from the new duplicate lead.
                    match.Task_Comment__c = t.Description;
                    System.debug('Changing matching fields');
                    if(match.Phone == null){
                        match.Phone = key.Phone;
                    }
                    if(match.Mobile__c == null){
                        if(key.Mobile__c != null){
                            match.Mobile__c = key.Mobile__c;
                        }
                        else if(key.MobilePhone != null){
                            match.Mobile__c = key.Mobile__c;
                        }
                    }
                    if(match.email == null){
                        System.debug('Changing email');
                        match.email = key.email;
                    }
                    if(match.Street == null){
                        match.Street  = key.Street;
                    }
                    if(match.FirstName == 'TBD' || match.FirstName == null || match.FirstName == 'Caller'){
                        match.FirstName = key.FirstName;
                    }
                    if(match.LastName == 'TBD' || match.LastName == null || match.LastName == 'Wireless'){
                        if(key.LastName != null){
                            match.LastName = key.LastName;
                        }
                    }
                    if(match.LeadSource+'' == 'Other' || match.LeadSource+'' == null){
                        if(key.LeadSource != null){
                            match.LeadSource = key.LeadSource;
                        }
                    }
                    if(match.Lead_Source_Detail__c+'' == 'Other' || match.Lead_Source_Detail__c == null){
                        if(key.Lead_Source_Detail__c != null){
                            match.Lead_Source_Detail__c = key.Lead_Source_Detail__c;
                        }
                    }
                    if(match.Status+'' == 'Disqualified'){
                        match.Status = 'Open';
                        if(defa != null){
                            match.OwnerId = ((ID)defa.Owner_Id__c);
                        }
                    }
                    else if(match.OwnerId != null){
                        if(String.ValueOf(match.OwnerId).substring(0,3) == '00G' ){
                            System.debug(String.ValueOf(match.OwnerId).substring(0,3));
                            match.OwnerId = ((ID)defa.Owner_Id__c);
                        }
                        else if(String.ValueOf(match.OwnerId).substring(0,3) == '005'){
                            match.Email_Owner__c = True;
                            t.OwnerId = match.OwnerId;
                        }
                    }
                    toBeUpd.add(match);
                    ts.add(t);
                }
            }
        }
        toBeUpdL.addAll(toBeUpd);
        Database.SaveResult[] results2 = Database.update(toBeUpdL,false);
        insert ts;
        if(dups.keySet().size() > 0){
            dupids.addAll(dups.keySet());
            Database.delete(dupids);
        }
        for(Database.SaveResult res: results2){
            if(!res.isSuccess()){
                System.debug('Updating duplicate record failed in Lead trigger');
            }
        }
    }
}
}
  • Can you provide more details on the execution of the code. It seems system is trying to upsert a custom object's object during lead creation process, where it is failing – Santanu Boral Sep 11 '17 at 3:00
  • Also, what is OWD and permissions of that user who is creating leads – Santanu Boral Sep 11 '17 at 3:00
  • What is owd? the user has system admin permissions. There are two triggers on lead creation I will add them above. – Roger Morris Sep 11 '17 at 3:02
  • OWD is Org Wide Default permissions. That sets up the base minimum access anyone is allowed by default. This is resources.docs.salesforce.com/208/21/en-us/sfdc/pdf/… good reference to go through if you have time. – realfire Sep 11 '17 at 3:07
0

The error is being thrown by ActionPlansBatchBuilderUtilities.generateActionPlans, so what is that trying to do? a0G3900002v7qQJ is probably the ID of the Action Plan record it is trying to create. Is a0G the prefix for Action Plan record IDs?

  • The issue turned out to be there were no action plans templates in the sandbox. No issues in a partial database org. – Roger Morris Sep 11 '17 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.