Skip to content

Catalogue Approval Steps Developer Guide

Ed Mozley edited this page Nov 23, 2026 · 2 revisions

Approval steps and chains - Developer Guide

User page: Catalogue Request Approvals - Approval in steps Β· Design: Financial approvals (#160) Part C Β· Built: 5.10.0, Part C1

A catalogue form's approval used to be one policy: a named person, or a team with a number of approvals. Since 5.10.0 it can be an ordered list of steps, either the form's own or a named chain shared by many forms. This page is how that works and where to change it.

The short version: no second approval engine was built. The existing snapshot columns on form_submissions always hold the current step, and passing a step copies the next one in and starts a new round. Votes, Stuck, Move, Override and the row lock all work per step because they never knew there was more than one.


1. πŸ“ The files involved

πŸ—„οΈ schema Β· βš™οΈ engine Β· ✏️ write Β· πŸ–₯️ UI Β· πŸ”” notify Β· πŸ“„ docs

File What you do there
πŸ—„οΈ database/freeitsm.sql, includes/db_verify_schema.php forms.approval_steps, forms.approval_chain_id, form_approval_chains, form_submissions.approval_steps + approval_step_no. Indexes: run scripts/gen_db_verify_indexes.php, never hand-edit
βš™οΈ includes/catalogue_approval_steps.php The whole step engine - normalising, resolving a form's steps, "Only when", reaching a step (fallback), advancing, progress, the bell
βš™οΈ includes/catalogue_approvals.php The approval engine it plugs into: catalogueFinishDecision() advances instead of approving; catalogueAfterStepPassed(); Override allowed on any step; the inbox list carries steps
✏️ includes/services/forms.php submitForm() plans and snapshots the steps; saveApprovalPolicy() saves them; copyApprovalPolicy() carries them to a new version
✏️ api/forms/approval_chains.php Chains: list (with analysts, teams, question labels), save, delete (refused while in use), the default fallback
πŸ–₯️ assets/js/forms-approval-steps.js + assets/css/forms-approval-steps.css The one step editor, used by both screens below
πŸ–₯️ forms/index.php Approval settings window: steps on this form, or a chain
πŸ–₯️ forms/settings/index.php + forms/settings/manifest.php Forms -> Settings -> Approvals tab (Cap::FORMS_APPROVALS)
πŸ–₯️ forms/approvals.php The inbox: "Step 2 of 3", the step trail, the step events
πŸ–₯️ api/self-service/get_dashboard.php, self-service/index.php The requester's Your requests: "waiting for Finance, step 2 of 3"
πŸ”” includes/services/notifications.php, includes/entity_links.php The catalogue_request.awaiting bell type and its link
βš™οΈ workflow/includes/engine.php The catalogue_request.step_passed trigger - label, fields, and SUBMISSION_FIELD_TRIGGERS
πŸ“„ forms/help/approvals.php, forms/help/_registry.php In-app help: More than one step, If nobody can decide, Approval chains
βœ… tests/catalogue-approval-steps.php 37 checks, on a throwaway database

What you do not touch: catalogueApprovalDecide(), catalogueApprovalProgress(), catalogueApprovalMove(), catalogueLockSubmission(), the votes table. That is the point of the design.


2. πŸ—„οΈ Schema

Where Column Meaning
forms approval_steps LONGTEXT NULL The form's own steps as JSON. NULL = the single policy, exactly as before - no migration
forms approval_chain_id INT NULL A chain instead of the form's own steps. The own steps are kept, so switching back restores them
form_approval_chains id, name (unique), description, steps, is_active, created_by, ... A named chain. steps is the same JSON
form_submissions approval_steps LONGTEXT NULL The steps snapshotted at submission, each marked skipped with a skip_detail
form_submissions approval_step_no INT NULL The step it is on, 1-based. NULL with steps = every step was skipped

One step:

{"name": "Finance", "who": "team",
 "approver_id": null, "team_id": 4, "approvals_required": 2, "rejections_required": 1, "exclude_requester": 1,
 "when": {"match": "all", "rules": [{"question": "Order total", "op": "greater_than", "value": "5000"}]},
 "fallback": {"who": "person", "approver_id": 7}}

πŸ”‘ A condition names its question by LABEL, not by form_fields.id. A chain is shared by many forms, and a form's field ids change with every new version. A question that is not on the form is an unreadable condition, and an unreadable condition means the step runs - the safe direction.

The install default fallback is system_settings.forms_approval_fallback, the same policy JSON, or empty for Nobody.


3. βš™οΈ At submission - catalogueStepsPlan()

FormsService::submitForm() asks the old gate first, then the step planner, and the planner wins when the form has steps:

$gate = catalogueApprovalGate($form, $portalUserId);
$stepPlan = null;
if ($portalUserId !== null && !empty($form['requires_approval']) && $teamColumns) {
    $stepPlan = catalogueStepsPlan($conn, $form, ['submitted_by_user_id' => $portalUserId], $fieldsById, $normalised);
    if ($stepPlan !== null) {
        $gate = array_intersect_key($stepPlan, array_flip(['approver_id', 'approval_team_id', 'approvals_required',
                                                           'rejections_required', 'approval_exclude_requester']));
    }
}

The planner:

  1. catalogueFormSteps() - the chain's steps (if approval_chain_id points at an active chain), else the form's own, else null (the old single policy). A chain that has gone returns one step with nobody, so the request is Stuck rather than waved through.
  2. catalogueStepApplies() for each step, against the answers keyed by lower-cased label (catalogueAnswersByLabel(), first question of a label wins).
  3. The first step that applies is reached - catalogueReachStep(), which may use a fallback (section 5).
  4. submitForm() inserts the snapshot columns plus approval_steps and approval_step_no, then - inside the same transaction - catalogueStepsRecordNew() writes a step_skipped event per skipped step and a step_fallback event if one was used.

Every step skipped = nothing to approve. catalogueStepsRecordNew() records auto_approved and calls catalogueFinishDecision($conn, $sub, 'approved', 0, 'No approval step applied') inside the transaction, and submitForm() runs catalogueAfterDecision() after the commit. So the ticket and the form's When approved list happen exactly as for any approval - a form whose ticket comes from its own action list still gets one.

"Only when" and the blank-answer trap

// TRAP: formLogicTestRule() says "is more than 5000" is FALSE for a blank answer,
// which would skip a threshold step exactly when the amount is missing.
if (in_array($op, ['greater_than', 'less_than'], true) && !is_numeric($scalar)) {
    return [true, '"' . ($labels[$key] ?? $r['question']) . '" has no number to compare'];
}

A rule that cannot be read - question not on the form, no number for a number comparison, no date for a date comparison - makes the whole step apply, whatever the other rules say. Everything else goes through formLogicTestRule(), so the operators mean exactly what they mean on a form's own conditions.


4. βš™οΈ Passing a step - catalogueAdvanceStep()

catalogueFinishDecision() is shared by a named approver's decision, a team's deciding vote and an override. It now starts with:

if ($decision === 'approved') {
    $advanced = catalogueAdvanceStep($conn, $sub, $actorId, $comment);
    if ($advanced !== null) {
        return ['ticket_id' => null, 'ticket_number' => null, 'list' => null, 'advanced' => $advanced];
    }
}

catalogueAdvanceStep() finds the next step that is not skipped. None = this was the last step, return null, and the request is approved as it always was. Otherwise it reaches that step and, in the same row lock:

UPDATE form_submissions SET approver_id = ?, approval_team_id = ?, approvals_required = ?, rejections_required = ?,
       approval_exclude_requester = ?, approval_step_no = ?, approval_round = approval_round + 1
 WHERE id = ?

The new round is what makes votes per step: form_submission_votes is counted by (submission_id, approval_round), so step 1's votes stop counting and the same person can vote again on step 2. It writes a step_passed event (actor, "Step 1 of 3: IT manager -> Step 2 of 3: Finance (Team: Finance (2 approvals))", the note as the reason).

After the commit, catalogueAfterDecision() hands a passed step to catalogueAfterStepPassed(): the catalogue_request.step_passed workflow event, and catalogueTellStepApprovers(). The API answers decision: 'step_passed' with step: {number, name, position, count}; the inbox toasts "Approved - passed on to step 2 of 3".

A rejection at any step goes straight through catalogueFinishDecision()'s rejection branch, untouched: any rejection ends the request.


5. βš™οΈ If nobody can decide - catalogueReachStep()

Reaching a step (at submission or on a pass) asks catalogueStepFindsNobody() - the same test as Stuck, asked of a synthetic row: a person who has left, a person who is the requester when that is not allowed, a team with too few independent members.

foreach (['step' => $step['fallback'] ?? null, 'default' => catalogueDefaultFallback($conn)] as $kind => $fb) {
    if (!$fb) continue;
    $fbCols = catalogueStepColumns($fb);
    if (!catalogueStepFindsNobody($conn, $fbCols, $sub)) return ['cols' => $fbCols, 'fallback' => $kind];
}
return ['cols' => $cols, 'fallback' => null];   // the step's own policy stands: Stuck, as without steps

Order: the step's own fallback, then the install default, then the step's own policy (Stuck). Never skipped. It is checked only when a step is reached: somebody leaving the team later makes the request Stuck in the usual way, for an administrator.


6. πŸ–₯️ The step editor - assets/js/forms-approval-steps.js

const ed = ApprovalSteps.mount(el, { steps, analysts, teams, questions });
const { steps, error } = ed.read();

One component, two screens. It renders every step from an array, and reads the screen back into the array (sync()) before every re-render, so adding, moving or switching Person to Team never loses what was typed. read() says the obvious problems (no approver, a condition with no question, a fallback with nobody); the server decides (catalogueNormaliseSteps($conn, $raw, true)).

πŸ”‘ One plain step is saved the old way. ApprovalSteps.isPlain() - one step, no name, no condition, no fallback - makes Approval settings save approver_id / approval_team_id and approval_steps: null. An existing form opens as one step and, saved unchanged, is the form it always was.

.as-list is in front of every selector in the CSS on purpose: forms/index.php styles every .ca-field select full-width, later in the page.


7. πŸ”” Telling approvers

catalogueTellStepApprovers($conn, $sub) runs after the commit at submission and on every pass, for requests with steps only - a single-policy request is told exactly as before (by a workflow rule, if any). It notifies the named approver, or every member of the team who may vote (catalogueEligibleMembers(), so never the requester), through NotificationsService::notify() with the type catalogue_request.awaiting - each person's own switch in Preferences applies. The bell opens forms/approvals.php (entityLink('catalogue_request', ...)); ENTITY_MODULES hides it when Forms is switched off.

Part C2 replaced the body with catalogueTellApprovers(), which adds people on the portal bell and email, and is shared with Remind. See Managers and cost centre owners on the portal - Developer Guide.


8. ⚠️ Traps

Trap Rule
A setting Save deletes approval_steps and approval_chain_id go through copyApprovalPolicy(), which createVersion() calls. Tested
Half a trigger catalogue_request.step_passed needs its dispatch() and its entry in availableTriggers(), the fields list and SUBMISSION_FIELD_TRIGGERS
Blank answers Never call formLogicTestRule() straight for a step: use catalogueStepApplies()
Chains in use Delete is refused while a current form (a leaf version) uses the chain. A deactivated or missing chain makes requests Stuck, never ungated
Snapshot, not live Never read forms.approval_steps or a chain for a waiting request. catalogueSubmissionSteps($sub) reads the snapshot
The lifecycle map form_approval_chains.created_by is on analystReferenceRegistry(). People named inside the steps JSON are not columns: a leaver there finds nobody, and the fallback decides
Top-level let in a page is not on window - a headless test cannot reach approvalEditor; drive the DOM instead

9. βœ… How it was verified

tests/catalogue-approval-steps.php (37 checks): no steps unchanged; bad lists refused; person then team with a new round, recorded, one ticket; rejection ends it; Only when skips and records, blank and missing questions run the step; all skipped = approved with a ticket; fallback, then default, then Stuck; chain followed, changing it affects new requests only, a gone chain is Stuck; snapshot survives editing the form; a new version keeps steps and chain; override passes one step; the bell reaches step 1's approver at submission and each team member on a pass. The existing catalogue-group-approvals (38), catalogue-answer-edits (26), catalogue-card (71) and analyst-lifecycle (21) still pass. The screens were driven headless on a test install: save and reopen, a chain made in Settings, and a request at step 2 in the inbox.

See also

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally