Use the following script to extend each resource’s capacity into the coming years with the hours and role they have now. It’s the script to run each year, before your current capacity records end.
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 active resource, the script finds the RH Capacity record with the latest End Date and copies its Role and its hours for Sunday through Saturday into new records, one per calendar year or one per month.
- New records start only after the latest record ends. The script never fills in dates before that record, never creates overlapping capacity, and is safe to run more than once.
- A resource with more than one record ending on that date, for example one record per role, gets a copy of each record for each year.
- A resource whose latest capacity ended more than six months before the first new year is skipped, so resources who have left are not extended. You can change the number of months.
- A resource with no capacity records is skipped and listed. Use Create Capacity with Standard Hours for those resources.
- Archived resources are skipped unless you change the setting.
Settings
DRY_RUN– Leave astrueto see what the script would create without creating anything. Set tofalseto create the records.FIRST_YEAR– The first calendar year to create, for example2027.NUMBER_OF_YEARS– The number of calendar years to create. The default is3.ONE_RECORD_PER_MONTH– Set totrueto create one record for each month instead of one record per year.SKIP_IF_ENDED_MONTHS_BEFORE– Skip resources whose latest capacity ended this many months or more before January 1 ofFIRST_YEAR. The default is6.MAX_RECORDS_PER_RUN– The number of records created in one run. The default and the maximum are200.INCLUDE_ARCHIVED_RESOURCES– Set totrueto also extend capacity for archived resources.
A run also stops early when the new records would make it slow to finish, so a run can create fewer records than MAX_RECORDS_PER_RUN.
The script
// Extends each resource's capacity by copying its most recent RH Capacity record: one new record
// per calendar year, or one per month, with the same role and the same Sunday-Saturday hours.
//
// The most recent record is the one with the latest End Date. A resource with several records
// ending on that date, for example one per role, gets a copy of each. A resource whose most recent
// capacity ended long before the first new year is skipped, so people who have left are not
// extended.
//
// New records start only after the resource's latest End Date, so the script never fills in dates
// before that record, never creates overlapping capacity, and is safe to run more than once. When
// the latest record ends partway through a year (or month), the rest of that year (or month) stays
// empty and the resource is listed for review.
//
// 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 create the records.
// 3. If the summary says resources 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 created
Integer FIRST_YEAR = 2027; // first calendar year to create
Integer NUMBER_OF_YEARS = 3; // how many calendar years to create
Boolean ONE_RECORD_PER_MONTH = false; // true = 12 records per year instead of 1
Integer SKIP_IF_ENDED_MONTHS_BEFORE = 6; // skip resources whose capacity ended this many months before FIRST_YEAR
Integer MAX_RECORDS_PER_RUN = 200; // keeps each run inside Salesforce limits; 200 at most
Boolean INCLUDE_ARCHIVED_RESOURCES = false;
// ---- Script ----
// The periods to create: whole calendar years, or calendar months.
List<Date> periodStarts = new List<Date>();
List<Date> periodEnds = new List<Date>();
for (Integer year = FIRST_YEAR; year < FIRST_YEAR + NUMBER_OF_YEARS; year++) {
for (Integer month = 1; month <= 12; month += (ONE_RECORD_PER_MONTH ? 1 : 12)) {
Date periodStart = Date.newInstance(year, month, 1);
periodStarts.add(periodStart);
periodEnds.add(ONE_RECORD_PER_MONTH ? periodStart.addMonths(1).addDays(-1) : Date.newInstance(year, 12, 31));
}
}
Date staleBefore = periodStarts[0].addMonths(-SKIP_IF_ENDED_MONTHS_BEFORE);
List<ResourceHeroApp__Resource__c> resources = INCLUDE_ARCHIVED_RESOURCES
? [SELECT Id, Name FROM ResourceHeroApp__Resource__c ORDER BY Name]
: [SELECT Id, Name FROM ResourceHeroApp__Resource__c WHERE ResourceHeroApp__Archive__c = FALSE ORDER BY Name];
// Each resource's most recent record(s): the first rows per resource when sorted by End Date, newest first.
Map<Id, List<ResourceHeroApp__RH_Capacity__c>> latestByResource = new Map<Id, List<ResourceHeroApp__RH_Capacity__c>>();
for (ResourceHeroApp__RH_Capacity__c capacity : [
SELECT
ResourceHeroApp__Resource__c,
ResourceHeroApp__Role__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
ORDER BY ResourceHeroApp__Resource__c, ResourceHeroApp__End_Date__c DESC, ResourceHeroApp__Start_Date__c
]) {
List<ResourceHeroApp__RH_Capacity__c> latest = latestByResource.get(capacity.ResourceHeroApp__Resource__c);
if (latest == null) {
latestByResource.put(capacity.ResourceHeroApp__Resource__c, new List<ResourceHeroApp__RH_Capacity__c>{ capacity });
} else if (latest[0].ResourceHeroApp__End_Date__c == capacity.ResourceHeroApp__End_Date__c) {
latest.add(capacity);
}
}
List<List<ResourceHeroApp__RH_Capacity__c>> recordsByResource = new List<List<ResourceHeroApp__RH_Capacity__c>>();
Integer recordsThisRun = 0;
List<String> noCapacity = new List<String>();
List<String> endedLongAgo = new List<String>();
List<String> reviewNotes = new List<String>();
Integer resourcesThisRun = 0;
Integer resourcesWaiting = 0;
Integer resourcesAlreadyDone = 0;
for (ResourceHeroApp__Resource__c resource : resources) {
List<ResourceHeroApp__RH_Capacity__c> templates = latestByResource.get(resource.Id);
if (templates == null) {
noCapacity.add(resource.Name);
continue;
}
Date latestEnd = templates[0].ResourceHeroApp__End_Date__c;
if (latestEnd < staleBefore) {
endedLongAgo.add(resource.Name + ': last day ' + latestEnd.format());
continue;
}
List<Integer> periodsToCreate = new List<Integer>();
for (Integer i = 0; i < periodStarts.size(); i++) {
if (periodStarts[i] > latestEnd) {
periodsToCreate.add(i);
} else if (latestEnd < periodEnds[i]) {
// The latest record ends partway through this period, so the rest of it has no capacity.
reviewNotes.add(resource.Name + ': capacity ends ' + latestEnd.format() + ', so ' + latestEnd.addDays(1).format() + ' to ' + periodEnds[i].format() + ' has none');
}
}
if (periodsToCreate.isEmpty()) {
resourcesAlreadyDone++;
continue;
}
// A resource's records all go in the same run; the first resource always fits.
Integer recordCount = periodsToCreate.size() * templates.size();
if (resourcesWaiting > 0 || (resourcesThisRun > 0 && recordsThisRun + recordCount > Math.min(MAX_RECORDS_PER_RUN, 200))) {
resourcesWaiting++;
continue;
}
resourcesThisRun++;
List<ResourceHeroApp__RH_Capacity__c> newRecords = new List<ResourceHeroApp__RH_Capacity__c>();
for (Integer i : periodsToCreate) {
for (ResourceHeroApp__RH_Capacity__c template : templates) {
newRecords.add(
new ResourceHeroApp__RH_Capacity__c(
ResourceHeroApp__Resource__c = resource.Id,
ResourceHeroApp__Role__c = template.ResourceHeroApp__Role__c,
ResourceHeroApp__Start_Date__c = periodStarts[i],
ResourceHeroApp__End_Date__c = periodEnds[i],
ResourceHeroApp__Sunday__c = template.ResourceHeroApp__Sunday__c,
ResourceHeroApp__Monday__c = template.ResourceHeroApp__Monday__c,
ResourceHeroApp__Tuesday__c = template.ResourceHeroApp__Tuesday__c,
ResourceHeroApp__Wednesday__c = template.ResourceHeroApp__Wednesday__c,
ResourceHeroApp__Thursday__c = template.ResourceHeroApp__Thursday__c,
ResourceHeroApp__Friday__c = template.ResourceHeroApp__Friday__c,
ResourceHeroApp__Saturday__c = template.ResourceHeroApp__Saturday__c
)
);
}
}
recordsByResource.add(newRecords);
recordsThisRun += 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.
Integer daysThisRun = 0;
for (List<ResourceHeroApp__RH_Capacity__c> records : recordsByResource) {
for (ResourceHeroApp__RH_Capacity__c newCapacity : records) {
daysThisRun += newCapacity.ResourceHeroApp__Start_Date__c.daysBetween(newCapacity.ResourceHeroApp__End_Date__c) + 1;
}
}
while (daysThisRun > 4000 && daysThisRun <= 9000 && recordsByResource.size() > 1) {
for (ResourceHeroApp__RH_Capacity__c newCapacity : recordsByResource.remove(recordsByResource.size() - 1)) {
daysThisRun -= newCapacity.ResourceHeroApp__Start_Date__c.daysBetween(newCapacity.ResourceHeroApp__End_Date__c) + 1;
}
resourcesThisRun--;
resourcesWaiting++;
}
List<ResourceHeroApp__RH_Capacity__c> capacitiesToCreate = new List<ResourceHeroApp__RH_Capacity__c>();
for (List<ResourceHeroApp__RH_Capacity__c> records : recordsByResource) {
capacitiesToCreate.addAll(records);
}
if (!DRY_RUN && !capacitiesToCreate.isEmpty()) {
insert capacitiesToCreate;
}
List<String> summary = new List<String>();
summary.add('');
summary.add('==== Copy latest capacity ' + FIRST_YEAR + '-' + (FIRST_YEAR + NUMBER_OF_YEARS - 1) + (ONE_RECORD_PER_MONTH ? ', monthly records' : '') + (DRY_RUN ? ' (DRY RUN - nothing created)' : '') + ' ====');
summary.add('Capacity records ' + (DRY_RUN ? 'that would be created: ' : 'created: ') + capacitiesToCreate.size() + ' for ' + resourcesThisRun + ' resources');
summary.add('Resources already complete: ' + resourcesAlreadyDone);
summary.add('Resources still waiting (run again): ' + resourcesWaiting);
summary.add('Resources with no capacity to copy (skipped): ' + noCapacity.size());
for (String name : noCapacity) {
summary.add(' ' + name);
}
summary.add('Resources whose capacity ended before ' + staleBefore.format() + ' (skipped): ' + endedLongAgo.size());
for (String note : endedLongAgo) {
summary.add(' ' + note);
}
summary.add('Resources to review: ' + reviewNotes.size());
for (String note : reviewNotes) {
summary.add(' ' + note);
}
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 created – The number of RH Capacity records created in this run, and the number of resources they belong to. In a dry run, this line reads “that would be created”.
- Resources already complete – Resources whose capacity already runs through the last year (or month). Nothing is created for them.
- Resources still waiting (run again) – Resources that didn’t fit in this run. Run the script again to create their records.
- Resources with no capacity to copy (skipped) – Active resources with no RH Capacity records, listed by name.
- Resources whose capacity ended before (skipped) – Resources whose latest capacity ended too long ago, with their last day.
- Resources to review – Resources whose latest record ends partway through a year (or month), with the dates left without capacity. Review this list in the dry run.
Fill a partial year
When a resource’s latest record ends partway through a year, for example on June 30, the yearly records start the following January, and the rest of that year has no capacity. To fill it, run the script for that year with ONE_RECORD_PER_MONTH set to true and NUMBER_OF_YEARS set to 1. The script creates monthly records for the remaining months. Then run it again for the following years with ONE_RECORD_PER_MONTH set back to false.