Skip to content

Ticket Watchers Developer Guide 2

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

πŸ› οΈ Watching a ticket - Developer Guide (2 of 2): the screens, the API and the tests

The browser endpoint, the Watch button and its panel, the right-click menu, the REST API, the traps and the tests for watching a ticket (#277, 5.0.0). User guide: Tickets β†’ Watching a ticket.

← Page 1: the files, the schema, the TicketWatchers service, who is told, the events setting, merge, delete and the analyst lifecycle.


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

/**
 * API: who watches a ticket, and watching / unwatching it (GitHub #277).
 *
 *   GET  ?ticket_id=N            the watchers, whether I watch, whether I may add others
 *   POST {action: 'watch',   ticket_id, analyst_id?}   analyst_id omitted = me
 *   POST {action: 'unwatch', ticket_id, analyst_id?}
 *   POST {action: 'watch_many', ticket_ids: [..]}      the right-click menu on a selection - me only
 */

The guards, then GET:

if (!isset($_SESSION['analyst_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}
requireModuleAccessJson('tickets');

$conn = connectToDatabase();
$me = (int)$_SESSION['analyst_id'];
$canWrite = analystCanWriteModule($conn, $me, 'tickets');

try {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
        $ticketId = (int)($_GET['ticket_id'] ?? 0);
        if (!TicketWatchers::canSee($conn, $me, $ticketId)) {
            throw new ServiceError('not_found', 'not_found', 'Ticket not found.');
        }
        $list = TicketWatchers::list($conn, $ticketId);
        echo json_encode([
            'success'   => true,
            'ready'     => TicketWatchers::ready($conn),
            'watchers'  => $list,
            'watching'  => in_array($me, array_column($list, 'analyst_id'), true),
            'can_add'   => $canWrite,
        ]);
        exit;
    }

    csrfRequireWriteMethod();

ready: false tells the page Database Verify has not run, so it draws no button rather than one that fails on every click. Everything after GET goes through csrfRequireWriteMethod(); the token itself is sent by assets/js/csrf.js, which every page loads (see CSRF protection).

watch_many - the right-click menu on a selection:

    if ($action === 'watch_many') {
        // Me on each selected ticket I can see; one that is not mine to see is skipped, not an error.
        $done = 0; $already = 0; $skipped = 0;
        foreach (array_slice(array_unique(array_map('intval', (array)($in['ticket_ids'] ?? []))), 0, 500) as $id) {
            try {
                $r = TicketWatchers::add($conn, $ctx, $id, $me, $canWrite);
                $r['added'] ? $done++ : $already++;
            } catch (ServiceError $e) {
                if ($e->kind === 'validation' && $e->errorCode === 'not_ready') throw $e;
                $skipped++;
            }
        }
        echo json_encode(['success' => true, 'added' => $done, 'already' => $already, 'skipped' => $skipped]);
        exit;
    }
  • Me only. watch_many always adds $me; there is no "put a colleague on 30 tickets".
  • Skipped, not failed. A selection can hold a ticket from a company the person can no longer see, or one deleted meanwhile. One bad id must not refuse the other 29. not_ready is the exception: it would fail every id, so it is thrown.
  • Capped at 500 ids per request.

watch and unwatch, then the error mapping:

    $ticketId = (int)($in['ticket_id'] ?? 0);
    $who = isset($in['analyst_id']) && (int)$in['analyst_id'] > 0 ? (int)$in['analyst_id'] : $me;
    if ($action === 'watch') {
        $r = TicketWatchers::add($conn, $ctx, $ticketId, $who, $canWrite);
    } elseif ($action === 'unwatch') {
        $r = TicketWatchers::remove($conn, $ctx, $ticketId, $who, $canWrite);
    } else {
        throw new ServiceError('validation', 'invalid_field', 'Unknown action.');
    }
    $list = TicketWatchers::list($conn, $ticketId);
    echo json_encode(['success' => true] + $r + [
        'watchers' => $list,
        'watching' => in_array($me, array_column($list, 'analyst_id'), true),
    ]);
} catch (ServiceError $e) {
    http_response_code($e->kind === 'not_found' ? 404 : ($e->kind === 'forbidden' ? 403 : 400));
    echo json_encode(['success' => false, 'error' => $e->getMessage(), 'code' => $e->errorCode]);
}

Every write returns the new list, so the panel (section 2) redraws from the server's answer, not from a guess.


2. The Watch button and panel - assets/js/ticket-watchers.js

One IIFE, loaded after inbox.js on tickets/index.php:

    <script src="../assets/js/inbox.js?v=194"></script>
    <script src="../assets/js/ticket-watchers.js?v=1"></script>

(The inbox.js version has moved on since; grep it, never recall it.) It reads inbox.js's globals by bare name, as its header says:

 * Talks to api/tickets/watchers.php. Uses inbox.js's globals: API_BASE, analysts,
 * escapeHtml, showToast, t, and the right-click menu's ctxTargetTicketId /
 * ctxActsOnSelection / selectedTicketIds().

⚠️ analysts, ctxTargetTicketId and ctxActsOnSelection are top-level let in inbox.js. A top-level let is reachable by its bare name from another classic script, but it is not on window. window.analysts would be undefined. That is why the file writes typeof analysts !== 'undefined' ? analysts : [].

Loading, when a ticket opens

displayEmail() in inbox.js calls it, next to the checklists:

    if (typeof loadTicketChecklists === "function") loadTicketChecklists(email.ticket_id);
    if (typeof loadTicketWatchers === "function") loadTicketWatchers(email.ticket_id);   // GH #277: the Watch button

displayEmail() draws the reading pane for both layouts, so the button appears in the classic pane and in the ticket workspace alike, and is redrawn whenever live updates re-render the open ticket.

    /** Loads the open ticket's watchers and draws its Watch button. Called by inbox.js when a ticket opens. */
    async function loadTicketWatchers(ticketId) {
        state = { ticketId, watchers: [], watching: false, canAdd: false, ready: true };
        try {
            const d = await call('GET', null, '?ticket_id=' + encodeURIComponent(ticketId));
            if (state.ticketId !== ticketId) return;   // another ticket opened meanwhile
            state = { ticketId, watchers: d.watchers || [], watching: !!d.watching, canAdd: !!d.can_add, ready: d.ready !== false };
        } catch (e) { /* the button still draws; the panel says what went wrong */ }
        renderButton();
    }

The state.ticketId !== ticketId line stops a slow answer for ticket A drawing over ticket B when the analyst clicks through the list quickly.

The button

    function renderButton() {
        const toolbar = document.querySelector('.action-toolbar');
        if (!toolbar || !state.ticketId || !state.ready) return;
        let btn = document.getElementById('btnTicketWatch');
        if (!btn) {
            btn = document.createElement('button');
            btn.id = 'btnTicketWatch';
            btn.type = 'button';
            btn.className = 'action-btn';
            btn.addEventListener('click', togglePanel);
            const chk = document.getElementById('btnSopChecklists');
            toolbar.insertBefore(btn, chk ? chk.nextSibling : toolbar.firstChild);
        }
        const n = state.watchers.length;
        btn.title = T('button_title');
        btn.setAttribute('aria-pressed', state.watching ? 'true' : 'false');
        btn.innerHTML = '<span class="action-btn-icon">' + EYE + '</span><span>'
            + esc(state.watching ? T('watching') : T('watch')) + (n ? ' Β· ' + n : '') + '</span>';
        btn.style.color = state.watching ? 'var(--primary, #2563eb)' : '';
    }

The button is created by script, not in displayEmail()'s markup, and placed after the Checklists button. assets/js/ticket-forms.js (GH #272) places its Forms button after btnTicketWatch when it exists, so the order is Checklists, Watch, Forms.

The panel

drawPanel() lists the watchers. Each row has Stop watching (your own row) or Remove (anyone else's, only with write access), and an added by note when someone else put them there:

        const rows = state.watchers.map(w => {
            const mine = w.analyst_id === me;
            const by = w.added_by && w.added_by !== w.analyst_id && w.added_by_name ? ' <span style="color:var(--text-muted,#64748b);font-size:11px;">' + esc(T('added_by', { name: w.added_by_name })) + '</span>' : '';
            const rm = (mine || state.canAdd)
                ? '<button type="button" class="btn-link-small" data-unwatch="' + w.analyst_id + '" style="margin-left:auto;">' + esc(mine ? T('stop') : T('remove')) + '</button>' : '';
            return '<div style="display:flex;align-items:center;gap:6px;padding:4px 0;"><span>' + esc(w.name) + (mine ? ' (' + esc(T('you')) + ')' : '') + '</span>' + by + rm + '</div>';
        }).join('') || '<div style="color:var(--text-muted,#64748b);padding:4px 0;">' + esc(T('none')) + '</div>';
        const watchedIds = new Set(state.watchers.map(w => w.analyst_id));
        const options = (typeof analysts !== 'undefined' ? analysts : [])
            .filter(a => a.is_active !== false && !watchedIds.has(Number(a.id)))
            .map(a => '<option value="' + Number(a.id) + '">' + esc(a.full_name || a.name || '') + '</option>').join('');
        const add = state.canAdd && options
            ? '<div style="display:flex;gap:6px;margin-top:10px;"><select id="ticketWatchAdd" aria-label="' + esc(T('add_label')) + '" style="flex:1;min-width:0;"><option value="">' + esc(T('add_label')) + '</option>' + options + '</select>'
              + '<button type="button" class="btn btn-secondary btn-sm" id="ticketWatchAddBtn">' + esc(T('add')) + '</button></div>' : '';
  • The add list is a convenience, the server is the rule. It offers every active analyst inbox.js loaded. One who can't see the ticket's company is refused by add() with That analyst cannot see this ticket, shown as a toast.
  • can_add only hides controls. A read-only analyst who posts analyst_id for a colleague by hand gets 403 read_only from the service.
  • Every name goes through escapeHtml().
    async function change(action, analystId, panel) {
        try {
            const d = await call('POST', { action, ticket_id: state.ticketId, analyst_id: analystId });
            state.watchers = d.watchers || [];
            state.watching = !!d.watching;
            renderButton();
            if (panel && document.body.contains(panel)) drawPanel(panel);
        } catch (e) {
            if (typeof showToast === 'function') showToast(e.message, 'error');
        }
    }

3. Right-click β†’ Watch / Stop watching

The menu item in tickets/index.php. Its label is set when the menu opens:

        <?php /* GH #277: Watch / Stop watching - the label is set when the menu opens
                 (populateContextWatchItem in assets/js/ticket-watchers.js). */ ?>
        <button class="ticket-context-menu-item" type="button" id="ctxWatchItem" data-mode="watch" onclick="watchFromContext()">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            <span><?php echo htmlspecialchars(t('tickets.watch.watch')); ?></span>
        </button>

openTicketContextMenu() in inbox.js calls the hook alongside the other submenus:

    populateContextChecklistSubmenu();
    if (typeof populateContextWatchItem === 'function') populateContextWatchItem();   // GH #277
    /** Sets the menu item's label for the right-clicked ticket(s): Watch, or Stop watching when I already do. */
    async function populateContextWatchItem() {
        const item = document.getElementById('ctxWatchItem');
        if (!item) return;
        const label = item.querySelector('span');
        item.dataset.mode = 'watch';
        label.textContent = T('watch');
        if (ctxActsOnSelection) return;   // a selection: "Watch" each of them
        const id = ctxTargetTicketId;
        // The ticket open in the reading pane is already known.
        if (state.ticketId === id) {
            item.dataset.mode = state.watching ? 'unwatch' : 'watch';
            label.textContent = state.watching ? T('stop') : T('watch');
            return;
        }
        try {
            const d = await call('GET', null, '?ticket_id=' + encodeURIComponent(id));
            if (ctxTargetTicketId !== id) return;
            item.dataset.mode = d.watching ? 'unwatch' : 'watch';
            label.textContent = d.watching ? T('stop') : T('watch');
        } catch (e) { /* stays "Watch" */ }
    }
  • The mode lives on the element (data-mode), so the click does what the label said when it was clicked.
  • A selection is always Watch. A mixed selection has no single right answer for Stop watching, and bulk unwatching was not asked for.
  • The menu opens with Watch straight away and changes to Stop watching when the GET answers, so a right-click never waits on the network.
    /** The right-click item: watch or stop watching the ticket, or watch every selected one. */
    async function watchFromContext() {
        const item = document.getElementById('ctxWatchItem');
        const mode = item ? item.dataset.mode : 'watch';
        if (typeof closeTicketContextMenu === 'function') closeTicketContextMenu();
        try {
            if (ctxActsOnSelection) {
                const d = await call('POST', { action: 'watch_many', ticket_ids: selectedTicketIds() });
                let msg = T('many_done', { n: d.added });
                if (d.already) msg += ' ' + T('many_already', { n: d.already });
                if (d.skipped) msg += ' ' + T('many_skipped', { n: d.skipped });
                showToast(msg, 'success');
            } else {
                const id = ctxTargetTicketId;
                const d = await call('POST', { action: mode, ticket_id: id });
                showToast(mode === 'watch' ? T('now_watching') : T('stopped'), 'success');
                if (state.ticketId === id) { state.watchers = d.watchers || []; state.watching = !!d.watching; renderButton(); }
            }
            if (state.ticketId) loadTicketWatchers(state.ticketId);
        } catch (e) {
            showToast(e.message, 'error');
        }
    }

    window.loadTicketWatchers = loadTicketWatchers;
    window.populateContextWatchItem = populateContextWatchItem;
    window.watchFromContext = watchFromContext;

mode is read before closeTicketContextMenu(), which resets the menu. The final loadTicketWatchers() refreshes the open ticket's button when a selection included it.


4. The REST API

Three routes in api/v1/lib/routes.php:

    ['GET',    '#^/tickets/(\d+)/watchers$#',              ['ticket_watchers', 'read'],       'apiTicketWatchersList'],
    ['POST',   '#^/tickets/(\d+)/watchers$#',              ['ticket_watchers', 'create'],     'apiTicketWatchersAdd'],
    ['DELETE', '#^/tickets/(\d+)/watchers/(\d+)$#',        ['ticket_watchers', 'delete'],     'apiTicketWatchersRemove'],

Their own permission resource, so a key can read a ticket without being able to change who hears about it:

// api/v1/lib/permissions.php
        // GH #277. Watchers are told about a ticket as if it were theirs, through their own settings.
        'ticket_watchers' => [
            'label'   => 'Ticket watchers',
            'actions' => [
                'read'   => 'List who is watching a ticket',
                'create' => 'Add an analyst (the key\'s own, or another who can see the ticket) as a watcher',
                'delete' => 'Take an analyst off a ticket\'s watchers',
            ],
        ],
// api/v1/lib/modules.php - API_V1_RESOURCE_MODULES
    'ticket_watchers' => ['tickets'],   // GH #277

The handlers in api/v1/resources/tickets.php:

/** One watcher as the API returns it. */
function apiTicketWatcherShape(array $w): array {
    return [
        'analyst'    => ['id' => $w['analyst_id'], 'name' => $w['name']],
        'added_by'   => $w['added_by'] !== null ? ['id' => $w['added_by'], 'name' => $w['added_by_name']] : null,
        'added_at'   => apiIsoDate($w['added_at']),
    ];
}

/** GET /tickets/{id}/watchers */
function apiTicketWatchersList(PDO $conn, array $apiKey, array $params, array $body): void {
    apiLoadTicket($conn, $apiKey, (int)$params[0]);
    require_once __DIR__ . '/../../../includes/services/ticket_watchers.php';
    apiRespond(array_map('apiTicketWatcherShape', TicketWatchers::list($conn, (int)$params[0])));
}

/**
 * POST /tickets/{id}/watchers - { "analyst_id": 7 }; omitted = the key's own analyst.
 * 201 when added, 200 when they already watched. The analyst must be able to see the ticket.
 */
function apiTicketWatchersAdd(PDO $conn, array $apiKey, array $params, array $body): void {
    apiLoadTicket($conn, $apiKey, (int)$params[0]);
    require_once __DIR__ . '/../../../includes/services/ticket_watchers.php';
    $who = isset($body['analyst_id']) ? (int)$body['analyst_id'] : (int)$apiKey['analyst_id'];
    try {
        // The key's ticket_watchers.create permission is the write access here.
        $r = TicketWatchers::add($conn, ActorContext::fromApiKey($apiKey), (int)$params[0], $who, true);
    } catch (ServiceError $e) { apiFailFromService($e); }
    $mine = array_values(array_filter(TicketWatchers::list($conn, (int)$params[0]), fn($w) => $w['analyst_id'] === $who));
    apiRespond($mine ? apiTicketWatcherShape($mine[0]) : null, $r['added'] ? 201 : 200);
}

/** DELETE /tickets/{id}/watchers/{analyst_id} - 404 when they were not watching. */
function apiTicketWatchersRemove(PDO $conn, array $apiKey, array $params, array $body): void {
    apiLoadTicket($conn, $apiKey, (int)$params[0]);
    require_once __DIR__ . '/../../../includes/services/ticket_watchers.php';
    try {
        $r = TicketWatchers::remove($conn, ActorContext::fromApiKey($apiKey), (int)$params[0], (int)$params[1], true);
    } catch (ServiceError $e) { apiFailFromService($e); }
    if (!$r['removed']) apiError(404, 'not_found', 'That analyst is not watching this ticket.');
    apiRespond(['ticket_id' => (int)$params[0], 'analyst_id' => (int)$params[1], 'removed' => true]);
}
  • Two scope checks. apiLoadTicket() checks the key's company scope (apiKeyCanAccessTicket()), then the service checks the key's analyst can see the ticket and that the watcher can too.
  • $canWrite is true. The key holder chose ticket_watchers.create / .delete; that is the write access. A key still can't reach further than its analyst: the service checks the analyst can see the ticket.
  • 201 vs 200 tells a script whether it added someone or they were already there. Both return the watcher.
  • Errors come from apiFailFromService() and serviceErrorHttpStatus(): validation (inactive, cannot see, not ready) is 422 invalid_field / not_ready. The browser endpoint maps the same validation errors to 400.

The responses are typed in api/v1/lib/openapi_schemas.php (TicketWatcher, TicketWatcherRemoved) and documented in api/v1/spec.json, which feeds the in-app API documentation. The user-facing reference is REST API: Tickets β†’ Watchers. The three routes are also listed by GET / in api/v1/index.php.


5. Traps and limits

What Why it matters
πŸ”΄ analystCanAccessTicket() is true for any id on a single-company install always check the ticket row exists too; canSee() does (page 1, section 3)
πŸ”΄ ticket.reassigned is derived, never dispatched a workflow cannot trigger on it; add new watcher wording in the router loop, not at a call site
⚠️ Top-level let in inbox.js is not on window ticket-watchers.js reads analysts, ctxTargetTicketId, ctxActsOnSelection by bare name
⚠️ No row vs empty string in ticket_watch_events no row = every event; '' = none. Do not seed an empty value
⚠️ A wrong column in MERGE_MOVE_DEDUPE fails silently the catch assumes the table is absent; the move just doesn't happen
⚠️ No foreign keys a new path that deletes tickets must delete ticket_watchers rows itself
Access is company-level the router re-checks company access at every event; it does not check Tickets module access for the watcher, the same as for the assignee
⚠️ A deactivated analyst's watches may still be in the table under the default stop setting (ticket_watch_inactive) the rows stay so they come back on reactivation. list() and audience() join analysts on is_active = 1; a new reader of ticket_watchers must do the same, or it will show or notify people who have left (page 1)
⚠️ Every path that deactivates an analyst calls TicketWatchers::analystDeactivated() analystDeactivate(), AnalystsService::update(), api/tickets/save_analyst.php. A fourth path that forgets it turns remove into stop for that path (nobody is notified, but the rows stay)
No live redraw of the panel adding a watcher doesn't stamp tickets.updated_datetime, so someone else's open panel shows the new watcher the next time the ticket is drawn

6. Tests

tests/ticket-watchers.php - 33 checks. It writes to a database, so it runs only from the command line (PHP_SAPI !== 'cli' is a 404) and only when config.php points at the throwaway database you name:

FREEITSM_TEST_DATABASE=<throwaway db> FREEITSM_TEST_URL=http://localhost/<that install> php tests/ticket-watchers.php

It runs Database Verify first (scripts/db_verify_cli.php --apply). It makes four ZZ analysts (owner, watcher, other, and an inactive one) with forged session files in FREEITSM_SESS_DIR (default C:/wamp64/tmp), and two API keys. It assigns the first ticket to the ZZ owner. In finally it removes the analysts, their watches, their notifications, the keys and the session files, puts the ticket's assignee back and restores ticket_watch_events and ticket_watch_inactive exactly as they were (including "never saved"). The deactivation checks put the ZZ watcher back to active before moving on.

Notifications are fired through the real router, not a stub:

$fire = function (string $event, int $actor) use ($ticketId, $conn) {
    $_SESSION = ['analyst_id' => $actor, 'analyst_name' => 'ZZ actor'];
    $t = $conn->query("SELECT id, subject, assigned_analyst_id, owner_id FROM tickets WHERE id = $ticketId")->fetch(PDO::FETCH_ASSOC);
    $t['id'] = (int)$t['id']; $t['assigned_analyst_id'] = (int)$t['assigned_analyst_id'];
    notificationsHandleEvent($event, ['ticket' => $t, 'analyst_id' => $t['assigned_analyst_id']]);
};
Area Proves
The rules read-only can watch; watching twice is one watch; adding a colleague needs write access, and works with it; an inactive analyst is refused; the list is oldest first
Who is told a note reaches the assignee and the watcher, never the watcher who wrote it; a reassignment reaches the new assignee as ticket.assigned and a watcher as ticket.reassigned; with notes unticked the watcher hears nothing about a note while the assignee still does; never saved = every event; ticket.reassigned has its own preference switch
Browser endpoint (forged session, real HTTP) GET says I watch and lists everyone; Stop watching; watch_many with a ticket that does not exist adds one and skips one; GET for a ticket I can't see is 404
REST API (real keys, real HTTP) GET lists with names; a read-only key gets 403 on POST; POST with no body watches as the key's analyst (201), again is 200; DELETE takes them off, then 404
A watcher who is deactivated never saved = stop; stop: deactivating through AnalystsService::update() keeps the row, hides it from list(), and a note fired through the real router tells them nothing; made active again, the watch is back in the list; remove: deactivating through AnalystsService::update() (System β†’ Analysts, the REST API) deletes the row, and so does analystDeactivate() (the leaving screen)
Merge MERGE_MOVE_DEDUPE['ticket_watchers'] is analyst_id (a configuration check, not a real merge)

The deactivation section, as it runs:

    echo "\nA watcher who is deactivated\n";
    require_once 'includes/services/analysts.php';
    require_once 'includes/analyst_lifecycle.php';
    TicketWatchers::add($conn, $wCtx, $ticketId, $watcher, false);
    $watching = fn(int $id) => (int)$conn->query("SELECT COUNT(*) FROM ticket_watchers WHERE ticket_id = $ticketId AND analyst_id = $id")->fetchColumn();
    $listed = fn(int $id) => in_array($id, array_column(TicketWatchers::list($conn, $ticketId), 'analyst_id'), true);
    $setInactive(null);
    check('never saved = stop', TicketWatchers::inactivePolicy($conn) === 'stop');
    AnalystsService::update($conn, $oCtx, $watcher, ['is_active' => false]);
    check('stop: the watch is kept', $watching($watcher) === 1);
    check('...but not shown on the ticket', !$listed($watcher));

$watching counts the raw rows and $listed asks list() - the difference between the two is exactly what stop means. api/tickets/save_analyst.php is not exercised (it needs a browser session and a full form post); it is the same one-line call.

The watch_many check is the one that found the canSee() trap: ticket 999999999 was watched, not skipped. More in Developer tests: Tickets.

Also run after a change here: tests/analyst-lifecycle.php (the registry). See OpenAPI standards before touching spec.json or openapi_schemas.php.


Related

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally