function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Gustavo Laufer 1Gustavo Laufer 1 

How hard is to create an Apex job that numerates Opportunities

Scenario
I am a non for profit and the sequence of opportunities of a contact (donations) is important.

Goal
I want to set the order of donation for each opportunity (grouped by donor).
So, if we have 
opportunity,contact,date
1,John,01/01/2020
2,Mary,02/01/2020
3,John,02/01/2020
4,Mary,05/01/2020

I would like to create a field Sequence No in Opportunity which contains:
opportunity,contact,date,Sequence No
1,John,01/01/2020,1
2,Mary,02/01/2020,1
3,John,02/01/2020,2
4,Mary,05/01/2020,2

I can think that we may have 
List <Contact> allAlive = [SELECT Id FROM Contact WHERE Deceased = 0 LIMIT 100];
 

For ( Contact currentContact : allAlive){
   sequence = 1;
   List <Opportunity> allOpp = [SELECT Id FROM Opportunity WHERE PrimaryContactId = " + currentContact + "] order by CreatedDate";
   For ( Opportunity currentOpportunity : allOpps )
  {
    currentOpportunity.SequenceNo = sequence;
    sequence = sequence + 1;
    update currentOpportunity;
  }
}
(I limited for 100 contact because I am worried about CPU TIME LIMIT, and APEX limits)

(I realized that this code is not going to work:
  * the next time it runs it will probably take the same 100 records, therefore no progress is going to happen)

So, afterwards, what would be the best way to enumerate the order of opportunities that a contact have done saving that in the opportunity?
Learn Salesforce 36Learn Salesforce 36
you can use before insert event of trigger on opportunity to calculate this. Find below psuedo code for that:

Opportunity ot = [trigger's opportuninty];
Opportunity o = [SELECT Id, SequenceNo FROM Opportunity WHERE PrimaryContactId = :ot.currentContact.Id order by CreatedDate DESC limit 1];
ot.SequenceNo = o.SequenceNo + 1;

PS : you will need to add some logic to bulkify the trigger and calculate sequence accordingly if more than one opportunity from the same contact is there in trigger to insert.