• AMR27
  • NEWBIE
  • 0 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 5
    Replies

Hey All,

 

I have written a trigger to fill a score field on a QA object that we use to vet Cases in the system for appropriate behavior.

 

I have atteched  both the trigger and the test class below; as of now it is not even hitting the trigger at all, so I assume I am missing something simple that will get the test class to call the trigger.

 

Please let me know what I am missing; I am going crazy with test classes for triggers lately and it must be something I am missing.

 

Thanks a lot!

 

Alex Roth

 

Trigger -

 

trigger Score on QA_Instance__c (before insert, before update) {

Decimal opening = 0;
decimal written = 0;
decimal Verbal = 0;
decimal listening = 0;
decimal empathy = 0;
decimal prof = 0;
decimal offer = 0;
decimal issue = 0;
decimal expect = 0;
decimal resource = 0;
decimal escalate = 0;
decimal create = 0;
decimal tool = 0;
decimal quality = 0;
decimal policy = 0;


For(QA_Instance__c qa: Trigger.new){

    If(qa.Case_Origin__c == 'Phone'){
    
        If(QA.Opening__c == 'Yes'){
        
            opening = 4;
            
            }
            
        If(QA.Listening_Skills__c == 'Yes'){
    
            listening = 7;
            
            }    
          
        If(QA.Empathy__c == 'Yes'){
    
            empathy = 7;
            
            }    
        
        If(QA.Communication_Skills_Verbal__c == 'Yes'){
    
            verbal = 8;
            
            }       
            
        If(QA.Communication_Skills_Written__c == 'Yes'){
        
            written = 7;
            
            }
        
        If(QA.Professional_Behavior__c == 'Yes'){
        
            prof = 8;
            
            }
        
        If(QA.Offer_Assistance__c == 'Yes'){
        
            offer = 4;
            
            }    
         
         If(QA.Issue_ID_and_Solution_Provided__c == 'Yes'){
        
            issue = 7;
            
            }  
           
         If(QA.Set_Expectations__c == 'Yes'){
        
            expect = 7;
            
            }
         
         If(QA.Resourcefulness__c == 'Yes'){
        
            resource = 7;
            
            }
         
         If(QA.Escalate_Transfer__c == 'Yes'){
        
            escalate = 4;
            
            }
         
         If(QA.Create_Case__c == 'Yes'){
        
            create = 8;
            
            }
         
         If(QA.Tool_Documentation__c == 'Yes'){
        
            tool = 8;
            
            }  
           
         If(QA.Quality_Documentation__c == 'Yes'){
        
            quality = 8;
            
            }   
           
         If(QA.Adherence_to_Policy__c == 'Yes'){
        
            policy = 6;
            
            }    
           
             If(QA.Professional_Behavior__c == 'No'){
           
               qa.Score__c = null;
           
               }
             Else{
         
               qa.Score__c = opening+written+verbal+listening+empathy+prof+offer+issue+expect+resource+escalate+create+tool+quality+policy;
           
               }  
       
           }
       
     If(qa.Case_Origin__c == 'Email'||qa.Case_Origin__c == 'Web'){
    
           
        If(QA.Listening_Skills__c == 'Yes'){
    
            listening = 9;
            
            }    
          
        If(QA.Empathy__c == 'Yes'){
    
            empathy = 9;
            
            }    
              
            
        If(QA.Communication_Skills_Written__c == 'Yes'){
        
            written = 10;
            
            }
        
        If(QA.Professional_Behavior__c == 'Yes'){
        
            prof = 10;
            
            }    
         
         If(QA.Issue_ID_and_Solution_Provided__c == 'Yes'){
        
            issue = 10;
            
            }  
           
         If(QA.Set_Expectations__c == 'Yes'){
        
            expect = 9;
            
            }
         
         If(QA.Resourcefulness__c == 'Yes'){
        
            resource = 9;
            
            }
         
         If(QA.Escalate_Transfer__c == 'Yes'){
        
            escalate = 6;
            
            }
         
         If(QA.Tool_Documentation__c == 'Yes'){
        
            tool = 10;
            
            }  
           
         If(QA.Quality_Documentation__c == 'Yes'){
        
            quality = 10;
            
            }   
            
          If(QA.Adherence_to_Policy__c == 'Yes'){
        
            policy = 8;
            
            }      
           
           
             If(QA.Professional_Behavior__c == 'No'){
           
               qa.Score__c = null;
           
               }
             Else{
         
               qa.Score__c = Math.roundtolong(written+listening+empathy+prof+issue+expect+resource+escalate+tool+quality+policy);
           
               }
       
            }
        
        
    }

}

 

