Skip to content

Problem Management Developer Guide

Ed Mozley edited this page Dec 5, 2026 · 2 revisions

Problem Management - Developer Guide

How the Problem Management module is built underneath. User side: Problem Management. This page starts with the newest piece - what happens to the linked tickets when a problem is resolved (#513) - and will grow as the module does.


1. πŸ“ The files

File Role
includes/services/problems.php ProblemsService - create/update/delete, notes, incident and change links, and (#513) openLinkedTickets(), tellLinkedTickets(), closeLinkedTickets()
api/problem-management/*.php Thin UI adapters over the service: get, save, link_ticket, unlink_ticket, close_linked_tickets (#513)...
api/v1/resources/problems.php The REST API, over the same service
assets/js/problem-management.js The list, the detail view and its dialogs (pmStillOpenBand(), pmOpenCloseTickets(), pmCloseTicketsGo() for #513)
problem-management/index.php The page, its modals (#pmCloseModal) and styles
includes/services/notifications.php The problem.resolved type
includes/services/tickets.php updateTicket() - every ticket close goes through it; the send_close_email switch (#513)
problem-management/table.php, assets/js/problem-table.js The table view (#514) on the shared data-table engine
api/problem-management/update_field.php One table cell - priority or assignee - through updateProblem() (#514)
includes/report_packs/blocks_problems.php The Report Packs blocks (#514)
Tables problems, problem_statuses (is_closed), problem_priorities, problem_tickets, problem_notes, problem_audit; the change link is change_relations

2. βœ… A resolved problem and its linked tickets (#513)

(After 5.19.0, asked for in #513 by @Dr4inder.)

The tickets waiting for a permanent fix are the ones nobody looks at again. So two things now happen when a problem is resolved: the people working its open tickets are told, and the problem page offers to close those tickets.

"Resolved" = the move from an open status into a closed one

There is no special Resolved status: problem_statuses.is_closed decides, as it decides closed_datetime. updateProblem() already knew the old and new is_closed; the hook sits right after the audit rows are written:

// GH #513: resolved (open -> closed) - tell the people working its open
// linked tickets, and say so on each ticket. Never blocks the save.
if ($statusChangedTo !== null && $newIsClosed && !$oldIsClosed) {
    try {
        self::tellLinkedTickets($conn, $ctx, $problemId, $current);
    } catch (Throwable $e) {
        error_log('Problem ' . $problemId . ' resolved: telling linked tickets failed: ' . $e->getMessage());
    }
}

So Resolved β†’ Closed tells nobody (both closed), a save that only changes the title tells nobody, and reopening then resolving again tells them again - each is a new open β†’ closed move. The REST API goes through the same updateProblem(), so a problem resolved through the API tells them too.

Which tickets: openLinkedTickets()

SELECT t.id, t.ticket_number, t.subject, ts.name AS status,
       t.assigned_analyst_id, a.full_name AS assignee
  FROM problem_tickets pt
  JOIN tickets t ON t.id = pt.ticket_id
  JOIN ticket_statuses ts ON ts.id = t.status_id
  LEFT JOIN analysts a ON a.id = t.assigned_analyst_id
 WHERE pt.problem_id = ? AND t.deleted_datetime IS NULL AND ts.is_closed = 0
 ORDER BY t.created_datetime

With an $analystId it adds ticketDepartmentScopeSql() - the departments rule - so a person only ever sees the tickets they may see. tellLinkedTickets() calls it without one: telling the assignees is FreeITSM's doing, and the assignee can see their own ticket.

Telling them: one bell per person, a line on every ticket

tellLinkedTickets() writes TicketsService::auditWriteBy($conn, $ticketId, $ctx, 'Problem', null, 'PRB-00003 resolved') on each open ticket, then groups the tickets by assignee and sends one problem.resolved notification per person, about the problem (entity_type = 'problem', so the bell opens the problem, not one of five tickets):

$id = NotificationsService::notify($conn, [
    'analyst_id'  => $analystId,
    'event_type'  => 'problem.resolved',
    'entity_type' => 'problem',
    'entity_id'   => $problemId,
    'entity_ref'  => $ref,
    'title'       => (string)$problem['title'],
    'body'        => count($theirs) === 1
        ? "Resolved. Your open ticket $refs is linked to it."
        : 'Resolved. ' . count($theirs) . " of your open tickets are linked to it: $refs.",
    'actor_id'    => $ctx->actorId,
    'actor_name'  => $ctx->actorName,
    'reason'      => 'assignee',
]);

The bell's own rules do the rest: never tell you about your own action (the person who resolved it is not told about their own ticket), the type can be switched off in Preferences (default => true), and coalescing merges it with anything else unread about that problem.

Closing them: closeLinkedTickets()

The problem page shows N linked tickets are still open with Close only when the problem is in a closed status (pmStillOpenBand()), counting the tickets the analyst sees in the table. The dialog posts to api/problem-management/close_linked_tickets.php (needs Problems and Tickets). The service then:

  1. refuses while the problem is still open, and refuses a ticket status that does not close;
  2. re-reads openLinkedTickets() and touches only ids that are in it - ids from the browser are a wish list, so a ticket not linked, already closed or made up is ignored;
  3. closes each through TicketsService::updateTicket(), catching ServiceError per ticket, then adds the internal note;
  4. writes one problem audit row, Linked tickets closed: N.
try {
    // Closing rules first, so a ticket that cannot close gets no stray note.
    TicketsService::updateTicket($conn, $ctx, $id, ['status_id' => $statusId, 'send_close_email' => $emailRequesters], true);
    if (trim($note) !== '') {
        TicketsService::createNote($conn, $ctx, $id, ['text' => $note, 'is_internal' => true]);
    }
    $closed[] = $id;
} catch (ServiceError $e) {
    $failed[] = ['id' => $id, 'ticket_number' => $open[$id]['ticket_number'], 'error' => $e->getMessage()];
}

πŸ”‘ Why through updateTicket() and not one UPDATE: closing a ticket is not a column write - it stamps closed_datetime, checks the mandatory fields at closing (block mode throws), the department rule, fires workflows, CSAT and the closing email. A ticket its rules refuse stays open and comes back in failed[] with the reason, which the dialog lists while closing the rest - the same contract as bulk_update_tickets.php.

Leaving the requester out: send_close_email

The requesters did not ask about the problem, so emailing them is off in the dialog. updateTicket() sends the ticket_closed template and the CSAT survey on every close; it now skips both when - and only when - the caller says so explicitly:

// TRAP: only an explicit false skips it - every other caller (the UI, bulk,
// the REST API, workflows) never sends the key, and must keep emailing.
$emailRequester = !(array_key_exists('send_close_email', $in) && $in['send_close_email'] === false);
if ($newIsClosed && !$oldIsClosed && $emailRequester) {

PATCH /tickets/{id} passes its JSON body straight into updateTicket(), so api/v1/resources/tickets.php unsets send_close_email first - it is FreeITSM's own switch, not an API field.

Tests

FREEITSM_TEST_DATABASE=<throwaway db> php tests/problem-resolved-tickets.php - 18 checks through the real services, rolled back: one bell per assignee, none for the resolver, a history line on open linked tickets only, no second telling without a status move, the refusals, ids that are not open-and-linked ignored, a ticket the closing rules refuse (priority mandatory, block mode) left open and reported with no stray note, the internal note, the problem's audit row, and the REST API stripping send_close_email. Not covered by the test: that no email is sent - sendTemplateEmail() only sends when an install has a closing template; the skip is the if above.

File Change
πŸ”΄ includes/services/problems.php openLinkedTickets(), tellLinkedTickets(), closeLinkedTickets(); the hook in updateProblem()
πŸ”΄ includes/services/tickets.php send_close_email (explicit false only)
🟑 api/problem-management/close_linked_tickets.php New endpoint
🟑 api/problem-management/get.php Linked incidents carry is_closed
🟑 api/v1/resources/tickets.php Strips send_close_email
🟑 assets/js/problem-management.js, problem-management/index.php The band, the dialog, styles (problem-management.js?v=25)
🟒 includes/services/notifications.php, lang/en/common.php problem.resolved and its two labels
🟒 tests/problem-resolved-tickets.php 18 checks

Design decisions (#513, 5 December 2026)

The requester proposed each of these; I kept their suggestion unless noted.

Decision Options Chosen, and why Who
Who is told The ticket's assignee; also the requester; also the ticket's team The assignee of each open linked ticket. Closest to ITIL: problem management hands back to incident management, whose owner of the incident decides what the requester hears Requester (@Dr4inder)
How often One per ticket; one per problem per person One per problem per person - five tickets, one bell Requester
When On Resolved only; on any open β†’ closed move Any open β†’ closed move - statuses are each install's own, is_closed is what they mean Requester
Close the tickets automatically Yes; offer Offer. Closest to ITIL: an incident is closed when the user's service is confirmed restored, which only the person working it knows Requester
Email the requesters on that close On; off; a setting Off, with a tick in the dialog - the requester did not ask about the problem; the tick is there for teams that want it Requester
A ticket that cannot close Skip silently; stop the run; close the rest and list it Close the rest and list it with the reason - the bulk-update contract Requester, house rule
A setting to turn the bell off Module setting; per person Per person, in Preferences - it is each person's own noise. No module setting: telling the people working the tickets is not something a team needs to stop for everyone Me
Workflow trigger "problem closed" Now; later Later, as the requester suggested - problem.status_changed already fires and can be filtered on the status Requester

3. πŸ“Š The table view and Report Packs (#514)

Asked for by @Dr4inder for a monthly problem review. User side: Reviewing problems, Report Packs. Test: tests/problems-table-and-report-packs.php (17).

3a. The table

problem-management/table.php is the same thin page as Change Management's: the skeleton from includes/data-table-skeleton.php, assets/js/data-table.js, and a config file - assets/js/problem-table.js - that hands createDataTable() its columns, a loader and a cell saver. Saved views needed one word: problems in TABLE_VIEW_KEYS (includes/table_views.php); the table key is also the module key, so api/table-views/save.php checks Problems access with it.

The list endpoint was extended rather than copied. api/problem-management/list.php now also returns closed_datetime, has_workaround, has_root_cause and the linked changes:

                   -- GH #514: the table's Change column - the changes linked to the problem.
                   (SELECT GROUP_CONCAT(cr.change_id ORDER BY cr.change_id SEPARATOR ',') FROM change_relations cr
                     WHERE cr.related_type = 'problem' AND cr.related_id = p.id) AS change_ids

A problem's change link lives in change_relations (written from the problem side, read by Changes), so the ids come back as one comma list and the table shows them as CHG-0001 refs. Days open is worked out in the browser so it never goes stale in a saved view:

    /** Whole days from opening to closing - or to now while it is open. */
    function daysOpen(p) {
        const from = parseUTCDate(p.created_datetime);
        if (!from || isNaN(from.getTime())) return null;
        const to = p.closed_datetime ? parseUTCDate(p.closed_datetime) : new Date();
        return Math.max(0, Math.floor((to.getTime() - from.getTime()) / 86400000));
    }

Inline edits. Only priority and assignee, the same rule as the change table:

        // Keyed on the id: the inline drop-down matches the row's value under the column key against valueKey.
        { key: 'priority_id', label: T('col_priority'), type: 'string', defaultVisible: true, defaultOrder: 3,
          display: p => p.priority_name || '',
          editable: { kind: 'lookup', listKey: 'priorities', valueKey: 'id', labelKey: 'name', colourKey: 'colour', allowNull: true, nullLabel: '-' } },

⚠️ TRAP: an editable lookup column must be keyed on the stored id (priority_id), not the name, with display showing the name. The engine selects the option whose valueKey equals row[col.key]; keyed on priority_name every row showed "-" (caught on the screenshot, not by a test).

The saver posts one field to update_field.php, which allows exactly two:

const PROBLEM_TABLE_FIELDS = ['priority_id', 'assigned_analyst_id'];

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new Exception('POST only');
    $d = json_decode(file_get_contents('php://input'), true) ?: [];
    $id = (int)($d['id'] ?? 0);
    $field = (string)($d['field'] ?? '');
    if ($id <= 0 || !in_array($field, PROBLEM_TABLE_FIELDS, true)) {
        echo json_encode(['success' => false, 'error' => 'That field cannot be changed here.']);
        exit;
    }

It goes through ProblemsService::updateProblem(), so the audit row is the form's. Status is deliberately not editable: resolving a problem in its own form offers to tell and close its linked tickets (Β§2), and a table cell has nowhere to ask. Problems has no Read only access level (MODULES_WITH_READ_ONLY is changes, forms, tasks), so there is no read-only case to handle.

3b. The Report Packs blocks

includes/report_packs/blocks_problems.php, module problems, company through rpTenantClause() like every block (Report Packs - Developer Guide). Seven toolbox entries over six handlers: problems.kpis, .breakdown (by status or priority), .known_errors, .list (opened or closed), .top_tickets, .no_root_cause (option days, default 30).

"Open" is one constant, so every block agrees with the problem list - a problem with no status counts as open:

/** " AND the problem is open" - a problem with no status counts as open, as on the problem list. */
const RP_PROBLEM_OPEN = ' AND COALESCE(ps.is_closed, 0) = 0';

Now versus the period. problems has closed_datetime but no date for becoming a known error or getting a root cause, so those blocks report the state when the pack is run, and the tool descriptions say so. The summary's median is done in PHP over the open problems' ages:

    sort($ages);
    $median = '-';
    if ($ages) {
        $m = intdiv(count($ages), 2);
        $median = count($ages) % 2 ? $ages[$m] : (int)round(($ages[$m - 1] + $ages[$m]) / 2);
    }

Most tickets counts the links made in the period (problem_tickets.created_datetime), with each problem's all-time total from a correlated subquery:

        "SELECT p.id, p.problem_number, p.title, ps.name AS status, ps.colour AS status_colour, pp.name AS priority, a.full_name AS assignee,
                COUNT(*) AS in_period,
                (SELECT COUNT(*) FROM problem_tickets t2 WHERE t2.problem_id = p.id) AS total
           FROM problem_tickets pt
           JOIN problems p ON p.id = pt.problem_id " . RP_PROBLEM_LOOKUPS . "
      LEFT JOIN analysts a ON a.id = p.assigned_analyst_id
          WHERE pt.created_datetime >= ? AND pt.created_datetime < ?" . $tSql . "
          GROUP BY p.id, p.problem_number, p.title, ps.name, ps.colour, pp.name, a.full_name
          ORDER BY in_period DESC, total DESC, p.id ASC
          LIMIT " . (int)$o['limit']);

No root cause - open, older than the days set, root cause empty:

                      WHERE (p.root_cause IS NULL OR p.root_cause = '')
                        AND p.created_datetime < UTC_TIMESTAMP() - INTERVAL ? DAY" . RP_PROBLEM_OPEN . $tSql . "
                      ORDER BY p.created_datetime ASC, p.id ASC"

3c. Decisions

Decision Why Who
Columns as suggested, plus workaround / root cause / closed / updated hidden until wanted the request's list; the extra ones answer "which have a workaround" without opening each Requester, me
Inline edit: priority and assignee only; status stays in the form the same rule as Changes; resolving offers to close the tickets (#513) Requester (suggested), me
Open / known error / root cause blocks report "now" nothing records when those became true; a guessed history would be wrong Me
Most tickets counts links made in the period "which keep collecting tickets" is about the period, not all time; the total is shown beside it Me
No-root-cause threshold is a block option (30 days) teams review on different cadences - a setting per block, not a guess Me
No new module settings nothing changes until someone opens the table or adds a block Me

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally