• Yadu
  • NEWBIE
  • 0 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 8
    Replies

Hi,

 

I am getting the below error in line 307 while deploying and doent show me any errors when I run it.Please help me out with this.

 

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Sales Opportunities must be linked to an Originating Officer but the system was not able to automatically determine your default officer code:

 

public class SalesTargetHandler {

// these class variables are used by the OnBeforeInsert and OnAfterInsert methods
Map<String, Sales_Target__c> offCodeToSalesTarget = new Map<String, Sales_Target__c>(); //map of officer codes to a new copy of a Sales Target object
Date salesTargetMaxEndDate;
Date salesTargetMinBegDate;

// these class variables are used by the OnBeforeInsert methods
set<Id> newRecordIds = new set<Id>();

// -------------------------------------------------------------------------------------------------------------------------------
// Constructor
public SalesTargetHandler(){
}

private void gatherQueryInfo(Sales_Target__c[] stRecords, Boolean createClones){
salesTargetMaxEndDate = system.today();
salesTargetMinBegDate = system.today();

if (stRecords.size()>0){
salesTargetMaxEndDate = stRecords.get(0).Target_Period_End__c;
salesTargetMinBegDate = stRecords.get(0).Target_Period_Start__c;
}

set<ID> officerCodeSfidSet = new set<ID>();
// first pass. get the data I need
for(Sales_Target__c st : stRecords){
officerCodeSfidSet.add(st.Officer_Code__c);
if(st.Target_Period_End__c > salesTargetMaxEndDate) salesTargetMaxEndDate = st.Target_Period_End__c;
if(st.Target_Period_Start__c < salesTargetMinBegDate) salesTargetMinBegDate = st.Target_Period_Start__c;
}

// retrieve the actual officer code values from the Officer_Code__c table
map<ID, Officer_Code__c> offCodeMap = new map<ID, Officer_Code__c>([select id, Officer_Code__c from Officer_Code__c where ID in :officerCodeSfidSet]);

for(Sales_Target__c st : stRecords){
Sales_Target__c mapST = st;
if (createClones){
mapST = st.Clone(true, true, true, true);
// we are going to depend on the object being configured to default these two fields to 0.
// The trigger code cannot handle null values for these fields
//if (mapST.Actual_Number_of_Calls__c==null) mapST.Actual_Number_of_Calls__c = 0;
//if (mapST.Actual_Number_of_Sales__c==null) mapST.Actual_Number_of_Sales__c = 0;
}
Officer_Code__c offCodeRec = offCodeMap.get(mapST.Officer_Code__c);
if (offCodeRec!=null) offCodeToSalesTarget.put(offCodeRec.Officer_Code__c, mapST);
}

}

private void checkSalesTargetOverlap(){
for(Sales_Target__c existST :[Select Id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Target_Period_Start__c ,Target_Period_End__c
from Sales_Target__c
where Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
and (Target_Period_End__c >= :salesTargetMinBegDate
or Target_Period_Start__c <= :salesTargetMaxEndDate) and Id NOT IN: newRecordIds])
{
Sales_Target__c newST = offCodeToSalesTarget.get(existST.Officer_Code__r.Officer_Code__c);

if(newST != null && existST.Officer_Code__c == newST.Officer_Code__c &&
((existST.Target_Period_Start__c <= newST.Target_Period_Start__c &&
existST.Target_Period_End__c >= newST.Target_Period_Start__c)
|| (existST.Target_Period_Start__c<= newST.Target_Period_End__c &&
existST.Target_Period_End__c>= newST.Target_Period_End__c) ||
(existST.Target_Period_Start__c<= newST.Target_Period_Start__c &&
existST.Target_Period_End__c >= newST.Target_Period_End__c)||
(existST.Target_Period_Start__c>= newST.Target_Period_Start__c &&
existST.Target_Period_End__c <= newST.Target_Period_End__c)

)){

String errorMsg = System.Label.Sales_Target_Error_Message;
newST.addError(errorMsg);
}
}
}

/**
*Method unlinks all the tasks and sales opp to the sales target.
*/
private void unlinkSOandTasks(Sales_Target__c[] stForUnlink){
set<Id> stIds = new set<Id>();
Map<Id,Sales_Target__c> oppStMap = new Map<Id,Sales_Target__c>();
Map<Id,Sales_Target__c> taskStMap = new Map<Id,Sales_Target__c>();
for(Sales_Target__c st : stForUnlink){
stIds.add(st.Id);
}
List<Sales_Opportunity__c> sopps = [Select Id, Sales_Target__c,Status__c,Referred_To__c,
Officer_Code__c, Product_Category__c
From Sales_Opportunity__c Where Sales_Target__c IN : stIds];

for(Sales_Opportunity__c sopp : sopps){
for(Sales_Target__c st : stForUnlink){
if(sopp.Sales_Target__c == st.Id){
oppStMap.put(sopp.Id,st);
}
}
}

for(Sales_Opportunity__c sopp : sopps){
sopp.Sales_Target__c = null;
if(sopp.Status__c == 'Closed Won'){
if(sopp.Product_Category__c == 'Loans'){
oppStMap.get(sopp.Id).Actual_Number_of_Sales__c--;
}else{
oppStMap.get(sopp.Id).Actual_Number_of_Sales_Non_Lending__c--;
}
if(sopp.Referred_To__c!=null && sopp.Referred_To__c!=sopp.Officer_Code__c)
oppStMap.get(sopp.Id).Actual_Number_of_Sales_Referred_By__c--;
}
}
update sopps;

List<Task> tasks = [Select Id, Sales_Target_Id__c,ActivityDate, Officer_Code__c, Type, Status, WhatId
From Task Where Sales_Target_Id__c IN : stIds];
for(Task t : tasks){
for(Sales_Target__c st : stForUnlink){
if(t.Sales_Target_Id__c == st.Id){
taskStMap.put(t.Id,st);
}
}
}
for(Task t : tasks){
t.Sales_Target_Id__c = null;
if((t.Type =='Call' || t.Type == 'In-Person Meeting') && t.Status=='Completed' && t.WhatId != null){
taskStMap.get(t.Id).Actual_Number_of_Calls_All__c--;
if(t.Type == 'In-Person Meeting')
taskStMap.get(t.Id).Actual_Number_of_Calls__c--;
}
}
update tasks;
}

private void linkSOandTasks(){
Sales_Opportunity__c[] salesOpp = new Sales_Opportunity__c[]{};
for(Sales_Opportunity__c opp : [SELECT id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Sales_Target__c,Count_Against_Targets__c,Close_Date__c,
Referred_To__c, Status__c, Product_Category__c FROM Sales_Opportunity__c
WHERE Count_Against_Targets__c = true
AND Sales_Target__c = null
AND Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND Close_Date__c <= :salesTargetMaxEndDate
AND Close_Date__c >= :salesTargetMinBegDate])
{
Sales_Target__c newST = offCodeToSalesTarget.get(opp.Officer_Code__r.Officer_Code__c);

if(newST != null && opp.Close_Date__c <= newST.Target_Period_End__c && opp.Close_Date__c >= newST.Target_Period_Start__c){
if(newST.Officer_Code__c == opp.Officer_Code__c
&& newST.Target_Period_End__c > opp.Close_Date__c && newST.Target_Period_Start__c < opp.Close_Date__c){//adding this if as a part of new changes.
opp.Sales_Target__c = newST.id;
salesOpp.add(opp);
System.debug('-----opp->>>>'+opp);
if(opp.Status__c == 'Closed Won'){
if(opp.Product_Category__c == 'Loans'){
newST.Actual_Number_of_Sales__c++;
}else{
newST.Actual_Number_of_Sales_Non_Lending__c++;
}
if(opp.Referred_To__c!=null && opp.Referred_To__c!=opp.Officer_Code__c)
newST.Actual_Number_of_Sales_Referred_By__c++;
}
}
}
}

if (!salesOpp.isEmpty())
update salesOpp;

Task[] tasksToUpdate = new Task[]{};
for(Task t : [SELECT Id, ActivityDate, Officer_Code__c, Type, Status,WhatId
FROM Task
WHERE Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND ActivityDate <= :salesTargetMaxEndDate
AND ActivityDate >= :salesTargetMinBegDate]){

Sales_Target__c newST = offCodeToSalesTarget.get(t.Officer_Code__c);

if(newST != null && t.ActivityDate <= newST.Target_Period_End__c && t.ActivityDate >= newST.Target_Period_Start__c && (t.Type =='Call' || t.Type == 'In-Person Meeting') ){
t.Sales_Target_Id__c = newST.Id;
tasksToUpdate.add(t);
if((t.Type =='Call' || t.Type == 'In-Person Meeting') && t.Status=='Completed' &&
t.WhatId != Null){
newST.Actual_Number_of_Calls_All__c++;
if(t.Type == 'In-Person Meeting')
newST.Actual_Number_of_Calls__c++;
}
}
}

if(!tasksToUpdate.isEmpty())
update tasksToUpdate;
}

private void setVisibility(Sales_Target__c[] stRecords, map<Id, Sales_Target__c> oldRecordMap,String event){
//Checks if new record is added, calculates sharing for them.
if(event == 'Insert'){
Visibility_Utility vu = new Visibility_Utility();
vu.createShare('Sales_Target__c',stRecords);
}

//checks if the office code values has been updated and
//re-calculate the sharing if it is so.
if(event == 'Update'){
List<Sales_Target__c> reShareSt = new List<Sales_Target__c>();

for(Sales_Target__c st : stRecords){
if(oldRecordMap.get(st.Id).Officer_Code__c != st.Officer_Code__c){
reShareSt.add(st);
}
}
Visibility_Utility vu = new Visibility_Utility();
vu.createShare('Sales_Target__c',reShareSt);
}
}

public void OnBeforeInsert(Sales_Target__c[] workingList){
gatherQueryInfo(workingList, false);
checkSalesTargetOverlap();
}

public void OnAfterInsert(Sales_Target__c[] workingList){
gatherQueryInfo(workingList, true);
linkSOandTasks();
if(offCodeToSalesTarget.size() > 0)
update offCodeToSalesTarget.values();

setVisibility(workingList,null,'Insert');
}

public void onBeforeUpdate(Sales_Target__c[] stRecords, map<Id, Sales_Target__c> oldRecordMap){
Sales_Target__c[] workingList = new Sales_Target__c[]{};
Sales_Target__c oldRec;

for(Sales_Target__c st: stRecords){
//if(oldRecordMap != null)
oldRec = oldRecordMap.get(st.Id);
if(st.Officer_Code__c!=oldRec.Officer_Code__c || st.Target_Period_Start__c!=oldRec.Target_Period_Start__c || st.Target_Period_End__c!=oldRec.Target_Period_End__c){
workingList.add(st);
newRecordIds.add(st.Id);
}
}

if(!workingList.isEmpty()){
gatherQueryInfo(workingList, false);
checkSalesTargetOverlap();
unlinkSOandTasks(workingList);
linkSOandTasks();
}

}

public void OnAfterUpdate(Sales_Target__c[] workingList, map<Id, Sales_Target__c> oldRecordMap){
setVisibility(workingList,oldRecordMap,'Update');
}


//Test method for this class.
public static testMethod void testThisClass(){
string TYPE_ROCODE = 'Rep Officer Code';
string TYPE_AOCODE = 'Account Officer Code';
User testAOUser = [select id from User where id!=:UserInfo.getUserId() and Profile.Name='Rep Officer' limit 1];
User testROUser = [select id from User where id!=:UserInfo.getUserId() and Profile.Name='Account Officer' limit 1];

if (testAOUser==null || testROUser==null) return;

Officer_Code__c aoCode = new Officer_Code__c(Type__c=TYPE_AOCODE, Officer_Code__c='AAA', Assigned_To_Id__c=testAOUser.Id);
Officer_Code__c roCode = new Officer_Code__c(Type__c=TYPE_ROCODE, Officer_Code__c='RR', Assigned_To_Id__c=testROUser.Id);
List<Officer_Code__c> ocList = new List<Officer_Code__c>();
ocList.add(aoCode);
ocList.add(roCode);
insert ocList;

Office__c testOffice1 = new Office__c(Office_Code__c='OO1', Region__c='Brazil');
Office__c testOffice2 = new Office__c(Office_Code__c='OO2', Region__c='Brazil');
insert new Office__c[]{testOffice1, testOffice2};

// create the two test cases for RO visibility
// Office = 'OO1', RO Code = 'RR' ==> RO User
Data_Visibility__c testRODV1 = new Data_Visibility__c(Office_Id__c=testOffice1.Id, Officer_Code_Id__c=roCode.Id, User_Id__c=testROUser.Id);
// Office = 'OO2' ==> RO User
Data_Visibility__c testRODV2 = new Data_Visibility__c(Office_Id__c=testOffice2.Id, User_Id__c=testROUser.Id);

// create the test case for AO visibility
// AO Code = 'AAA' ==> AO User
Data_Visibility__c testAODV = new Data_Visibility__c(Officer_Code_Id__c=aoCode.Id, User_Id__c=testAOUser.Id);


insert new Data_Visibility__c[]{testRODV1, testRODV2, testAODV};



Sales_Opportunity__c so = new Sales_Opportunity__c();
List<Sales_Opportunity__c> soList = new List<Sales_Opportunity__c>();
so.Name = 'test';
so.Close_Date__c = System.Today();
so.Officer_Code__c= ocList[0].Id;
so.Product_Category__c = 'Domestic Deposits';
so.stage__c ='Closed Won';
soList.add(so);
insert soList;

Sales_Opportunity__c so1 = new Sales_Opportunity__c();
so.Name = 'test';
so.Close_Date__c = System.Today();
so.Officer_Code__c= ocList[0].Id;
so.Product_Category__c = 'Loans';
so.stage__c ='Closed Won';
insert so1;




Task t = new Task();
t.ActivityDate = System.Today();
// t.Officer_Code__c= ocList[0].Officer_Code__c;
t.status = 'Completed';
t.Type = 'In-Person Meeting';
t.WhatId = soList[0].Id;
insert t;


Sales_Target__c st = new Sales_Target__c();
List<Sales_Target__c> stList = new List<Sales_Target__c>();
st.Name = 'test';
st.Target_Period_Start__c = System.Today().addDays(-2);
st.Target_Period_End__c = System.Today().addDays(5);
st.Target_Number_of_Sales__c = 3;
st.Target_Number_of_Sales_Non_Lending__c= 3;
st.Target_Number_of_Calls_All__c = 3;
st.Target_Number_of_Calls__c = 3;
st.Officer_Code__c = ocList[0].Id;


Sales_Target__c st1 = new Sales_Target__c();
st1.Name = 'test';
st1.Target_Period_Start__c = System.Today();
st1.Target_Period_End__c = System.Today().addDays(2);
st1.Target_Number_of_Sales__c = 3;
st1.Target_Number_of_Sales_Non_Lending__c= 3;
st1.Target_Number_of_Calls_All__c = 3;
st1.Target_Number_of_Calls__c = 3;
st1.Officer_Code__c = ocList[0].Id;

stList.add(st1);
insert stList;

stList[0].Officer_Code__c = ocList[1].Id;
st1.Target_Period_End__c = System.Today();
update stList[0];

delete stList;
undelete stList;

}
}

  • March 22, 2012
  • Like
  • 0

