Apex and automation API reference

This article documents the parts of the managed package (namespace b3s) that are reachable from Apex you write in your own org, from Flow, or over REST. It covers four things:

The native invoicing components are documented in Invoicing.

Only the publicly accessible surface is described here. Package internals are not callable and are not documented.


Remoting services

The calling contract

Every remoting service implements the platform System.Callable interface and exposes a single entry point:

global static Object call(String action, Map<String, Object> args)

action selects the operation; args carries its parameters. You never instantiate a service and call call directly across a namespace - requests are routed through a single dispatcher, b3s.GlobalRemotingRouter, which invokes call(action, args) on the service you name.

There are two ways in.

From Apex or Aura (in-process):

String payload = JSON.serialize(new Map<String, Object>{
    'endp'       => 'lookupRecords',   // the action name
    'objectName' => 'Contact',
    'titleField' => 'Name',
    'searchTerm' => 'smith'
});

Object response = b3s.GlobalRemotingRouter.callObject('b3s.FieldsService', payload);

controllerName is always the namespaced class name (b3s.FieldsService). params is a JSON string whose endp key names the action - the rest of the object is the argument map that reaches call as args.

Over REST:

POST /services/apexrest/b3s/GlobalRemotingRouter/
Content-Type: application/json

{
  "controllerName": "b3s.FieldsService",
  "endp": "lookupRecords",
  "objectName": "Contact",
  "titleField": "Name",
  "searchTerm": "smith"
}

The whole request body is passed through as the argument map, so endp and the arguments sit at the same level. Custom clients using the REST endpoint must supply their own Salesforce authentication. WFM portal calls use the portal session key.

Both paths return a JSON-serialized SuccessResponse or ErrorResponse (see Response contract). An unknown action returns an ErrorResponse rather than throwing.

Access is checked on every call. Authenticated users see only what their sharing, object and field permissions allow. Portal requests require a valid session key and are scoped to the signed-in contact's access. Requests for objects outside the permitted set are rejected.

The services below are the ones you can call by name.


Shared - file management

b3s.Shared reads and writes Salesforce Files (ContentDocument / ContentVersion) and their links to records.

Action Purpose Key args
getRecordFiles List every file linked to a record (one row per link, newest first), with the fields needed to render, download and delete. recordId
getDocumentLinks The raw ContentDocumentLink rows for a file title on a record. fileName, recordId
getContentVersionById Version metadata (type, path, size, created date) for a version Id. contentVersionId
getContentVersionByName Latest (or a specified) version of a named file on a record. fileName, recordId, contentVersionId?
getContentVersions Latest (or a specified) version under a content document. contentDocumentId, contentVersionId?
getVersionData The file bytes for a version, base64 encoded. Returns raw data, not a wrapper (see note). contentVersionId
createContentVersion Upload a new version / file. Returns the new version Id. Title, PathOnClient, VersionData (base64), Origin, ContentLocation, ContentDocumentId?, FirstPublishLocationId?, Description?
relateDocumentToRecord Link an existing content document to a record. contentDocumentId, recordId
relateContentVersionToRecord Link the document behind a version to a record. contentVersionId, recordId
shareFile Widen an existing link's visibility to all users. contentVersionId, linkedEntityId
deleteContentDocument Delete a file entirely (cascades links and versions). contentDocumentId

getVersionData deliberately returns the base64 string directly rather than wrapping it in a SuccessResponse, to avoid doubling a large payload in memory. Every other action returns the standard wrapper. createContentVersion returns the new version Id string.

Example - upload a file and attach it to a record:

String versionId = (String) b3s.GlobalRemotingRouter.callObject(
    'b3s.Shared',
    JSON.serialize(new Map<String, Object>{
        'endp'         => 'createContentVersion',
        'Title'        => 'Timesheet.pdf',
        'PathOnClient' => 'Timesheet.pdf',
        'Origin'       => 'H',
        'VersionData'  => EncodingUtil.base64Encode(fileBlob)
    })
);

RemoteSchemaManager - schema lookup

b3s.RemoteSchemaManager exposes lightweight schema helpers.

Action Purpose Key args
getObjectNameFromId Resolve the object API name from any record Id. recordId

Returns a SuccessResponse whose responseObject is the object API name string.


RemoteRecordsManager - CRUD, DML, describe, user context

b3s.RemoteRecordsManager is the general record service. All DML respects the resolved access level.

Action Purpose Key args
upsertRecords Insert/update a batch of records of one object. objectName, recordsToUpsert (JSON array of records), allowPartial? (12.8.0; defaults to false)
deleteRecords Delete a batch of records. objectName, recordsToDelete (JSON array), allowPartial? (accepted but ignored; always all or nothing)
commitBatch Save upserts and deletes across objects in one transaction. changes: JSON string containing upserts and deletes groups, each with objectName and records.
getRecords Query records of an object (legacy read path). objectName, getAllFields?, additionalFields?, queryFilter?, getDescribe?
describeObjects Describe metadata for a list of objects. objectNames (array of API names)
getRunningUser The Contact representing the calling user (for internal users a userId must be supplied; portal sessions return the signed-in contact). userId?, sessionKey?

Notes:

Example - update a shift:

b3s__Shift__c shift = new b3s__Shift__c(Id = shiftId, b3s__Status__c = 'Confirmed');

Object resp = b3s.GlobalRemotingRouter.callObject(
    'b3s.RemoteRecordsManager',
    JSON.serialize(new Map<String, Object>{
        'endp'            => 'upsertRecords',
        'objectName'      => 'b3s__Shift__c',
        'recordsToUpsert' => JSON.serialize(new List<b3s__Shift__c>{ shift })
    })
);

commitBatch - several objects in one transaction

commitBatch saves a set of upserts and deletes, possibly across several objects, as one transaction. The Scheduler uses it for every calendar save (see Scheduler saving and live sync).

Request (changes is a JSON string inside the params):

