Skip to content

Watchtower Links Developer Guide

Ed Mozley edited this page Nov 21, 2026 · 1 revision

Every Watchtower number is a link - Developer Guide

(5.8.0, discussion #388)

How a count on a Watchtower card becomes a link into its module, what each module's list accepts on its query string, and the two rules that keep a count and the list it opens telling the same story. The user-facing description is Watchtower; the refresh preference is in Watchtower too.


Files

File What it holds
watchtower/index.php metric() (a count, as a link when given an href), wtScopeQuery(), linkCardMetrics(), the card-icon shortcut, the refresh timer
includes/watchtower_settings.php WT_REFRESH_CHOICES, wtRefreshMinutes(), wtCountedStatusIds() - the "open" rule shared with the Changes and Tasks lists
includes/watchtower_queries.php the counts; status rows now carry their id; the Contracts count uses contractListSql(); the Projects this week count is projects_week
tickets/index.php + assets/js/inbox.js ?status_id= resolved to window.TICKET_LINK_STATUS, then All Tickets on that status with its folder lit
change-management/index.php, api/change-management/list.php, assets/js/change-management.js ?status_id= -> window.CHG_LINK_STATUS; ?statuses=open -> a chip and wtCountedStatusIds('changes.by_status')
tasks/index.php, assets/js/tasks.js ?status_id= / ?statuses=open resolved to status names, board switched to All tasks for that visit
api/contracts/get_contracts.php, contracts/index.php ?expiring=30|90, ?notice=30
api/software/get_licences.php, software/licences/index.php the same three, on licences
api/domains/list.php, includes/domains/read.php (domainWatchtowerMatchIds()), assets/js/domains-register.js ?expiring=30|90, ?ssl=due
projects/index.php, api/projects/list.php, assets/js/projects-portfolio.js ?health=red|amber, ?stages=week, &scope=mine|team (window.PRJ_SCOPE)
asset-management/table.php, api/assets/get_assets.php, assets/js/asset-table.js, includes/asset_expiry_due.php ?stale=7, ?due=warranty|lease
system/preferences/index.php Watchtower refreshes every (user_preferences.watchtower_refresh_minutes)

1. A count is a link

Every card is drawn by a render*() function that builds its numbers with metric(). Given a fourth argument it draws an <a>; without one it draws a <div>:

function metric(value, label, color, href) {
    const inner = `<div class="wt-metric-value" style="color:${color || 'var(--text, #334155)'}">${value}</div><div class="wt-metric-label">${label}</div>`;
    return href ? `<a class="wt-metric wt-metric-link" href="${escapeHtml(href)}">${inner}</a>` : `<div class="wt-metric">${inner}</div>`;
}

A count that has a list of its own passes the filtered URL:

html += metric(ct.expiring_30d, window.t('watchtower.contracts.metric_30d'), ct.expiring_30d > 0 ? '#ef4444' : '#94a3b8', '../contracts/?expiring=30');
html += metric(s.count, escapeHtml(s.name), /* colour */ ..., '../change-management/?status_id=' + Number(s.id));

Everything else - Morning Checks, Calendar, Service Status, Knowledge, the totals - still goes somewhere. After every render, linkCardMetrics() points each remaining div.wt-metric at the card's own module, by copying the href of the card name's link:

function linkCardMetrics() {
    document.querySelectorAll('.wt-card').forEach(card => {
        const a = card.querySelector('.wt-card-name a');
        if (!a) return;
        card.querySelectorAll('div.wt-metric:not(.wt-metric-link)').forEach(m => {
            m.classList.add('wt-metric-link');
            m.setAttribute('role', 'link');
            m.tabIndex = 0;
            m.title = a.textContent.trim();
            const go = () => { window.location.href = a.href; };
            m.addEventListener('click', go);
            m.addEventListener('keydown', e => { if (e.key === 'Enter') go(); });
        });
    });
}

It runs in loadDashboard() after the last render*() call and before markImpersonalCards(), which must stay last (it and two renderers set display themselves). The card's icon is a pointer shortcut to the same place, not a second link: it is aria-hidden, because the card name is the link a keyboard or screen reader reaches.

Mine / My team travel with the Projects links

Only the Projects list has a personal view that matches the card's, so only its links carry the scope:

function wtScopeQuery() { return (typeof wtScope !== 'undefined' && (wtScope === 'mine' || wtScope === 'team')) ? '&scope=' + wtScope : ''; }
html += metric(pj.red, T('metric_red'), ..., '../projects/?health=red' + wtScopeQuery());

projects/index.php turns &scope= into the owners the card counted - the person, or wtTeamAnalystIds() - and hands them to the page as window.PRJ_SCOPE. The other lists have no personal view, so on Mine their numbers are the team's, as the card already says when it cannot narrow.


2. What each list accepts

No parameter always means the page exactly as before. Every filter only narrows what the list already returns to this person - none of them widens access.

Card Count Link Resolved by
Tickets a status tickets/?status_id=<id> tickets/index.php looks the id up in ticket_statuses (active only) and emits window.TICKET_LINK_STATUS; inbox.js opens All Tickets on that status (the GH #73 view) with its folder expanded and lit
Tickets open tickets/ -
Changes a status change-management/?status_id=<id> change-management/index.php -> window.CHG_LINK_STATUS; the sidebar row lights
Changes open change-management/?statuses=open api/change-management/list.php: c.status_id IN wtCountedStatusIds('changes.by_status'); a chip above the list
Tasks a status / open tasks/?status_id=<id> / ?statuses=open tasks/index.php resolves to status names (the board matches by name) and shows All tasks for that visit; the saved My/All choice comes back when the chip is removed
Contracts ending in 30 / 90 days, notice in 30 contracts/?expiring=30 / 90, ?notice=30 api/contracts/get_contracts.php
Software renewing in 30 / 90, notice in 30 software/licences/?expiring=30 / 90, ?notice=30 api/software/get_licences.php (notice = renewal_date - notice_period_days, which is not stored)
Domains expiring in 30 / 90, certificates domains/?expiring=30 / 90, ?ssl=due api/domains/list.php returns watch_ids from domainWatchtowerMatchIds(); the register narrows to them and keeps its sidebar counts
Projects off track, at risk, dates this week projects/?health=red / amber, ?stages=week, &scope=mine|team projects-portfolio.js (health is projectDecorate()'s shown_health); api/projects/list.php answers stages_week
Assets not seen in 7 days, warranty, lease asset-management/table.php?stale=7, ?due=warranty, ?due=lease ?stale=N is the older #97 filter, applied in asset-table.js (staleDaysFromUrl()); ?due= is filtered by api/assets/get_assets.php with includes/asset_expiry_due.php. Either way retired assets are left out, whatever Show retired says

Each filtered list says why it is short - a lit folder or sidebar row, or a removable chip/banner (.link-filter-chip, #assetStaleNotice) - so a short list is never a mystery. Removing it returns to the normal list.


3. Rule: links carry database ids, never names

Decided with Ed, 20 November 2026. A status link is ?status_id=3, never ?status=Open. A name can be renamed or translated, and a URL with a name in it breaks the day somebody does either; an id does not change. The page resolves the id on the server:

// tickets/index.php (change-management/index.php is the same, on change_statuses)
$__linkStatus = null;
if (isset($_GET['status_id']) && ctype_digit((string)$_GET['status_id'])) {
    try {
        $__ls = connectToDatabase()->prepare("SELECT name FROM ticket_statuses WHERE id = ? AND is_active = 1");
        $__ls->execute([(int)$_GET['status_id']]);
        $__linkStatus = $__ls->fetchColumn() ?: null;
    } catch (Throwable $e) { $__linkStatus = null; }
} ?>
<script>window.TICKET_LINK_STATUS = <?php echo json_encode($__linkStatus, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;</script>

The name only exists inside the page, because the ticket folders and the change sidebar match by name. An unknown or retired id resolves to null and the page opens as normal. To make that possible the status rows in getWatchtowerData() now carry 'id' => (int)$row['id'].


4. Rule: a count and its list must agree

Clicking 3 and getting a list of 5 is worse than no link at all. Every list filter uses the card's own conditions - the same columns, the same BETWEEN today AND today + N, the same naive "today" (naive_today_sql(), GH #126), the same exclusions - and where it can, the same function.

  • "Open" changes and tasks come from one function, used by the card and the list:

    // includes/watchtower_settings.php
    function wtCountedStatusIds(PDO $conn, string $itemKey): array
    {
        $items = wtSelectableItems();
        if (!isset($items[$itemKey])) return [];
        $spec = $items[$itemKey];
        try {
            $ids = array_map('intval', $conn->query(
                "SELECT `{$spec['id']}` FROM `{$spec['table']}` WHERE {$spec['where']}"
            )->fetchAll(PDO::FETCH_COLUMN));
        } catch (Exception) {
            return [];
        }
        $picked = wtItemMembers($conn, $itemKey);
        return $picked === null ? $ids : array_values(array_intersect($ids, $picked));
    }

    It respects the admin's pick in Watchtower Settings. An empty result means "match nothing" - the card said 0, so the list is empty, not everything.

  • Contracts follow the company switcher. The card used contractVisibilitySql() (every company you may see) while the list used contractListSql() (the company you are working in). They now both use the list's rule, as the Domains and Projects cards already did:

    // includes/watchtower_queries.php
    [$ctVis, $ctArgs] = contractListSql($conn, (int)$analystId, 'k');
    $ctCount = function (string $where) use ($conn, $ctVis, $ctArgs): int {
        $s = $conn->prepare("SELECT COUNT(*) FROM contracts k WHERE $where$ctVis");
        $s->execute($ctArgs);
        return (int)$s->fetchColumn();
    };
    $ctExp30 = $ctCount("k.is_active = 1 AND k.contract_end BETWEEN {$todaySql} AND DATE_ADD({$todaySql}, INTERVAL 30 DAY)");

    and the list repeats the condition exactly:

    // api/contracts/get_contracts.php
    foreach (['expiring' => 'c.contract_end', 'notice' => 'c.notice_date'] as $key => $col) {
        $days = (int)($_GET[$key] ?? 0);
        if ($days < 1 || $days > 366) continue;
        $today = naive_today_sql();
        $sql .= " AND c.is_active = 1 AND $col IS NOT NULL AND $col BETWEEN {$today} AND DATE_ADD({$today}, INTERVAL $days DAY)";
    }
  • Projects this week counts projects, not dates. It used to add stages ending and milestones due, so one project with two dates counted twice and no list of projects could ever match. Now projects_week is the number of distinct projects with either, and api/projects/list.php (stages_week) asks the same question:

    $pjWeekIds = $conn->query(
        "SELECT DISTINCT project_id FROM project_stages
          WHERE project_id IN $ids AND status <> 'closed'
            AND end_date BETWEEN {$todaySql} AND DATE_ADD({$todaySql}, INTERVAL 7 DAY)"
    )->fetchAll(PDO::FETCH_COLUMN);
    // ...plus project_milestones WHERE done_date IS NULL AND due_date in the same window
    $pj['projects_week'] = count(array_unique(array_map('intval', $pjWeekIds)));
  • Warranty and lease live once, in includes/asset_expiry_due.php: assetExpiryWindow() (Assets -> Settings -> Expiry alerts: where it surfaces and how many days) and assetExpiryDueSql() (expired or due within the window; a lease also excludes machines already handed back). The card and get_assets.php?due= both call them.

  • Domains use domainWatchtowerMatchIds(), a copy of the card's conditions - deliberately not the register's own Expiring and Certificate views, which count every domain over a fixed 21 days.

TRAP: the domain conditions, the Projects this week query and the Software notice rule exist in two places - the card in includes/watchtower_queries.php and the list's endpoint. Each copy carries a comment naming the other. Change one, change the other, or the link opens a different number.

Known, by design: under All companies the asset table shows the selected company only, so there it can list fewer than the card.


5. The refresh preference

// includes/watchtower_settings.php
const WT_REFRESH_CHOICES = [1, 2, 5, 10, 15];

function wtRefreshMinutes(PDO $conn, int $analystId): int
{
    try {
        $st = $conn->prepare("SELECT preference_value FROM user_preferences WHERE analyst_id = ? AND preference_key = 'watchtower_refresh_minutes' LIMIT 1");
        $st->execute([$analystId]);
        $v = (int)$st->fetchColumn();
        return in_array($v, WT_REFRESH_CHOICES, true) ? $v : 5;
    } catch (Throwable $e) {
        return 5;
    }
}

watchtower/index.php writes it straight into the timer: setInterval(loadDashboard, <?php echo (int)wtRefreshMinutes(...); ?> * 60 * 1000). Anything not in the list (a hand-edited row) falls back to 5. A wall screen left on stays signed in because every refresh is a request and includes/session_keepalive.php (GH #107) keeps the session's clock fresh. The buttons are in Preferences beside On "Mine", cards that have no owner.


Adding a link to a new count

  1. Give the count's metric() call an href - by id for anything that can be renamed.
  2. Make the target list accept the parameter, using the card's own condition (share a function where you can; otherwise comment both copies).
  3. Show why the list is short (chip, lit row or banner) with a way back.
  4. Keep "no parameter" exactly as before, and never widen what the list returns.

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally