• Gabe Rothman
  • NEWBIE
  • 50 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 13
    Replies
trigger OpptyOwnerChangeAlert on Opportunity (before update) {

  List<Messaging.SingleEmailMessage> mails= new List<Messaging.SingleEmailMessage>();
  List<User> obsoleteUsers =  new List<User>();
  
  //Ensure that both Maps contain the same ID's
  system.assert(trigger.oldMap.keySet().containsAll(trigger.newMap.keySet()));  
  system.assert(trigger.newMap.keySet().containsAll(trigger.oldMap.keySet()));
    
  system.assert(trigger.oldMap.keySet().size()>0);
  
  Boolean test=false;
  
  Opportunity oldOpp = null;
  User oldOppOwner = null;
  Opportunity newOpp = null;
  User newOppOwner = null;
  
  for (Opportunity opp : trigger.new) {
    newOpp=opp;
    newOppOwner=[select Id from User where Id=:newOpp.OwnerId];
    if ((trigger.oldMap!=null)&&(trigger.oldMap.get(newOpp.Id)!=null)) {
      oldOpp=trigger.oldMap.get(newOpp.Id);
      oldOppOwner=[select Id,Email from User where Id=:oldOpp.OwnerId];
    }
    system.assert(oldOpp!=null);
    system.assert(oldOppOwner!=null);
    system.assert(newOpp!=null);
    system.assert(newOppOwner!=null);
    if (newOppOwner.Id != oldOppOwner.Id) {
       obsoleteUsers.add(oldOppOwner);   
    }
  }
    
  //obsolete_users = [Select Name, id, Email From User where Id in :obsolete_user_ids];
  for(User u: obsoleteUsers) {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject('[ALERT] Someone has snaked one of your Opportunities ');
    List<String> toAdrs = new List<String>();
    toAdrs.add(u.Email);
    system.assert(u.Email!=null);
    if (u.Email==null) continue; 
    mail.setToAddresses(toAdrs);
    mail.setBccSender(false);
    mail.setUseSignature(false);
    String mailContent = 'Someone is messin with your money; ownership of'+' '+'-'+' '+ newOpp.Name +' '+'-'+' '+'has been changed. Please contact your Admin in order to arrange your grudge match in the Thunderdome' ;
    mail.setPlainTextBody(mailContent);
    mails.add(mail); 
  }
  if (mails.size()>0){
    Messaging.sendEmail(mails);
  }
}
Thanks a bunch for your help!
Can anyone give me some direction on a service class I'm trying to write?  Essentially, I have a custom object called Transactions__c, which looks up to another custom object called PD_Data__c, which in turn looks up to the Account.  When a field called Amount_Due__c on a Transaction record is updated to a value greater than 0, I want to set the stage on any open oppty on the same Account to closed won. See illustration below:

User-added image

I've written some of the code, but I'm kinda stuck and I'm not sure if I'm even on the right track.