I am trying to deploy into Production and getting these error message

 

Failure Message: "System.DmlException: Update failed. First exception on row 0 with id a0mE0000000PDHGIA4; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Sales Opportunities must be linked to an Originating Officer but the system was not able to automatically determine your default officer code: []"

 

Deployment says error in line 518

public class SalesOppurtunityHandler {

public SalesOppurtunityHandler(){}

public void OnBeforeCall(Sales_Opportunity__c[] newRecords, Map<Id, Sales_Opportunity__c> oldRecordMap, String flag){
List<Sales_Opportunity__c> workingList = new List<Sales_Opportunity__c>();

for(Sales_Opportunity__c opp : newRecords){
if(opp.Referred_To__c!=opp.Officer_Code__c || (opp.Referred_To__c== null && opp.Officer_Code__c == null)){
workingList.add(opp);
}else {
opp.addError(Label.Sales_Oppurtunity_Error_Message);
}
}

Sales_Opportunity__c[] validRecords = new Sales_Opportunity__c[]{};
set<Id> offCodeIdSet = new set<Id>();

System.debug('*************In OnBeforeCall');
assignOfficerCodes(workingList, validRecords, oldRecordMap, offCodeIdSet, flag);

map<Id, Officer_Code__c> offCodeMap = new map<Id, Officer_Code__c>([select Id, Officer_Code__c from Officer_Code__c where Id in :offCodeIdSet]);
System.debug('*******Office Code Map: ' + offCodeMap);
System.debug('*******Valid recs: ' + validRecords);
linkSalesTargets(validRecords, oldRecordMap, offCodeMap, flag);


referalOwnerChange(workingList,oldRecordMap);
}

//Adding to change the ownership to refered to.
public void referalOwnerChange(Sales_Opportunity__c[] newRecords, Map<Id, Sales_Opportunity__c> oldRecordMap){
set<Id> ocIdSet = new set<Id>();
Boolean isSendMail = false;
List<Sales_Opportunity__c> oppForMailSending = new List<Sales_Opportunity__c>();
for(Sales_Opportunity__c so : newRecords){
if(so.Referred_To__c!= null)
ocIdSet.add(so.Referred_To__c);
}

Map<Id,Officer_Code__c> ocMap = new Map<Id,Officer_Code__c>([Select Assigned_To_Id__c, Assigned_To_Id__r.isActive,Assigned_To_Id__r.Email
From Officer_Code__c Where Id IN: ocIdSet AND Assigned_To_Id__r.isActive = true]);
if(oldRecordMap == null){
for(Sales_Opportunity__c so : newRecords){
if(so.Referred_To__c!= null && ocMap.get(so.Referred_To__c) != null){
so.ownerId = ocMap.get(so.Referred_To__c).Assigned_To_Id__c;
}
}
}else{
for(Sales_Opportunity__c so : newRecords){
if(so.Referred_To__c!= null && ocMap.get(so.Referred_To__c) != null && so.Referred_To__c!= oldRecordMap.get(so.id).Referred_To__c){
if(ocMap.get(so.Referred_To__c).Assigned_To_Id__r.isActive){
isSendMail = true;
oppForMailSending.add(so);
so.ownerId = ocMap.get(so.Referred_To__c).Assigned_To_Id__c;
}
}
}
}
if(isSendMail)
sendMail(oppForMailSending,ocMap);

}

//Method Send email Logic
public void sendMail(List<Sales_Opportunity__c> newRecords,Map<Id,Officer_Code__c> ocMap){
Messaging.SingleEmailMessage[] grpmails = new Messaging.SingleEmailMessage[]{};
//String templateName = CommonSettings__c.getInstance('Referred To Email').Value__c; // not doing a null check just to make sure we always create a custom setting record for this.
//List<EmailTemplate> myEmailTemplate= [select Id,Name from EmailTemplate where Name=:templateName LIMIT 1 ];
List<string> addresses;
Boolean sendMail = false;
for(Sales_Opportunity__c so : newRecords){
Messaging.SingleEmailMessage oEmail;
if(so.Referred_To__c!= null){
sendMail = true;
addresses = new List<String>();
if(ocMap.get(so.Referred_To__c) != null)
addresses.add(ocMap.get(so.Referred_To__c).Assigned_To_Id__r.Email);
oEmail = new Messaging.SingleEmailMessage();
oEmail.setTargetObjectId(UserInfo.getUserId());
oEmail.setToAddresses(addresses);
oEmail.setSubject('Refered To Mail');
oEmail.setHtmlBody(EmailContent(so));
//oEmail.setTemplateId(myEmailTemplate[0].Id);
oEmail.setsaveAsActivity(false);
if(!addresses.isEmpty())
grpmails.add(oEmail);
}

}
if(sendMail)
Messaging.SendEmailResult [] oResult =
Messaging.sendEmail(grpmails);
}

public String EmailContent(Sales_Opportunity__c salesopp)
{
//String emilbodycontent='Dear Sir,';
String emilbodycontent='<p>A Sales Opportunity has been referred to you by '+ salesopp.Officer__c+'.</p>';
emilbodycontent+='If you have a Salesforce login, you can view this Sales Opportunity here: <br/> <href>'+CommonSettings__c.getInstance('serverUrl').Value__c +salesopp.Id+ '</href>';

return emilbodycontent;
}

public void OnAfterCall(Sales_Opportunity__c[] soRecords, String flag){
Set<Id> stIds = new Set<Id>();
if(flag == 'Insert'){
set<Id> ocIdSet = new set<Id>();
Boolean isSendMail = false;
List<Sales_Opportunity__c> oppForMailSending = new List<Sales_Opportunity__c>();
for(Sales_Opportunity__c so : soRecords){
if(so.Referred_To__c!= null)
ocIdSet.add(so.Referred_To__c);
}

Map<Id,Officer_Code__c> ocMap = new Map<Id,Officer_Code__c>([Select Assigned_To_Id__c, Assigned_To_Id__r.isActive,Assigned_To_Id__r.Email
From Officer_Code__c Where Id IN: ocIdSet AND Assigned_To_Id__r.isActive = true]);

for(Sales_Opportunity__c so : soRecords){
if(so.Referred_To__c!= null){
isSendMail = true;
oppForMailSending.add(so);
}
}
if(isSendMail)
sendMail(oppForMailSending,ocMap);
}

for(Sales_Opportunity__c opp : soRecords){
if(opp.Sales_Target__c != null)
stIds.add(opp.Sales_Target__c);
}

map<Id,Sales_Target__c> stRecords = new map<Id, Sales_Target__c>([Select Id, Actual_Number_of_Sales_Non_Lending__c, Actual_Number_of_Sales__c, Actual_Number_of_Sales_Referred_By__c from Sales_Target__c where Id IN :stIds]);

if(stRecords.size() > 0){
for(Sales_Opportunity__c opp : soRecords){
if(opp.Sales_Target__c!=null && opp.Status__c=='Closed Won' && opp.Count_Against_Targets__c==true){
if(flag=='Delete'){
//stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales__c--;
if(opp.Product_Category__c == 'Loans'){
stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales__c--;
}else{
stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales_Non_Lending__c--;
}
}
else{
//stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales__c++;
if(opp.Product_Category__c == 'Loans'){
//stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales__c++;
}else{
//stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales_Non_Lending__c++;
}
}

if(opp.Referred_To__c!=null && opp.Referred_To__c!=opp.Officer_Code__c){
if(flag=='Delete')
stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales_Referred_By__c--;
else
stRecords.get(opp.Sales_Target__c).Actual_Number_of_Sales_Referred_By__c++;
}
}
}
update stRecords.values();
}


//For sharing records using Visibility_Utility class.
if(flag == 'Insert'){
Visibility_Utility vu = new Visibility_Utility();
vu.createShare('Sales_Opportunity__c',soRecords);
}
}


//Adding this method to check if the office code values has been updated and
//re-calculate the sharing if it is so.
public void OnAfterUpdateCall(Map<Id,Sales_Opportunity__c> oldSoMap,Sales_Opportunity__c[] newSo, String flag){
if(flag == 'Update'){
List<Sales_Opportunity__c> reShareSo = new List<Sales_Opportunity__c>();

for(Sales_Opportunity__c so : newSo){
if(oldSoMap.get(so.Id).Officer_Code__c != so.Officer_Code__c ||
oldSoMap.get(so.Id).Referred_To__c != so.Referred_To__c){
reShareSo.add(so);
}
}
Visibility_Utility vu = new Visibility_Utility();
vu.createShare('Sales_Opportunity__c',reShareSo);
}
}

private void assignOfficerCodes(Sales_Opportunity__c[] newRecords, Sales_Opportunity__c[] validRecords, map<Id, Sales_Opportunity__c> oldRecordMap,
set<Id> offCodeIdSet, String flag){

User currUser = [Select Id, Default_Officer_Code__c from User where Id = :UserInfo.getUserId()];

//Get the Officer codes according to Assigned To field and Default Office code
List<Officer_Code__c> offCodeAssignedList = new List<Officer_Code__c>([select id, Officer_Code__c from Officer_Code__c where Assigned_To_Id__c = :currUser.Id]);
List<Officer_Code__c> offCodeDefaultList = new List<Officer_Code__c>([select id, Officer_Code__c from Officer_Code__c
where Officer_Code__c = :currUser.Default_Officer_Code__c]);
Sales_Opportunity__c oldOpp;
for(Sales_Opportunity__c optyRec: newRecords){
Boolean addRecord = false;
if(oldRecordMap != null)
oldOpp = oldRecordMap.get(optyRec.Id);
if(flag=='Insert' || (flag=='Update' && oldOpp!=null &&
(optyRec.Close_Date__c!=oldOpp.Close_Date__c ||
optyRec.Product_Category__c !=oldOpp.Product_Category__c ||
optyRec.Officer_Code__c!=oldOpp.Officer_Code__c ||
optyRec.Count_Against_Targets__c!=oldOpp.Count_Against_Targets__c ||
optyRec.Referred_To__c!=oldOpp.Referred_To__c || optyRec.Status__c!=oldOpp.Status__c))){

if(optyRec.Officer_Code__c == null){
if(offCodeAssignedList.size() == 1){
optyRec.Officer_Code__c = offCodeAssignedList[0].Id;
addRecord = true;
}else if(offCodeDefaultList.size() > 0){
optyRec.Officer_Code__c = offCodeDefaultList[0].Id;
addRecord = true;
}else{
optyRec.addError(Label.Populating_Originating_Officer);
}
}else
addRecord = true;
if(addRecord==true || flag=='Update')
validRecords.add(optyRec);
offCodeIdSet.add(optyRec.Officer_Code__c);
if(oldOpp != null)
offCodeIdSet.add(oldOpp.Officer_Code__c);
}
}
}

private void linkSalesTargets(Sales_Opportunity__c[] salesOptyList, Map<Id, Sales_Opportunity__c> oldRecordMap, Map<Id, Officer_Code__c> offCodeMap, String flag){
map<Id, Sales_Target__c> stRecords = new map<Id, Sales_Target__c>([Select Id,Actual_Number_of_Sales_Non_Lending__c, Target_Period_Start__c, Target_Period_End__c, Actual_Number_of_Sales__c, Officer_Code__c,
Actual_Number_of_Sales_Referred_By__c from Sales_Target__c where Officer_Code__c IN :offCodeMap.keySet()]);

map<String, List<Sales_Target__c>> offCodeToSalesTarget = new map<String, List<Sales_Target__c>>();

for(Sales_Target__c st : stRecords.values()){
Officer_Code__c offCodeRec = offCodeMap.get(st.Officer_Code__c);
if(offCodeToSalesTarget.get(offCodeRec.Officer_Code__c) != null){
offCodeToSalesTarget.get(offCodeRec.Officer_Code__c).add(st);
}else{
offCodeToSalesTarget.put(offCodeRec.Officer_Code__c, new Sales_Target__c[]{st});
}
}

System.debug('********Officer Codes to Sales Target: ' + offCodeToSalesTarget);
List<Sales_Target__c> stUpdateList = new List<Sales_Target__c>();
List<Id> decOriginatedList = new List<Id>();
List<Sales_Opportunity__c> decSaleOpp = new List<Sales_Opportunity__c>();
List<Id> decReferredList = new List<Id>();

if(flag=='Insert'){
for(Sales_Opportunity__c opp : salesOptyList){
if(opp.Count_Against_Targets__c == true){
Officer_Code__c ofCode = offCodeMap.get(opp.Officer_Code__c);
List<Sales_Target__c> newSTList = offCodeToSalesTarget.get(ofCode.Officer_Code__c);
System.debug('********Linked newSTList ' +newSTList );
if(newSTList!=null){
for(Sales_Target__c st : newSTList){
if(opp.Close_Date__c >= st.Target_Period_Start__c && opp.Close_Date__c <= st.Target_Period_End__c){
System.debug('********Linked Sales Target ' + st.Id + ' to Opty ' + opp.Id);
opp.Sales_Target__c = st.Id;
if(opp.Status__c == 'Closed Won'){
if(opp.Product_Category__c == 'Loans'){
st.Actual_Number_of_Sales__c++;
}else{
st.Actual_Number_of_Sales_Non_Lending__c++;
}
//st.Actual_Number_of_Sales__c++;
if(opp.Referred_To__c!=null && opp.Referred_To__c!=ofCode.Id)
st.Actual_Number_of_Sales_Referred_By__c++;
stUpdateList.add(st);
}break;
}
}
}
}
}
}else{
System.debug('***********In Update'+salesOptyList);
for(Sales_Opportunity__c opp : salesOptyList){
Sales_Opportunity__c oldOpp = oldRecordMap.get(opp.Id);
if(opp.Close_Date__c!=oldOpp.Close_Date__c || opp.Officer_Code__c!=oldOpp.Officer_Code__c || opp.Count_Against_Targets__c!=oldOpp.Count_Against_Targets__c){
if(opp.Count_Against_Targets__c==true && opp.Officer_Code__c!=null){
Officer_Code__c ofCode = offCodeMap.get(opp.Officer_Code__c);
List<Sales_Target__c> newSTList = offCodeToSalesTarget.get(ofCode.Officer_Code__c);
if(newSTList!=null){
for(Sales_Target__c st : newSTList){
if(opp.Close_Date__c >= st.Target_Period_Start__c && opp.Close_Date__c <= st.Target_Period_End__c){
opp.Sales_Target__c = st.Id;
if(oldOpp.Sales_Target__c!=null && oldOpp.Status__c=='Closed Won' && oldOpp.Count_Against_Targets__c==true){
decOriginatedList.add(oldOpp.Sales_Target__c);
decSaleOpp.add(oldOpp);
if(oldOpp.Referred_To__c!=null && oldOpp.Referred_To__c!=oldOpp.Officer_Code__c)
decReferredList.add(oldOpp.Sales_Target__c);
}
if(opp.Status__c == CommonSettings__c.getInstance('Closed Won').Value__c){// make sure config value is always present
if(opp.Product_Category__c == 'Loans'){
st.Actual_Number_of_Sales__c++;
}else{
st.Actual_Number_of_Sales_Non_Lending__c++;
}
//st.Actual_Number_of_Sales__c++;
if(opp.Referred_To__c!=null && opp.Referred_To__c!=ofCode.Id)
st.Actual_Number_of_Sales_Referred_By__c++;
stUpdateList.add(st);
}
}
}
}else{

opp.Sales_Target__c = null;
Officer_Code__c ofCode1;
List<Sales_Target__c> newSTList1;
System.debug('===In decrement block===='+oldOpp.Officer_Code__c);
if(oldOpp.Officer_Code__c != null)
ofCode1 = offCodeMap.get(oldOpp.Officer_Code__c);
System.debug('===In decrement block2===='+ofCode1 );
if(ofCode1 != null)
newSTList1 = offCodeToSalesTarget.get(ofCode1.Officer_Code__c);
System.debug('===In decrement block3===='+newSTList1 );
if(newSTList1 != null){
for(Sales_Target__c st : newSTList1){
if(oldopp.Status__c == CommonSettings__c.getInstance('Closed Won').Value__c){// make sure config value is always present
if(oldopp.Product_Category__c == 'Loans'){
st.Actual_Number_of_Sales__c--;
}else{
st.Actual_Number_of_Sales_Non_Lending__c--;
}

stUpdateList.add(st);
}
}
}
}
}else{
opp.Sales_Target__c = null;
if(oldOpp.Sales_Target__c!=null && oldOpp.Status__c=='Closed Won' && oldOpp.Count_Against_Targets__c==true){
decOriginatedList.add(oldOpp.Sales_Target__c);
decSaleOpp.add(oldOpp);
if(oldOpp.Referred_To__c!=null && oldOpp.Referred_To__c!=oldOpp.Officer_Code__c)
decReferredList.add(oldOpp.Sales_Target__c);
}
}
}else if(opp.Status__c!=oldOpp.Status__c){
if(opp.Sales_Target__c!=null && opp.Count_Against_Targets__c==true){
if(opp.Status__c == 'Closed Won'){
Sales_Target__c stRec = stRecords.get(opp.Sales_Target__c);
//stRec.Actual_Number_of_Sales__c++;
if(opp.Product_Category__c == 'Loans'){
stRec.Actual_Number_of_Sales__c++;
}else{
stRec.Actual_Number_of_Sales_Non_Lending__c++;
}
if(opp.Referred_To__c!=null && opp.Referred_To__c!=opp.Officer_Code__c)
stRec.Actual_Number_of_Sales_Referred_By__c++;

stUpdateList.add(stRec);
}else if(oldOpp.Status__c == 'Closed Won'){
Sales_Target__c stRec = stRecords.get(opp.Sales_Target__c);
if(opp.Product_Category__c == 'Loans'){
stRec.Actual_Number_of_Sales__c--;
}else{
stRec.Actual_Number_of_Sales_Non_Lending__c--;
}
stUpdateList.add(stRec);
}else{
decOriginatedList.add(opp.Sales_Target__c);
decSaleOpp.add(oldOpp);
if(opp.Referred_To__c!=null && opp.Referred_To__c!=opp.Officer_Code__c)
decReferredList.add(opp.Sales_Target__c);
}
}
}else if(opp.Referred_To__c!=oldOpp.Referred_To__c){
if(opp.Status__c == 'Closed Won' && opp.Sales_Target__c!=null && opp.Count_Against_Targets__c==true){
Sales_Target__c stRec = stRecords.get(opp.Sales_Target__c);
if(opp.Referred_To__c!=null && opp.Referred_To__c!=opp.Officer_Code__c && oldOpp.Referred_To__c==null){
stRec.Actual_Number_of_Sales_Referred_By__c++;
stUpdateList.add(stRec);
}else if(opp.Referred_To__c==null && oldOpp.Referred_To__c!=null && oldOpp.Referred_To__c!=oldOpp.Officer_Code__c){
if(stRec != null){
stRec.Actual_Number_of_Sales_Referred_By__c--;
stUpdateList.add(stRec);
}
}
}
}else{
System.debug('else--------');
if(opp.Status__c == 'Closed Won'){
Sales_Target__c stRec = stRecords.get(opp.Sales_Target__c);
if(stRec != null){
if(opp.Product_Category__c == 'Loans'){
if(oldOpp.Product_Category__c != 'Loans'){
stRec.Actual_Number_of_Sales_Non_Lending__c--;
stRec.Actual_Number_of_Sales__c++;
stUpdateList.add(stRec);
}
}else{
if(oldOpp.Product_Category__c == 'Loans'){
stRec.Actual_Number_of_Sales_Non_Lending__c++;
stRec.Actual_Number_of_Sales__c--;
stUpdateList.add(stRec);
}
}
}
}
}
}
}

if(stUpdateList.size() > 0)
update stUpdateList;

map<Id, Sales_Target__c> targetRecords = new map<Id, Sales_Target__c>([Select Id, Target_Period_Start__c, Target_Period_End__c, Actual_Number_of_Sales__c, Actual_Number_of_Sales_Non_Lending__c, Officer_Code__c,
Actual_Number_of_Sales_Referred_By__c from Sales_Target__c where Id IN :decOriginatedList OR Id IN :decReferredList]);

for(Sales_Opportunity__c so: decSaleOpp){
if(so.Product_Category__c == 'Loans'){
targetRecords.get(so.Sales_Target__c).Actual_Number_of_Sales__c--;
}else{
targetRecords.get(so.Sales_Target__c).Actual_Number_of_Sales_Non_Lending__c--;
}
}

for(Id stId: decReferredList)
targetRecords.get(stId).Actual_Number_of_Sales_Referred_By__c--;

update targetRecords.values();
}

 

}


  • March 21, 2012
  • Like
  • 0

 

