Change Capacity Hours from a Date

Use the following script when one or more resources start working different hours on a set date, for example when someone moves to a four-day week. The script changes every capacity record from that date onward, so you don’t need to edit or split each record by hand.

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

What the script does

For each resource you name, the script gives the new hours to every RH Capacity record from CHANGE_DATE onward:

  • A record that starts on or after CHANGE_DATE gets the new hours.
  • A record that runs across CHANGE_DATE is split. The existing record keeps its hours and now ends the day before CHANGE_DATE. A new record with the same role and the new hours covers the rest of its dates.
  • Records that end before CHANGE_DATE are not changed.
  • A resource with more than one record on the same dates after CHANGE_DATE, for example one record per role, is skipped and listed. The new hours would count once for each record, so change those records by hand.
  • Running the script again changes nothing, because the records already have the new hours.

Settings

  • DRY_RUN – Leave as true to see what the script would change without changing anything. Set to false to change the records.
  • RESOURCE_NAMES – The names of the resources to change, in quotes and separated by commas, for example new List<String>{ 'Jane Example', 'Sam Example' }.
  • CHANGE_DATE – The first day of the new hours, for example Date.newInstance(2027, 1, 1) for January 1, 2027.
  • SUNDAY through SATURDAY – The new hours per day. The defaults are 8 hours Monday through Thursday and 0 on the other days.
  • MAX_DAYS_PER_RUN – The total length, in days, of the records changed and created in one run. The default is 3000, about 8 records of one year each. Resource Hero rebuilds the daily capacity across each changed record’s whole date range, so long records use more of each run.

The script

// Changes the weekly hours of the named resources from a date onward, for example when someone
// moves to a four-day week.
//
// Every RH Capacity record of those resources that starts on or after CHANGE_DATE gets the new
// hours. A record that runs across CHANGE_DATE is split: it now ends the day before CHANGE_DATE and
// keeps its hours, and a new record with the same role and the new hours covers the rest of its
// dates. Records that end before CHANGE_DATE are not changed.
//
// A resource with more than one capacity record on the same dates after CHANGE_DATE, for example
// one per role, is skipped and listed, because the new hours would count once for each record.
// Running the script again changes nothing, because the records already have the new hours.
//
// 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 change the records.
//   3. If the summary says resources are still waiting, run again until it says none are.
//
// Resource Hero rebuilds a changed record's daily capacity across its whole date range, so each run
// is limited by the total length of the records it changes and creates. 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
List<String> RESOURCE_NAMES = new List<String>{ 'Jane Example' }; // the resources to change, by name
Date CHANGE_DATE = Date.newInstance(2027, 1, 1); // first day of the new hours
Decimal SUNDAY = 0; // new hours per day
Decimal MONDAY = 8;
Decimal TUESDAY = 8;
Decimal WEDNESDAY = 8;
Decimal THURSDAY = 8;
Decimal FRIDAY = 0;
Decimal SATURDAY = 0;
Integer MAX_DAYS_PER_RUN = 3000; // total length of the records changed and created in one run; keeps each run inside Salesforce limits

// ---- Script ----
List<String> notFound = new List<String>();
List<String> duplicateNames = new List<String>();
Map<String, List<ResourceHeroApp__Resource__c>> resourcesByName = new Map<String, List<ResourceHeroApp__Resource__c>>();
for (ResourceHeroApp__Resource__c resource : [SELECT Id, Name FROM ResourceHeroApp__Resource__c WHERE Name IN :RESOURCE_NAMES ORDER BY Name]) {
   if (!resourcesByName.containsKey(resource.Name.toLowerCase())) {
      resourcesByName.put(resource.Name.toLowerCase(), new List<ResourceHeroApp__Resource__c>());
   }
   resourcesByName.get(resource.Name.toLowerCase()).add(resource);
}
List<ResourceHeroApp__Resource__c> resources = new List<ResourceHeroApp__Resource__c>();
for (String name : RESOURCE_NAMES) {
   List<ResourceHeroApp__Resource__c> matches = resourcesByName.get(name.toLowerCase());
   if (matches == null) {
      notFound.add(name);
   } else if (matches.size() > 1) {
      duplicateNames.add(name);
   } else {
      resources.add(matches[0]);
   }
}