public with sharing class CloseOutOpptyService {

    public static list<Transactions__c> filterAmountDueChange(map<id, Transactions__c> oldMap, list<Transactions__c> newList) {
    	list<Transactions__c> temp=new list<Transactions__c>();
    	for (Transactions__c trxs : newList){
 			if ( 
 			      (oldMap.get(trxs.id).pd_amount_due__c == null || oldMap.get(trxs.id).pd_amount_due__c == 0) 
 			      && (trxs.pd_amount_due__c > 0)
 			      ){
 			temp.add(trxs);
 			}
    		
    	}
    	return temp;  
    }
    
	public static Set<Id> closeOpptys (list<Transactions__c> trxAccount) {        
		list<Transactions__c> trxAccountIds = [SELECT Id, Parent_PD_Data__r.SFDC_Account__r.Id FROM Transactions__c Where Id in: trxAccount];

		Set<Id> accountIds = new Set<Id>();
		for(Transactions__c trxAccountId : trxAccountIds) {
       		accountIds.add(trxAccountId.Parent_PD_Data__r.SFDC_Account__c);
		}

		return accountIds;




Any help would be greatly appreciated.  Thanks!







Hey all, I am pretty new to APEX, and I have built a lead conversion trigger, which is causing a "Too many future calls" error.  Based on my investigation it looks like I need to bulkify the service class that I am calling in the trigger, but I haven't been able to figure out the correct synatx.  Here is the class:

public with sharing class ConvertLeadOnActiveService {
    
    public static void convertLead(list<lead> convertList) {
    
    	for (Lead lead : convertList) {
      		if (lead.isConverted == false && lead.State__c == 'Active'){
       
        	Database.LeadConvert lc = new Database.LeadConvert();
        	lc.setLeadId(lead.Id);
       
     	    String oppName = lead.Company;
        	lc.setOpportunityName(oppName);
       
	        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
    	    lc.setConvertedStatus(convertStatus.MasterLabel);
       
       		Database.LeadConvertResult lcr = Database.convertLead(lc);
       		System.assert(lcr.isSuccess());
       
    		}
  	}
    }
}

I am pretty sure that I need to move the following outside of the for loop, but I am not sure how to do it.

         LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
         lc.setConvertedStatus(convertStatus.MasterLabel);
      
         Database.LeadConvertResult lcr = Database.convertLead(lc);
         System.assert(lcr.isSuccess());

Any help greatly appreciated.  Thanks!
Trigger:

trigger Lead on Lead (after insert, after update) {
 
   if(trigger.isInsert || trigger.isUpdate){
  	 	ConvertLeadOnActiveService.convertLead(trigger.new);
   }
	
   if(trigger.isInsert){
		List<lead> leads = new List<Lead>();
		for(lead l : trigger.new){
 			if(l.PagerDuty_Account_ID__c != null) {
  			leads.add(l);
			}
		}
		CreatePddOnLeadService.createPDD(leads);
   }

   if(trigger.isUpdate){
		CreatePddOnLeadService.createPDD(CreatePddOnLeadService.filterPDIDIsNull(trigger.oldmap,trigger.new));
		ReassociatePDDToAccountService.movePDD(ReassociatePDDToAccountService.filterConverted(trigger.oldmap,trigger.new));
   }

}

Service Class
public with sharing class ConvertLeadOnActiveService {
   
    public static void convertLead(list<lead> convertList) {
   
     for (Lead lead : convertList) {
        if (lead.isConverted == false && lead.State__c == 'Active'){
      
         Database.LeadConvert lc = new Database.LeadConvert();
         lc.setLeadId(lead.Id);
      
          String oppName = lead.Company;
         lc.setOpportunityName(oppName);
      
         LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
         lc.setConvertedStatus(convertStatus.MasterLabel);
      
         Database.LeadConvertResult lcr = Database.convertLead(lc);
         System.assert(lcr.isSuccess());
      
      }
    }
  }
}


Test:
@isTest
public class TestConvertLeadonActive {
        static testMethod void verifyleadConvert(){
        
       Lead l = new Lead();
       l.FirstName = 'Test';
       l.LastName = 'Test';
       l.Company = 'Test, Inc.';
       l.Status = 'A. New-Open';
       l.State__c = 'trial';
       l.Email = 'test@test.com';
       l.State__c = 'Active';
       insert l;    
       
       List<Lead> retrieveLead = [SELECT id FROM Lead WHERE id =: l.Id AND isConverted = true];
        
      Integer size = retrieveLead.size();
      system.assertEquals(1,size);            

               
        }
    }
Error Message:

Class.TestConvertLeadonActive.verifyleadConvert: line 13, column 1
14:47:09.467 (8467634625)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Lead: execution of AfterInsert

caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, An unexpected error occurred. Please include this ErrorId if you contact support: 1544795524-319229 (-1093901949): []

I downloaded the Salesforce labs case assignment unmanaged package and hacked the trigger to round robin assign leads, which works great.

I tried to update the test code, but every time I run the test I get a MIXED_DML_OPERATION error on 4 different lines of code.  I've researched the error and found some advice, but I haven't been able to implement the fixes that people suggested.  Can any help me fix these errors?

Here is the test class:
 
@isTest
public class TestLeadAssignment{

    static testMethod void myTest1() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;

       // Second Queue      
       Group testGroup2 = new Group ();
       testGroup2.Name = 'TestQueue2';
       testGroup2.Type = 'Queue';
       insert testGroup2;
      
       QueueSObject testQueue2 = new QueueSObject();
       testQueue2.QueueId = testGroup2.id;
       testQueue2.SObjectType = 'Lead';
       insert testQueue2;


       test.starttest();
       
        //Run test

        //Assign Lead with out any Assignment Groups
        Lead ld = new Lead (FirstName='Tim',LastName='Jones', Company='ABC Corp', tempOwnerID__c=testGroup2.id, OwnerID=u1.id); //tempOwnerID__c=testGroup2.id, 
        insert ld;
        update ld;
       
       
        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;

        
        //Add bad queue name
        Assignment_Group_Queues__c agqBad = new Assignment_Group_Queues__c(name='Bad Queue',Assignment_Group_Name__c = ag1.id );

        try {
            insert agqBad;
        } catch (DmlException e){
             System.assert(e.getMessage().contains('CUSTOM_VALIDATION_EXCEPTION'), e.getMessage());
       
        } //catch

        test.stoptest();
       
    }
   
    static testMethod void myTest2() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;

       // Second Queue      
       Group testGroup2 = new Group ();
       testGroup2.Name = 'TestQueue2';
       testGroup2.Type = 'Queue';
       insert testGroup2;
      
       QueueSObject testQueue2 = new QueueSObject();
       testQueue2.QueueId = testGroup2.id;
       testQueue2.SObjectType = 'Lead';
       insert testQueue2;


       test.starttest();
       
        //Run test
      
       
        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;       

        //Add Good Queue to Assignment Group
        Assignment_Group_Queues__c agq1 = new Assignment_Group_Queues__c(name=testGroup.Name ,Assignment_Group_Name__c = ag1.id );
        insert agq1;
       
       
        //Add User to Assignment Groups Users
        Assignment_Groups__c agu1 = new Assignment_Groups__c (User__c = u1.id, Active__c='True', Group_Name__c = ag1.id, Last_Assignment__c = datetime.valueOf('2009-01-01 21:13:24') );
        insert agu1;

        Lead l2 = new Lead (FirstName='Tom',LastName='Dunn', Company='JKL Corp', tempOwnerID__c=testGroup2.id , OwnerID=testGroup.id); //Set owner ID to Queue
        insert l2;
        update l2;       

        test.stoptest();
       
    }

    static testMethod void myTest3() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;

       test.starttest();
       
        //Run test       
       
        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;       

        //Add Good Queue to Assignment Group
        Assignment_Group_Queues__c agq1 = new Assignment_Group_Queues__c(name=testGroup.Name ,Assignment_Group_Name__c = ag1.id );
        insert agq1;
       
       
        //Add User to Assignment Groups Users
        Assignment_Groups__c agu1 = new Assignment_Groups__c (User__c = u1.id, Active__c='True', Group_Name__c = ag1.id, Last_Assignment__c = datetime.valueOf('2009-01-01 21:13:24') );
        insert agu1;     

        Lead l3 = new Lead (FirstName='Dave',LastName='Barry', Company='CBS Corp', OwnerID=testGroup.id); //Set owner ID to Queue
        insert l3;
        update l3;

        test.stoptest();
       
    }

    static testMethod void myTest4() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;
     

       test.starttest();
       
        //Run test

        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;       

        //Add Good Queue to Assignment Group
        Assignment_Group_Queues__c agq1 = new Assignment_Group_Queues__c(name=testGroup.Name ,Assignment_Group_Name__c = ag1.id );
        insert agq1;
       
          //Test for AG-Queues already assigned to another Assignment Group
        Assignment_Group_Queues__c agq2 = new Assignment_Group_Queues__c(name=testGroup.Name,Assignment_Group_Name__c = ag1.id );
        try {
            insert agq2;
        } catch (DmlException e){
             System.assert(e.getMessage().contains('CUSTOM_VALIDATION_EXCEPTION'), e.getMessage());
        } //catch

        test.stoptest();
    
 
  }
}