Good Morning..!!!

 

I have two Objects - Sales Oppurtunity and Sales Target.

On Sales Oppurtunity, there are Close_Date__c(Date),Count_Against_Targets__c(Checkbox),Officer_Code__c(Lookup to Officer Code Table), Sales_Target__c(Lookup to Sales target) fields

 

On Sales target there are Target_Period_End__c(Date),Target_Period_Start__c(Date),Officer_Code__c(Lookup to Officer Code Table),Actual_Number_of_Calls__c(Number),

Actual_Number_of_Sales__c(Number) fields.

 

I wrote the Trigger on Sales Target with the below mentioned requirement

I.e If a new Sales Target record is created, it should check for records in Sales Oppurtunity with same Officer_Code__c,Count_Against_Targets__c = True and 

Close_Date__c  <= Target_Period_End__c

AND  SO.Close_Date__c       >= Target_Period_Start__c

If record exists, then that new Sales Target record should contain those Sales Oppurtunity records in the Related list. After that the Actual_Number_of_Sales__c filed get re-calculated in Sales Target.

 

Now with the Same requirement I need to write the Trigger on Sales Oppurtunity with Before Insert, i.e when a new Sales Oppurtunity Record is created, it should look for any Sales Target record with the conditions having

same Officer_Code__c,