// The records each resource has on or after the change date, in start-date order.
Map<Id, List<ResourceHeroApp__RH_Capacity__c>> capacityByResource = new Map<Id, List<ResourceHeroApp__RH_Capacity__c>>();
for (ResourceHeroApp__RH_Capacity__c capacity : [
   SELECT
      Id,
      ResourceHeroApp__Resource__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__Resource__c IN :resources AND ResourceHeroApp__End_Date__c >= :CHANGE_DATE
   ORDER BY ResourceHeroApp__Start_Date__c
]) {
   if (!capacityByResource.containsKey(capacity.ResourceHeroApp__Resource__c)) {
      capacityByResource.put(capacity.ResourceHeroApp__Resource__c, new List<ResourceHeroApp__RH_Capacity__c>());
   }
   capacityByResource.get(capacity.ResourceHeroApp__Resource__c).add(capacity);
}

List<ResourceHeroApp__RH_Capacity__c> capacitiesToUpdate = new List<ResourceHeroApp__RH_Capacity__c>();
List<ResourceHeroApp__RH_Capacity__c> capacitiesToCreate = new List<ResourceHeroApp__RH_Capacity__c>();
List<String> changed = new List<String>();
List<String> noCapacity = new List<String>();
List<String> overlapping = new List<String>();
Integer resourcesWaiting = 0;
Integer resourcesAlreadyDone = 0;
Integer daysThisRun = 0;

for (ResourceHeroApp__Resource__c resource : resources) {
   List<ResourceHeroApp__RH_Capacity__c> capacities = capacityByResource.get(resource.Id);
   if (capacities == null) {
      noCapacity.add(resource.Name);
      continue;
   }

   Boolean hasOverlap = false;
   Date coveredThrough = capacities[0].ResourceHeroApp__End_Date__c;
   for (Integer i = 1; i < capacities.size(); i++) {
      if (capacities[i].ResourceHeroApp__Start_Date__c <= coveredThrough) {
         hasOverlap = true;
      }
      if (capacities[i].ResourceHeroApp__End_Date__c > coveredThrough) {
         coveredThrough = capacities[i].ResourceHeroApp__End_Date__c;
      }
   }
   if (hasOverlap) {
      overlapping.add(resource.Name);
      continue;
   }

   List<ResourceHeroApp__RH_Capacity__c> recordsToChange = new List<ResourceHeroApp__RH_Capacity__c>();
   for (ResourceHeroApp__RH_Capacity__c capacity : capacities) {
      Boolean sameHours =
         capacity.ResourceHeroApp__Sunday__c == SUNDAY &&
         capacity.ResourceHeroApp__Monday__c == MONDAY &&
         capacity.ResourceHeroApp__Tuesday__c == TUESDAY &&
         capacity.ResourceHeroApp__Wednesday__c == WEDNESDAY &&
         capacity.ResourceHeroApp__Thursday__c == THURSDAY &&
         capacity.ResourceHeroApp__Friday__c == FRIDAY &&
         capacity.ResourceHeroApp__Saturday__c == SATURDAY;
      if (!sameHours) {
         recordsToChange.add(capacity);
      }
   }

   if (recordsToChange.isEmpty()) {
      resourcesAlreadyDone++;
      continue;
   }

   // A changed record counts its whole date range; a split record counts twice, once for the
   // shortened record and once for the new one. A resource's records all go in the same run, and the
   // first resource always fits.
   Integer days = 0;
   for (ResourceHeroApp__RH_Capacity__c capacity : recordsToChange) {
      days += (capacity.ResourceHeroApp__Start_Date__c.daysBetween(capacity.ResourceHeroApp__End_Date__c) + 1) * (capacity.ResourceHeroApp__Start_Date__c < CHANGE_DATE ? 2 : 1);
   }
   if (resourcesWaiting > 0 || (daysThisRun > 0 && daysThisRun + days > MAX_DAYS_PER_RUN)) {
      resourcesWaiting++;
      continue;
   }
   daysThisRun += days;

   for (ResourceHeroApp__RH_Capacity__c capacity : recordsToChange) {
      ResourceHeroApp__RH_Capacity__c newHours = capacity;
      if (capacity.ResourceHeroApp__Start_Date__c < CHANGE_DATE) {
         // Split: the existing record keeps its hours up to the day before the change.
         newHours = new ResourceHeroApp__RH_Capacity__c(
            ResourceHeroApp__Resource__c = resource.Id,
            ResourceHeroApp__Role__c = capacity.ResourceHeroApp__Role__c,
            ResourceHeroApp__Start_Date__c = CHANGE_DATE,
            ResourceHeroApp__End_Date__c = capacity.ResourceHeroApp__End_Date__c
         );
         capacitiesToCreate.add(newHours);
         changed.add(resource.Name + ': ' + capacity.ResourceHeroApp__Start_Date__c.format() + '-' + capacity.ResourceHeroApp__End_Date__c.format() + ' split at ' + CHANGE_DATE.format());
         capacity.ResourceHeroApp__End_Date__c = CHANGE_DATE.addDays(-1);
         capacitiesToUpdate.add(capacity);
      } else {
         changed.add(resource.Name + ': ' + capacity.ResourceHeroApp__Start_Date__c.format() + '-' + capacity.ResourceHeroApp__End_Date__c.format() + ' new hours');
         capacitiesToUpdate.add(capacity);
      }
      newHours.ResourceHeroApp__Sunday__c = SUNDAY;
      newHours.ResourceHeroApp__Monday__c = MONDAY;
      newHours.ResourceHeroApp__Tuesday__c = TUESDAY;
      newHours.ResourceHeroApp__Wednesday__c = WEDNESDAY;
      newHours.ResourceHeroApp__Thursday__c = THURSDAY;
      newHours.ResourceHeroApp__Friday__c = FRIDAY;
      newHours.ResourceHeroApp__Saturday__c = SATURDAY;
   }
}