Summary:

My trigger is supposed to update a custom field on the related Account called Owner_s_Last_Activity_Date__c with the CreatedDate of the Task any time a new task created on the Account is assigned to the Account owner.  The trigger works great in the positive case (i.e. the Related Account lookup is populated), but I'm getting a null pointer exception any time the related Account lookup is null.  I know I need to filter tasks with no related Account out of my trigger logic, but I just can't seem to figure out how to do it.  Any help would be greatly appreciated.  Thanks!

trigger UpdateAccountFromActivity on Task (after insert) {

  Map<ID, Account> parentAccts = new Map<ID, Account>();
  List<Id> listIds = new List<Id>();

  for (Task task : Trigger.new){
    if(task.AccountId!=null)
      listIds.add(task.AccountId);
  }
   
  parentAccts = new Map<Id, Account>([SELECT ID, Owner_s_Last_Activity__c, OwnerID, (SELECT ID, CreatedDate, OwnerId, AccountID FROM Tasks WHERE AccountID!=null ) FROM Account WHERE ID IN :listIds]);

  for (Task task: Trigger.new){
      Account myParentAcc = parentAccts.get(task.AccountId);
      if(myParentAcc.OwnerId == task.OwnerId && task.AccountID != null){
       myParentAcc.Owner_s_Last_Activity__c = task.CreatedDate;
        }     
      }  
   update parentAccts.values();
}

