Break engine

The break engine generates b3s__Break__c rows for shifts from configurable break rulesets. Admins model a jurisdiction's break law (or a client contract) as a b3s__Break_Ruleset__c with child b3s__Break_Rule__c rows; the engine resolves which ruleset applies to each shift, places the entitled breaks inside the shift window (with packaged placement logic or your own plugin), and materializes them as auto-created break records. The pay and bill engine then carves those breaks out of worked time (pay and bill sides independently) and detects missed-break premium pay.

Generation runs automatically from the Shift trigger, on demand from Apex, Flow, the remoting router or the Shift Rate Previewer, and as a pre-step of every Pay/Bill Runner batch.

Data model

Break_Ruleset__c  (effective-dated; context lookups + Country/State jurisdiction; time source, rounding, plugin, premium cap)
 └── Break_Rule__c  (master-detail; one row = one break entitlement)

Shift__c ──< Break__c  (+ Is_Billable__c, Break_Rule__c, Applied_Rule__c)

Break_Ruleset__c

Break_Rule__c (master-detail child)

One row is one break entitlement. Rules are evaluated in b3s__Priority__c ascending order (nulls last); b3s__Active__c = false rows are ignored.

Break__c additions

b3s__Is_Billable__c (bill-side analog of b3s__Is_Paid__c), b3s__Break_Rule__c (lookup to the rule that generated an auto row), b3s__Applied_Rule__c (human trace, "US-CA California › First Meal Break"). Auto rows are marked b3s__Is_Auto_Created__c = true; manual rows never are.

Shift__c addition

b3s__Suppress_Break_Premiums__c: when checked, missed-break premium lines are not generated for the shift (for example the employee attested the missed break was their own election). Break generation itself is unaffected.

Break_Setting__mdt

b3s__Hierarchy__c on the Default record overrides the resolution hierarchy order (see below). Absent, the shipped default applies.

Ruleset resolution

The hierarchy order comes from Break_Setting__mdt.Default.Hierarchy__c (default Contact,Job,Site,Account,ParentAccount,CostCenter,State,Country,Default). The first six tokens match shift context Ids against the same-named ruleset lookups, exactly like rate card resolution; three jurisdiction levels follow:

Token Match
Contact Shift__c.Contact__c to Break_Ruleset__c.Contact__c
Job Work_Job__c to Work_Job__c
Site Work_Site__c to Work_Site__c
Account job account (Work_Job__r.Account__c), then site account (Work_Site__r.Account__c), to Account__c
ParentAccount job account's ParentId, then site account's ParentId, to Account__c
CostCenter Cost_Center__c to Cost_Center__c
State site's Province_State__c matches the ruleset's, and the ruleset's Country__c is blank or matches the site's
Country site's Country__c matches, and the ruleset's Province_State__c is blank
Default all five context lookups and both jurisdiction fields blank: the org-wide fallback

At the Account and ParentAccount levels the job's account is tried first and the site's account second; the first with an effective ruleset wins. Rate cards match the same accounts at the same levels, so one shift resolves its card and its ruleset on the same account. Jurisdiction text matching is case-insensitive and trimmed. The first level with a matching active, effective ruleset wins; ties break on latest Valid_From__c, then newest created. Effective dating is evaluated on the local date of the shift window start (scheduled, falling back to actual) in the site timezone. Unlike rate cards there is no temporal splitting: one ruleset governs the whole shift.

Populate Site Country. A state-level ruleset with Country__c = 'US' only matches sites whose b3s__Country__c is also US. A site with a state but a blank country does not match it.

Resolution does not depend on the running user's access to ruleset records, so every user's shifts resolve the same ruleset. You can keep Break_Ruleset__c private to admins.

Every level walked is recorded as a ResolutionStep trace ("Matched on State level: US-CA California" / "Shift site has no state value"), rendered by the Shift Rate Previewer. No ruleset resolving simply means no auto breaks: it is not an error.

How breaks are generated

