Forms on Tickets Developer Guide 2 - edmozley/freeitsm GitHub Wiki

🛠️ Forms on tickets - Developer Guide (2 of 2): endpoints, screens, REST and tests

Page 1 covers the schema, the shared TaskForms / TicketForms engine, submitting, the evidence guard and the close gate. This page is everything a person or an integration touches. User guide: Forms on tickets.


1. The browser endpoint - api/tickets/forms.php

The twin of api/tasks/forms.php, and a thin adapter: every rule lives in TicketForms.

Request Answer
GET ?ticket_id=N {enabled, forms, available, can_write} - the panel. ?answers=1 adds each form's answers where the viewer may read them
GET ?task_form_id=N (or ticket_form_id) {fill, may_fill} - what the fill page needs
POST {action: add, ticket_id, form_id, required, mode} {forms}
POST {action: update, task_form_id, required, mode} {forms}
POST {action: remove, task_form_id} {forms}
POST {action: draft, task_form_id, revision, answers} {revision, forms} or {conflict}
POST {action: submit, task_form_id, revision, client_reference, data} {submission_id, revision, replayed, forms} or {conflict}

task_form_id is the requirement's id. The shared fill page sends that name to both endpoints, and this one accepts ticket_form_id too.

session_start(['read_and_close' => true]);
require_once __DIR__ . '/../../includes/service_context.php';
require_once '../../config.php';
require_once '../../includes/functions.php';
require_once '../../includes/tenancy.php';
require_once '../../includes/rbac.php';
require_once '../../includes/services/task_forms.php';
header('Content-Type: application/json');
if (!isset($_SESSION['analyst_id'])) { echo json_encode(['success' => false, 'error' => 'Not authenticated']); exit; }
requireModuleAccessJson('tickets');

/** Refuse unless this analyst can reach the ticket (and it exists). Same wording for "gone" and "not yours". */
function ticketFormsGate(PDO $conn, int $ticketId): void
{
    $s = $conn->prepare("SELECT 1 FROM tickets WHERE id = ?");
    $s->execute([$ticketId]);
    if ($ticketId <= 0 || !$s->fetchColumn() || !analystCanAccessTicket($conn, (int)$_SESSION['analyst_id'], $ticketId)) {
        throw new ServiceError('not_found', 'not_found', 'Ticket not found.');
    }
}

