Skip to content

Ticket Waiting Trigger Developer Guide

Ed Mozley edited this page Dec 1, 2026 · 1 revision

Reminders: a ticket that has waited a number of days - developer guide

5.17.0. Raised by @bigtrodat in #504. The user's view: Workflows - Β§ Reminders: a ticket that has waited a number of days (#504), and the {{last_message.*}} codes in Β§ Variables. The list of every time-based trigger: Time-Based Triggers.

A new time-based workflow trigger, A ticket has waited a number of days in its status (ticket.waiting), and four merge codes for the last message an analyst sent ({{last_message.text}}, .from_name, .sent, .subject). Nothing happens on a write path: the workflow_scheduled job looks for open tickets every 5 minutes, works out how long each has waited, and fires the trigger once per step through the same fire-once ledger as the contract and warranty expiry triggers. The days are not configured anywhere - they are read out of the workflows' own waiting.days conditions. One new column, tickets.status_changed_datetime, records when a ticket entered its current status.

πŸ“ Files

File What
includes/ticket_waiting.php New. The detector: ticketWaitingThresholds(), ticketWaitingCollect(), ticketWaitingSinceSql(), workflowEmitTicketsWaiting(), ticketWaitingMarkDone()
includes/ticket_status_since.php New. ticketStatusSinceReady() - has Database Verification added the column yet
includes/workflow_scheduled.php workflowScheduledRun() has a new part, tickets_waiting (only while the Tickets module is on)
includes/job_registry.php workflow_scheduled is "needed" when an active ticket.waiting workflow exists; new source part:tickets_waiting
cron/workflow_scheduled.php Labels the new part Tickets waiting in the run history
workflow/includes/engine.php The trigger, its fields (waiting.days, waiting.actual, waiting.since), enrichWithLastMessage(), the confidential rule in replyTextForAction(), and set_ticket_status stamping the column
includes/workflow_reply.php WORKFLOW_LAST_MESSAGE_PATHS, workflowLastMessageWanted(), workflowLastAnalystMessage() - reusing the reply-text helpers from discussion #451
includes/services/tickets.php updateTicket() stamps the column when the status changes (screen, REST API, bulk)
includes/ticket_reply.php reopenTicketForCustomerReply() stamps it too
api/workflow/save.php Refuses an active ticket.waiting workflow that names no day
database/freeitsm.sql, includes/db_verify_schema.php tickets.status_changed_datetime DATETIME NULL
lang/en/workflow.php triggers_waiting_body, triggers_waiting_count, variables_last_message (the in-app help)
includes/feature_bingo/cards/workflow.php Card workflow.ticket_waiting
tests/workflow-ticket-waiting.php New. See Tests

πŸ—“οΈ The column: when a ticket entered its status

`status_changed_datetime` DATETIME NULL,

A new ticket leaves it NULL - it has been in its status since it was created. Every path that changes a status stamps it, and each one only when Database Verification has added the column:

// includes/services/tickets.php - updateTicket()
if ($newStatusId !== (int)$current['status_id']) {
    $updates[] = 'status_id = ?';
    $args[]    = $newStatusId;
    if (ticketStatusSinceReady($conn)) $updates[] = 'status_changed_datetime = UTC_TIMESTAMP()';   // GH #504
// workflow/includes/engine.php - set_ticket_status
// GH #504 - only when the status really changes, so re-setting the same one does not restart a wait.
if (ticketStatusSinceReady($conn) && (int)($curRow['status_id'] ?? 0) !== (int)$statusId) {
    $sets[] = 'status_changed_datetime = UTC_TIMESTAMP()';
}

reopenTicketForCustomerReply() in includes/ticket_reply.php (a reply to a closed ticket reopens it) adds , status_changed_datetime = UTC_TIMESTAMP() to its own UPDATE.

ticketStatusSinceReady() asks SHOW COLUMNS FROM tickets LIKE 'status_changed_datetime' once per connection (a static keyed by spl_object_id($conn)), and answers false if the query fails.

  • TRAP: only on a real change. A save that sends the same status_id (an edit of the subject, a workflow setting the status the ticket already has) must not restart the wait, or a ticket edited every day would never reach day 3. Both updateTicket() and set_ticket_status compare before stamping.
  • TRAP: a new status-changing path must stamp the column too. Anything that writes tickets.status_id directly, outside these three, leaves the old time in place and the wait counts from the previous status.

⏳ When the wait started

ticketWaitingSinceSql() returns one SQL expression (alias t = tickets) - the later of two moments:

$statusSince = ticketStatusSinceReady($conn)
    ? "COALESCE(t.status_changed_datetime,
                (SELECT MAX(a.created_datetime) FROM ticket_audit a WHERE a.ticket_id = t.id AND a.field_name = 'Status'),
                t.created_datetime)"
    : "COALESCE((SELECT MAX(a.created_datetime) FROM ticket_audit a WHERE a.ticket_id = t.id AND a.field_name = 'Status'),
                t.created_datetime)";