For each shift the engine:

  1. Resolves the ruleset (see above).
  2. Picks the window: Shift Billable_Start/End_Time__c when set, else the ruleset's Time_Source__c (Prefer Scheduled / Prefer Actual with per-field fallback to scheduled). A shift with no usable window is skipped with a reason and keeps its existing break rows. A change to a billable field regenerates breaks like any other time change.
  3. Places breaks with the ruleset's b3s__Plugin__c class, or the packaged default placement when blank. A class that does not implement BreakPlugin fails the shift.
  4. Respects manual breaks: a worker-entered break (b3s__Is_Auto_Created__c = false) of a given Type__c suppresses all auto breaks of that same Break_Type__c, with a trace step recording it. A worker who logged their own meal does not also get a generated one.
  5. Rounds each break's start and end when the ruleset configures an interval (local wall clock, DST safe).
  6. Clamps breaks inside the window; zero or negative length breaks are dropped.
  7. Saves: existing auto rows for the shift are replaced with fresh rows stamped with Is_Auto_Created__c = true, Break_Rule__c, Applied_Rule__c ("Ruleset › Rule"), Is_Paid__c, Is_Billable__c, Type__c, Start__c, End__c. Manual rows are never touched. Re-running regenerates; it never duplicates.

A failure on one shift never stops the others: that shift's BreakResult.error carries the message and its break rows stay as they were. BreakEngine.simulate(shiftIds) returns the same result with no DML (the previewer uses it).

Default placement

Recurring breaks are spread evenly across the window, one per equal segment. Middle centres a break in its segment, Start and Offset sit at the segment start (Offset honours Earliest_Start_Hours for a single occurrence) and End sits at the segment end. Breaks always respect the rule's offset bounds and clock window. When the constraints cannot all be met, the break is placed at the nearest bound and its reason says so. Breaks never overlap. Each break carries a readable reason ("Shift length 10.5h > 5h: First Meal Break (30 min), occurrence 1 of 2 placed to end by hour 5").

Worker edits win

When a worker or manager edits an auto-created break's Start__c, End__c or Type__c, the row's Is_Auto_Created__c flips to false. It becomes worker-owned and the engine stops regenerating or deleting it. Because the row's type now suppresses the matching auto rules, the edit sticks across regenerations.

Automation

Missed-break premiums (pay and bill engine)

The pay and bill engine detects missed-break premiums when it prices a shift. A shift qualifies only when it has both Actual_Start_Time__c and Actual_End_Time__c (the required window is the actual worked window) and b3s__Suppress_Break_Premiums__c is unchecked. For each premium-typed rule of the shift's resolved ruleset that fires for the actual worked length:

Each violation emits a Pay staging line with Pay_Code__c = 'Missed_Break', Unit__c = 'Hours', quantity = the (cap-clipped) premium hours, rate = a Per Hour Missed_Break line on the matched rate sheet, else the claiming (or first Standard) Per Hour line times the Missed_Break pay code multipliers, Applied_Rule__c ending in Missed Meal Break Premium: First Meal Break, and no start/end times. Supplier and Bill lines are added only when the ruleset's Premium_Billable__c is true. See the pay and bill engine. Premium money rolls into Total_Pay__c / Total_Bill__c through the staging lines, but premium hours never touch the billable window, the overtime-hour rollups, or timesheet gross hours.

The Shift Rate Previewer shows the shift's break rows, the ruleset resolution trace and the capped premium hours (2 decimal places).

Pay-side and bill-side carving

Break carving is side-aware: pay-side work blocks carve breaks that are not Is_Paid__c, bill-side blocks carve breaks that are not Is_Billable__c (a paid-but-not-billable rest break reduces the invoice but not the paycheck). The card's Breaks_Paid__c still disables carving on both sides. When the pay and bill sides carve different breaks, each side is priced, including overtime, independently. See the pay and bill engine reference.

APIs

Apex (global statics)

// Regenerate: delete existing auto rows, insert fresh ones. Map keyed by shift Id.
Map<Id, b3s.BreakEngine.BreakResult> results = b3s.BreakEngine.run(shiftIds);

// Same result, no DML.
Map<Id, b3s.BreakEngine.BreakResult> preview = b3s.BreakEngine.simulate(shiftIds);

BreakResult: shiftId, breaks (list of BreakSpec: breakType, startTime, endTime, isPaid, isBillable, ruleId, ruleLabel, reason), trace (resolution steps), rulesetName, timeSource, timezoneName, error.

Remoting - b3s.BreakService

Action Purpose Key args
previewBreaks Simulate generation for one shift: zero DML. shiftId, appType?, hostType?, sessionKey?
generateBreaks Regenerate breaks for a set of shifts (synchronous DML). shiftIds (list), appType?, hostType?, sessionKey?