{
    "endp": "commitBatch",
    "changes": "{\"upserts\":[{\"objectName\":\"b3s__Shift__c\",\"records\":[{\"Id\":\"a0X000000000001AAA\",\"b3s__Scheduled_Start_Time__c\":\"2026-11-16T08:00:00.000Z\",\"b3s__Scheduled_End_Time__c\":\"2026-11-16T16:00:00.000Z\"},{\"b3s__Contact__c\":\"003000000000001AAA\",\"b3s__Scheduled_Start_Time__c\":\"2026-11-17T08:00:00.000Z\",\"b3s__Scheduled_End_Time__c\":\"2026-11-17T16:00:00.000Z\"}]}],\"deletes\":[{\"objectName\":\"b3s__Shift__c\",\"records\":[{\"Id\":\"a0X000000000002AAA\"}]}]}"
}

The changes value, unescaped:

{
    "upserts": [
        {
            "objectName": "b3s__Shift__c",
            "records": [
                {
                    "Id": "a0X000000000001AAA",
                    "b3s__Scheduled_Start_Time__c": "2026-11-16T08:00:00.000Z",
                    "b3s__Scheduled_End_Time__c": "2026-11-16T16:00:00.000Z"
                },
                {
                    "b3s__Contact__c": "003000000000001AAA",
                    "b3s__Scheduled_Start_Time__c": "2026-11-17T08:00:00.000Z",
                    "b3s__Scheduled_End_Time__c": "2026-11-17T16:00:00.000Z"
                }
            ]
        }
    ],
    "deletes": [
        {
            "objectName": "b3s__Shift__c",
            "records": [{ "Id": "a0X000000000002AAA" }]
        }
    ]
}

Response when everything saved (responseObject of a SuccessResponse; groups and rows are index aligned with the request, record abbreviated):

{
    "success": true,
    "upserts": [
        {
            "objectName": "b3s__Shift__c",
            "results": [
                {
                    "isSuccess": true,
                    "recordId": "a0X000000000001AAA",
                    "errors": null,
                    "record": { "Id": "a0X000000000001AAA" }
                },
                {
                    "isSuccess": true,
                    "recordId": "a0X000000000003AAA",
                    "errors": null,
                    "record": { "Id": "a0X000000000003AAA" }
                }
            ]
        }
    ],
    "deletes": [
        {
            "objectName": "b3s__Shift__c",
            "results": [
                {
                    "isSuccess": true,
                    "recordId": "a0X000000000002AAA",
                    "errors": null,
                    "record": { "Id": "a0X000000000002AAA" }
                }
            ]
        }
    ]
}

Response when one row failed (still a SuccessResponse; nothing was saved):

{
    "success": false,
    "upserts": [
        {
            "objectName": "b3s__Shift__c",
            "results": [
                {
                    "isSuccess": false,
                    "recordId": null,
                    "errors": [
                        "Not saved: another change in the same request failed."
                    ],
                    "record": { "Id": "a0X000000000001AAA" }
                },
                {
                    "isSuccess": false,
                    "recordId": null,
                    "errors": ["Scheduled End must be after Scheduled Start"],
                    "record": { "Id": null }
                }
            ]
        }
    ],
    "deletes": [
        {
            "objectName": "b3s__Shift__c",
            "results": [
                {
                    "isSuccess": false,
                    "recordId": null,
                    "errors": [
                        "Not saved: another change in the same request failed."
                    ],
                    "record": { "Id": "a0X000000000002AAA" }
                }
            ]
        }
    ]
}

Apex example:

Map<String, Object> changes = new Map<String, Object>{
    'upserts' => new List<Object>{
        new Map<String, Object>{ 'objectName' => 'b3s__Shift__c', 'records' => new List<b3s__Shift__c>{ moved, created } }
    },
    'deletes' => new List<Object>{
        new Map<String, Object>{ 'objectName' => 'b3s__Shift__c', 'records' => new List<b3s__Shift__c>{ new b3s__Shift__c(Id = sourceId) } }
    }
};
Object resp = b3s.GlobalRemotingRouter.callObject(
    'b3s.RemoteRecordsManager',
    JSON.serialize(new Map<String, Object>{ 'endp' => 'commitBatch', 'changes' => JSON.serialize(changes) })
);

DataLoadingService - app data loading

b3s.DataLoadingService is the facade for all app-driven data loading: boot metadata, server-executed loaders and record loads, structured queries and dashboard widgets. Query definitions live in Custom Metadata and app definitions and run on the server - the client never builds SOQL.

Action Purpose Key args
getSupportingMetadata Single-trip boot payload for an app: context record, running user, group assignments, app definition, loader descriptors, filters, translations and object describes. type (app/component type), recordId?, contactId?, sessionKey?, hostType?, requireUser?, groupName?
getLoaderData Execute one page of a Custom-Metadata loader definition. loaderName (loader DeveloperName), recordId?, contactId?, sessionKey?, hostType?, contextStart?, contextEnd?, contextDate?, clauseIndex?, lastId?, getDescribe?, filterRecordId?
loadRecords Load records defined by an app definition (by Id list, by schedulable type, or by object override), with delta-sync support. appType, definitionKey, plus one of eventsToReload / schedulable type / objectName; window and delta args as configured
queryRecords Structured query for authenticated users. Not available to portal sessions. objectName, fields, filters (AND-joined list: {field, value} equality, {field, values} IN on text or Id columns, {field, from?, to?} inclusive ISO date or datetime range), orderByField?, limitCount?, offsetCount?
getChanges Ids of records of one object modified or deleted since a server timestamp (delta sync feed). Authenticated users only. objectName, since? (epoch milliseconds)
listRecords One page of a server-paged list declared under the definition root lists: sorted, scoped, searched and counted on the server, with related loader rows. appType, definitionKey, listKey, scope, source?, search?, page?, contextStart? / contextEnd?, ids?, withCounts?, getDescribe?
getContextRecord Resolve a contextual record and its object API name in one trip. recordId, appType?, hostType?, sessionKey?
getUserGroupAssignments The running user's sharing-group assignments (user resolved server-side). none
dashboardData Compute dashboard / badge widget values declared in an app definition. widgetSet? (for example badges), plus definition-driven args