$lastHuman = "(SELECT MAX(e.received_datetime) FROM emails e
                WHERE e.ticket_id = t.id
                  AND ((e.direction IN ('Inbound', 'Portal') AND COALESCE(e.is_auto_reply, 0) = 0)
                       OR e.sent_by_analyst_id IS NOT NULL))";
return "GREATEST({$statusSince}, COALESCE({$lastHuman}, '1970-01-01'))";
  1. When the ticket entered its status - status_changed_datetime; for a ticket whose status last changed before 5.17.0 (NULL), its last Status row in ticket_audit; with neither, when it was created.
  2. The last message a person wrote on it - the requester (an Inbound email or a Portal reply that is not an out-of-office, is_auto_reply) or an analyst (sent_by_analyst_id, see Who sent a reply).

So a requester who answers, or an analyst who writes again, starts the wait again.

  • TRAP: FreeITSM's own messages must NOT count. Acknowledgements and workflow emails - these reminders included - have no sent_by_analyst_id and are not inbound. If the first reminder restarted the wait, the ticket would be back at day 0 and the second reminder could never come.
  • TRAP: GREATEST() returns NULL if any argument is NULL in MySQL. A ticket with no human message at all would drop out of the query, hence the COALESCE(..., '1970-01-01') round the message part.

πŸ”’ Which days fire

Nothing is configured twice. ticketWaitingThresholds() reads every active ticket.waiting workflow and walks both its conditions and its actions JSON for a waiting.days condition:

function ticketWaitingCollect(array $node, array &$days): void
{
    if (($node['field'] ?? null) === TICKET_WAITING_FIELD) {
        $op = (string)($node['op'] ?? 'equals');
        $vals = $node['value'] ?? null;
        $vals = is_array($vals) ? $vals : preg_split('/\s*,\s*/', (string)$vals, -1, PREG_SPLIT_NO_EMPTY);
        foreach ($vals as $v) {
            if (!is_numeric($v)) continue;
            $n = (int)$v;
            if ($op === 'equals' || $op === 'in') $days[] = $n;
            elseif ($op === 'gt')                 $days[] = $n + 1;
            // lt / not_equals / not_in name no day of their own - nothing to fire on.
        }
    }
    foreach ($node as $child) {
        if (is_array($child)) ticketWaitingCollect($child, $days);
    }
}
Condition Day(s)
waiting.days equals 3 3
waiting.days is one of 3, 7 (a comma list or an array) 3 and 7
waiting.days is greater than 6 7
is less than / not equals / not one of none

The result is de-duplicated, kept between 1 and 3650, and sorted smallest first.

  • Branches count. The walk is recursive over the whole decoded JSON, so a waiting.days condition inside a branch in the actions names a day as well.
  • TRAP: the condition is tested against the STEP, not the real wait. The payload's waiting.days is the step that fired; waiting.actual is how long the ticket has really waited. This is why the user page and the in-app help say use equals for each step: with steps 3, 7 and 14 in play, a "second reminder" written as greater than 6 is also true when the 14-day step fires (14 > 6), so the second reminder goes out again with the closing email.
  • TRAP: an active workflow with no day is refused. Without a waiting.days condition it would never fire and nothing would say why. api/workflow/save.php runs the same walk and refuses the save; a draft (inactive) can still be saved:
if ($triggerEvent === 'ticket.waiting' && $isActive) {
    require_once __DIR__ . '/../../includes/ticket_waiting.php';
    $days = [];
    ticketWaitingCollect(['c' => $conditions, 'a' => $actions], $days);
    if (!array_filter($days, fn($d) => $d >= 1)) {
        echo json_encode(['success' => false, 'error' => 'Add a condition "waiting.days" equals the number of days ...']);
        exit;
    }
}

