-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
3Questions
-
8Replies
Running automated upload batches via a command line
To be clear, I am not a developer, my dev team at work is asking these questions as we prepare to migrate our legacy tickets in to SF cases. Any help or knowledge would be greatly appreciated.
Thank you in advance!
DaNae
- DaNae Graham
- May 17, 2017
- Like
- 0
How to populate setToAddresses in SingleEmail in my controller
Hi All,
I am trying to update a controller to send an email to 1 of 2 support teams in our company (depending on criteria). Currently the controller sends an email to our support team in Canada whenever a lead is converted (the email address is being queried by the name of the license the support team shares). What I want it to do is send an email to our US Support team if the lead is in the US and all other leads get sent to CA Support as is. I am having trouble setting this up. I know I need to use the SingleEmail class and populate setToAddresses but am having trouble with syntax and delivery.
Please advise and thank you so much!
Here is how the code is currently set up:
Here is what I have tried to do and did not work:
I also tried:
Lastly here is the whole controller if it helps:
/*
This is the controller for the Visual Force page leadConvertPage.
*/
public with sharing class leadConvertController extends PageControllerBase {
// This is the lead that is to be converted
public Lead leadToConvert {get; set;}
public List<Attachment> attachments {get; set;}
// Constructor for this controller
public leadConvertController(ApexPages.StandardController stdController) {
//get the ID to query for the Lead fields
Id leadId = stdController.getId();
leadToConvert = [SELECT Id, Status, OwnerId, Name, Company, Country, Lead_Type__c, Title__c, Dealer_Number__c, Promo_Code__c, LeadSource FROM Lead WHERE Id = :leadId];
attachments = [Select Id, ParentId, Body, Name FROM Attachment WHERE ParentId = :leadId];
}
/*
These are instances of the components' controllers which this class will access.
If you add new custom components, add an instance of the class here
*/
public leadConvertCoreComponentController myComponentController { get; set; }
public leadConvertTaskInfoComponentController myTaskComponentController { get; set; }
public leadConvertTaskDescComponentController myDescriptionComponentController { get; set; }
/*
These are the set methods which override the methods in PageControllerBase.
These methods will be called by the ComponentControllerBase class.
If you add new custom components, a new overridden set method must be added here.
*/
public override void setComponentController(ComponentControllerBase compController) {
myComponentController = (leadConvertCoreComponentController)compController;
}
public override void setTaskComponentController(ComponentControllerBase compController) {
myTaskComponentController = (leadConvertTaskInfoComponentController)compController;
}
public override void setDescriptionComponentController(ComponentControllerBase compController) {
myDescriptionComponentController = (leadConvertTaskDescComponentController)compController;
}
/*
These are the get methods which override the methods in PageControllerBase.
If you add new custom components, a new overridden get method must be added here.
*/
public override ComponentControllerBase getMyComponentController() {
return myComponentController;
}
public override ComponentControllerBase getmyTaskComponentController() {
return myTaskComponentController;
}
public override ComponentControllerBase getmyDescriptionComponentController() {
return myDescriptionComponentController;
}
// This method is called when the user clicks the Convert button on the VF Page
public PageReference convertLead() {
// This is the lead convert object that will convert the lead
Database.LeadConvert leadConvert = new database.LeadConvert();
// if a due date is set but the subject is not, then show an error
if (myTaskComponentController != null && myTaskComponentController.taskID.ActivityDate != null && string.isBlank(myTaskComponentController.taskID.Subject)){
PrintError('You must enter a Subject if a Due Date is set..');
return null;
}
// if Lead Status is not entered show an error
if (myComponentController != null && myComponentController.leadConvert.Status == 'NONE'){
PrintError('Please select a Lead Status.');
return null;
}
//set lead ID
leadConvert.setLeadId(leadToConvert.Id);
//if the main lead convert component is not set then return
if (myComponentController == NULL) return null;
//if the Account is not set, then show an error
if (myComponentController.selectedAccount == 'NONE')
{
PrintError('Please select an Account.');
return null;
}
// otherwise set the account id
else if (myComponentController != NULL && myComponentController.selectedAccount != 'NEW') {
leadConvert.setAccountId(myComponentController.selectedAccount);
}
//else if(myComponentController != null && myComponentController.selectedAccount == 'NEW' && attachments.size() <= 0) {
// PrintError('Cannot convert lead without contract! Please wait for the completed contract to be sent back.');
// return null;
//}
//set the lead convert status
leadConvert.setConvertedStatus(myComponentController.leadConvert.Status);
//set the variable to create or not create an opportunity
leadConvert.setDoNotCreateOpportunity(true);
//set the Opportunity name
leadConvert.setOpportunityName(((true)
? null : myComponentController.opportunityID.Name));
//set the owner id
leadConvert.setOwnerId(myComponentController.contactID.ownerID);
//set whether to have a notification email
leadConvert.setSendNotificationEmail(myComponentController.sendOwnerEmail);
system.debug('leadConvert --> ' + leadConvert);
//convert the lead
Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvert);
// Only update account new is selected.
if(myComponentController.selectedAccount == 'NEW') {
//get the ID to query for the Lead fields
Id accountId = leadConvertResult.getAccountId();
Account account = [SELECT Id, V1_Origin_ID__c, AFC_Dealer_ID__c, Internal_Notes__c FROM Account WHERE Id = :accountId];
account.Account_Type__c = leadToConvert.Lead_Type__c;
account.V1_Origin_ID__c = myComponentController.accountId.V1_Origin_ID__c;
account.AFC_Dealer_ID__c = myComponentController.accountId.AFC_Dealer_ID__c;
account.Internal_Notes__c = myComponentController.accountId.Internal_Notes__c;
account.AccountSource = leadToConvert.LeadSource;
account.Promo_Code__c = leadToConvert.Promo_Code__c;
// Email support for creating TradeRev Dealer
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Work around to retrieve necessary template and target object IDs
List<EmailTemplate> templates = [SELECT Id FROM EmailTemplate WHERE Name = 'Create Dealer Support Email'];
List<User> supportUsers = [SELECT Id FROM User WHERE FirstName = 'TradeRev' AND LastName = 'Support'];
mail.setTemplateId(templates.get(0).Id);
mail.setTargetObjectId(supportUsers.get(0).Id);
mail.setBccSender(false);
if (leadToConvert.Country == 'United States') {
List<String> myStrings = new List<String> { 'registrations@openlane.com' };
mail.setCcAddresses(myStrings);
}
if (leadToConvert.Country == 'Canada') {
List<String> myStrings = new List<String> { 'registrationscanada@openlane.com' };
mail.setCcAddresses(myStrings);
}
if (leadToConvert.Country == 'Ireland') {
List<String> myStrings = new List<String> { 'registrationscanada@openlane.com' };
mail.setCcAddresses(myStrings);
}
if (leadToConvert.Country == 'Mexico') {
List<String> myStrings = new List<String> { 'registrationscanada@openlane.com' };
mail.setCcAddresses(myStrings);
}
mail.setUseSignature(false);
mail.setWhatId(account.Id);
mail.saveAsActivity = false;
//Set email file attachments
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
// Get all of the attachments an add it to the account
for (Attachment a : attachments) {
// Adds attachment to emails
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
}
update account;
//Set attachment and send email
mail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
// Set Contact Title and Create TR User
Id newContactId = leadConvertResult.getContactId();
Contact contact = [SELECT Id from Contact WHERE Id = :newContactId];
contact.Title__c = leadToConvert.Title__c;
contact.Create_TR_User__c = true;
update contact;
// if the lead converting was a success then create a task
if (leadConvertResult.success)
{
// make sure that the task information component is being used and check to see if the user has filled out the Subject field
if(myTaskComponentController != NULL
&& myDescriptionComponentController != NULL
&& myTaskComponentController.taskID.subject != null)
{
//create a new task
Task taskToCreate = new Task();
//set whether there is a reminder
taskToCreate.IsReminderSet = myTaskComponentController.remCon.taskID.IsReminderSet;
//if the reminder is set, and the reminder's date is set
if (taskToCreate.IsReminderSet
&& myTaskComponentController.remCon.taskID.ActivityDate != null) {
//set the reminder time based on the reminder class's ActivityDate
//The date and time in the reminder class is converted into a datetime by the convertToDatetime() method
taskToCreate.ReminderDateTime =
convertToDatetime(
myTaskComponentController.remCon.taskID.ActivityDate,
myTaskComponentController.remCon.reminderTime
);
system.debug('taskToCreate.ReminderDateTime --> ' + taskToCreate.ReminderDateTime);
}
//set the whatId to the Opportunity Id
taskToCreate.WhatId = leadConvertResult.getOpportunityId();
//set the whoId to the contact Id
taskToCreate.WhoId = leadConvertResult.getContactId();
//set the subject
taskToCreate.Subject = myTaskComponentController.taskID.Subject;
//set the status
taskToCreate.Status = myTaskComponentController.taskID.Status;
//set the activity date
taskToCreate.ActivityDate = myTaskComponentController.taskID.ActivityDate;
//set the Priority
taskToCreate.Priority = myTaskComponentController.taskID.Priority;
//set the custom field Primary Resource (this is a custom field on the Task showing an example of adding custom fields to the page)
taskToCreate.Primary_Resource__c = myTaskComponentController.taskID.Primary_Resource__c;
//set the Description field which comes from the leadConvertTaskDescComponent
taskToCreate.Description = myDescriptionComponentController.taskID.Description;
//if the sendNotificationEmail variable in the leadConvertTaskDescComponent class is set then send an email
if (myDescriptionComponentController.sendNotificationEmail)
{
//create a new DMLOptions class instance
Database.DMLOptions dmlo = new Database.DMLOptions();
//set the trigger user email flag to true
dmlo.EmailHeader.triggerUserEmail = true;
//insert the task
database.insert(taskToCreate, dmlo);
}
else
{
//if the sendNotificationEmail field was not checked by the user then simply insert the task
insert taskToCreate;
}
}
// redirect the user to the newly created Account
PageReference pageRef = new PageReference('/' + leadConvertResult.getAccountId());
pageRef.setRedirect(true);
return pageRef;
}
else
{
//if converting was unsucessful, print the errors to the pageMessages and return null
System.Debug(leadConvertResult.errors);
PrintErrors(leadConvertResult.errors);
return null;
}
return null;
}
//this method will take database errors and print them to teh PageMessages
public void PrintErrors(Database.Error[] errors)
{
for(Database.Error error : errors)
{
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, error.message);
ApexPages.addMessage(msg);
}
}
//This method will put an error into the PageMessages on the page
public void PrintError(string error) {
ApexPages.Message msg = new
ApexPages.Message(ApexPages.Severity.ERROR, error);
ApexPages.addMessage(msg);
}
// given a date and time, where time is a string this method will return a DateTime
private DateTime convertToDatetime(Date d, string t) {
String timeFormat = DateTimeUtility.LocaleToTimeFormatMap().get(UserInfo.getLocale());
//if the local of the user uses AM/PM
if (timeFormat != null && timeFormat.endsWith('a')) {
//split the time into 2 strings 1 time and 1 am r pm
string [] reminderTime = t.split(' ');
//split the time into hour and minute
string hour = reminderTime[0].split(':')[0];
string min = reminderTime[0].split(':')[1];
//get the am or pm
string AM_PM = reminderTime[1];
//turn the hour into an integer
integer hr = Integer.valueOf(hour);
//if the am/pm part of the string is PM then add 12 hours
if (AM_PM.equalsIgnoreCase('PM')) hr += 12;
//return a new DateTime based on the above information
return (
DateTime.newInstance(
d,
Time.newInstance(
hr,
Integer.valueOf(min),
0,
0
)
)
);
}
//If the user's local does not use AM/PM and uses 24 hour time
else {
//split the time by a : to get hour and minute
string hour = t.split(':')[0];
string min = t.split(':')[1];
//turn the hour into an integer
integer hr = Integer.valueOf(hour);
//return a new DateTime based on the above information
return (
DateTime.newInstance(
d,
Time.newInstance(
hr,
Integer.valueOf(min),
0,
0
)
)
);
}
}
}
- DaNae Graham
- March 28, 2017
- Like
- 0
Apex Error: List index out of bounds: 0
System.ListException: List index out of bounds: 0
This error occurs on lines 13, 34, 64, and 93. It looks like the list is pulling no records and I cannot figure out why. I have confirmed that all required fields are captured. I referenced another article that said to use @isTest (seeAllData=true) and it is still not working.
Help would be greatly appreciated - thank you in advance!!
@isTest (seeAllData=true)
private class leadsTaskHandlerTest {
@isTest static void testLeadsWorkflow() {
Lead newLead = new Lead(
Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
LeadSource = 'Web', Country = 'Canada', Email = 'something@gmail.com',
Status = 'Open', Lead_Type__c = 'New Car Franchise');
insert newLead;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForLead('Email Introduction of TradeRev to main contact person', newLead.Id));
System.assert(taskCreatedForLead('Phone call to follow up from email of introduction', newLead.Id));
System.assert(taskCreatedForLead('Schedule an appointment with lead; no voicemail if you don\'t connect', newLead.Id));
System.assert(taskCreatedForLead('Attempt to contact lead to set appointment second time in the week', newLead.Id));
System.assert(taskCreatedForLead('Any interest in TradeRev?; let\'s schedule a demo', newLead.Id));
System.assert(taskCreatedForLead('Touch base to let them know about growth/updates of TradeRev', newLead.Id));
System.assert(taskCreatedForLead('Are they ready to talk about TradeRev?', newLead.Id));
}
@isTest static void testContractWorkflow() {
Lead newLead = new Lead(
Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
LeadSource = 'Web', Country = 'Canada',
Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
insert newLead;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Any questions on the Registration Forms?'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForLead('Are the Registration Forms complete?', newLead.Id));
}
@isTest static void testDueDateEmail() {
Lead newLead = new Lead(
Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
LeadSource = 'Web', Country = 'Canada', Email = 'something@gmail.com',
Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
insert newLead;
Task newTask = new Task( Priority = 'Normal',
Status = 'Not Started',
ActivityDate = Date.today(),
WhoId = newLead.Id);
insert newTask;
update newTask;
}
@isTest static void testFranchiseDealerWorkflow() {
Account newAccount = new Account(
Name = 'Test Franchise Dealer',
AccountSource = 'Web',
Account_Type__c = 'New Car Franchise');
insert newAccount;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training Franchise'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
System.assert(taskCreatedForAccount('Launch Cars; Walk back lot and try identify more cars they can load', newAccount.Id));
System.assert(taskCreatedForAccount('Has buyer been in touch to make arrangements for payment/pickup?', newAccount.Id));
System.assert(taskCreatedForAccount('Has buyer taken car? Mark car delivered', newAccount.Id));
System.assert(taskCreatedForAccount('Use TradeRev for the Live Appraisals', newAccount.Id));
System.assert(taskCreatedForAccount('Any other cars to launch?', newAccount.Id));
System.assert(taskCreatedForAccount('Reminder to buy cars on TradeRev', newAccount.Id));
System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
//System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));
//System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
//System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));
}
@isTest static void testIndepedentDealerWorkflow() {
Account newAccount = new Account(
Name = 'Test Independent Dealer',
AccountSource = 'Web',
Account_Type__c = 'Independent Dealer');
insert newAccount;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
System.assert(taskCreatedForAccount('Any questions on bidding?', newAccount.Id));
System.assert(taskCreatedForAccount('Have they been bidding? Any cars in pending?', newAccount.Id));
System.assert(taskCreatedForAccount('Won any cars? Discuss timing expectations for payment and pickup', newAccount.Id));
System.assert(taskCreatedForAccount('If a car has been won; have they paid and picked up car yet?', newAccount.Id));
System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));
System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));
}
static boolean taskCreatedForLead(String subject, Id id) {
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :id AND Subject = :subject];
if (tasks.size() > 0) {
tasks[0].Status = 'Completed';
update tasks[0];
return true;
}
else {
return false;
}
}
static boolean taskCreatedForAccount(String subject, Id id) {
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :id AND Subject = :subject];
if (tasks.size() > 0) {
tasks[0].Status = 'Completed';
update tasks[0];
return true;
}
else {
return false;
}
}
}
- DaNae Graham
- March 10, 2017
- Like
- 0
How to populate setToAddresses in SingleEmail in my controller
Hi All,
I am trying to update a controller to send an email to 1 of 2 support teams in our company (depending on criteria). Currently the controller sends an email to our support team in Canada whenever a lead is converted (the email address is being queried by the name of the license the support team shares). What I want it to do is send an email to our US Support team if the lead is in the US and all other leads get sent to CA Support as is. I am having trouble setting this up. I know I need to use the SingleEmail class and populate setToAddresses but am having trouble with syntax and delivery.
Please advise and thank you so much!
Here is how the code is currently set up:
Here is what I have tried to do and did not work:
I also tried:
Lastly here is the whole controller if it helps:
/*
This is the controller for the Visual Force page leadConvertPage.
*/
public with sharing class leadConvertController extends PageControllerBase {
// This is the lead that is to be converted
public Lead leadToConvert {get; set;}
public List<Attachment> attachments {get; set;}
// Constructor for this controller
public leadConvertController(ApexPages.StandardController stdController) {
//get the ID to query for the Lead fields
Id leadId = stdController.getId();
leadToConvert = [SELECT Id, Status, OwnerId, Name, Company, Country, Lead_Type__c, Title__c, Dealer_Number__c, Promo_Code__c, LeadSource FROM Lead WHERE Id = :leadId];
attachments = [Select Id, ParentId, Body, Name FROM Attachment WHERE ParentId = :leadId];
}
/*
These are instances of the components' controllers which this class will access.
If you add new custom components, add an instance of the class here
*/
public leadConvertCoreComponentController myComponentController { get; set; }
public leadConvertTaskInfoComponentController myTaskComponentController { get; set; }
public leadConvertTaskDescComponentController myDescriptionComponentController { get; set; }
/*
These are the set methods which override the methods in PageControllerBase.
These methods will be called by the ComponentControllerBase class.
If you add new custom components, a new overridden set method must be added here.
*/
public override void setComponentController(ComponentControllerBase compController) {
myComponentController = (leadConvertCoreComponentController)compController;
}
public override void setTaskComponentController(ComponentControllerBase compController) {
myTaskComponentController = (leadConvertTaskInfoComponentController)compController;
}
public override void setDescriptionComponentController(ComponentControllerBase compController) {
myDescriptionComponentController = (leadConvertTaskDescComponentController)compController;
}
/*
These are the get methods which override the methods in PageControllerBase.
If you add new custom components, a new overridden get method must be added here.
*/
public override ComponentControllerBase getMyComponentController() {
return myComponentController;
}
public override ComponentControllerBase getmyTaskComponentController() {
return myTaskComponentController;
}
public override ComponentControllerBase getmyDescriptionComponentController() {
return myDescriptionComponentController;
}
// This method is called when the user clicks the Convert button on the VF Page
public PageReference convertLead() {
// This is the lead convert object that will convert the lead
Database.LeadConvert leadConvert = new database.LeadConvert();
// if a due date is set but the subject is not, then show an error
if (myTaskComponentController != null && myTaskComponentController.taskID.ActivityDate != null && string.isBlank(myTaskComponentController.taskID.Subject)){
PrintError('You must enter a Subject if a Due Date is set..');
return null;
}
// if Lead Status is not entered show an error
if (myComponentController != null && myComponentController.leadConvert.Status == 'NONE'){
PrintError('Please select a Lead Status.');
return null;
}
//set lead ID
leadConvert.setLeadId(leadToConvert.Id);
//if the main lead convert component is not set then return
if (myComponentController == NULL) return null;
//if the Account is not set, then show an error
if (myComponentController.selectedAccount == 'NONE')
{
PrintError('Please select an Account.');
return null;
}
// otherwise set the account id
else if (myComponentController != NULL && myComponentController.selectedAccount != 'NEW') {
leadConvert.setAccountId(myComponentController.selectedAccount);
}
//else if(myComponentController != null && myComponentController.selectedAccount == 'NEW' && attachments.size() <= 0) {
// PrintError('Cannot convert lead without contract! Please wait for the completed contract to be sent back.');
// return null;
//}
//set the lead convert status
leadConvert.setConvertedStatus(myComponentController.leadConvert.Status);
//set the variable to create or not create an opportunity
leadConvert.setDoNotCreateOpportunity(true);
//set the Opportunity name
leadConvert.setOpportunityName(((true)
? null : myComponentController.opportunityID.Name));
//set the owner id
leadConvert.setOwnerId(myComponentController.contactID.ownerID);
//set whether to have a notification email
leadConvert.setSendNotificationEmail(myComponentController.sendOwnerEmail);
system.debug('leadConvert --> ' + leadConvert);
//convert the lead
Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvert);
// Only update account new is selected.
if(myComponentController.selectedAccount == 'NEW') {
//get the ID to query for the Lead fields
Id accountId = leadConvertResult.getAccountId();
Account account = [SELECT Id, V1_Origin_ID__c, AFC_Dealer_ID__c, Internal_Notes__c FROM Account WHERE Id = :accountId];
account.Account_Type__c = leadToConvert.Lead_Type__c;
account.V1_Origin_ID__c = myComponentController.accountId.V1_Origin_ID__c;
account.AFC_Dealer_ID__c = myComponentController.accountId.AFC_Dealer_ID__c;
account.Internal_Notes__c = myComponentController.accountId.Internal_Notes__c;
account.AccountSource = leadToConvert.LeadSource;
account.Promo_Code__c = leadToConvert.Promo_Code__c;
// Email support for creating TradeRev Dealer
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Work around to retrieve necessary template and target object IDs
List<EmailTemplate> templates = [SELECT Id FROM EmailTemplate WHERE Name = 'Create Dealer Support Email'];
List<User> supportUsers = [SELECT Id FROM User WHERE FirstName = 'TradeRev' AND LastName = 'Support'];
mail.setTemplateId(templates.get(0).Id);
mail.setTargetObjectId(supportUsers.get(0).Id);
mail.setBccSender(false);
if (leadToConvert.Country == 'United States') {
List<String> myStrings = new List<String> { 'registrations@openlane.com' };
mail.setCcAddresses(myStrings);
}
if (leadToConvert.Country == 'Canada') {
List<String> myStrings = new List<String> { 'registrationscanada@openlane.com' };
mail.setCcAddresses(myStrings);
}
if (leadToConvert.Country == 'Ireland') {
List<String> myStrings = new List<String> { 'registrationscanada@openlane.com' };
mail.setCcAddresses(myStrings);
}
if (leadToConvert.Country == 'Mexico') {
List<String> myStrings = new List<String> { 'registrationscanada@openlane.com' };
mail.setCcAddresses(myStrings);
}
mail.setUseSignature(false);
mail.setWhatId(account.Id);
mail.saveAsActivity = false;
//Set email file attachments
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
// Get all of the attachments an add it to the account
for (Attachment a : attachments) {
// Adds attachment to emails
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
}
update account;
//Set attachment and send email
mail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
// Set Contact Title and Create TR User
Id newContactId = leadConvertResult.getContactId();
Contact contact = [SELECT Id from Contact WHERE Id = :newContactId];
contact.Title__c = leadToConvert.Title__c;
contact.Create_TR_User__c = true;
update contact;
// if the lead converting was a success then create a task
if (leadConvertResult.success)
{
// make sure that the task information component is being used and check to see if the user has filled out the Subject field
if(myTaskComponentController != NULL
&& myDescriptionComponentController != NULL
&& myTaskComponentController.taskID.subject != null)
{
//create a new task
Task taskToCreate = new Task();
//set whether there is a reminder
taskToCreate.IsReminderSet = myTaskComponentController.remCon.taskID.IsReminderSet;
//if the reminder is set, and the reminder's date is set
if (taskToCreate.IsReminderSet
&& myTaskComponentController.remCon.taskID.ActivityDate != null) {
//set the reminder time based on the reminder class's ActivityDate
//The date and time in the reminder class is converted into a datetime by the convertToDatetime() method
taskToCreate.ReminderDateTime =
convertToDatetime(
myTaskComponentController.remCon.taskID.ActivityDate,
myTaskComponentController.remCon.reminderTime
);
system.debug('taskToCreate.ReminderDateTime --> ' + taskToCreate.ReminderDateTime);
}
//set the whatId to the Opportunity Id
taskToCreate.WhatId = leadConvertResult.getOpportunityId();
//set the whoId to the contact Id
taskToCreate.WhoId = leadConvertResult.getContactId();
//set the subject
taskToCreate.Subject = myTaskComponentController.taskID.Subject;
//set the status
taskToCreate.Status = myTaskComponentController.taskID.Status;
//set the activity date
taskToCreate.ActivityDate = myTaskComponentController.taskID.ActivityDate;
//set the Priority
taskToCreate.Priority = myTaskComponentController.taskID.Priority;
//set the custom field Primary Resource (this is a custom field on the Task showing an example of adding custom fields to the page)
taskToCreate.Primary_Resource__c = myTaskComponentController.taskID.Primary_Resource__c;
//set the Description field which comes from the leadConvertTaskDescComponent
taskToCreate.Description = myDescriptionComponentController.taskID.Description;
//if the sendNotificationEmail variable in the leadConvertTaskDescComponent class is set then send an email
if (myDescriptionComponentController.sendNotificationEmail)
{
//create a new DMLOptions class instance
Database.DMLOptions dmlo = new Database.DMLOptions();
//set the trigger user email flag to true
dmlo.EmailHeader.triggerUserEmail = true;
//insert the task
database.insert(taskToCreate, dmlo);
}
else
{
//if the sendNotificationEmail field was not checked by the user then simply insert the task
insert taskToCreate;
}
}
// redirect the user to the newly created Account
PageReference pageRef = new PageReference('/' + leadConvertResult.getAccountId());
pageRef.setRedirect(true);
return pageRef;
}
else
{
//if converting was unsucessful, print the errors to the pageMessages and return null
System.Debug(leadConvertResult.errors);
PrintErrors(leadConvertResult.errors);
return null;
}
return null;
}
//this method will take database errors and print them to teh PageMessages
public void PrintErrors(Database.Error[] errors)
{
for(Database.Error error : errors)
{
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, error.message);
ApexPages.addMessage(msg);
}
}
//This method will put an error into the PageMessages on the page
public void PrintError(string error) {
ApexPages.Message msg = new
ApexPages.Message(ApexPages.Severity.ERROR, error);
ApexPages.addMessage(msg);
}
// given a date and time, where time is a string this method will return a DateTime
private DateTime convertToDatetime(Date d, string t) {
String timeFormat = DateTimeUtility.LocaleToTimeFormatMap().get(UserInfo.getLocale());
//if the local of the user uses AM/PM
if (timeFormat != null && timeFormat.endsWith('a')) {
//split the time into 2 strings 1 time and 1 am r pm
string [] reminderTime = t.split(' ');
//split the time into hour and minute
string hour = reminderTime[0].split(':')[0];
string min = reminderTime[0].split(':')[1];
//get the am or pm
string AM_PM = reminderTime[1];
//turn the hour into an integer
integer hr = Integer.valueOf(hour);
//if the am/pm part of the string is PM then add 12 hours
if (AM_PM.equalsIgnoreCase('PM')) hr += 12;
//return a new DateTime based on the above information
return (
DateTime.newInstance(
d,
Time.newInstance(
hr,
Integer.valueOf(min),
0,
0
)
)
);
}
//If the user's local does not use AM/PM and uses 24 hour time
else {
//split the time by a : to get hour and minute
string hour = t.split(':')[0];
string min = t.split(':')[1];
//turn the hour into an integer
integer hr = Integer.valueOf(hour);
//return a new DateTime based on the above information
return (
DateTime.newInstance(
d,
Time.newInstance(
hr,
Integer.valueOf(min),
0,
0
)
)
);
}
}
}
- DaNae Graham
- March 28, 2017
- Like
- 0
Apex Error: List index out of bounds: 0
System.ListException: List index out of bounds: 0
This error occurs on lines 13, 34, 64, and 93. It looks like the list is pulling no records and I cannot figure out why. I have confirmed that all required fields are captured. I referenced another article that said to use @isTest (seeAllData=true) and it is still not working.
Help would be greatly appreciated - thank you in advance!!
@isTest (seeAllData=true)
private class leadsTaskHandlerTest {
@isTest static void testLeadsWorkflow() {
Lead newLead = new Lead(
Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
LeadSource = 'Web', Country = 'Canada', Email = 'something@gmail.com',
Status = 'Open', Lead_Type__c = 'New Car Franchise');
insert newLead;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForLead('Email Introduction of TradeRev to main contact person', newLead.Id));
System.assert(taskCreatedForLead('Phone call to follow up from email of introduction', newLead.Id));
System.assert(taskCreatedForLead('Schedule an appointment with lead; no voicemail if you don\'t connect', newLead.Id));
System.assert(taskCreatedForLead('Attempt to contact lead to set appointment second time in the week', newLead.Id));
System.assert(taskCreatedForLead('Any interest in TradeRev?; let\'s schedule a demo', newLead.Id));
System.assert(taskCreatedForLead('Touch base to let them know about growth/updates of TradeRev', newLead.Id));
System.assert(taskCreatedForLead('Are they ready to talk about TradeRev?', newLead.Id));
}
@isTest static void testContractWorkflow() {
Lead newLead = new Lead(
Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
LeadSource = 'Web', Country = 'Canada',
Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
insert newLead;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Any questions on the Registration Forms?'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForLead('Are the Registration Forms complete?', newLead.Id));
}
@isTest static void testDueDateEmail() {
Lead newLead = new Lead(
Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
LeadSource = 'Web', Country = 'Canada', Email = 'something@gmail.com',
Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
insert newLead;
Task newTask = new Task( Priority = 'Normal',
Status = 'Not Started',
ActivityDate = Date.today(),
WhoId = newLead.Id);
insert newTask;
update newTask;
}
@isTest static void testFranchiseDealerWorkflow() {
Account newAccount = new Account(
Name = 'Test Franchise Dealer',
AccountSource = 'Web',
Account_Type__c = 'New Car Franchise');
insert newAccount;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training Franchise'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
System.assert(taskCreatedForAccount('Launch Cars; Walk back lot and try identify more cars they can load', newAccount.Id));
System.assert(taskCreatedForAccount('Has buyer been in touch to make arrangements for payment/pickup?', newAccount.Id));
System.assert(taskCreatedForAccount('Has buyer taken car? Mark car delivered', newAccount.Id));
System.assert(taskCreatedForAccount('Use TradeRev for the Live Appraisals', newAccount.Id));
System.assert(taskCreatedForAccount('Any other cars to launch?', newAccount.Id));
System.assert(taskCreatedForAccount('Reminder to buy cars on TradeRev', newAccount.Id));
System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
//System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));
//System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
//System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));
}
@isTest static void testIndepedentDealerWorkflow() {
Account newAccount = new Account(
Name = 'Test Independent Dealer',
AccountSource = 'Web',
Account_Type__c = 'Independent Dealer');
insert newAccount;
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training'];
tasks[0].Status = 'Completed';
update tasks[0];
System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
System.assert(taskCreatedForAccount('Any questions on bidding?', newAccount.Id));
System.assert(taskCreatedForAccount('Have they been bidding? Any cars in pending?', newAccount.Id));
System.assert(taskCreatedForAccount('Won any cars? Discuss timing expectations for payment and pickup', newAccount.Id));
System.assert(taskCreatedForAccount('If a car has been won; have they paid and picked up car yet?', newAccount.Id));
System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));
System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));
}
static boolean taskCreatedForLead(String subject, Id id) {
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :id AND Subject = :subject];
if (tasks.size() > 0) {
tasks[0].Status = 'Completed';
update tasks[0];
return true;
}
else {
return false;
}
}
static boolean taskCreatedForAccount(String subject, Id id) {
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :id AND Subject = :subject];
if (tasks.size() > 0) {
tasks[0].Status = 'Completed';
update tasks[0];
return true;
}
else {
return false;
}
}
}
- DaNae Graham
- March 10, 2017
- Like
- 0