Key behaviours:

Loaders and definitions can also delegate filtering to an Apex class you write - see FilterPlugin and the Apex filters guide.

Example - one page of a loader:

Object page = b3s.GlobalRemotingRouter.callObject(
    'b3s.DataLoadingService',
    JSON.serialize(new Map<String, Object>{
        'endp'       => 'getLoaderData',
        'loaderName' => 'My_Shift_Loader',
        'recordId'   => contextRecordId,
        'clauseIndex'=> 0
    })
);

getChanges - delta sync feed

Returns which records of objectName changed since since, so a client can merge them without reloading everything.

Request:

{ "endp": "getChanges", "objectName": "b3s__Shift__c", "since": 1794653970000 }

Response (responseObject of a SuccessResponse):

{
    "serverNow": 1794654000000,
    "modifiedIds": ["a0X000000000001AAA", "a0X000000000004AAA"],
    "deletedIds": ["a0X000000000002AAA"],
    "capped": false
}

Prime call (since omitted) response:

{
    "serverNow": 1794654000000,
    "modifiedIds": [],
    "deletedIds": [],
    "capped": false
}

Error (ErrorResponse), for example { "success": false, "message": "Invalid objectName [Not_An_Object__c]" }.

listRecords - server-paged lists

Returns one page of a list declared under the app definition root lists (configuration contract: Data loaders, server-paged lists). The Client Shift Manager Requests tab (requests) and the Vendor Portal Invites tab (invites) use it. The definition is re-resolved on the server from appType + definitionKey, so the caller names a list, a scope and a page, never a query.

Request:

{
  "endp": "listRecords",
  "appType": "Client Shift Manager",
  "definitionKey": "Client Shift Manager",
  "listKey": "requests",
  "scope": "all",
  "search": "night",
  "page": 1,
  "ids": ["a0B000000000009AAA"],
  "withCounts": true,
  "getDescribe": false,
  "sessionKey": "<portal session key>"
}

Response (responseObject of a SuccessResponse):

{
  "order": ["a0B000000000001AAA", "a0C000000000002AAA"],
  "total": 2,
  "pageSize": 12,
  "counts": { "all": 2, "active": 1, "stale": 0, "filled": 1, "canceled": 0 },
  "sources": {
    "shift": { "objectName": "b3s__Shift__c", "records": [{ "Id": "a0B000000000001AAA", "Name": "Night cover" }, { "Id": "a0B000000000009AAA", "Name": "Open in console" }] },
    "booking": { "objectName": "b3s__Booking_Request__c", "records": [{ "Id": "a0C000000000002AAA", "Name": "Night porter" }] }
  },
  "related": {
    "vmsInvites": { "objectName": "b3s__Vendor_Invite__c", "records": [{ "Id": "a0D000000000003AAA", "b3s__Shift__c": "a0B000000000001AAA" }] }
  }
}

order is the page in display order across all sources. total is the row count of the current scope. sources.<name>.records holds the page rows of that source plus its pinned rows.

Errors (ErrorResponse, { "success": false, "message": "..." }):

Message Cause
Unknown list [x] / Unknown scope [x] / Unknown source [x] The name is not in the definition's lists config.
Missing app definition for [...] No definition record for appType / definitionKey.
Invalid pageSize on list [x] pageSize outside 1 to 200.
Source [x] has no valid sort path for [key] A scope sorts by a key the source does not map (or maps to an invalid path).
Invalid search field path [x] on source [y], Invalid field path [...], Invalid clauseField [...], Invalid key on related loader [x] A config identifier failed validation.
List clauses cannot carry LIMIT or ORDER BY [...] A source, scope or related loader clause holds LIMIT or ORDER BY.
Loader [x] has an apexFilter and cannot be a related loader / Loader [x] not found in the definition for [...] A related entry names an unusable loader.
ids must be a list / At most 20 pinned ids / an invalid Id Bad ids argument.
A date validation error naming contextStart / contextEnd A period scope was called without valid dates.
listRecords is not available to delegated sessions A vendor key acting for a worker (vendor delegation).
The session error (Portal_InvalidSession) A portal guest without a valid sessionKey.

FieldsService - lookup and record-select queries

b3s.FieldsService backs the lookup / record-select input components with a fixed, safe query shape.

Action Purpose Key args
lookupRecords Search or fetch records of one object for a picker. objectName, titleField, descriptionField?, searchTerm?, recordId?, maxResults?, appType?, hostType?, sessionKey?

Behaviour:

Returns a SuccessResponse whose responseObject is { "records": [ ... ] }.


InvoicePortalService - portal invoice PDFs

b3s.InvoicePortalService serves invoice PDFs to the portal invoice lists (Client Shift Manager and Vendor Portal), including Site Guest Users. Every download is access checked on the server.

Action Purpose Key args
getInvoicePdf The issued invoice's PDF, base64 encoded. invoiceId, appType, hostType?, sessionKey?
getBackingSheet The invoice's backing sheet CSV (b3s__Backing_Sheet_Document_Id__c), base64 encoded. Same checks as getInvoicePdf; refused with Backing sheet not available. invoiceId, appType, hostType?, sessionKey?

The request is refused (an ErrorResponse with message Invoice PDF not available) unless all of these hold:

Request:

{
    "controllerName": "b3s.InvoicePortalService",
    "params": "{\"endp\":\"getInvoicePdf\",\"invoiceId\":\"a2ZHu000000Inv1AAA\",\"appType\":\"Vendor Portal\",\"sessionKey\":\"<portal session key>\"}"
}

Response on success: the base64 file string itself, like Shared.getVersionData (no wrapper):

"JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+..."

Response when refused:

{
    "statusCode": 400,
    "success": false,
    "statusType": "ERROR",
    "message": "Invoice PDF not available",
    "responseObject": null
}

BookingConfirmationService - client booking confirmation download

