I need to maintain a record for each month up to 10 years away, so 120 records ahead. This might be extended in the future!
The code
global with sharing class AccountingPeriodCreationService { public static List <AcctSeed__Accounting_Period__c> accountingPeriod; public static Date currentDate; public static Date firstDayOfCurrentMonth; public static Date lastDayOfCurrentMonth; public void createdAPLogic(){ for(Integer i = 0; i < 120; i++){ currentDate = Date.today(); firstDayOfCurrentMonth = currentDate.addMonths(i).toStartofMonth(); lastDayOfCurrentMonth = currentDate.addMonths(i + 1).toStartofMonth().addDays(-1); List<AcctSeed__Accounting_Period__c> checkAccountingPeriodAlreadyExist = [SELECT Id, AcctSeed__Start_Date__c, AcctSeed__End_Date__c FROM AcctSeed__Accounting_Period__c where AcctSeed__Start_Date__c = :firstDayOfCurrentMonth]; if(checkAccountingPeriodAlreadyExist.isEmpty()){ accountingPeriod.add( new AcctSeed__Accounting_Period__c( Name = 'Name', AcctSeed__Status__c = 'Status', AcctSeed__Start_Date__c = firstDayOfCurrentMonth, AcctSeed__End_Date__c = lastDayOfCurrentMonth ) ); } } System.debug( 'accountingPeriod: ' + accountingPeriod.size()); List<Database.SaveResult> accountingPeriod = Database.insert(accountingPeriod, false); } } The logic
For each loop iteration, I'm getting the first day and the last day of the month. Storing it in a variable. Then a query to see if a record with the same first date exists (there should only ever be 1 instance). If it doesn't, add the record to a list.
Then I insert the list at the end.
The problem
Is essentially that I'm going to hit limits and I know there are better ways to code this. If I'm correct, I'll have to store all current records into a map, then loop over that map X amount of times to check if it already exists?
Could I get some assistance on how to most efficiently do this please?
Any insight is always appreciated! Thank you