if (!DRY_RUN) {
   // Shorten the split records first so the new records never overlap them.
   if (!capacitiesToUpdate.isEmpty()) {
      update capacitiesToUpdate;
   }
   if (!capacitiesToCreate.isEmpty()) {
      insert capacitiesToCreate;
   }
}

List<String> summary = new List<String>();
summary.add('');
summary.add('==== Change capacity hours from ' + CHANGE_DATE.format() + (DRY_RUN ? ' (DRY RUN - nothing changed)' : '') + ' ====');
summary.add('Capacity records ' + (DRY_RUN ? 'that would be changed: ' : 'changed: ') + capacitiesToUpdate.size() + ', new records ' + (DRY_RUN ? 'that would be created: ' : 'created: ') + capacitiesToCreate.size());
for (String note : changed) {
   summary.add('   ' + note);
}
summary.add('Resources already complete: ' + resourcesAlreadyDone);
summary.add('Resources still waiting (run again): ' + resourcesWaiting);
summary.add('Resources with no capacity on or after ' + CHANGE_DATE.format() + ' (skipped): ' + noCapacity.size());
for (String name : noCapacity) {
   summary.add('   ' + name);
}
summary.add('Resources with more than one record on the same dates (skipped): ' + overlapping.size());
for (String name : overlapping) {
   summary.add('   ' + name);
}
summary.add('Names not found: ' + notFound.size());
for (String name : notFound) {
   summary.add('   ' + name);
}
summary.add('Names that match more than one resource (skipped): ' + duplicateNames.size());
for (String name : duplicateNames) {
   summary.add('   ' + name);
}
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 changed, new records created – The number of records that get the new hours or a new end date, and the number of new records created by splits. Each changed record is listed with its dates. In a dry run, these read “that would be changed” and “that would be created”.
  • Resources already complete – Resources whose records from CHANGE_DATE onward already have the new hours.
  • Resources still waiting (run again) – Resources that didn’t fit in this run. Run the script again to change their records.
  • Resources with no capacity on or after the change date (skipped) – Resources with nothing to change. To give them capacity, use Create Capacity with Standard Hours.
  • Resources with more than one record on the same dates (skipped) – Resources with overlapping records, such as one record per role. Change their records by hand.
  • Names not found – Names in RESOURCE_NAMES that don’t match a resource. Check the spelling.
  • Names that match more than one resource (skipped) – Names shared by more than one resource. Change those resources by hand.

Related Support Posts:

Ready to get started?

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

Book now