Split Multi-Year Capacity Records

Use the following script to replace RH Capacity records that run for several years with one record per calendar year. One record per year keeps each record small, so later changes to a year’s hours finish faster. For more on why, see How far ahead to create capacity.

This is one of the scripts in Create Capacity Records in Bulk. Read Before you run a script first.

What the script does

The script deletes each record that spans more than one calendar year and replaces it with one record for each year it covered:

  • The first new record starts on the original Start Date, and the last new record ends on the original End Date.
  • Every new record has the same resource, Role, and hours for Sunday through Saturday, so the resource’s capacity on every date stays the same.
  • Only records that end today or later are split. Records that have already ended are not changed.
  • Values in custom fields that you’ve added to RH Capacity are not copied to the new records.
  • Archived resources are skipped unless you change the setting.
  • Running the script again changes nothing.

Settings

  • DRY_RUN – Leave as true to see what the script would change without changing anything. Set to false to split the records.
  • MAX_RECORDS_PER_RUN – The number of multi-year records split in one run. The default is 20.
  • INCLUDE_ARCHIVED_RESOURCES – Set to true to also split records of archived resources.

A run also stops early when the new records would make it slow to finish, so a run can split fewer records than MAX_RECORDS_PER_RUN.

The script

// Splits RH Capacity records that span more than one calendar year into one record per year.
//
// Each multi-year record is deleted and replaced with one record per calendar year it covered. The
// first new record starts on the original Start Date, the last ends on the original End Date, and
// every new record has the same resource, role, and Sunday-Saturday hours, so the resource's
// capacity on every date stays the same. Values in custom fields you have added to RH Capacity are
// not copied. Only records that end today or later are split. Running the script again changes
// nothing.
//
// How to run (Developer Console > Debug > Open Execute Anonymous Window, tick "Open Log"):
//   1. Run with DRY_RUN = true and read the summary (filter the log to "Debug Only").
//   2. Set DRY_RUN = false and run again to split the records.
//   3. If the summary says records are still waiting, run again until it says none are.
//
// Resource Hero builds the daily capacity behind each new record in the background. Watch the
// Async Job Status field on the RH Capacity records; a blank or "Completed" status means done.

// ---- Settings ----
Boolean DRY_RUN = true; // true = report only, nothing is changed
Integer MAX_RECORDS_PER_RUN = 20; // multi-year records split per run; keeps each run inside Salesforce limits
Boolean INCLUDE_ARCHIVED_RESOURCES = false;

// ---- Script ----
Date firstDayToSplit = Date.today();
List<ResourceHeroApp__RH_Capacity__c> capacitiesToDelete = new List<ResourceHeroApp__RH_Capacity__c>();
List<List<ResourceHeroApp__RH_Capacity__c>> replacements = new List<List<ResourceHeroApp__RH_Capacity__c>>();
Integer recordsWaiting = 0;
Integer newRecordCount = 0;

for (ResourceHeroApp__RH_Capacity__c capacity : [
   SELECT
      Id,
      ResourceHeroApp__Resource__c,
      ResourceHeroApp__Resource__r.Name,
      ResourceHeroApp__Resource__r.ResourceHeroApp__Archive__c,
      ResourceHeroApp__Role__c,
      ResourceHeroApp__Start_Date__c,
      ResourceHeroApp__End_Date__c,
      ResourceHeroApp__Sunday__c,
      ResourceHeroApp__Monday__c,
      ResourceHeroApp__Tuesday__c,
      ResourceHeroApp__Wednesday__c,
      ResourceHeroApp__Thursday__c,
      ResourceHeroApp__Friday__c,
      ResourceHeroApp__Saturday__c
   FROM ResourceHeroApp__RH_Capacity__c
   WHERE ResourceHeroApp__End_Date__c >= :firstDayToSplit
   ORDER BY ResourceHeroApp__Resource__r.Name, ResourceHeroApp__Start_Date__c
]) {
   Integer firstYear = capacity.ResourceHeroApp__Start_Date__c.year();
   Integer lastYear = capacity.ResourceHeroApp__End_Date__c.year();
   if (firstYear == lastYear || (!INCLUDE_ARCHIVED_RESOURCES && capacity.ResourceHeroApp__Resource__r.ResourceHeroApp__Archive__c)) {
      continue;
   }

   // At most 200 new records per run, so Salesforce processes them as a single batch.
   if (recordsWaiting > 0 || capacitiesToDelete.size() >= MAX_RECORDS_PER_RUN || (newRecordCount > 0 && newRecordCount + lastYear - firstYear + 1 > 200)) {
      recordsWaiting++;
      continue;
   }

   List<ResourceHeroApp__RH_Capacity__c> newRecords = new List<ResourceHeroApp__RH_Capacity__c>();
   for (Integer year = firstYear; year <= lastYear; year++) {
      newRecords.add(
         new ResourceHeroApp__RH_Capacity__c(
            ResourceHeroApp__Resource__c = capacity.ResourceHeroApp__Resource__c,
            ResourceHeroApp__Role__c = capacity.ResourceHeroApp__Role__c,
            ResourceHeroApp__Start_Date__c = year == firstYear ? capacity.ResourceHeroApp__Start_Date__c : Date.newInstance(year, 1, 1),
            ResourceHeroApp__End_Date__c = year == lastYear ? capacity.ResourceHeroApp__End_Date__c : Date.newInstance(year, 12, 31),
            ResourceHeroApp__Sunday__c = capacity.ResourceHeroApp__Sunday__c,
            ResourceHeroApp__Monday__c = capacity.ResourceHeroApp__Monday__c,
            ResourceHeroApp__Tuesday__c = capacity.ResourceHeroApp__Tuesday__c,
            ResourceHeroApp__Wednesday__c = capacity.ResourceHeroApp__Wednesday__c,
            ResourceHeroApp__Thursday__c = capacity.ResourceHeroApp__Thursday__c,
            ResourceHeroApp__Friday__c = capacity.ResourceHeroApp__Friday__c,
            ResourceHeroApp__Saturday__c = capacity.ResourceHeroApp__Saturday__c
         )
      );
   }
   capacitiesToDelete.add(capacity);
   replacements.add(newRecords);
   newRecordCount += newRecords.size();
}