The caller needs access to b3s__Break__c and to every target shift; an unknown or inaccessible shift Id returns an ErrorResponse. Portal sessions may act only on shifts whose b3s__Contact__c is the signed-in contact. generateBreaks also rejects approval-locked shifts (Submitted/Approved) and requires create and delete on b3s__Break__c for authenticated users. previewBreaks performs no DML and stays available on locked shifts.

Object resp = b3s.GlobalRemotingRouter.callObject(
    'b3s.BreakService',
    JSON.serialize(new Map<String, Object>{
        'endp'    => 'previewBreaks',
        'shiftId' => shiftId
    })
);

Returns a SuccessResponse whose responseObject is a BreakResult (previewBreaks) or a map of shift Id to BreakResult (generateBreaks); failures return an ErrorResponse with the reason in message:

{
  "statusCode": 200,
  "success": true,
  "statusType": "OK",
  "responseObject": {
    "shiftId": "a0X...",
    "rulesetName": "US-CA California",
    "timeSource": "Scheduled",
    "timezoneName": "America/Los_Angeles",
    "breaks": [
      {
        "breakType": "Meal",
        "startTime": "2026-03-02T20:00:00.000Z",
        "endTime": "2026-03-02T20:30:00.000Z",
        "isPaid": false,
        "isBillable": false,
        "ruleLabel": "First Meal Break",
        "reason": "Shift length 8h > 5h: First Meal Break (30 min) placed to end by hour 5"
      }
    ],
    "trace": [ { "level": "State", "matched": true, "detail": "Matched on State level: US-CA California" } ]
  }
}

Lightning (@AuraEnabled) - b3s.BreakService

@AuraEnabled global static b3s.BreakEngine.BreakResult preview(Id shiftId)   // zero DML
@AuraEnabled global static b3s.BreakEngine.BreakResult generate(Id shiftId)  // persists

generate requires the caller to hold create + delete on b3s__Break__c and rejects approval-locked (Submitted/Approved) shifts with an AuraHandledException; preview performs no DML and carries no such gates.

The Shift Rate Previewer's break card is built on these. See the next section.

Review in the Shift Rate Previewer

The shiftRatePreviewer native LWC (on the b3s__Shift__c record page) is the observability surface for both engines. Between the rate segments and the line breakdown it renders, from the simulate payload:

Flow (invocable) - Generate Shift Breaks

@InvocableMethod(label='Generate Shift Breaks' category='Workforce Management')
global static void generateBreaks(List<BreakService.Request> requests)

Request - b3s.BreakService.Request

Variable Type Required Notes
shiftIds List<Id> yes Shifts to regenerate breaks for.

All requests are processed in one background job, 200 shifts at a time, so a bulk Flow run stays within platform limits. Requests with no shift Ids are skipped, and approval-locked shifts (Submitted/Approved) are left unchanged. The method returns nothing; generation is asynchronous. Use it from Flows that run as admins or trusted automation.

Writing a custom break plugin

For rules that fields cannot express (New York's evening-meal span condition, headcount gates, industry carve-outs), implement BreakPlugin and name the class in Break_Ruleset__c.Plugin__c (ns.Class or a bare name; resolution is namespace aware, as for Apex filters). Plugins do placement only: no SOQL, no DML. Everything arrives in memory via the context; rounding, clamping, manual-coexistence suppression and DML remain the engine's job.

global with sharing class NyEveningMealPlugin implements b3s.BreakPlugin {
    global List<b3s.BreakEngine.BreakSpec> compute(b3s.BreakEngine.BreakContext ctx) {
        // ctx: shiftId, contactId, windowStart/windowEnd (from the ruleset's
        // Time_Source), timezoneName, ruleset, rules (active, Priority ASC),
        // existingManualBreaks (Is_Auto_Created__c = false)
        List<b3s.BreakEngine.BreakSpec> specs = new List<b3s.BreakEngine.BreakSpec>();
        // ... place breaks; set breakType, startTime, endTime, isPaid,
        //     isBillable, ruleId, ruleLabel, reason ...
        return specs;
    }
}

The packaged default placement (see Default placement) handles thresholds, tiers, recurrence and placement. Implement a plugin only for what your jurisdiction needs beyond it.

Setup