TestClass - 

 

@isTest(seealldata=true)
private class TestScore {

    static testMethod void TestScore() {
    
    
        Test.startTest();
        
        RecordType RT = [select ID from RecordType where sObjectType = 'Case' AND Name = 'CSRCase'];

        Case newCase = new Case(RecordTypeId = RT.ID,
        Subject = 'Instant iPad Setup',
        Status = 'New',
        Deal_Type__c = 'Instant',
        Reason_for_Contact__c = 'iPad Set-Up - Outbound', 
        Resolution_Type__c = 'iPad Set-Up Complete', 
        Origin = 'Phone', 
        Case_Source__c = 'Instant Support');
      
        insert newCase;
        
        QA_Instance__c qa = new QA_Instance__c(
        Case_Origin__c = 'Phone',
        Professional_Behavior__c = 'Yes',
        Case__c = newCase.id);
        
        insert qa;
        
        qa.Score__c = 9;
        
        update qa;
        
        Test.stopTest();
        
        }
        
}

 

  • March 14, 2012
  • Like
  • 0

Hey All,

 

I am having an issue with a class that is supposed to handle incoming email-to-cases and associate the email address to a group of existing contacts.

 

I have seem to hit an impasse at lines 123 and 124, in that the debug log states that both CasestoUpdate and emailToContactMap are empty, but I cannot figure out why.

 

This has been in production running without part of this newly updated code, so the bulk of the code should work.  I do not know where I am going wrong, but as of now NO case is being created and NO contact is being associated as such.

 

Below is the code, please get back to me with any ideas.  I believe it has to do with the map, but since the list is also empty, I really don't know where to start.

 

Thanks in advance!!

 