Hey all,
I started the process of teaching myself Apex after several years as an advanced admin and I'm having a heck of a time trying to write a simple trigger. I've tried to hack it together based on what I've learned so far and so sample code from other triggers, but I just can't seem to figure it out.  Frankly, I'm embarrassed to post what I have so far because I don't think it's even in the ballpark. 
 

Can anyone help me sort out how to write this very simple trigger? Here's the use case:

We have a custom checkbox on the Lead object called Claim_Lead__c which is used as part of a claiming process by our reps.  Essentially, because we use round robin assignment sometimes leads get assigned to reps as part of the round robin, but another rep has already been working a lead from the same company (via prospecting, event list upload, etc.). In that case the rep who has been working the lead can claim it by clicking the Claim_Lead__c checkbox and submitting the Lead for approval. If the manager approves the request, the approval process automatically updates the Lead owner to the claiming rep and unchecks the Claim_Lead__c box. Both the Lead owner change and the unchecking of the Claim_Lead__c box happen as part of the final approval action on the approval flow. 

We also have another custom field on the User object called 'Lead_Owner_Reassign_Stamp__c'.  When the owner of a lead changes, if the Claim_Lead__c field also changes from True to False I want a trigger to fire which stamps the new Lead owner's ID into the Lead_Owner_Reassign_Stamp__c text field. 

Thanks in advance for your help!