In the engine, waiting.days and waiting.actual are typed numeric in FIELD_TYPES, so the condition editor offers equals, is one of, greater than and so on, and no contains.

πŸ” Firing once per step, per wait

workflowEmitTicketsWaiting() asks for the open tickets that have waited at least the smallest step, with their whole days:

"SELECT w.id, w.since, TIMESTAMPDIFF(DAY, w.since, UTC_TIMESTAMP()) AS days
   FROM (SELECT t.id, {$since} AS since
           FROM tickets t
           JOIN ticket_statuses s ON s.id = t.status_id
          WHERE s.is_closed = 0 AND t.deleted_datetime IS NULL) w
  WHERE w.since <= UTC_TIMESTAMP() - INTERVAL ? DAY"
  • Whole 24-hour days, so it is the same in every time zone. Every time involved is stored in UTC and TIMESTAMPDIFF(DAY, ...) counts complete 24-hour periods - not calendar dates, which would depend on whose midnight.
  • Closed and deleted tickets are never looked at (s.is_closed = 0 AND t.deleted_datetime IS NULL). Snoozed tickets are not excluded.

Each step then goes through workflowEmitOnce() (includes/workflow_scheduled.php):

$fired += workflowEmitOnce($conn, TICKET_WAITING_EVENT, "ticket:{$id}:waiting:{$latest}", $fp, [
    'ticket'  => $ticket,
    'waiting' => [
        'days'   => $latest,   // the step - what a Waiting Β· Days condition tests
        'actual' => $days,     // how long it has really waited (more than days after a catch-up)
        'since'  => $fp,
    ],
]) ? 1 : 0;
Ledger column Value
trigger_event ticket.waiting
entity_key ticket:<id>:waiting:<days> - one per ticket per step
fingerprint since - when this wait started

workflow_scheduled_emissions has a UNIQUE key over all three and the insert is INSERT IGNORE, so only the run that created the row dispatches - two overlapping cron runs cannot send the same reminder twice.

  • Re-arming is free. A new status or a new human message moves since, which is the fingerprint, so every step is a new ledger row and can fire again in the new wait. No cleanup is needed when a ticket moves on.
  • Nobody listening, nothing recorded. workflowEmitOnce() writes no ledger row while no ticket.waiting workflow is active, so switching one on later fires for tickets already in the window rather than finding them "already done".
  • The ticket in the payload is TicketsService::workflowPayload(), so every ticket field is a condition, as on the other ticket triggers.

Catch-up: only the latest step

A ticket that has passed several steps at once - the workflows were just switched on, or the job was not running - fires only the latest step it has reached. The earlier ones are written into the ledger as done, without firing:

$reached = array_values(array_filter($steps, fn($d) => $d <= $days));
if (!$reached) continue;
$latest = end($reached);
...
foreach ($reached as $d) {
    if ($d === $latest) continue;
    ticketWaitingMarkDone($conn, $id, $d, $fp);
}

ticketWaitingMarkDone() is a bare INSERT IGNORE into the ledger with the same entity key and fingerprint a real firing would use. A ticket that has waited 20 days with steps 3, 7 and 14 is closed with its closing message - it is not sent two reminders in the same minute first. waiting.actual (20) tells a workflow it was a catch-up.

  • TRAP: the earlier steps must be marked, not just skipped. The loop only holds an earlier step back while a later one is in the list. Without a ledger row, switching off or deleting the later step's workflow while the ticket still waits would make the earlier step the latest - and it would fire, days late, for a ticket that had already passed it. The ledger is the only record that the step was passed.

⏰ The job

workflowScheduledRun() runs the new part inside its own try/catch, like the others, and only while the Tickets module is switched on:

'ticket_waiting' => $part('tickets_waiting', function () use ($conn, $on) {
    if (!$on('tickets')) return 0;
    require_once __DIR__ . '/ticket_waiting.php';
    return workflowEmitTicketsWaiting($conn);
}),

includes/job_registry.php counts the job as needed when an active workflow has trigger_event IN ('contract.expiring','asset.warranty_expiring','ticket.waiting'), and lists part:tickets_waiting among its sources - so a failure here makes the run PARTIAL and is named Tickets waiting in Reporting β†’ System logs β†’ Background jobs, rather than hiding behind "OK". The job runs every 5 minutes (interval => 5); workflowEmitTicketsWaiting() returns early when no active workflow names a day.