trigger CSR_CreateContact on Case (before insert) {
    /*
     * Get CSR Case record type id
     */ 
    Id csrRTID = [select Id from recordtype where developername = 'CSRCase'].Id;
    
    /*
     * Email Loop Killer
     * Will not process new email if there are atleast 4 emails from 
     * the same email with the same subject and the previous email was less than 5 minutes ago
     */
    case[] c = trigger.new;
    if(c[0].RecordTypeId == csrRTID && c[0].Origin != 'Phone' && c[0].Origin != 'Other'){
        Integer caseCreateLimit = 10;
        case[] check = [select ID, CreatedDate, subject from Case where RecordTypeId =: csrRTID and SuppliedEmail = :c[0].SuppliedEmail and isclosed = false and createdDate >: DateTime.Now().addMinutes(-60) order by CreatedDate desc];
        system.debug(c[0].SuppliedEmail);
          
        if(check.size()>caseCreateLimit-1){
            c[0].addError('Automatic email loop has been terminated');
        }else if(check.size()>caseCreateLimit-2 && 
                    c[0].suppliedEmail != null && 
                    c[0].SuppliedEmail != ''){
                String[] toAddresses = new String[]{c[0].SuppliedEmail};
                String replyToAddress = 'help@livingsocial.com';
                String subject = c[0].Subject;
                String htmlMessageBody = '<h3>Case creation limit reached'+' </h3>';
                
                htmlMessageBody += '<hr/>';
                htmlMessageBody += '<h4> You have reached the maximum number of support cases you can create at this time. Please try your request again after one hour. Thanks for LivingSocial!</h4></b><p>';
                String senderDisplayName = 'LivingSocial';
                /*List <Messaging.SendEmailResult> results = 
                    CSR_EmailUtil.sendSingleEmail(toAddresses, replyToAddress, 
                        senderDisplayName, subject, htmlMessageBody);
                System.debug('Send Email Result:' +results.get(0).isSuccess());*/
        }
    }
    
    
    /*
     * Auto-Creation and Update of Contacts.
     * Will create new contacts if the email id does not exist and 
     * update contact if its Name changes from the last time it was saved.
     */     
    List<String> emailAddresses = new List<String>();
    //Get a list of email address for Cases not associated to a Contact.
    for (Case caseObj:Trigger.new) {
        if(caseObj.RecordTypeId == csrRTID
            && caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!=''){
                emailAddresses.add(caseObj.SuppliedEmail);
            }
    }
    System.debug('emailAddresses:'+emailAddresses);
    
    //Get the LivingSocial account to associate newly created Contacts to it.
    List<Account> account = new List<Account>([select id, AccountNumber from Account where (Name LIKE 'LivingSocial Consumers%' and isConsumerAccount__c = 'yes') ORDER BY AccountNumber DESC limit 3]);
    
    System.debug('ACCOUNTS IS:'+account);
    
    //Get the existing LivingSocial Consumer account ids to build Contact list to querry email addresses against
    Set<ID> acctIDs = new Set<ID>();
    
    for (Account a : account) {
        
            acctIDs.add(a.id);
            
    }
    
    System.debug('ACCTIDS IS:'+acctIDs);
    
    Map<String, Contact> existingRecords = new Map<String, Contact>();
    
    //Get a list of contacts already using one of the Email Addresses.
    for(List<Contact> contacts:[Select Id, LastName, FirstName, Email From Contact Where Email != NULL AND Email IN :emailAddresses AND AccountId in :acctIDs]){
        for (Contact cont:contacts) {
            existingRecords.put(cont.Email, cont);
        }
    }
    
    System.debug(' existingRecords:'+existingRecords);
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Contact> existingContacts = new List<Contact>();
    List<Case> casesToUpdate = new List<Case>();
    
    for (Case caseObj:Trigger.new) {
        if (caseObj.RecordTypeId == csrRTID && 
            //caseObj.ContactId==null &&
            caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!='' &&
            !existingRecords.keySet().contains(caseObj.SuppliedEmail)){
                //If case has a Web Name (Supplied Name)
                if(caseObj.SuppliedName!=null && caseObj.SuppliedName!=''){
                    String[] fullName = caseObj.SuppliedName.split(' ',5);
                    Integer listSize = fullName.size();
                    Contact cont = new Contact(AccountId = account[0].id,
                                                FirstName=fullName[0],
                                                LastName=fullName[listSize-1],
                                                Email=caseObj.SuppliedEmail);
                    emailToContactMap.put(caseObj.SuppliedEmail,cont);
                    casesToUpdate.add(caseObj);
                    }
     
                //Update Account Field to 'LivingSocial' if Case Origin is Phone
                //else if(caseObj.Origin == 'Phone'){
                    //caseObj.AccountId = account.id;
                      // }
                //If case does not have a Web Name (Supplied Name)
                else{
                    Integer index = caseObj.SuppliedEmail.indexOf('@');
                    String lastName = caseObj.SuppliedEmail.substring(0,index);
                    Contact cont = new Contact(AccountId = account[0].id,
                                               LastName=lastName,
                                               Email=caseObj.SuppliedEmail);
                    emailToContactMap.put(caseObj.SuppliedEmail,cont);
                    casesToUpdate.add(caseObj);

                }
        }
      System.debug('existing records is:'+existingRecords);
      System.debug('RTYPE IS:'+csrRTID);
      System.debug('SuppliedEmail:'+ caseObj.SuppliedEmail);                                                   
      System.debug('SuppliedEmail:'+ caseObj.SuppliedEmail);                                                   
      System.debug('CASESTOUPDATE IS:'+casesToUpdate);
      System.debug('EMAILTOCONTACTMAP IS:'+emailToContactMap);
      
        //Code to update Contact Name if different from the last time it was saved.
        /*else if(caseObj.RecordTypeId == csrRTID && 
                caseObj.SuppliedEmail!=null &&
                caseObj.SuppliedEmail!='' &&
                caseObj.SuppliedName!=null && 
                caseObj.SuppliedName!='' && 
                existingRecords.keySet().contains(caseObj.SuppliedEmail)){
            String ID = existingRecords.get(caseObj.SuppliedEmail).id;
            String[] fullName = caseObj.SuppliedName.split(' ',5);
            Integer listSize = fullName.size();
            String lName = fullName[listSize-1];
            String fName = fullName[0];
            if(existingRecords.get(caseObj.SuppliedEmail).LastName != lName ||
                existingRecords.get(caseObj.SuppliedEmail).FirstName != fName){
                existingContacts.add(new Contact(id = ID, LastName = lName, FirstName = fName));
            }
        }*/
    }
    System.debug(' emailToContactMap:'+emailToContactMap);
    
    //Create Contacts.
    List<Contact> newContacts = emailToContactMap.values();
    System.debug('newContacts:'+newContacts);
    if(!newContacts.isEmpty()){
        //Insert New Merchant Case
        Database.SaveResult[] lsr = Database.insert(newContacts,false);
        List<String> errMessages = new List<String>();
        // Iterate through the Save Results
        for(Database.SaveResult sr:lsr){
            if(!sr.isSuccess()){
                Database.Error err = sr.getErrors()[0];
                errMessages.add(err.getMessage());
            }
        }
        if(!errMessages.isEmpty()){
            system.debug('errMessages for New Contacts:'+errMessages);
        }
    }
    //Update Contacts
    System.debug(' existingContacts:'+existingContacts);
    if(!existingContacts.isEmpty()){
        //Update New Merchant Case
        Database.SaveResult[] lsr = Database.update(existingContacts,false);
        List<String> errMessages = new List<String>();
        // Iterate through the Save Results
        for(Database.SaveResult sr:lsr){
            if(!sr.isSuccess()){
                Database.Error err = sr.getErrors()[0];
                errMessages.add(err.getMessage());
            }
        }
        if(!errMessages.isEmpty()){
            system.debug('errMessages for updates to Existing Contacts:'+errMessages);
        }
    }
    
    //Associate newly created Contacts to respective Cases.
    System.debug(' casesToUpdate:'+casesToUpdate);
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
        caseObj.ContactId = newContact.Id;
    }
}

 

  • March 13, 2012
  • Like
  • 0