trigger OpptyOwnerChangeAlert on Opportunity (before update) {

  List<Messaging.SingleEmailMessage> mails= new List<Messaging.SingleEmailMessage>();
  List<User> obsoleteUsers =  new List<User>();
  
  //Ensure that both Maps contain the same ID's
  system.assert(trigger.oldMap.keySet().containsAll(trigger.newMap.keySet()));  
  system.assert(trigger.newMap.keySet().containsAll(trigger.oldMap.keySet()));
    
  system.assert(trigger.oldMap.keySet().size()>0);
  
  Boolean test=false;
  
  Opportunity oldOpp = null;
  User oldOppOwner = null;
  Opportunity newOpp = null;
  User newOppOwner = null;
  
  for (Opportunity opp : trigger.new) {
    newOpp=opp;
    newOppOwner=[select Id from User where Id=:newOpp.OwnerId];
    if ((trigger.oldMap!=null)&&(trigger.oldMap.get(newOpp.Id)!=null)) {
      oldOpp=trigger.oldMap.get(newOpp.Id);
      oldOppOwner=[select Id,Email from User where Id=:oldOpp.OwnerId];
    }
    system.assert(oldOpp!=null);
    system.assert(oldOppOwner!=null);
    system.assert(newOpp!=null);
    system.assert(newOppOwner!=null);
    if (newOppOwner.Id != oldOppOwner.Id) {
       obsoleteUsers.add(oldOppOwner);   
    }
  }
    
  //obsolete_users = [Select Name, id, Email From User where Id in :obsolete_user_ids];
  for(User u: obsoleteUsers) {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject('[ALERT] Someone has snaked one of your Opportunities ');
    List<String> toAdrs = new List<String>();
    toAdrs.add(u.Email);
    system.assert(u.Email!=null);
    if (u.Email==null) continue; 
    mail.setToAddresses(toAdrs);
    mail.setBccSender(false);
    mail.setUseSignature(false);
    String mailContent = 'Someone is messin with your money; ownership of'+' '+'-'+' '+ newOpp.Name +' '+'-'+' '+'has been changed. Please contact your Admin in order to arrange your grudge match in the Thunderdome' ;
    mail.setPlainTextBody(mailContent);
    mails.add(mail); 
  }
  if (mails.size()>0){
    Messaging.sendEmail(mails);
  }
}
Thanks a bunch for your help!
Can anyone give me some direction on a service class I'm trying to write?  Essentially, I have a custom object called Transactions__c, which looks up to another custom object called PD_Data__c, which in turn looks up to the Account.  When a field called Amount_Due__c on a Transaction record is updated to a value greater than 0, I want to set the stage on any open oppty on the same Account to closed won. See illustration below:

User-added image

I've written some of the code, but I'm kinda stuck and I'm not sure if I'm even on the right track.