getClientConfirmation returns the latest client booking confirmation PDF of an accepted proposal's placement, for Client Shift Manager sessions inside the proposal's client accounts.

Request:

{ "controllerName": "b3s.BookingConfirmationService", "endp": "getClientConfirmation", "proposalId": "a0X..." }

Response: the PDF as a raw base64 string (not wrapped), or an error response such as { "success": false, "message": "No booking confirmation is available yet." }. See Booking confirmations.

Pass placementId instead of proposalId to download by placement (Workers tab, booked workers). The placement's job or site account must grant Tab Workers to the contact.

{ "controllerName": "b3s.BookingConfirmationService", "endp": "getClientConfirmation", "placementId": "a0Y..." }

WorkerPhotoService - booked worker photo

getBookingPhoto returns the photo of the worker on a placement or shift, for Client Shift Manager sessions whose Tab Workers accounts include the booking's job or site account.

{ "controllerName": "b3s.WorkerPhotoService", "endp": "getBookingPhoto", "recordId": "a0Y..." }

Response: { "success": true, "responseObject": { "photoId": "069...", "dataUrl": "data:image/png;base64,..." } }. See Worker photos.

TerminalService - terminal QR verification

b3s.TerminalService checks the rotating code in a Terminal's QR (reverse QR). Called by the Clock app before it clocks the worker in or out at the scanned site. See Terminal sign-in methods.