Hello all, 

 

I am having an issue with two triggers I have written.  One trigger creates a task of a certain recordtype whenever a field  on an Opportunity is set to a certain value, while the second trigger assigns some values from this task back to the related opportunity upon update to specific Task fields.

 

This should work without issue, in theory anyway, but it seems as though the two triggers are acting simultaneously (though they should not be).


The error I get is:

 

Error:Apex trigger assignUnscheduledTask caused an unexpected exception, contact your administrator: assignUnscheduledTask: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateUnschedOpp: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 006K0000003dWJPIA2; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 006K0000003dWJP) is currently in trigger assignUnscheduledTask, therefore it cannot recursively update itself: [] Trigger.UpdateUnschedOpp: line 19, column 1: []: Trigger.assignUnscheduledTask: line 25, column 1

 

The initial trigger is :

 

trigger assignUnscheduledTask on Opportunity (before update, before insert) {

    public Task tsk {get; set;}
    
Recordtype RT = [select Id, Name from RecordType where sObjectType = 'Task' AND Name = 'Un-Scheduled Deal Task'];
 
    for (Opportunity o : trigger.new) {
        
               system.debug('CREATE NEW TASK FOR ' + o.id);
           
             if (o.Deal_Queue_Status__c == 'DNR') {
             
             
                System.debug('triggerfire');
                tsk = new Task(
                  
                    whatid=o.Id,
                    OwnerId=o.ownerid,
                    Subject='ACTION REQUIRED - Your Signed Merchant has been UNSCHEDULED',
                    RecordTypeId = RT.Id
                    
                    );
         insert tsk;
         
         
                 }
     
   
    
    
    }


}

 And the follow up trigger is 

 

trigger UpdateUnschedOpp on Task (before update) {
          

  if(Trigger.new.size() == 1 ) {

    Task tk = Trigger.New[0];
    String str = tk.whatid;
    if(str != null && str.substring(0,3)== '006')
    {

        Opportunity opp = [select Id, Merchant_willing_to_run__c, Requested_Run_Month__c  from Opportunity where Id = :tk.WhatId ];

        List<Task> tsks = [Select Merchant_willing_to_run__c, Requested_Run_Month__c From Task where whatid=:tk.whatid and  what.type = 'Opportunity' and isClosed  = false and Merchant_willing_to_run__c != null];  

        if (tsks.size()>0) {
                opp.Merchant_willing_to_run__c = tsks[0].Merchant_willing_to_run__c;
                opp.Requested_Run_Month__c  = tsks[0].Requested_Run_Month__c;
        }
        update opp;
    }
}
}

 Any help at all would be great, I am at an impasse and need to figure this out ASAP.

 

Thanks a lot all!

 