public with sharing class CloseOutOpptyService {

    public static list<Transactions__c> filterAmountDueChange(map<id, Transactions__c> oldMap, list<Transactions__c> newList) {
    	list<Transactions__c> temp=new list<Transactions__c>();
    	for (Transactions__c trxs : newList){
 			if ( 
 			      (oldMap.get(trxs.id).pd_amount_due__c == null || oldMap.get(trxs.id).pd_amount_due__c == 0) 
 			      && (trxs.pd_amount_due__c > 0)
 			      ){
 			temp.add(trxs);
 			}
    		
    	}
    	return temp;  
    }
    
	public static Set<Id> closeOpptys (list<Transactions__c> trxAccount) {        
		list<Transactions__c> trxAccountIds = [SELECT Id, Parent_PD_Data__r.SFDC_Account__r.Id FROM Transactions__c Where Id in: trxAccount];

		Set<Id> accountIds = new Set<Id>();
		for(Transactions__c trxAccountId : trxAccountIds) {
       		accountIds.add(trxAccountId.Parent_PD_Data__r.SFDC_Account__c);
		}

		return accountIds;




Any help would be greatly appreciated.  Thanks!







Hey all, I am pretty new to APEX, and I have built a lead conversion trigger, which is causing a "Too many future calls" error.  Based on my investigation it looks like I need to bulkify the service class that I am calling in the trigger, but I haven't been able to figure out the correct synatx.  Here is the class:

public with sharing class ConvertLeadOnActiveService {
    
    public static void convertLead(list<lead> convertList) {
    
    	for (Lead lead : convertList) {
      		if (lead.isConverted == false && lead.State__c == 'Active'){
       
        	Database.LeadConvert lc = new Database.LeadConvert();
        	lc.setLeadId(lead.Id);
       
     	    String oppName = lead.Company;
        	lc.setOpportunityName(oppName);
       
	        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
    	    lc.setConvertedStatus(convertStatus.MasterLabel);
       
       		Database.LeadConvertResult lcr = Database.convertLead(lc);
       		System.assert(lcr.isSuccess());
       
    		}
  	}
    }
}

I am pretty sure that I need to move the following outside of the for loop, but I am not sure how to do it.

         LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
         lc.setConvertedStatus(convertStatus.MasterLabel);
      
         Database.LeadConvertResult lcr = Database.convertLead(lc);
         System.assert(lcr.isSuccess());

Any help greatly appreciated.  Thanks!
Trigger:

trigger Lead on Lead (after insert, after update) {
 
   if(trigger.isInsert || trigger.isUpdate){
  	 	ConvertLeadOnActiveService.convertLead(trigger.new);
   }
	
   if(trigger.isInsert){
		List<lead> leads = new List<Lead>();
		for(lead l : trigger.new){
 			if(l.PagerDuty_Account_ID__c != null) {
  			leads.add(l);
			}
		}
		CreatePddOnLeadService.createPDD(leads);
   }

   if(trigger.isUpdate){
		CreatePddOnLeadService.createPDD(CreatePddOnLeadService.filterPDIDIsNull(trigger.oldmap,trigger.new));
		ReassociatePDDToAccountService.movePDD(ReassociatePDDToAccountService.filterConverted(trigger.oldmap,trigger.new));
   }

}

Service Class
public with sharing class ConvertLeadOnActiveService {
   
    public static void convertLead(list<lead> convertList) {
   
     for (Lead lead : convertList) {
        if (lead.isConverted == false && lead.State__c == 'Active'){
      
         Database.LeadConvert lc = new Database.LeadConvert();
         lc.setLeadId(lead.Id);
      
          String oppName = lead.Company;
         lc.setOpportunityName(oppName);
      
         LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
         lc.setConvertedStatus(convertStatus.MasterLabel);
      
         Database.LeadConvertResult lcr = Database.convertLead(lc);
         System.assert(lcr.isSuccess());
      
      }
    }
  }
}


Test:
@isTest
public class TestConvertLeadonActive {
        static testMethod void verifyleadConvert(){
        
       Lead l = new Lead();
       l.FirstName = 'Test';
       l.LastName = 'Test';
       l.Company = 'Test, Inc.';
       l.Status = 'A. New-Open';
       l.State__c = 'trial';
       l.Email = 'test@test.com';
       l.State__c = 'Active';
       insert l;    
       
       List<Lead> retrieveLead = [SELECT id FROM Lead WHERE id =: l.Id AND isConverted = true];
        
      Integer size = retrieveLead.size();
      system.assertEquals(1,size);            

               
        }
    }
Error Message:

Class.TestConvertLeadonActive.verifyleadConvert: line 13, column 1
14:47:09.467 (8467634625)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Lead: execution of AfterInsert

caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, An unexpected error occurred. Please include this ErrorId if you contact support: 1544795524-319229 (-1093901949): []

I downloaded the Salesforce labs case assignment unmanaged package and hacked the trigger to round robin assign leads, which works great.

I tried to update the test code, but every time I run the test I get a MIXED_DML_OPERATION error on 4 different lines of code.  I've researched the error and found some advice, but I haven't been able to implement the fixes that people suggested.  Can any help me fix these errors?

Here is the test class:
 
@isTest
public class TestLeadAssignment{

    static testMethod void myTest1() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;

       // Second Queue      
       Group testGroup2 = new Group ();
       testGroup2.Name = 'TestQueue2';
       testGroup2.Type = 'Queue';
       insert testGroup2;
      
       QueueSObject testQueue2 = new QueueSObject();
       testQueue2.QueueId = testGroup2.id;
       testQueue2.SObjectType = 'Lead';
       insert testQueue2;


       test.starttest();
       
        //Run test

        //Assign Lead with out any Assignment Groups
        Lead ld = new Lead (FirstName='Tim',LastName='Jones', Company='ABC Corp', tempOwnerID__c=testGroup2.id, OwnerID=u1.id); //tempOwnerID__c=testGroup2.id, 
        insert ld;
        update ld;
       
       
        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;

        
        //Add bad queue name
        Assignment_Group_Queues__c agqBad = new Assignment_Group_Queues__c(name='Bad Queue',Assignment_Group_Name__c = ag1.id );

        try {
            insert agqBad;
        } catch (DmlException e){
             System.assert(e.getMessage().contains('CUSTOM_VALIDATION_EXCEPTION'), e.getMessage());
       
        } //catch

        test.stoptest();
       
    }
   
    static testMethod void myTest2() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;

       // Second Queue      
       Group testGroup2 = new Group ();
       testGroup2.Name = 'TestQueue2';
       testGroup2.Type = 'Queue';
       insert testGroup2;
      
       QueueSObject testQueue2 = new QueueSObject();
       testQueue2.QueueId = testGroup2.id;
       testQueue2.SObjectType = 'Lead';
       insert testQueue2;


       test.starttest();
       
        //Run test
      
       
        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;       

        //Add Good Queue to Assignment Group
        Assignment_Group_Queues__c agq1 = new Assignment_Group_Queues__c(name=testGroup.Name ,Assignment_Group_Name__c = ag1.id );
        insert agq1;
       
       
        //Add User to Assignment Groups Users
        Assignment_Groups__c agu1 = new Assignment_Groups__c (User__c = u1.id, Active__c='True', Group_Name__c = ag1.id, Last_Assignment__c = datetime.valueOf('2009-01-01 21:13:24') );
        insert agu1;

        Lead l2 = new Lead (FirstName='Tom',LastName='Dunn', Company='JKL Corp', tempOwnerID__c=testGroup2.id , OwnerID=testGroup.id); //Set owner ID to Queue
        insert l2;
        update l2;       

        test.stoptest();
       
    }

    static testMethod void myTest3() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;

       test.starttest();
       
        //Run test       
       
        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;       

        //Add Good Queue to Assignment Group
        Assignment_Group_Queues__c agq1 = new Assignment_Group_Queues__c(name=testGroup.Name ,Assignment_Group_Name__c = ag1.id );
        insert agq1;
       
       
        //Add User to Assignment Groups Users
        Assignment_Groups__c agu1 = new Assignment_Groups__c (User__c = u1.id, Active__c='True', Group_Name__c = ag1.id, Last_Assignment__c = datetime.valueOf('2009-01-01 21:13:24') );
        insert agu1;     

        Lead l3 = new Lead (FirstName='Dave',LastName='Barry', Company='CBS Corp', OwnerID=testGroup.id); //Set owner ID to Queue
        insert l3;
        update l3;

        test.stoptest();
       
    }

    static testMethod void myTest4() {

        // This code runs as the system user

        User u1;

        try{
          u1 = [select Id from User WHERE IsActive=True AND Profile.Name = 'System Administrator'  LIMIT 1];
        } catch (QueryException qe){

        List<User> users = [SELECT Id, Profile.PermissionsModifyAllData FROM User WHERE IsActive = true LIMIT 1000];

        for(User u : users){
            if(u.Profile.PermissionsModifyAllData = true){
              u1 = u;
              break;
        }
        }

        }

        System.debug(u1);

       //*****Create Queue
      
       Group testGroup = new Group ();
       testGroup.Name = 'TestQueue';
       testGroup.Type = 'Queue';
       insert testGroup;
      
       QueueSObject testQueue = new QueueSObject();
       testQueue.QueueId = testGroup.id;
       testQueue.SObjectType = 'Lead';
       insert testQueue;
     

       test.starttest();
       
        //Run test

        //Create Assignment Group
        Assignment_Group_Name__c ag1 = new Assignment_Group_Name__c (Name='TestAG', Type__c = 'Lead');
        insert ag1;       

        //Add Good Queue to Assignment Group
        Assignment_Group_Queues__c agq1 = new Assignment_Group_Queues__c(name=testGroup.Name ,Assignment_Group_Name__c = ag1.id );
        insert agq1;
       
          //Test for AG-Queues already assigned to another Assignment Group
        Assignment_Group_Queues__c agq2 = new Assignment_Group_Queues__c(name=testGroup.Name,Assignment_Group_Name__c = ag1.id );
        try {
            insert agq2;
        } catch (DmlException e){
             System.assert(e.getMessage().contains('CUSTOM_VALIDATION_EXCEPTION'), e.getMessage());
        } //catch

        test.stoptest();
    
 
  }
}