Close_Date__c  <= Target_Period_End__c

AND  SO.Close_Date__c       >= Target_Period_Start__c. If exists, then the new sales oppurtunity record should get update with the  Sales_Target__c(Lookup to Sales target) field with the respective record. Then the Actual_Number_of_Sales__c field in Sales target should get re-calculated.

 

trigger SalesTargetTrigger on Sales_Target__c (before insert , after insert ,before update) {
SalesTargetHandler handler = new SalesTargetHandler();
if(Trigger.isBefore){
handler.OnBeforeInsert(Trigger.new);
if(Trigger.isUpdate)
handler.OnAfterInsert(Trigger.new,'Before');
}else if(Trigger.isInsert && Trigger.isAfter){
handler.OnAfterInsert(Trigger.new,'After');
}
}

 

public with sharing class SalesTargetHandler {

 

Map<String, Sales_Target__c> offCodeToSalesTarget = new Map<String, Sales_Target__c>(); //map of officer codes to a new copy of a Sales Target object
Date salesTargetMaxEndDate;
Date salesTargetMinBegDate;

 

public SalesTargetHandler(){
}

 

public void OnAfterInsert(Sales_Target__c[] newRecords, string flg){
// note the way the trigger works is that every invocation of every "trigger mode" instantiatiates a new handler.
// so each method, is in effect, on a new instance of this class.
gatherQueryInfo(newRecords, true);

Sales_Opportunity__c[] salesOpp = new Sales_Opportunity__c[]{};
for(Sales_Opportunity__c opp : [SELECT id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Sales_Target__c,Count_Against_Targets__c,Close_Date__c
FROM Sales_Opportunity__c
WHERE Count_Against_Targets__c = true
AND Sales_Target__c = null
AND Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND Close_Date__c <= :salesTargetMaxEndDate
AND Close_Date__c >= :salesTargetMinBegDate])
{
Sales_Target__c newST = offCodeToSalesTarget.get(opp.Officer_Code__r.Officer_Code__c);

if(newST != null && opp.Close_Date__c <= newST.Target_Period_End__c && opp.Close_Date__c >= newST.Target_Period_Start__c){

opp.Sales_Target__c = newST.id;
salesOpp.add(opp);
newST.Actual_Number_of_Sales__c++;
}
}

if (salesOpp.isEmpty()==false)
update salesOpp;

 

private void gatherQueryInfo(Sales_Target__c[] stRecords, Boolean createClones){
salesTargetMaxEndDate = system.today();
salesTargetMinBegDate = system.today();

if (stRecords.size()>0){
salesTargetMaxEndDate = stRecords.get(0).Target_Period_End__c;
salesTargetMinBegDate = stRecords.get(0).Target_Period_Start__c;
}

set<ID> officerCodeSfidSet = new set<ID>();
// first pass. get the data I need
for(Sales_Target__c st : stRecords){
officerCodeSfidSet.add(st.Officer_Code__c);
if(st.Target_Period_End__c > salesTargetMaxEndDate) salesTargetMaxEndDate = st.Target_Period_End__c;
if(st.Target_Period_Start__c < salesTargetMinBegDate) salesTargetMinBegDate = st.Target_Period_Start__c;
}

// retrieve the actual officer code values from the Officer_Code__c table
map<ID, Officer_Code__c> offCodeMap = new map<ID, Officer_Code__c>([select id, Officer_Code__c from Officer_Code__c where ID in :officerCodeSfidSet]);

for(Sales_Target__c st : stRecords){
Sales_Target__c mapST = st;
if (createClones){
mapST = st.Clone(true, true, true, true);
// we are going to depend on the object being configured to default these two fields to 0.
// The trigger code cannot handle null values for these fields
//if (mapST.Actual_Number_of_Calls__c==null) mapST.Actual_Number_of_Calls__c = 0;
//if (mapST.Actual_Number_of_Sales__c==null) mapST.Actual_Number_of_Sales__c = 0;
}
Officer_Code__c offCodeRec = offCodeMap.get(mapST.Officer_Code__c);
if (offCodeRec!=null) offCodeToSalesTarget.put(offCodeRec.Officer_Code__c, mapST);
}
}

}

 

 

Thanks!

 

Yadu

  • January 13, 2012
  • Like
  • 0

Hi,

 

I have the trigger for Before Insert and After Insert with the Code written below. It perfectly works good. But I have to write the Same logic of Before Insert and After Insert Trigger on Before Update.

I am new to Apex. Thanks for the Help.

 

Code 

 

public with sharing class SalesTargetHandler {

// these class variables are used by the OnBeforeInsert and OnAfterInsert methods
Map<String, Sales_Target__c> offCodeToSalesTarget = new Map<String, Sales_Target__c>(); //map of officer codes to a new copy of a Sales Target object
Date salesTargetMaxEndDate;
Date salesTargetMinBegDate;

// these class variables are used by the OnBeforeInsert methods
set<Id> newRecordIds = new set<Id>();

// -------------------------------------------------------------------------------------------------------------------------------
// Constructor
public SalesTargetHandler(){
}

// -------------------------------------------------------------------------------------------------------------------------------
// Methods
public void OnBeforeInsert(Sales_Target__c[] newRecords){
// note the way the trigger works is that every invocation of every "trigger mode" instantiatiates a new handler.
// so each method, is in effect, on a new instance of this class.
gatherQueryInfo(newRecords, false);

for(Sales_Target__c existST :[Select Id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Target_Period_Start__c ,Target_Period_End__c
from Sales_Target__c
where Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
and Target_Period_End__c >= :salesTargetMinBegDate
and Target_Period_Start__c <= :salesTargetMaxEndDate])
{
Sales_Target__c newST = offCodeToSalesTarget.get(existST.Officer_Code__r.Officer_Code__c);

if(newST != null && existST.Officer_Code__c == newST.Officer_Code__c &&
((existST.Target_Period_Start__c <= newST.Target_Period_Start__c &&
existST.Target_Period_End__c >= newST.Target_Period_Start__c)
|| (existST.Target_Period_Start__c<= newST.Target_Period_End__c &&
existST.Target_Period_End__c>= newST.Target_Period_End__c)
)){

String errorMsg = System.Label.Sales_Target_Error_Message;
newST.addError(errorMsg);
}
}
}

public void OnAfterInsert(Sales_Target__c[] newRecords){
// note the way the trigger works is that every invocation of every "trigger mode" instantiatiates a new handler.
// so each method, is in effect, on a new instance of this class.
gatherQueryInfo(newRecords, true);

Sales_Opportunity__c[] salesOpp = new Sales_Opportunity__c[]{};
for(Sales_Opportunity__c opp : [SELECT id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Sales_Target__c,Count_Against_Targets__c,Close_Date__c
FROM Sales_Opportunity__c
WHERE Count_Against_Targets__c = true
AND Sales_Target__c = null
AND Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND Close_Date__c <= :salesTargetMaxEndDate
AND Close_Date__c >= :salesTargetMinBegDate])
{
Sales_Target__c newST = offCodeToSalesTarget.get(opp.Officer_Code__r.Officer_Code__c);

if(newST != null && opp.Close_Date__c <= newST.Target_Period_End__c && opp.Close_Date__c >= newST.Target_Period_Start__c){

opp.Sales_Target__c = newST.id;
salesOpp.add(opp);
newST.Actual_Number_of_Sales__c++;
}
}
if (salesOpp.isEmpty()==false)
update salesOpp;

Task[] tasksToUpdate = new Task[]{};
for(Task t : [SELECT Id, ActivityDate, Officer_Code__c
FROM Task
WHERE Count_Against_Targets__c = true
AND Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND ActivityDate <= :salesTargetMaxEndDate
AND ActivityDate >= :salesTargetMinBegDate]){

Sales_Target__c newST = offCodeToSalesTarget.get(t.Officer_Code__c);

if(newST != null && t.ActivityDate <= newST.Target_Period_End__c && t.ActivityDate >= newST.Target_Period_Start__c){

t.Sales_Target_Id__c = newST.Id;
tasksToUpdate.add(t);
newST.Actual_Number_of_Calls__c++;
}
}

if(tasksToUpdate.isEmpty()==false)
update tasksToUpdate;


if(offCodeToSalesTarget.values().isEmpty()==false)
update offCodeToSalesTarget.values();
}

private void gatherQueryInfo(Sales_Target__c[] stRecords, Boolean createClones){
salesTargetMaxEndDate = system.today();
salesTargetMinBegDate = system.today();

if (stRecords.size()>0){
salesTargetMaxEndDate = stRecords.get(0).Target_Period_End__c;
salesTargetMinBegDate = stRecords.get(0).Target_Period_Start__c;
}

set<ID> officerCodeSfidSet = new set<ID>();
// first pass. get the data I need
for(Sales_Target__c st : stRecords){
officerCodeSfidSet.add(st.Officer_Code__c);
if(st.Target_Period_End__c > salesTargetMaxEndDate) salesTargetMaxEndDate = st.Target_Period_End__c;
if(st.Target_Period_Start__c < salesTargetMinBegDate) salesTargetMinBegDate = st.Target_Period_Start__c;
}

// retrieve the actual officer code values from the Officer_Code__c table
map<ID, Officer_Code__c> offCodeMap = new map<ID, Officer_Code__c>([select id, Officer_Code__c from Officer_Code__c where ID in :officerCodeSfidSet]);

for(Sales_Target__c st : stRecords){
Sales_Target__c mapST = st;
if (createClones){
mapST = st.Clone(true, true, true, true);
// we are going to depend on the object being configured to default these two fields to 0.
// The trigger code cannot handle null values for these fields
//if (mapST.Actual_Number_of_Calls__c==null) mapST.Actual_Number_of_Calls__c = 0;
//if (mapST.Actual_Number_of_Sales__c==null) mapST.Actual_Number_of_Sales__c = 0;
}
Officer_Code__c offCodeRec = offCodeMap.get(mapST.Officer_Code__c);
if (offCodeRec!=null) offCodeToSalesTarget.put(offCodeRec.Officer_Code__c, mapST);
}
}

}

  • January 12, 2012
  • Like
  • 0
  • Update the Sales_Target__c field (Lookup to Sales Target) for Sales Opportunities that match on Officer Code and Close Date/Period Start-End (with Count Against Targets checked)
  • SELECT SO.Id, … FROM Sales_Opportunity__c SO,
  •        Sales_Target__c ST

    WHERE      SO.Count_Against_Targets__c = true

    AND  SO.Officer_Code__c = ST.Officer_Code__c

    AND  SO.Close_Date__c  <= ST.Target_Period_End__c

    AND  SO.Close_Date__c      >= ST.Target_Period_Start__c

     

    If there are any SalesTarget that match the above criteria i need to update the SalesOppurtunity. sales target field on sales oppurtunity Object. This should handle bulk records

     

    Have a dead line. Please help me.

     

    Thanks

  • January 04, 2012
  • Like
  • 0
  • Update the Sales_Target__c field (Lookup to Sales Target) for Sales Opportunities that match on Officer Code and Close Date/Period Start-End (with Count Against Targets checked)
  • SELECT SO.Id, … FROM Sales_Opportunity__c SO,
  •        Sales_Target__c ST

    WHERE      SO.Count_Against_Targets__c = true

    AND  SO.Officer_Code__c = ST.Officer_Code__c

    AND  SO.Close_Date__c  <= ST.Target_Period_End__c

    AND  SO.Close_Date__c      >= ST.Target_Period_Start__c

     

    If there are any SalesTarget that match the above criteria i need to update the SalesOppurtunity. sales target field on sales oppurtunity. This should handle bulk records

     

    Have a dead line. Please help me.

     

    Thanks!

  • January 04, 2012
  • Like
  • 0

Hi,

 

I have the trigger for Before Insert and After Insert with the Code written below. It perfectly works good. But I have to write the Same logic of Before Insert and After Insert Trigger on Before Update.

I am new to Apex. Thanks for the Help.

 

Code 

 

public with sharing class SalesTargetHandler {

// these class variables are used by the OnBeforeInsert and OnAfterInsert methods
Map<String, Sales_Target__c> offCodeToSalesTarget = new Map<String, Sales_Target__c>(); //map of officer codes to a new copy of a Sales Target object
Date salesTargetMaxEndDate;
Date salesTargetMinBegDate;

// these class variables are used by the OnBeforeInsert methods
set<Id> newRecordIds = new set<Id>();

// -------------------------------------------------------------------------------------------------------------------------------
// Constructor
public SalesTargetHandler(){
}

// -------------------------------------------------------------------------------------------------------------------------------
// Methods
public void OnBeforeInsert(Sales_Target__c[] newRecords){
// note the way the trigger works is that every invocation of every "trigger mode" instantiatiates a new handler.
// so each method, is in effect, on a new instance of this class.
gatherQueryInfo(newRecords, false);

for(Sales_Target__c existST :[Select Id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Target_Period_Start__c ,Target_Period_End__c
from Sales_Target__c
where Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
and Target_Period_End__c >= :salesTargetMinBegDate
and Target_Period_Start__c <= :salesTargetMaxEndDate])
{
Sales_Target__c newST = offCodeToSalesTarget.get(existST.Officer_Code__r.Officer_Code__c);

if(newST != null && existST.Officer_Code__c == newST.Officer_Code__c &&
((existST.Target_Period_Start__c <= newST.Target_Period_Start__c &&
existST.Target_Period_End__c >= newST.Target_Period_Start__c)
|| (existST.Target_Period_Start__c<= newST.Target_Period_End__c &&
existST.Target_Period_End__c>= newST.Target_Period_End__c)
)){

String errorMsg = System.Label.Sales_Target_Error_Message;
newST.addError(errorMsg);
}
}
}

public void OnAfterInsert(Sales_Target__c[] newRecords){
// note the way the trigger works is that every invocation of every "trigger mode" instantiatiates a new handler.
// so each method, is in effect, on a new instance of this class.
gatherQueryInfo(newRecords, true);

Sales_Opportunity__c[] salesOpp = new Sales_Opportunity__c[]{};
for(Sales_Opportunity__c opp : [SELECT id ,Officer_Code__c, Officer_Code__r.Officer_Code__c, Sales_Target__c,Count_Against_Targets__c,Close_Date__c
FROM Sales_Opportunity__c
WHERE Count_Against_Targets__c = true
AND Sales_Target__c = null
AND Officer_Code__r.Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND Close_Date__c <= :salesTargetMaxEndDate
AND Close_Date__c >= :salesTargetMinBegDate])
{
Sales_Target__c newST = offCodeToSalesTarget.get(opp.Officer_Code__r.Officer_Code__c);

if(newST != null && opp.Close_Date__c <= newST.Target_Period_End__c && opp.Close_Date__c >= newST.Target_Period_Start__c){

opp.Sales_Target__c = newST.id;
salesOpp.add(opp);
newST.Actual_Number_of_Sales__c++;
}
}
if (salesOpp.isEmpty()==false)
update salesOpp;

Task[] tasksToUpdate = new Task[]{};
for(Task t : [SELECT Id, ActivityDate, Officer_Code__c
FROM Task
WHERE Count_Against_Targets__c = true
AND Officer_Code__c IN :offCodeToSalesTarget.keySet()
AND ActivityDate <= :salesTargetMaxEndDate
AND ActivityDate >= :salesTargetMinBegDate]){

Sales_Target__c newST = offCodeToSalesTarget.get(t.Officer_Code__c);

if(newST != null && t.ActivityDate <= newST.Target_Period_End__c && t.ActivityDate >= newST.Target_Period_Start__c){

t.Sales_Target_Id__c = newST.Id;
tasksToUpdate.add(t);
newST.Actual_Number_of_Calls__c++;
}
}

if(tasksToUpdate.isEmpty()==false)
update tasksToUpdate;


if(offCodeToSalesTarget.values().isEmpty()==false)
update offCodeToSalesTarget.values();
}

private void gatherQueryInfo(Sales_Target__c[] stRecords, Boolean createClones){
salesTargetMaxEndDate = system.today();
salesTargetMinBegDate = system.today();

if (stRecords.size()>0){
salesTargetMaxEndDate = stRecords.get(0).Target_Period_End__c;
salesTargetMinBegDate = stRecords.get(0).Target_Period_Start__c;
}

set<ID> officerCodeSfidSet = new set<ID>();
// first pass. get the data I need
for(Sales_Target__c st : stRecords){
officerCodeSfidSet.add(st.Officer_Code__c);
if(st.Target_Period_End__c > salesTargetMaxEndDate) salesTargetMaxEndDate = st.Target_Period_End__c;
if(st.Target_Period_Start__c < salesTargetMinBegDate) salesTargetMinBegDate = st.Target_Period_Start__c;
}

// retrieve the actual officer code values from the Officer_Code__c table
map<ID, Officer_Code__c> offCodeMap = new map<ID, Officer_Code__c>([select id, Officer_Code__c from Officer_Code__c where ID in :officerCodeSfidSet]);

for(Sales_Target__c st : stRecords){
Sales_Target__c mapST = st;
if (createClones){
mapST = st.Clone(true, true, true, true);
// we are going to depend on the object being configured to default these two fields to 0.
// The trigger code cannot handle null values for these fields
//if (mapST.Actual_Number_of_Calls__c==null) mapST.Actual_Number_of_Calls__c = 0;
//if (mapST.Actual_Number_of_Sales__c==null) mapST.Actual_Number_of_Sales__c = 0;
}
Officer_Code__c offCodeRec = offCodeMap.get(mapST.Officer_Code__c);
if (offCodeRec!=null) offCodeToSalesTarget.put(offCodeRec.Officer_Code__c, mapST);
}
}

}

  • January 12, 2012
  • Like
  • 0
  • Update the Sales_Target__c field (Lookup to Sales Target) for Sales Opportunities that match on Officer Code and Close Date/Period Start-End (with Count Against Targets checked)
  • SELECT SO.Id, … FROM Sales_Opportunity__c SO,
  •        Sales_Target__c ST

    WHERE      SO.Count_Against_Targets__c = true

    AND  SO.Officer_Code__c = ST.Officer_Code__c

    AND  SO.Close_Date__c  <= ST.Target_Period_End__c

    AND  SO.Close_Date__c      >= ST.Target_Period_Start__c

     

    If there are any SalesTarget that match the above criteria i need to update the SalesOppurtunity. sales target field on sales oppurtunity Object. This should handle bulk records

     

    Have a dead line. Please help me.

     

    Thanks

  • January 04, 2012
  • Like
  • 0