Action Purpose Key args
verifySiteCode Confirm a scanned terminal code is current for the site. siteId, code, appType?, sessionKey? (the worker's Clock app session)
createClockLoginKey Issue a Portals session key for the worker the Terminal just signed in, so they can open the Clock app on their phone. contactId

Behaviour:

Request:

{
    "endp": "verifySiteCode",
    "siteId": "a0B5g00000XyZabEAF",
    "code": "c145487789"
}

Response (SuccessResponse):

{
    "success": true,
    "responseObject": {
        "siteId": "a0B5g00000XyZabEAF",
        "siteName": "Madrid Warehouse"
    }
}

createClockLoginKey behaviour:

Request:

{ "endp": "createClockLoginKey", "contactId": "0035g00000AbCdEAAZ" }

Response (SuccessResponse):

{ "success": true, "responseObject": { "sessionKey": "<encrypted key>" } }

TimeCaptureService - third-party clock events

b3s.TimeCaptureService records a clock in or clock out from an external clock, badge reader or time system, resolving the shift the same way the Clock app does and inserting the matching Geo Tag. Reach it through the remoting router or over REST at POST /services/apexrest/b3s/wfm/clock/ (same JSON body, HTTP 200 on success, 400 on any error). Full guide: Time capture integration.

Action Purpose Key args
clockEvent Clock a worker in or out; creates an ad hoc shift on clock in when nothing is scheduled nearby. eventType (in / out), timestamp (ISO 8601 or epoch ms), contactId or contactExternalId (+ contactExternalIdField?, default b3s__External_QR_Tag__c), siteId? or siteTag?, latitude?, longitude?, locationError?, searchRangeMinutes? (default 60), allowAdhoc? (default true)

Behaviour:

Request:

{
    "endp": "clockEvent",
    "eventType": "in",
    "timestamp": "2026-11-05T08:58:00Z",
    "contactExternalId": "BADGE-1042",
    "siteId": "a0B5g00000XyZabEAF",
    "latitude": 51.5072,
    "longitude": -0.1276
}

Response (SuccessResponse):

{
    "success": true,
    "responseObject": {
        "shiftId": "a0D5g00000Shf01EAB",
        "geoTagId": "a0E5g00000Geo01EAB",
        "eventType": "Clock In",
        "isAdhoc": false,
        "created": false
    }
}

VmsPortalService - proposal review and booking schedules

b3s.VmsPortalService approves or rejects a VMS worker proposal from the Client Shift Manager in one server-side transaction (the internal broadcast panel uses the same review logic), and saves and reads the custom schedule of a booking request.

Action Purpose Key args
reviewProposal Approve or reject one worker proposal. proposalId, reviewAction (approve or reject), appType, sessionKey?, contactId?
saveBookingPattern Save (replace) a booking request's custom schedule as a one-off Working Pattern Type. See saveBookingPattern. bookingRequestId, days, appType, sessionKey?, contactId?
getBookingPattern Read the working pattern days of a booking request (template or custom). See getBookingPattern. bookingRequestId, appType, sessionKey?, contactId?

reviewProposal - approve or reject a proposal

Behaviour:

Request:

{
    "endp": "reviewProposal",
    "proposalId": "a0X5g00000AbCdEAAZ",
    "reviewAction": "approve"
}

Response (SuccessResponse; convertedId is the child shift or placement Id, null on reject):

{ "success": true, "responseObject": { "convertedId": "a0S5g00000QrStUAAZ" } }

saveBookingPattern - save a custom booking schedule

Stores the per day schedule of one booking request as a Working Pattern Type with One Off (b3s__One_Off__c) = true plus its Working Pattern Day rows, and stamps the type on the request's b3s__Working_Pattern_Type__c. The Client Shift Manager request wizard calls it on Next of its Schedule step. Each call replaces the whole schedule. Everything runs in one transaction; any failure rolls it back.

Args:

Arg Type Notes
bookingRequestId Id The b3s__Booking_Request__c.
days list (or the same list as a JSON string) One entry per working day, at least one.
days[].week Integer 0 to 11 Rotation week (0 = week 1). At most 12 weeks.
days[].day Integer 0 to 6 Weekday, 0 = Monday to 6 = Sunday. Each week and day pair once.
days[].start, days[].end Text HH:mm Site wall clock times, 24 hour. An end at or before the start is an overnight shift ending the next day.
days[].rateBasis Text, optional A Rate Basis picklist value. Blank = the day inherits (no value of its own).

Behaviour:

Request:

{
  "endp": "saveBookingPattern",
  "bookingRequestId": "a0B5g00000XyZaBEAV",
  "days": [
    { "week": 0, "day": 0, "start": "07:30", "end": "14:00", "rateBasis": "Full Day" },
    { "week": 0, "day": 1, "start": "07:30", "end": "14:00", "rateBasis": "Full Day" },
    { "week": 0, "day": 2, "start": "07:30", "end": "14:00", "rateBasis": "Full Day" },
    { "week": 0, "day": 3, "start": "07:30", "end": "11:00", "rateBasis": "Half Day" }
  ]
}

Response (SuccessResponse, same shape as getBookingPattern, days ordered by week then day):

{
  "success": true,
  "responseObject": {
    "patternTypeId": "a0C5g00000LmNoPEAV",
    "oneOff": true,
    "timezone": "Europe/London",
    "days": [
      { "week": 0, "day": 0, "start": "07:30", "end": "14:00", "rateBasis": "Full Day" },
      { "week": 0, "day": 1, "start": "07:30", "end": "14:00", "rateBasis": "Full Day" },
      { "week": 0, "day": 2, "start": "07:30", "end": "14:00", "rateBasis": "Full Day" },
      { "week": 0, "day": 3, "start": "07:30", "end": "11:00", "rateBasis": "Half Day" }
    ]
  }
}

Errors (ErrorResponse.message):

Custom label Message Cause
Booking_Pattern_Denied Your profile does not allow viewing or changing the schedule of this booking request. Wrong app, guest without a profile, request not found, or the update rules do not grant the request.
Booking_Pattern_Locked The schedule can no longer change: the request was submitted or a worker is already placed. VMS Stage past New, or a placement exists.
Booking_Pattern_Invalid Invalid schedule day: {0} {0} is the offending entry as JSON ([] for an empty list): bad week or day, bad time, or a duplicate week and day.
Rate_Basis_Not_Allowed Rate Basis {0} is not allowed for this job. Allowed values: {1}. A day's Rate Basis is outside the request's templates.

An unparseable bookingRequestId returns Invalid Id [<value>].

getBookingPattern - read a booking schedule

Returns the Working Pattern Day rows of the request's pattern type, whether it is a reusable template or a One Off custom schedule. The Client Shift Manager wizard Preview step and the Vendor Portal View schedule action use it.

Request:

{ "endp": "getBookingPattern", "bookingRequestId": "a0B5g00000XyZaBEAV" }

Response: the same { patternTypeId, oneOff, timezone, days } shape as saveBookingPattern. A template pattern returns "oneOff": false. Errors: Booking_Pattern_Denied when neither read path grants the request, Invalid Id [<value>].


OnboardingTemplateService - worker onboarding status

b3s.OnboardingTemplateService returns how far one or more workers are through their onboarding templates. The Vendor Portal uses it for the worker badges and the onboarding wizard. Status is computed on every call from the workers' Tickets; nothing is stored. See Worker onboarding templates for the status rules.

Action Purpose Key args
getOnboardingStatus Onboarding status per worker, per template and per credential. contactIds (list, required), templateIds? (list; given = ad hoc check of exactly these templates, omitted = each worker's assigned templates), appType?, hostType?, sessionKey?

Behaviour:

Request:

{ "endp": "getOnboardingStatus", "contactIds": ["0035g00000AbCdEAAZ"] }

Response (SuccessResponse, shortened; the full shape is in the feature article):

{
    "success": true,
    "responseObject": {
        "workers": [
            {
                "contactId": "0035g00000AbCdEAAZ",
                "status": "Pending",
                "templates": [
                    {
                        "templateId": "a1F5g00000OnBrDEAZ",
                        "name": "Supply teacher",
                        "assigned": true,
                        "workerOnboardingId": "a1H5g00000WoNbDEAZ",
                        "status": "Pending"
                    }
                ],
                "items": [
                    {
                        "ticketTypeId": "a0T5g00000DbScKEAZ",
                        "ticketTypeName": "Enhanced DBS",
                        "level": "Required",
                        "status": "Pending",
                        "ticketId": "a0U5g00000TkT1aEAZ",
                        "validFrom": "2026-10-01",
                        "validUntil": "2029-09-30",
                        "approvalStatus": null
                    }
                ]
            }
        ]
    }
}

UserProvisioningService - portal user provisioning

b3s.UserProvisioningService backs Settings → Users in the Client Shift Manager and Vendor Portal. See VMS user provisioning.

Action Purpose Key args
getAssignableProfiles Accounts a new user may be added to (own account, then its direct children) and the profiles the contact may assign. appType, sessionKey?, contactId?
provisionUser Create a portal user on the contact's own account or a direct child account (AccountId; blank = own; clients may send several as id1;id2). Every new user (client and vendor) gets one Account Membership per account with the picked profile; the Contact carries no profile. record: only the fields of the definition's user.recordFormFields (FirstName, LastName, Email, AccountId, and the profile pick as $userProfileId in the samples)
getUserProfiles Profile names each listed user holds through their Account Memberships (distinct, sorted, comma-joined). Same scope as the users loader: contacts with the app's VMS Role whose account or parent account grants Settings Tab. appType, sessionKey?, contactId?
setUserDisabled Deactivate or reactivate a portal user (b3p__Disabled_Portal_User__c). userId, disabled

Behaviour:

Request and response:

{ "endp": "getAssignableProfiles" }
{
    "success": true,
    "responseObject": {
        "accountId": "001...",
        "accounts": [{ "label": "Oakwood Trust", "value": "001..." }],
        "profiles": [{ "label": "Client Finance", "value": "a0X..." }]
    }
}
{
    "endp": "provisionUser",
    "record": {
        "FirstName": "Ana",
        "LastName": "Diaz",
        "Email": "ana@client.example",
        "AccountId": "001...",
        "$userProfileId": "a0X..."
    }
}
{ "success": true, "responseObject": { "contactId": "003..." } }
{ "endp": "getUserProfiles" }
{
    "success": true,
    "responseObject": {
        "profilesByContact": {
            "003AA000001": "Client Admin",
            "003AA000002": "Client Admin, Client Finance"
        }
    }
}

BreakService - break preview and generation

b3s.BreakService previews and regenerates auto-created b3s__Break__c rows from the shift's resolved Break Ruleset.

Action Purpose Key args
previewBreaks Simulate break generation for one shift - zero DML. shiftId, appType?, hostType?, sessionKey?
generateBreaks Regenerate auto breaks for a set of shifts (synchronous DML: existing auto rows deleted, fresh rows inserted; manual rows untouched). 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.

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): shiftId, breaks (placed specs: breakType, startTime, endTime, isPaid, isBillable, ruleId, ruleLabel, reason), trace (resolution steps), rulesetName, timeSource, timezoneName, error. Full semantics: Break engine.


Direct Apex APIs

VmsProposalApi - propose a worker from your own interface

b3s.VmsProposalApi.createProposal lets you build your own worker proposal screen (for example a component that proposes a worker held in another WFM system and converts their credentials to b3s__Ticket__c in the same transaction). It is a plain global static method, not a remoting service: call it from your own Apex, typically an @AuraEnabled controller behind your LWC.

global static Id createProposal(
    Id recordId,                      // demand b3s__Shift__c or b3s__Booking_Request__c
    Id contactId,                     // the worker
    Decimal proposedRate,             // optional
    String comments,                  // optional
    List<Id> ticketIds,               // existing tickets of the worker to attach (optional)
    List<b3s__Ticket__c> newTickets   // tickets to insert and attach (optional)
)

Behaviour (the same as Propose worker on the internal broadcast panel):

Example (converting another system's credentials; the ats__ object and field names are illustrative):

@AuraEnabled
public static Id proposeExternalWorker(Id requisitionId, Id contactId, List<Id> sourceTicketIds) {
    List<b3s__Ticket__c> tickets = new List<b3s__Ticket__c>();
    for (ats__Ticket__c source : [
        SELECT ats__TicketType__c, ats__Valid_from__c, ats__Valid_until__c
        FROM ats__Ticket__c WHERE Id IN :sourceTicketIds
    ]) {
        tickets.add(new b3s__Ticket__c(
            b3s__Ticket_Type__c = typeMap.get(source.ats__TicketType__c), // your type mapping
            b3s__Valid_From__c = source.ats__Valid_from__c,
            b3s__Valid_Until__c = source.ats__Valid_until__c
        ));
    }
    return b3s.VmsProposalApi.createProposal(requisitionId, contactId, null, null, null, tickets);
}

Returns the new b3s__Worker_Proposal__c Id. Review then follows the normal flow (broadcast panel, or the client in the Client Shift Manager).


Invocable actions (Flow)

These @InvocableMethod entry points are callable from Flow and Process Builder. Each declares typed request/response inner classes whose @InvocableVariable fields appear as inputs and outputs in the Flow builder.

Geocode Address - GoogleMapsService

Geocodes address strings server-side (one HTTP callout per address). Use it where there is no browser in the loop, for example auto-inserting records that need coordinates.

@InvocableMethod(label='Geocode Address' category='Location' callout=true)
global static List<GoogleMapsService.GeocodeResult> geocodeAddresses(
    List<GoogleMapsService.GeocodeRequest> requests
)

Request - b3s.GoogleMapsService.GeocodeRequest

Variable Type Required Notes
address String yes Single-line address to geocode.

Result - b3s.GoogleMapsService.GeocodeResult

Variable Type Notes
success Boolean True when the lookup resolved.
latitude Decimal Resolved latitude.
longitude Decimal Resolved longitude.
formattedAddress String Google's normalized address.
errorMessage String Populated when success is false.

Results are returned in request order, so a bulk invocation maps one result per input row. Failures are returned as a result with success = false rather than thrown, so one bad address does not fail the batch. Bulk usage is bounded by the per-transaction callout limit.

Requires a Google Maps API key configured on the b3s__Scheduler__c custom setting (b3s__Google_Maps_API_Key__c) and a Remote Site Setting for https://maps.googleapis.com.

There is also an Aura/LWC-cacheable variant for a single address, callable from Lightning components:

@AuraEnabled(cacheable=true)
global static GoogleMapsService.GeocodeResult geocodeAddress(String address)

Generate Booking Confirmation - BookingConfirmationService

Queues (re)generation of a placement's booking confirmation PDFs. Inputs: Placement Id (required, Working Pattern Id) and Kind (Client, Provider, blank for both). Returns nothing; the PDF renders asynchronously as the platform event subscriber user and a regeneration adds a new version to the same file. Invalid Ids or kinds throw. See Booking confirmations.

Generate Working Pattern Shifts - WorkingPatternShiftService

Generates b3s__Shift__c records for a set of contacts from a Working Pattern Type template over a date range. Validates and enqueues; the expansion runs asynchronously.

@InvocableMethod(label='Generate Working Pattern Shifts' category='Workforce Management')
global static void generate(List<WorkingPatternShiftService.Request> requests)

Request - b3s.WorkingPatternShiftService.Request

Variable Type Required Notes
contactIds List<Id> yes Contacts to generate shifts for.
workingPatternTypeId Id yes The b3s__Working_Pattern_Type__c template.
startDate Date yes First day of the range.
endDate Date yes Last day of the range.
workingPatternId Id no Reuse an existing working pattern instead of creating one.
mode Integer no 1 create (default), 2 regenerate (delete the contact's existing pattern shifts and recreate), 3 delta (insert only missing shifts).

Requests missing contacts or a start/end date are skipped, as are requests with neither a pattern type nor a working pattern (when workingPatternId is supplied, workingPatternTypeId is optional - see type resolution below). Each request enqueues its own async job, so keep bulk inserts modest (batch large volumes across requests).

Pattern type resolution. When workingPatternId is supplied, the expansion template is resolved with this precedence: the Working Pattern's own b3s__Working_Pattern_Type__c wins; if blank, the linked Booking Request's b3s__Working_Pattern_Type__c; if both are blank, the request's workingPatternTypeId argument. If none resolve, the job exits without creating shifts.

Job/Site/Site Location stamping on generated shifts. The Working Pattern's own b3s__Job__c / b3s__Site__c / b3s__Site_Location__c always win when set. If one is blank and the pattern is linked to a b3s__Booking_Request__c, that blank value falls back to the request's matching field. With no Booking Request, only the pattern's fields are used - the pattern type's Work Job/Site/Site Location are never read at shift time (they only seed the fields on patterns the job auto-creates).

Generate Shift Breaks - BreakService

Regenerates auto-created break records for the given shifts from their resolved Break Ruleset. Validates and enqueues; generation runs asynchronously.

@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 collapse into a single queued job that processes 200 shifts per execution and chains itself, so a bulk Flow run cannot hit the queueable enqueue cap. Requests with no shift Ids are skipped, and approval-locked shifts (Submitted/Approved) are filtered out before enqueue.


Extension interfaces (implement your own)

These are global interface types you implement in your own Apex. The platform discovers your class by name, usually from a Custom Metadata record an org admin configures - the class name never comes from a client request. Class resolution is namespace aware: a bare class name resolves in the subscriber org, and a Namespace.Class name is honoured where supplied, so you can ship your own implementations.

FilterPlugin - Apex record filters

Restrict what a loader or app definition loads with logic SOQL cannot express (for example a multi-level semi-join). Your class returns the set of record Ids that pass; the query is restricted to Id IN :ids.

global interface FilterPlugin {
    Set<Id> execute(Map<String, Object> context);
}

Wiring. Add an apexFilter key (or matchApexFilter, paired with a match clause) to a loader's b3s__JSON__c or to a schedulable in an app definition, naming your class:

{ "objectType": "b3s__Shift__c", "apexFilter": "myns.MyShiftFilter" }

Context keys passed to execute:

Key Type Notes
contextId Id The contextual record, when the app runs in a record context.
contactId String The effective contact (the signed-in contact for portal sessions).
contextStart Datetime Window start, when the app supplies one.
contextEnd Datetime Window end.
contextDate String A context date, when supplied.

Your plugin runs in its own sharing context, so declare with sharing or without sharing deliberately. Portal contacts own no records, so a with sharing filter used by a portal app returns nothing. The returned Ids can only narrow the query, and they are bound into it, so there is no SOQL length limit. Full walkthrough and a worked example: Apex filters.

global without sharing class MyShiftFilter implements b3s.FilterPlugin {
    global Set<Id> execute(Map<String, Object> context) {
        Id contactId = (Id) context.get('contactId');
        // ... compute the Ids that should pass ...
        return new Set<Id>{ /* ... */ };
    }
}

NotificationRulePlugin - detection rules

Decide which records qualify for a bulk notification. Named from a b3s__Notification_Rule__mdt row's JSON ("plugin": "Namespace.Class"). The engine pre-queries the change events and records and hands them to you; the plugin is pure evaluation - no SOQL, no DML.

global interface NotificationRulePlugin {
    List<NotificationDraft> evaluate(NotificationRuleContext ctx);
}

b3s.NotificationRuleContext (input):

Field Type Notes
changesByShift Map<Id, List<ChangeEvent>> Field-history change events grouped by record.
shiftsById Map<Id, SObject> The scoped records, queried with the rule's field paths.
ruleConfig Map<String, Object> The rule JSON's config subtree (with the recipient field path injected).
changesFrom / changesUntil Datetime The scan window.

Each ChangeEvent carries historyId, recordId, field, oldValue, newValue, changedAt, changedBy.

b3s.NotificationDraft (return one per qualifying record):

Field Type Notes
recipientContactId Id Who the notification is for.
recordIds List<Id> Records this draft concerns.
consumedHistoryIds List<Id> Change-history rows that produced this draft (used for cross-campaign dedup).
mergeData Map<String, Object> Values available to the notification template.

The engine groups drafts into one notification per recipient - you emit per qualifying record. See Scheduling notifications.

NotificationSenderPlugin - custom send channels

Deliver notifications through a channel the package does not ship natively. Named from a b3s__Notification_Channel__mdt row (b3s__Sender_Plugin__c). The send job hands you the rows addressed to your channel in chunks of up to 50.

global interface NotificationSenderPlugin {
    void send(List<b3s__Outbound_Notification__c> notifications);
}

Mutate b3s__Status__c, b3s__Error__c and b3s__Send_Results__c on the passed rows to report per-row outcome - the engine performs the DML afterwards. You may make callouts. You must not call System.enqueueJob.

global class SmsChannelSender implements b3s.NotificationSenderPlugin {
    global void send(List<b3s__Outbound_Notification__c> notifications) {
        for (b3s__Outbound_Notification__c row : notifications) {
            // ... deliver, then stamp the row ...
            row.b3s__Status__c = 'Sent';
        }
    }
}

PayBillPlugin - time interpretation (deprecated)

Deprecated: the engine prices with rate sheets, lines and modifiers and no longer calls this interface. Do not implement it in new code. See the pay and bill engine.

b3s.PayBillEngine exposes DST-safe timezone helpers you can reuse in your own Apex:

global static Date     localDateOf(Datetime instant, TimeZone tz);   // local calendar date of an instant
global static Datetime toUtc(Date localDate, Time localTime, TimeZone tz); // local wall clock -> UTC
global static String   weekdayOf(Date localDate);                    // 'Monday'..'Sunday'

Full engine reference: Pay/Bill engine.

BreakPlugin - break placement

Place a shift's entitled breaks with your own jurisdictional logic (for example New York's span-condition meals or headcount-gated rules). Named from b3s__Break_Ruleset__c.b3s__Plugin__c; blank means the packaged default placement. Placement only - no SOQL, no DML. Rounding, window clamping, manual-break suppression and b3s__Break__c materialization stay with the engine.

global interface BreakPlugin {
    List<BreakEngine.BreakSpec> compute(BreakEngine.BreakContext ctx);
}

b3s.BreakEngine.BreakContext (input):

Field Type Notes
shiftId / contactId Id The shift and worker.
windowStart / windowEnd Datetime The window breaks are placed in: Shift Billable_Start/End_Time__c when set, else the ruleset's Time_Source__c (Prefer Scheduled / Prefer Actual, actuals fall back to scheduled).
timezoneName String Site (or user) timezone for local-clock maths.
ruleset b3s__Break_Ruleset__c The resolved ruleset.
rules List<b3s__Break_Rule__c> Active rules, Priority__c ascending (nulls last).
existingManualBreaks List<b3s__Break__c> Worker-entered rows (Is_Auto_Created__c false).

b3s.BreakEngine.BreakSpec (return one per placed break): breakType, startTime, endTime, isPaid, isBillable, ruleId, ruleLabel, reason (human trace).

b3s.BreakEngine also exposes the engine entry points directly:

// Regenerate auto breaks (delete + fresh insert). Map keyed by shift Id.
global static Map<Id, BreakResult> run(Set<Id> shiftIds);

// Same result as run, with no DML.
global static Map<Id, BreakResult> simulate(Set<Id> shiftIds);

Full engine reference: Break engine.

InvoiceTaxPlugin - invoice tax

Set the tax rate of every invoice line with your own jurisdictional logic (reverse charge, exempt services, multi-rate GST, US sales tax lookups). Named from b3s__Invoice_Configuration__c.b3s__Tax_Plugin__c; blank means the shipped default (client lines get Client_Tax_Rate__c, self-bill lines get Self_Bill_Tax_Rate__c only when the vendor account is Tax_Registered__c, else 0). No DML; SOQL is allowed but must be bulk.

global interface InvoiceTaxPlugin {
    void applyTax(List<InvoiceTaxRequest> requests);
}

The engine calls applyTax once per generate with one request per invoice line it built. Set taxRate on each; the engine then computes Tax = Net x rate / 100 (half-up, 2 decimals) and Gross = Net + Tax per line.

b3s.InvoiceTaxRequest:

Field Type Notes
invoice b3s__Invoice__c The header: Kind__c, Document_Type__c, Account__c, Client_Account__c, Currency__c and mapped fields. No Id on a fresh draft; has its Id when Amend Existing rebuilds an issued invoice.
line b3s__Invoice_Line__c The line: Net__c, Quantity__c, Rate__c, Detail__c, Group_Key__c and mapped fields.
config b3s__Invoice_Configuration__c The resolved configuration, including both tax rates.
billTo Account Bill-to account with Name, b3s__Tax_Registered__c, b3s__Tax_Registration_Number__c, BillingCountry, BillingState.
taxRate Decimal Output. Percent, for example 20. Blank counts as 0.
global with sharing class ZeroRateExportsPlugin implements b3s.InvoiceTaxPlugin {
    public void applyTax(List<b3s.InvoiceTaxRequest> requests) {
        for (b3s.InvoiceTaxRequest request : requests) {
            Boolean domestic = request.billTo == null || request.billTo.BillingCountry == 'United Kingdom';
            request.taxRate = domestic ? request.config.b3s__Client_Tax_Rate__c : 0;
        }
    }
}

The configuration save rejects a class that cannot be resolved or does not implement the interface. Full reference: Invoicing.

ShiftRoundingEngine - billable-window rounding

b3s.ShiftRoundingEngine rounds a shift's effective window (billable override, else the policy time source) to the interval configured on its winning rate card. It never writes the shift: Billable_Start/End_Time__c are an input override. It exposes global static hooks you can call directly:

// Deprecated alias of simulate (no longer writes the shift).
global static Map<Id, RoundingResult> run(Set<Id> shiftIds);

// Same result as run, with no DML.
global static Map<Id, RoundingResult> simulate(Set<Id> shiftIds);

// Pure computation against an already-resolved rate card. No SOQL, no DML.
global static RoundingResult compute(b3s__Rate_Card__c card,
                                     Datetime windowStart, Datetime windowEnd, TimeZone tz);

// Round a single instant to an interval boundary on the local wall clock.
global static Datetime roundInstant(Datetime instant, Integer intervalMinutes,
                                    String direction, TimeZone tz);   // direction: 'Nearest' | 'Up' | 'Down'

b3s.ShiftRoundingEngine.RoundingResult: billableStart, billableEnd (Datetime), rounded (Boolean - false when no interval is configured), error (String). Per-shift failures never abort the batch; the failed shift's result carries the error.


Response contract

Every remoting call returns a subclass of b3s.Response, JSON-serialized on the wire. There are two concrete types.

b3s.Response (abstract base):

Field Type Notes
statusCode Integer 200 on success, 400 on error.
success Boolean true / false.
statusType String 'OK' or 'ERROR'.
message String Human-readable message; carries the error text on failure.
responseObject Object The payload (records, a map, a describe, an Id, and so on).

b3s.SuccessResponse - statusCode = 200, success = true, statusType = 'OK'. Its responseObject holds the result. Many actions wrap their result in a map, for example { "records": [ ... ] }.

b3s.ErrorResponse - statusCode = 400, success = false, statusType = 'ERROR'. The failure reason is in message.

How errors surface: services catch exceptions internally and return an ErrorResponse rather than letting the exception propagate, so a call almost always resolves to a well-formed wrapper. Check success (or statusCode) before reading responseObject. An unrecognized action also returns an ErrorResponse naming the bad action.

{
    "statusCode": 200,
    "success": true,
    "statusType": "OK",
    "message": null,
    "responseObject": { "records": [{ "Id": "003...", "Name": "Jane Smith" }] }
}
{
    "statusCode": 400,
    "success": false,
    "statusType": "ERROR",
    "message": "objectName and titleField are required",
    "responseObject": null
}

Deliberate exceptions: Shared.getVersionData and InvoicePortalService.getInvoicePdf return the base64 file string directly on success, not a wrapper, to avoid doubling large binaries in memory. Every other action (and every failure) returns a Response.