/** The forms that can be added: the newest version of each active form. */
function ticketFormsAvailable(PDO $conn): array
{
    $st = $conn->query("SELECT f.id, f.title FROM forms f
                         WHERE f.is_active = 1
                           AND NOT EXISTS (SELECT 1 FROM forms c WHERE c.parent_form_id = f.id)
                         ORDER BY f.title");
    return array_map(fn($r) => ['id' => (int)$r['id'], 'title' => (string)$r['title']], $st->fetchAll(PDO::FETCH_ASSOC));
}

🔒 Every action is gated on the ticket, including those addressed by a requirement id. The requirement is resolved to its ticket first:

csrfRequireWriteMethod();
if (!$enabled) throw new ServiceError('validation', 'disabled', $off);
$in     = json_decode(file_get_contents('php://input'), true) ?: [];
$action = (string)($in['action'] ?? '');
$reqId  = (int)($in['task_form_id'] ?? $in['ticket_form_id'] ?? 0);

if ($action === 'add') {
    $ticketId = (int)($in['ticket_id'] ?? 0);
    ticketFormsGate($conn, $ticketId);
    TicketForms::add($conn, $ctx, $ticketId, (int)($in['form_id'] ?? 0),
                     !array_key_exists('required', $in) || !empty($in['required']), (string)($in['mode'] ?? 'block'));
} else {
    $row = TicketForms::row($conn, $reqId);
    $ticketId = TicketForms::hostOf($row);
    ticketFormsGate($conn, $ticketId);
    switch ($action) {
        case 'update': TicketForms::update($conn, $ctx, (int)$row['id'], !empty($in['required']), (string)($in['mode'] ?? 'block')); break;
        case 'remove': TicketForms::remove($conn, $ctx, (int)$row['id']); break;
        case 'draft':  $extra = TicketForms::saveDraft($conn, $ctx, (int)$row['id'], (int)($in['revision'] ?? -1), (array)($in['answers'] ?? [])); break;
        case 'submit': $extra = TicketForms::submit($conn, $ctx, (int)$row['id'], (int)($in['revision'] ?? -1),
                                                     (string)($in['client_reference'] ?? ''), (array)($in['data'] ?? [])); break;
        default: throw new ServiceError('validation', 'invalid_field', 'Unknown action.');
    }
}
// The whole state back, so the panel re-renders from one source of truth.
echo json_encode(['success' => true, 'enabled' => true] + $extra + [
    'forms' => TicketForms::forTicket($conn, $ticketId, $viewerId, false),
]);
  • Why ticketFormsGate() reads the row first. analystCanAccessTicket() alone is true for any id on a single-company install.
  • Off means refused. While Forms on tickets (or the Forms module) is off, GET says enabled: false and every write is refused with code disabled.
  • Errors. TaskFormConflict answers {conflict: {by, at, revision, draft}}. Other ServiceErrors answer {error, code}, and anything else logs and answers a generic message.
  • The available list is the newest version of each active form: a form with a child version (parent_form_id pointing at it) is an old version and is left out.

What forTicket() returns

forHost() (inherited) reads every requirement with its live form and submission. The answers come only when asked for and allowed:

$st = $conn->prepare(
    "SELECT tf.*, f.title AS form_title_now, f.is_active AS form_active,
            s.submitted_date, s.submitted_by, a.full_name AS submitted_by_name
       FROM " . static::TABLE . " tf
       LEFT JOIN forms f ON f.id = tf.form_id
       LEFT JOIN form_submissions s ON s.id = tf.submission_id
       LEFT JOIN analysts a ON a.id = s.submitted_by
      WHERE tf." . static::FK . " = ?
      ORDER BY tf.sort_order, tf.id");
// … each row becomes:
// ['id', 'form_id', 'title', 'form_exists', 'form_active', 'is_required', 'requirement_mode',
//  'submission_id', 'submitted_utc', 'submitted_by', 'has_draft', 'draft_by', 'draft_utc',
//  'revision', 'may_read', 'may_fill'] + ['answers' => [...]] when $withAnswers && may_read

may_read is mayReadAnswers(): Forms module access, or static::answersCap(), which for a ticket is Cap::TICKETS_FORM_ANSWERS. may_fill is write access to Forms.


2. The fill page - forms/fill.php

The page that fills a form on a task fills it on a ticket. ?ticket_form=N&embed=1 only changes the endpoint it talks to:

// GH #272: ?ticket_form=N fills a form on a TICKET - the same page and the same rules
// (TicketForms is TaskForms with the ticket as host); only the endpoint differs.
const HOST_PARAMS = new URLSearchParams(window.location.search);
const TASK_FORM_ID = HOST_PARAMS.get('task_form') || HOST_PARAMS.get('ticket_form');
const FILL_API = HOST_PARAMS.get('ticket_form') ? '../api/tickets/forms.php' : '../api/tasks/forms.php';
const taskClientRef = 'tf-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
// the embedded layout (no header) for a ticket's form too
$embed = !empty($_GET['embed']) && (!empty($_GET['task_form']) || !empty($_GET['ticket_form']));   // GH #272: a ticket's form too
  • The client reference is made once per page load, so pressing Submit twice, or a retried request, makes one submission (page 1 §4).

  • The banner says whose work this is:

    b.textContent = (taskFill.host === 'ticket'
            ? window.t('forms.fill.for_ticket', { ticket: taskFill.task.title })   // "For the ticket "INC-1234 Laptop""
            : window.t('tasks.forms.fill_for', { task: taskFill.task.title }));

    taskFill.host is forFill()'s 'host' => static::NOUN.

  • Talking to the window that opened it. Embedded, it posts to its parent: tf-saved after a draft or submit, and tf-height so the frame can size itself.

    window.parent.postMessage({ type: 'tf-saved', task_id: taskFill && taskFill.task.id, task_form_id: taskFill && taskFill.task_form_id, submitted: !!submitted }, location.origin);
    window.parent.postMessage({ type: 'tf-height', task_form_id: Number(TASK_FORM_ID), height: Math.ceil(content.getBoundingClientRect().height) }, location.origin);

3. The ticket's Forms panel - assets/js/ticket-forms.js

A self-contained IIFE, loaded by tickets/index.php after inbox.js. displayEmail() calls loadTicketForms(email.ticket_id) on every draw.

let state = { ticketId: null, enabled: false, forms: [], available: [], canWrite: false };

async function loadTicketForms(ticketId) {
    state = { ticketId, enabled: false, forms: [], available: [], canWrite: false };
    try {
        const d = await getJson('?ticket_id=' + encodeURIComponent(ticketId));
        if (state.ticketId !== ticketId) return;   // another ticket opened meanwhile
        if (d.success) state = { ticketId, enabled: !!d.enabled, forms: d.forms || [], available: d.available || [], canWrite: !!d.can_write };
    } catch (e) { /* no button */ }
    renderButton();
    drawInline();      // the workspace Work tab (§4)
}
  • The toolbar button. renderButton() inserts a .action-btn after Watch (or Checklist). It shows Forms · 1/2 (submitted / total), and is removed while the feature is off.
  • The modal uses the app's shared modal (.modal / .modal-content / -header / -body / -footer from inbox.css), so it fades, closes on Esc or a backdrop click, and themes like every other dialog. Its own look is a small stylesheet injected once (#ticketFormsStyle, .tf-* classes): pill badges with dark-mode colours, one button size, and a quiet Remove that turns red on hover.

One renderer, two places

The cards are drawn by one function and wired by another, so the modal and the Work tab can't drift apart:

/** The cards and the add row - the same in the modal and in the workspace's Work tab. */
function formsHtml() {
    const rows = state.forms.map(f => {
        const mode = f.is_required ? f.requirement_mode : 'optional';
        const badge = '<span class="tf-badge ' + mode + '">' + esc(/* Required (blocks) | Required (warns) | Optional */) + '</span>';
        const fill = f.may_fill && state.canWrite && f.form_exists
            ? '<button type="button" class="btn ' + (f.submission_id ? 'btn-secondary' : 'btn-primary') + '" data-fill="' + f.id + '">'
              + esc(f.submission_id ? T('correct') : T('fill')) + '</button>' : '';
        const ans = f.submission_id && f.may_read ? '<button type="button" class="btn btn-secondary" data-answers="' + f.id + '">' + esc(T('answers')) + '</button>' : '';
        // … requirement <select data-req>, <button class="tf-remove" data-remove>, the state line
    }).join('') || '<p class="tf-empty">' + esc(T('none')) + '</p>';
    // … the add row: <select data-add-select> of state.available minus forms already on it, <button data-add-btn disabled>
    return rows + add;
}

function wire(container) {
    container.querySelectorAll('[data-fill]').forEach(b => { b.onclick = () => openFill(Number(b.dataset.fill)); });
    container.querySelectorAll('[data-answers]').forEach(b => { b.onclick = () => showAnswers(container, Number(b.dataset.answers)); });
    container.querySelectorAll('[data-remove]').forEach(b => { b.onclick = () => removeForm(container, Number(b.dataset.remove)); });
    container.querySelectorAll('[data-req]').forEach(s => { s.onchange = () => setRequirement(container, Number(s.dataset.req), s.value); });
    // the add select enables its button; the button posts {action: 'add'}
}

/** Both places at once, from the one state. */
function redrawAll() {
    const panel = document.querySelector('#ticketFormsModal.active > .modal-content');
    if (panel) drawPanel(panel);
    drawInline();
}
  • Controls are found by data attributes, never ids, because the same markup can be on screen twice: the modal over the Work tab.
  • Every write answers with the whole list ({forms}), so act() replaces state.forms and calls redrawAll(). There's no hand-patching of rows.

Filling, in a window

function openFill(id) {
    const f = state.forms.find(x => x.id === id);
    const box = modal('ticketFormFill', 820);
    const base = (window.API_BASE || '../api/tickets/').replace(/api\/tickets\/$/, '');
    box.innerHTML = '<div class="modal-header">' + esc(f ? f.title : T('fill')) + '</div>'
        + '<div class="modal-body" style="padding:8px 16px;">'
        + '<iframe id="ticketFormFrame" title="…" src="' + base + 'forms/fill.php?ticket_form=' + encodeURIComponent(id) + '&embed=1" …></iframe></div>'
        + '<div class="modal-footer"><button type="button" class="btn btn-secondary" id="ticketFormFillClose">' + esc(T('close')) + '</button></div>';
}

// The fill page says when it saved or submitted, and how tall it is.
window.addEventListener('message', (e) => {
    if (e.origin !== location.origin || !e.data || typeof e.data !== 'object') return;
    const frame = document.getElementById('ticketFormFrame');
    if (!frame || e.source !== frame.contentWindow) return;
    if (e.data.type === 'tf-height' && e.data.height) frame.style.height = Math.min(Math.max(e.data.height + 24, 240), window.innerHeight * 0.8) + 'px';
    if (e.data.type === 'tf-saved') {
        refresh();
        if (e.data.submitted) { closeModal('ticketFormFill'); showToast(T('submitted'), 'success'); return; }
    }
});

The message handler checks both the origin and that the source is our frame, so another window can't fake a "submitted".


4. The workspace Work tab

In a workspace, the forms also appear on the Work tab, beside the checklists and the linked tasks. inbox.js gives the tab a holder:

work: checklistHtml + '<div id="twTicketForms" hidden></div><div class="tw-task-list" id="twTaskList"></div><div class="tw-tasks" id="twTaskArea"></div>',
/**
 * The workspace's Work tab (#twTicketForms, inbox.js): the same cards, beside the
 * checklists and tasks. Only while the ticket has forms - adding the first one is
 * the toolbar button's job, so an empty Work tab keeps its "nothing here yet" note.
 */
function drawInline() {
    const host = document.getElementById('twTicketForms');
    if (!host) return;
    if (!state.enabled || !state.forms.length) { host.innerHTML = ''; host.hidden = true; return; }
    injectStyle();
    host.hidden = false;
    host.innerHTML = '<h3 class="tf-inline-title">' + esc(T('title')) + '</h3>' + formsHtml();
    wire(host);
}

ticket-workspace.js's "nothing here yet" observer counts it:

const forms = panel.querySelector('#twTicketForms');   // GH #272: forms on the ticket (ticket-forms.js)
const hasForms = !!forms && !forms.hidden && forms.childElementCount > 0;
const hide = !!(hasChecklist || hasForms || hasTasks);

5. Right-click → Add form ▸

A submenu on the ticket list's right-click menu, built like Attach checklist ▸. The markup is in tickets/index.php, hidden until the script knows the feature is on:

<div class="ticket-context-menu-item ticket-context-menu-parent" role="menuitem" tabindex="0" id="ctxFormsItem" style="display:none;">
    <svg …></svg>
    <span><?php echo htmlspecialchars(t('tickets.context.add_form')); ?></span>
    <svg class="ctx-sub-arrow" …></svg>
    <div class="ticket-context-submenu" id="ctxFormsSubmenu" role="menu"></div>
</div>

inbox.js fills it each time the menu opens, for the right-clicked ticket or the whole selection:

if (typeof populateContextFormsSubmenu === 'function') populateContextFormsSubmenu(ctxActsOnSelection ? selectedTicketIds() : [ctxTargetTicketId]);   // GH #272
async function populateContextFormsSubmenu(ids) {
    // … loading row; GET ?ticket_id=<first>; stale-guard on sub.dataset.for
    if (!d.enabled || !d.can_write) { item.style.display = 'none'; return; }
    item.style.display = '';
    const on = new Set(ctxIds.length === 1 ? (d.forms || []).map(f => f.form_id) : []);   // ticks: one ticket only
    sub.innerHTML = list.slice(0, CTX_FORMS_SHOWN).map(a => on.has(a.id)
        ? ctxRow('<span class="ctx-status-name">' + esc(a.title) + '</span><span class="ctx-status-check">&#10003;</span>', ' style="cursor:default;opacity:.6;" …')
        : ctxRow('<span class="ctx-status-name">' + esc(a.title) + '</span>', ' onclick="addFormFromContext(' + Number(a.id) + ')"')).join('')
        + /* "All forms…" when there are more than 12, for one ticket */ '';
}

async function addFormFromContext(formId) {
    closeTicketContextMenu();
    let done = 0, already = 0, failed = 0;
    for (const id of ctxIds) {
        const d = await post({ action: 'add', ticket_id: id, form_id: formId });
        if (d.success) done++;
        else if (d.code === 'conflict') already++;   // TicketForms::add(): "That form is already on this ticket."
        else failed++;
    }
    // toast: "Form added." / "Added to 3 ticket(s). 1 already had it."
}

🔴 Rows use inline onclick, unlike the rest of the file. On a phone the menu is a full-screen sheet that copies the submenu's HTML (openTicketMenuLevel() in inbox.js), so listeners attached with addEventListener would be lost in the copy. That's why addFormFromContext and openFormsFromContext are put on window.


6. The setting

Tickets → Settings → Checklists → Forms on tickets. The key is declared on the tab in tickets/settings/manifest.php ('tickets_forms_enabled', so the setting-key map and the tab agree on who owns it), and seeded to '0' by Database Verify. The tab's existing Save sends it, but only writes it when it was sent, so an older caller can't switch it off by leaving it out:

// api/tickets/save_checklist_settings.php
$upsert->execute([SETTING_TICKET_CHECKLIST_EMPTY_CLOSURE, $emptyMode]);
// GH #272: "Forms on tickets". Only written when sent, so an older caller leaves it alone.
if (array_key_exists('forms_enabled', $in)) {
    $upsert->execute(['tickets_forms_enabled', !empty($in['forms_enabled']) ? '1' : '0']);
}

TicketForms::enabled() (inherited) also requires the Forms module to be on. The settings page shows a warning under the tick when it isn't.


7. The case report

The ticket's case report shows its forms beside its checklists, with the answers only for a reader allowed to see them:

// includes/case_report.php - CaseReport::forTicket()
// GH #272: forms on the ticket, beside its checklists. Answers only where TicketForms::mayReadAnswers() says.
$r['ticket_forms'] = $on('checklists') && TicketForms::columnsReady($conn)
    ? self::attempt($r, 'checklists', fn() => TicketForms::forTicket($conn, $ticketId, $viewer, true), []) : [];

includes/case_report_page.php lays them out with the same markup as a task's forms. A form not yet submitted, or answers the reader may not see, says so instead of showing nothing (form_not_submitted, form_answers_hidden).


8. The REST API

Route Permission Handler
GET /tickets/{id}/forms ticket_forms.read apiTicketFormsList()
POST /tickets/{id}/forms/{ticket_form_id}/submissions ticket_forms.create apiTicketFormSubmit()
// api/v1/lib/routes.php
['GET',    '#^/tickets/(\d+)/forms$#',                 ['ticket_forms', 'read'],          'apiTicketFormsList'],
['POST',   '#^/tickets/(\d+)/forms/(\d+)/submissions$#', ['ticket_forms', 'create'],      'apiTicketFormSubmit'],

// api/v1/lib/modules.php - both modules must be on for the routes to answer
'ticket_forms' => ['tickets', 'forms'],   // GH #272
// api/v1/resources/tickets.php
function apiTicketFormSubmit(PDO $conn, array $apiKey, array $params, array $body): void {
    apiLoadTicket($conn, $apiKey, (int)$params[0]);                       // the ticket's gate, company scope included
    require_once __DIR__ . '/../../../includes/services/task_forms.php';
    try {
        if (!TicketForms::enabled($conn) || !TicketForms::columnsReady($conn)) {
            throw new ServiceError('validation', 'disabled', 'Forms on tickets are switched off (Tickets -> Settings -> Checklists).');
        }
        $row = TicketForms::row($conn, (int)$params[1]);
        if ((int)$row['ticket_id'] !== (int)$params[0]) throw new ServiceError('not_found', 'not_found', 'That form is not on this ticket.');
        $revision = isset($body['revision']) ? (int)$body['revision'] : (int)$row['revision'];
        $res = TicketForms::submit($conn, ActorContext::fromApiKey($apiKey), (int)$row['id'], $revision,
                                   (string)($body['client_reference'] ?? ''), (array)($body['data'] ?? []));
        apiRespond(['ticket_id' => (int)$params[0], 'ticket_form_id' => (int)$row['id'], 'submission_id' => $res['submission_id'],
                    'revision' => $res['revision'], 'replayed' => $res['replayed']], $res['replayed'] ? 200 : 201);
    } catch (ServiceError $e) { apiFailFromService($e); }
}
  • The list has the same shape as GET /tasks/{id}/forms. answers is absent, not empty, unless the key's analyst may read form answers.
  • revision is optional on submit. Without it the current revision is used, so an integration that is the only writer doesn't have to track it; one that isn't can send it and get 409.
  • A requirement addressed through the wrong ticket answers 404, not the form.
  • The catalogue. Both routes are in api/v1/spec.json, added as text, because the file mixes escaped and unescaped Unicode and a whole-file re-encode is never byte-identical. php api/v1/lib/openapi_check.php passes. User docs: REST API - Tickets.

9. Tests

tests/ticket-forms.php runs on a disposable install, through the service, the real endpoint (forged session) and the REST API (real keys). 30 checks:

FREEITSM_TEST_DATABASE=<throwaway db> FREEITSM_TEST_URL=http://localhost/<that install> php tests/ticket-forms.php
Area Proves
Off GET says off and lists nothing; add is refused (disabled); a required form left in the table does not hold up the close
Adding only the newest version of each active form is offered; adding version 1 fills version 2; the same form twice is refused; Form added in ticket_audit; a nonexistent ticket is not_found
The close block refuses and names the form (forms_outstanding); warn does not
Filling host is ticket; a draft moves the revision; a stale draft is a conflict naming who saved; a missing required answer is refused; the submission is linked by for_ticket_id, not task_id, on the newest version; Form submitted in the history; the close then lets go; the panel shows the answers
Answers the ticket permission, not the task one (answersCap() via reflection)
Forms deleting the submission is refused with ticket_evidence
Case report carries the answers
REST list with answers; a read-only key cannot submit (403); submit 201, then the same reference is 200 with the same submission; the wrong ticket is 404
Removing the requirement goes, both submissions stay in Forms; merge moves forms once each

After the host refactor, tests/task-forms.php (103) still passes, so every task behaviour survived static::.

Browser checks (headless Chrome on a test install): the button and modal on a ticket, the fill window loading the real form, the polished modal in light and dark, the Work tab showing the cards in a workspace, and Add form ▸ listing forms with ticks on the ones already added.


Related

⚠️ **GitHub.com Fallback** ⚠️