• Gustavo Laufer 1
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
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?