βœ‰οΈ {{last_message.*}} - the last message an analyst sent

Offered on every ticket trigger, not only this one - they are in the engine's shared $fullTicket field list. What a reminder quotes:

Code From
{{last_message.text}} The message's body as plain text, without the quoted emails underneath, capped at 10,000 characters
{{last_message.from_name}} analysts.full_name of sent_by_analyst_id
{{last_message.sent}} received_datetime, through fmt_datetime()
{{last_message.subject}} The email's subject
function workflowLastAnalystMessage(PDO $conn, int $ticketId): array
{
    ...
        "SELECT e.subject, e.received_datetime, e.body_content, e.body_type, a.full_name
           FROM emails e
      LEFT JOIN analysts a ON a.id = e.sent_by_analyst_id
          WHERE e.ticket_id = ? AND e.sent_by_analyst_id IS NOT NULL
       ORDER BY e.received_datetime DESC, e.id DESC LIMIT 1"
    ...
    $text = workflowReplyCutText(workflowReplyPlain(workflowReplyCutHtml($html), $type));
    if ($text === '') $text = workflowReplyPlain($html, $type);

It reuses the reply-text helpers from discussion #451 (see Workflow reply text - Developer Guide): the same plain-text conversion and the same cautious cuts as {{reply.new_text}}, falling back to the whole body if the cut would leave nothing. All four are '' when no analyst has written, or when the query fails before Database Verification.

  • TRAP: only sent_by_analyst_id IS NOT NULL. The second reminder must quote what the analyst asked, not the first reminder - FreeITSM's own emails have no analyst, so they are never "the last message". The same rule as the wait above.

Loaded only when used, after the snapshot

// GH #504: the last message an analyst sent - same rules as the reply text above.
if (workflowLastMessageWanted($conditions, $actions)) {
    $payload = self::enrichWithLastMessage($conn, $payload);
}

workflowLastMessageWanted() is a plain str_contains(..., 'last_message.') over the workflow's conditions and actions JSON. enrichWithLastMessage() runs after the run's payload snapshot is stored, so the message text is not copied into Workflows β†’ History (it is stored once already: on the ticket), and it never replaces a last_message already in the payload.

Confidential tickets

replyTextForAction() builds the payload each action sees. On a confidential ticket last_message.text is blanked for every action except Send email, whose recipients are already held to the requester and analysts:

if (($payload['last_message']['text'] ?? '') !== '') $has = true;   // GH #504, same rule
...
if ($confidential) {
    ...
    if (isset($payload['last_message']) && is_array($payload['last_message'])) $payload['last_message']['text'] = '';
}

The same rule as {{reply.body}} and {{ticket.full}}: a confidential message cannot be copied into an ordinary ticket, a task or a chat post. If the confidentiality check itself fails, the ticket is treated as confidential. The name, date and subject are left alone.

πŸ§ͺ Tests

tests/workflow-ticket-waiting.php - 17 checks against a test database (FREEITSM_TEST_DATABASE). It makes ZZ tickets, emails and three log_message workflows (3, 7 and 14 days, each limited to the ZZ tickets by a subject condition), runs workflowEmitTicketsWaiting() and reads the run history:

  • the days come from the workflows (equals 3, in 7, in ['14']); greater than 6 names day 7 and less than names none
  • 4 days: the 3-day step fires; 8 days at once: only the 7-day step
  • an analyst wrote yesterday, or the requester answered yesterday: nothing fires; an out-of-office does not restart the wait
  • a closed ticket is never looked at
  • 15 days: the 14-day step, with waiting.actual = 15; {{last_message.text}} is the analyst's text without the quoted email and not FreeITSM's own later reminder; {{last_message.from_name}} is the analyst
  • a second run fires nothing again
  • set_ticket_status stamps the column, and a new wait reaching day 3 fires the 3-day step again
  • TicketsService::updateTicket() stamps it on a status change, and leaves it alone on a save that does not change the status
  • no analyst message: the codes are blank, not an error

It needs the column (it stops with "Run Database Verification first" otherwise). Its cleanup deletes every ticket.waiting ledger row, because the detector also passes other open tickets in the test database - one more reason never to point it at a real install.

See also

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally