Scheduling compliance rules

The scheduler and mobile app evaluate compliance by executing custom, dynamic, JavaScript based rules. A compliance rule tells the scheduler whether a worker is a good fit for a shift, and by how much: it can warn about missing certificates, reward relevant experience, flag rest period breaches, or block an assignment outright.

A compliance rule is defined as a Custom Metadata record of type Scheduling Compliance Rule (b3s__Scheduling_Compliance_Rule__mdt). The rule logic goes in the Javascript Code field, and optional rule configuration (user selectable modifiers) goes in the rule config.

Rule signature

Every rule is an async function with this exact footprint. It receives the shift being evaluated, all other loaded events, the worker's contact id, the data loaders, the user's modifier selections, and the result class.

async ({ event, events, contactId, loaders, matchingModifiers, EvaluationResult }) => {
    // Must return an array of EvaluationResult instances.
    // If the array is empty, no compliance item is generated against the shift.
    return [];
}

Arguments

Argument What it is
event The contextual shift or event being evaluated. Custom fields are read via event.extendedProps.record?.<Field_API_Name>. event.title is 'shift', 'request' (availability) or 'placement'. event.start and event.end are JavaScript Dates.
contactId The Salesforce Id of the worker (Contact) being evaluated or matched against the shift.
events An array of all other client side events currently in memory. Use this for overlap checks, minimum rest verification, or weekly hours capping.
loaders The data records fetched before rule execution (see Loaders below).
matchingModifiers A key value object of the user's selections from the search modifiers (for example { priority: "1" }).
EvaluationResult The constructor used to return rule feedback.

EvaluationResult

new EvaluationResult({
    event: null,        // the event to attach the result to
    events: [],          // alternatively, multiple events to attach to
    category: '',        // grouping label used to aggregate results in the UI
    detail: '',          // message shown to the user (emojis supported)
    points: 0,           // positive or negative integer, feeds the ranking engine
    maxPoints: 15,       // optional: the best this result could have scored (see below)
    isBlocking: false    // if true, hard-blocks the assignment / certain actions
})

Return an array of these. Positive points reward a match, negative points penalize it, and isBlocking: true prevents the assignment from being made.

In 12.5.0, a blocking result can also be saved as a blocking event alert. Configure Scheduler compliance restrictions to restrict fields or values such as Status Confirmed while those alerts remain. The unpackaged WFM_Scheduler_Worker_Status example now returns a blocking result for workers who do not meet its status condition. Merge this rule and the relevant context-provider changes into your own metadata deliberately; package installation does not replace authored rules.

maxPoints is what an ideal worker would have scored for the same check. Pass it whenever a result can earn points the worker did not get: a missing certificate scores -50 but a held one would have scored +15, so both results pass maxPoints: 15. When omitted it defaults to Math.max(points, 0), so an award counts as its own best case and a penalty's best case is neutral (0).

How the match % is calculated

Each match result carries three percentages:

Value Meaning
absolutePercentage 100 × totalScore / Σ maxPoints, clamped to 0 to 100. How close the worker is to a perfect fit. If nothing can be earned, 100 when the total is not negative, else 0.
relativePercentage Min-max position within this search: the best result is 100, the worst 0.
matchPercentage 0.7 × absolute + 0.3 × relative. Shown on the match card bar and used by allowBookingThreshold, allowSelectingThreshold, group matching and the scheduler's auto match.

A worker on -400 out of a possible +235 who is still the best in the pool shows 30%, not 100%. Set absoluteScoreWeight (0 to 1) on the invitation definition to change the 0.7 split. Results are still sorted by totalScore.

Thresholds tuned against the old relative-only score may need lowering, since the best candidate no longer always reaches 100. The auto match threshold now defaults to 75.

Loaders and matching loaders

Loaders make the supporting data your rule needs available client side (certificates a worker holds, requirements a job demands, and so on). Associate loaders with a schedule by listing their names on the schedule definition, on the shift schedulable, in an array of strings called matchingLoaders.

Inside the rule, each loader exposes:

interface LoaderState {
    objectName?: string;
    records: SalesforceRecord[];               // flat list
    grouped: Record<string, SalesforceRecord[]>; // keyed by the loader's groupRecordsBy field
}

Find a loader and read its records or its grouped view:

const certificatesLoader = loaders.find((l) => l.name === 'certificates');
const contactCertificates = certificatesLoader?.loader?.grouped[contactId]; // this worker's tickets

const certRequirementsLoader = loaders.find((l) => l.name === 'certRequirements');
const certRequirements = certRequirementsLoader?.loader.records;

Any field your rule reads must be included in the loader's fieldToLoad. See Data loaders.

Search modifiers

The rule config can declare searchModifiers, which render as inputs in the scheduler's matching panel. The user's choices arrive in matchingModifiers. Example config that adds a Priority dropdown:

{
    "searchModifiers": [
        {
            "label": "Priority",
            "type": "field-select",
            "field": "priority",
            "default": "1",
            "options": [
                { "label": "1", "value": "1" },
                { "label": "2", "value": "2" },
                { "label": "3", "value": "3" },
                { "label": "4", "value": "4" },
                { "label": "5", "value": "5" }
            ]
        }
    ]
}

Design patterns

These patterns keep rules reliable and consistent across the app.

Hierarchical context filtering

A requirement record can target different levels of granularity (Account, Site, Job, Job Group, Location). A requirement applies to a shift only if every populated criteria field on the record matches the corresponding field on the shift. Iterate the candidate requirements, and for each one check every field it defines. If a requirement names both an Account and a Site, enforce it only when the shift matches both. If any populated field mismatches, exclude the requirement.

Boundless date validation

When validating effective dated windows (b3s__Valid_From__c, b3s__Valid_Until__c), treat missing constraints as unconditional:

Convert both the event dates (JavaScript Date) and the field values (ISO strings) to timestamps before comparing, and confirm the record covers the full range of the shift.

Priority based point scaling

When rules scale penalties or awards by a numerical priority (1 to 5) against maximum thresholds (b3s__Max_Penalty__c, b3s__Max_Award__c), use a uniform linear reduction so priority 1 allocates 100 percent and priority 5 allocates 20 percent:

const scoreFactor = Math.max(0.2, 1 - (priority - 1) * 0.2);
const points = Math.round(maxPoints * scoreFactor);

Worked example, certificate check

This rule checks whether the worker holds the certificates a shift's account, job, job group, site or location requires, awarding points for held certificates and penalizing missing ones.

async ({ event, events, contactId, loaders, matchingModifiers, EvaluationResult }) => {
    let results = [];
    if (!contactId) return results;

    const certificatesLoader = loaders.find((l) => l.name === 'certificates');
    const contactCertificates = certificatesLoader?.loader?.grouped[contactId] || [];

    const certRequirementsLoader = loaders.find((l) => l.name === 'certRequirements');
    const certRequirements = certRequirementsLoader?.loader.records || [];

    const rec = event.extendedProps.record;
    const eventAccountId = rec?.b3s__Work_Job__r?.b3s__Account__c;
    const eventJobTypeId = rec?.b3s__Work_Job__r?.b3s__Job_Group__c;
    const eventJobId = rec?.b3s__Work_Job__c;
    const eventSiteId = rec?.b3s__Work_Site__c;

    // Hierarchical filter: keep only requirements whose populated context matches the shift.
    const applicable = certRequirements.filter((req) =>
        (req.b3s__Account__c == null || req.b3s__Account__c === eventAccountId) &&
        (req.b3s__Job_Group__c == null || req.b3s__Job_Group__c === eventJobTypeId) &&
        (req.b3s__Job__c == null || req.b3s__Job__c === eventJobId) &&
        (req.b3s__Work_Site__c == null || req.b3s__Work_Site__c === eventSiteId)
    );

    const heldTypes = new Set(contactCertificates.map((c) => c.b3s__Ticket_Type__c));

    for (const req of applicable) {
        if (heldTypes.has(req.b3s__Ticket_Type__c)) {
            results.push(new EvaluationResult({
                event, category: 'Certificates', points: 25, maxPoints: 25,
                detail: `👍 Has ${req.b3s__Ticket_Type__r?.Name}`
            }));
        } else {
            results.push(new EvaluationResult({
                event, category: 'Certificates', points: -50, maxPoints: 25,
                detail: `👎 Missing ${req.b3s__Ticket_Type__r?.Name}`
            }));
        }
    }

    return results;
}

Supporting loader definitions (referenced from matchingLoaders):

{
    "name": "certificates",
    "objectName": "b3s__Ticket__c",
    "filterRecordsBy": ["b3s__Contact__r.AccountId =:contextId"],
    "groupRecordsBy": "b3s__Contact__c",
    "fieldToLoad": ["Name", "b3s__Ticket_Type__c", "b3s__Ticket_Type__r.Name", "b3s__Valid_From__c", "b3s__Valid_Until__c"]
}
{
    "name": "certRequirements",
    "objectName": "b3s__Certificate_Requirement__c",
    "filterRecordsBy": ["Id != null"],
    "fieldToLoad": ["Name", "b3s__Priority__c", "b3s__Max_Award__c", "b3s__Max_Penalty__c", "b3s__Account__c", "b3s__Job_Group__c", "b3s__Job__c", "b3s__Ticket_Type__c", "b3s__Ticket_Type__r.Name", "b3s__Work_Site__c", "b3s__Work_Location__c"]
}

Template to start from

async ({ event, events, contactId, loaders, matchingModifiers, EvaluationResult }) => {
    let results = [];

    // 1. Guard clauses
    if (!contactId) return results;

    const shiftStart = new Date(event.start);
    const shiftEnd = new Date(event.end);

    // 2. Fetch loader collections
    const customLoader = loaders.find((l) => l.name === 'your_loader_name');
    const records = customLoader?.loader?.records || [];
    const groupedForContact = customLoader?.loader?.grouped[contactId] || [];

    // 3. Extract context from the shift event
    const shiftContextId = event.extendedProps.record?.Your_Context_Field__c;

    // 4. Apply hierarchical filters, boundless date checks and priority scaling.

    // 5. Build and return results
    results.push(new EvaluationResult({
        event, category: 'General', points: 10, detail: '🚀 Evaluation completed.'
    }));

    return results;
}

Tips

Shipped rules

Rule What it checks
Availability the worker has an availability request covering the shift
Double booking the worker is not already scheduled over the shift
Max daily hours the worker stays under the daily hours cap
Breaks rest periods between shifts
Distance travel distance between the worker and the site
Tickets the worker holds the certificates the shift requires
Suitabilities the worker's suitability rating for the account, job, site or location
Worker status the worker's status allows assignment
Rate card the worker's personal rate card is not more expensive than the shift's