Alex Roth

  • December 05, 2011
  • Like
  • 0

Hello all, 

 

I am having an issue with two triggers I have written.  One trigger creates a task of a certain recordtype whenever a field  on an Opportunity is set to a certain value, while the second trigger assigns some values from this task back to the related opportunity upon update to specific Task fields.

 

This should work without issue, in theory anyway, but it seems as though the two triggers are acting simultaneously (though they should not be).


The error I get is:

 

Error:Apex trigger assignUnscheduledTask caused an unexpected exception, contact your administrator: assignUnscheduledTask: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateUnschedOpp: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 006K0000003dWJPIA2; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 006K0000003dWJP) is currently in trigger assignUnscheduledTask, therefore it cannot recursively update itself: [] Trigger.UpdateUnschedOpp: line 19, column 1: []: Trigger.assignUnscheduledTask: line 25, column 1

 

The initial trigger is :

 

trigger assignUnscheduledTask on Opportunity (before update, before insert) {

    public Task tsk {get; set;}
    
Recordtype RT = [select Id, Name from RecordType where sObjectType = 'Task' AND Name = 'Un-Scheduled Deal Task'];
 
    for (Opportunity o : trigger.new) {
        
               system.debug('CREATE NEW TASK FOR ' + o.id);
           
             if (o.Deal_Queue_Status__c == 'DNR') {
             
             
                System.debug('triggerfire');
                tsk = new Task(
                  
                    whatid=o.Id,
                    OwnerId=o.ownerid,
                    Subject='ACTION REQUIRED - Your Signed Merchant has been UNSCHEDULED',
                    RecordTypeId = RT.Id
                    
                    );
         insert tsk;
         
         
                 }
     
   
    
    
    }


}

 And the follow up trigger is 

 

trigger UpdateUnschedOpp on Task (before update) {
          

  if(Trigger.new.size() == 1 ) {

    Task tk = Trigger.New[0];
    String str = tk.whatid;
    if(str != null && str.substring(0,3)== '006')
    {

        Opportunity opp = [select Id, Merchant_willing_to_run__c, Requested_Run_Month__c  from Opportunity where Id = :tk.WhatId ];

        List<Task> tsks = [Select Merchant_willing_to_run__c, Requested_Run_Month__c From Task where whatid=:tk.whatid and  what.type = 'Opportunity' and isClosed  = false and Merchant_willing_to_run__c != null];  

        if (tsks.size()>0) {
                opp.Merchant_willing_to_run__c = tsks[0].Merchant_willing_to_run__c;
                opp.Requested_Run_Month__c  = tsks[0].Requested_Run_Month__c;
        }
        update opp;
    }
}
}

 Any help at all would be great, I am at an impasse and need to figure this out ASAP.

 

Thanks a lot all!

 

Alex Roth

  • December 05, 2011
  • Like
  • 0

I'm just getting into a SF admin seat so I don't have much Apex experience.

 

I want 2 fields in the opportunities object to be updated once a field in a custom object is updated.

 

When the text field in Object 1 (the custom object) is entered as complete, I need two seperate fields in the opportunity object updated.

 

I want status changed to approved and a custom checkbox to go from unchecked to checked.

 

Thanks in advance

Hy Guys,

 

I've a workflow rule with a field update as action.

My new field value shall be: Today() - 3 Business days.

How can I calculate that only Business days are subtracted?

Can anybody help me?

 

Thanks and best regards,

Freddy 

Message Edited by Freddy99 on 02-23-2010 12:21 AM
Hi,I have created following trigger, this trigger supposed o evaluate opportunity ifType is equal to new business and CC coordinator is not blank it should create new task with subject first contact, but it does not and I have no idea how to fix, can any one help please

trigger assignTask on Opportunity (before insert, before update) { List<Task> task = new List<Task>(); List<Opportunity> newOpportunity = new List<Opportunity>(); for (Integer i = 0; i < Trigger.new.size(); i++) { if ((Trigger.new[i].Type == 'New Business')&&(Trigger.new[i].CC_Co_ordinator__c ==null)) { System.debug('triggerfire'); task.add(new Task( whatid=Trigger.new[i].Id, OwnerId=Trigger.new[i].CC_Co_ordinator__c, Subject='First Contact ' )); } } insert task; }

 

  • March 17, 2009
  • Like
  • 0