Summary:

My trigger is supposed to update a custom field on the related Account called Owner_s_Last_Activity_Date__c with the CreatedDate of the Task any time a new task created on the Account is assigned to the Account owner.  The trigger works great in the positive case (i.e. the Related Account lookup is populated), but I'm getting a null pointer exception any time the related Account lookup is null.  I know I need to filter tasks with no related Account out of my trigger logic, but I just can't seem to figure out how to do it.  Any help would be greatly appreciated.  Thanks!

trigger UpdateAccountFromActivity on Task (after insert) {

  Map<ID, Account> parentAccts = new Map<ID, Account>();
  List<Id> listIds = new List<Id>();

  for (Task task : Trigger.new){
    if(task.AccountId!=null)
      listIds.add(task.AccountId);
  }
   
  parentAccts = new Map<Id, Account>([SELECT ID, Owner_s_Last_Activity__c, OwnerID, (SELECT ID, CreatedDate, OwnerId, AccountID FROM Tasks WHERE AccountID!=null ) FROM Account WHERE ID IN :listIds]);

  for (Task task: Trigger.new){
      Account myParentAcc = parentAccts.get(task.AccountId);
      if(myParentAcc.OwnerId == task.OwnerId && task.AccountID != null){
       myParentAcc.Owner_s_Last_Activity__c = task.CreatedDate;
        }     
      }  
   update parentAccts.values();
}