// Measured in a v16.2 org: new records that add up to fewer than about 9,000 days are processed while
// the run is still going, and near that size they can exceed Salesforce's query limit. Larger runs
// are processed in the background. A run that would land between 4,000 and 9,000 days is therefore
// cut back to 4,000. The new records cover the same days
// as the records they replace.
Integer daysThisRun = 0;
for (ResourceHeroApp__RH_Capacity__c capacity : capacitiesToDelete) {
   daysThisRun += capacity.ResourceHeroApp__Start_Date__c.daysBetween(capacity.ResourceHeroApp__End_Date__c) + 1;
}
while (daysThisRun > 4000 && daysThisRun <= 9000 && capacitiesToDelete.size() > 1) {
   ResourceHeroApp__RH_Capacity__c capacity = capacitiesToDelete.remove(capacitiesToDelete.size() - 1);
   replacements.remove(replacements.size() - 1);
   daysThisRun -= capacity.ResourceHeroApp__Start_Date__c.daysBetween(capacity.ResourceHeroApp__End_Date__c) + 1;
   recordsWaiting++;
}

List<ResourceHeroApp__RH_Capacity__c> capacitiesToCreate = new List<ResourceHeroApp__RH_Capacity__c>();
List<String> changed = new List<String>();
for (Integer i = 0; i < capacitiesToDelete.size(); i++) {
   ResourceHeroApp__RH_Capacity__c capacity = capacitiesToDelete[i];
   capacitiesToCreate.addAll(replacements[i]);
   changed.add(
      capacity.ResourceHeroApp__Resource__r.Name + ': ' + capacity.ResourceHeroApp__Start_Date__c.format() + '-' + capacity.ResourceHeroApp__End_Date__c.format() +
      ' becomes ' + replacements[i].size() + ' records'
   );
}

if (!DRY_RUN) {
   // Delete first so the new records never overlap the originals. If either step fails, neither
   // takes effect.
   if (!capacitiesToDelete.isEmpty()) {
      delete capacitiesToDelete;
   }
   if (!capacitiesToCreate.isEmpty()) {
      insert capacitiesToCreate;
   }
}

List<String> summary = new List<String>();
summary.add('');
summary.add('==== Split capacity by calendar year' + (DRY_RUN ? ' (DRY RUN - nothing changed)' : '') + ' ====');
summary.add('Capacity records ' + (DRY_RUN ? 'that would be split: ' : 'split: ') + capacitiesToDelete.size() + ', new records ' + (DRY_RUN ? 'that would be created: ' : 'created: ') + capacitiesToCreate.size());
for (String note : changed) {
   summary.add('   ' + note);
}
summary.add('Records still waiting (run again): ' + recordsWaiting);
System.debug(LoggingLevel.ERROR, String.join(summary, '\n'));

Run the script

Run the script with the steps in Run a script.

Read the summary

The script prints a summary each time it runs:

  • Capacity records split, new records created – The number of multi-year records replaced and the number of yearly records created, with each split record listed by resource and dates. In a dry run, these read “that would be split” and “that would be created”.
  • Records still waiting (run again) – Multi-year records that didn’t fit in this run. Run the script again to split them.

Related Support Posts:

Ready to get started?

Schedule a call to see if Resource Hero is right for you

Book now