Hey all,
I started the process of teaching myself Apex after several years as an advanced admin and I'm having a heck of a time trying to write a simple trigger. I've tried to hack it together based on what I've learned so far and so sample code from other triggers, but I just can't seem to figure it out.  Frankly, I'm embarrassed to post what I have so far because I don't think it's even in the ballpark. 
 

Can anyone help me sort out how to write this very simple trigger? Here's the use case:

We have a custom checkbox on the Lead object called Claim_Lead__c which is used as part of a claiming process by our reps.  Essentially, because we use round robin assignment sometimes leads get assigned to reps as part of the round robin, but another rep has already been working a lead from the same company (via prospecting, event list upload, etc.). In that case the rep who has been working the lead can claim it by clicking the Claim_Lead__c checkbox and submitting the Lead for approval. If the manager approves the request, the approval process automatically updates the Lead owner to the claiming rep and unchecks the Claim_Lead__c box. Both the Lead owner change and the unchecking of the Claim_Lead__c box happen as part of the final approval action on the approval flow. 

We also have another custom field on the User object called 'Lead_Owner_Reassign_Stamp__c'.  When the owner of a lead changes, if the Claim_Lead__c field also changes from True to False I want a trigger to fire which stamps the new Lead owner's ID into the Lead_Owner_Reassign_Stamp__c text field. 

Thanks in advance for your help!