Tickets: link related tickets, such as one outage at several clients, from a ticket's menu or Link together on the tickets list, each in one group with the others; the Related card lists them with Reply to all and Resolve all for the open ones and an x to take one out, the list shows a count, and merging passes them on; database 4.0.8 adds ticket_links

This commit is contained in:
johnnyq
2026-11-20 00:13:32 -05:00
parent 3d2bfbcad5
commit 352b0e3c50
11 changed files with 497 additions and 1 deletions

View File

@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
### Upgrading to 26.12
Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's forty database changes (3.6.6 to 4.0.7) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, a column on agents' settings for compact rows, a table for reply drafts, a table for which tickets each agent has opened, two columns on contacts for an email that bounces, a table for credentials' earlier passwords, a column on recurring invoices for a pause with an end, a column on calendar events, two columns on agents' settings and a table for reminders, four settings for the weekly summary, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates.
Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's forty-one database changes (3.6.6 to 4.0.8) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, a column on agents' settings for compact rows, a table for reply drafts, a table for which tickets each agent has opened, two columns on contacts for an email that bounces, a table for credentials' earlier passwords, a column on recurring invoices for a pause with an end, a column on calendar events, two columns on agents' settings and a table for reminders, four settings for the weekly summary and a table for related tickets, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates.
### Security
@@ -105,6 +105,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- Calendar: Holidays, under From ITFlow, shows the closure days from Admin > SLA, and is on to start with. From Mountaineer IT's build of ITFlow.
- Calendar: what you have shown - calendars, sources, Whose and the view - is kept to your account, so the calendar opens the same way on every computer and phone. The first time, it opens on your own calendar. With Whose set to Everyone, To schedule lists everyone's open tickets that aren't booked, with who has each. From Mountaineer IT's build of ITFlow.
- Tickets: more than one agent can work a ticket. Under Assigned to on the ticket, Additional agents adds others to help, while the ticket stays assigned to its lead. Each helper is booked at the same time as the lead - moving and cancelled with the lead's booking - at a time of their own, or not booked. A helper finds the ticket under Mine and on the dashboard, is emailed the client's replies as the lead is, and is sent their own booking with a calendar file that doesn't replace the lead's. The client's emails stay about the lead's booking. Click a helper to change their booking or take them off. From Mountaineer IT's build of ITFlow.
- Tickets: link related tickets - the same outage at several clients, or a problem that keeps coming back. Link related tickets, in a ticket's ⋮ menu, picks any client's open tickets (or ones closed in the last 90 days), and Link together on the tickets list's Bulk Action links the ones ticked. Linking a ticket to one already related to others brings it in with them all. Each ticket's Related card lists the others with their client, status and who has them; its menu has Reply to all and Resolve all for the open ones, and the × takes one out. A related ticket shows a link and how many on the tickets list, and merging a ticket passes its related tickets to the one it goes into. An agent sees only the related tickets of clients they can open, and is told how many others there are.
- Tickets: the tickets list and board show +1, +2 after the lead when others are helping - Helping when one of them is you. A helper's booking is on the calendar in their color, can be dragged to a time of their own, shows in their calendar link, and counts when someone books them for something else at the same time. From Mountaineer IT's build of ITFlow.
- Time zones: an agent who works away from the company can pick My time zone under Account > Preferences. The calendar, the ticket's booking, the Schedule window, New Event and Edit, and the event's quick look are then on their own clock, with a note saying so, and their booking emails give their time with the company's beside it. Bookings are still kept in the company's time, so the client's emails and calendar files, and everyone else's view, don't change. From Mountaineer IT's build of ITFlow.
- Dispatch: a new page under Support puts each agent's booked work beside the tickets still to give out. The queue on the left has three tabs - No agent, Not booked (with an agent, nothing booked) and Left behind - most urgent first, with a search, a client and a priority filter. Day shows a column for each agent through the day; Week a row for each agent with a column for each day. Drag a ticket from the queue onto an agent and a time, or drag a booking to another agent or time, and the Schedule window opens with the agent, the time, how long and onsite or remote filled in - Schedule it gives the ticket to that agent and books it, emailing them the calendar file, the agent who had it the cancellation, and the contact and watchers unless you switch that off. Drag a booking back onto the queue to take it off the schedule. One-off events move the same way, to another time or agent. Workload shows each agent's open tickets (leading and helping), SLAs breached or close to it, tickets past due, not booked or gone quiet, and the hours booked today and this week against the working hours in Admin > SLA - flagged Falling behind, Watch, Overloaded or Has room against the team. Click an agent for their tickets, or drop a ticket from the queue on one to give it to them. Under it, This week shows tickets in and closed each day, against last week and the last four, the week's SLA results and each agent's share. Which agents show, the view and weekends are kept to your account, and an agent on their own time zone sees it on their clock. Seeing Dispatch takes Support in your role; booking from it takes Support at Modify. From Mountaineer IT's build of ITFlow.
@@ -400,6 +401,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- Users: `invite_users_bulk` (`admin/post/users.php`, `admin/modals/user/user_invite_bulk.php`) - `userInviteBulkParse()` (up to `USER_INVITE_BULK_MAX`, 50) in `functions/user_invite.php`, then `userCheckIdentity()`, the seat limit, `userInviteSave()` and `userInviteSend()` for each, as `add_user` does for one.
- Tickets: `ticketMailTry($from, $subject, $auto_reply)` in `functions/ticket_mail_try.php` asks what `cron/ticket_email_parser.php` asks, in its order, with no writes - `ticketMailTryReply()` mirrors `addReply()`. Kept in step with the parser by hand. `admin/modals/ticket_mail/ticket_mail_try.php` (`?try=1` answers JSON with the result).
- Weekly summary: database 4.0.7 adds `settings.config_weekly_summary`, `_day` (1 Monday to 7 Sunday), `_to` (NULL for every admin) and `_sent_at`. `functions/weekly_summary.php`: `weeklySummaryReady()`, `weeklySummarySettings()`, `weeklySummaryRecipients()`, `weeklySummaryNumbers($from, $to)`, `weeklySummaryNeeds()`, `weeklySummaryEmail($until)`, `weeklySummarySend()` and `weeklySummaryRun()`, called by `cron/nightly_tasks.php`, which sends once on the day (`config_weekly_summary_sent_at`). `send_weekly_summary_now` in `admin/post/settings_notification.php`; the `weekly_summary` email preview.
- Related tickets: database 4.0.8 adds `ticket_links` (`ticket_id` as the primary key, `link_group`, `linked_by`, `linked_at`; deleted with its ticket). `functions/ticket_link.php`: `ticketLinksReady()`, `ticketLinkGroup()`, `ticketLinkMembers()`, `ticketLinkTogether()` (any number of tickets and everything already related to them into one group, with a ticket history line naming the newly related ones), `ticketUnlink()`, `ticketRelated()` and `ticketLinkCounts()` (scoped to the agent's clients), `ticketLinkHidden()`, `ticketLinkCandidates()` and `ticketLinkCarry()` (from `ticketMergeInto()`). A group is numbered by its lowest ticket id, renumbered by `ticketLinkTidy()` as tickets leave, so one number never names two groups; a group left with one ticket is deleted. `agent/post/ticket_link.php` handles `link_tickets`, `unlink_ticket` and `bulk_link_tickets`; Reply to all and Resolve all open `ticket_bulk_reply.php` and `ticket_bulk_resolve.php` with `ticket_ids[]`.
## [26.11.8]

View File

@@ -0,0 +1,25 @@
<?php
/*
* ITFlow - Database update to version 4.0.8 (from 4.0.7)
* Included by admin/database_updates.php - do not access directly
*
* Related tickets (functions/ticket_link.php): ticket_links puts a ticket in a group
* of related ones - the same outage at several clients, say. Each ticket is in one
* group at most (link_group, the lowest ticket id in it), with who linked it and when.
* A deleted ticket's row goes with it.
*
* Re-runnable: the table is made only where it isn't there yet.
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `ticket_links` (
`ticket_id` int(11) NOT NULL,
`link_group` int(11) NOT NULL,
`linked_by` int(11) NOT NULL DEFAULT 0,
`linked_at` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`ticket_id`),
KEY `ticket_links_group` (`link_group`),
CONSTRAINT `ticket_links_ticket` FOREIGN KEY (`ticket_id`) REFERENCES `tickets` (`ticket_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");

View File

@@ -0,0 +1,67 @@
<?php
/*
* Link related tickets (functions/ticket_link.php) - pick the tickets this one is about the same
* thing as, of any client the agent can open. Posts link_tickets (agent/post/ticket_link.php).
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
// The ticket, after the module and client checks - or the modal's error
$row = ticketForModal($_GET['ticket_id'] ?? 0, 2);
$ticket_id = intval($row['ticket_id']);
$reference = escapeHtml(ticketReference($row));
$candidates = ticketLinksReady() ? ticketLinkCandidates($ticket_id) : [];
$related_count = count(ticketRelated($ticket_id));
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-link me-2"></i>Link related tickets <small class="ms-1 opacity-75"><?= $reference ?></small></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<div class="modal-body">
<p class="small text-body-secondary">
Tickets about the same thing - one outage at several clients, or a problem that keeps coming back. Each shows the others, and one update or resolve can go to them all.
<?php if ($related_count) { ?>
<strong><?= $reference ?></strong> is related to <?= $related_count ?> already - the ones you pick join them.
<?php } ?>
</p>
<div class="mb-3">
<label class="form-label">Related to <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-life-ring"></i></span>
<select class="form-select select2" name="related_ticket_ids[]" data-placeholder="- Pick tickets -" multiple required>
<?php foreach ($candidates as $candidate) {
$is_open = ticketIsOpen($candidate);
$client = $candidate['client_name'] !== null ? $candidate['client_name'] : 'Internal'; ?>
<option value="<?= intval($candidate['ticket_id']) ?>"<?= selectOptionData([
'icon' => 'fas fa-life-ring',
'description' => $client . ' · ' . ($candidate['ticket_status_name'] ?? '') . ($is_open ? '' : ' - ' . timeAgo($candidate['ticket_closed_at'] ?: $candidate['ticket_resolved_at'])),
'keywords' => $client,
]) ?>><?= escapeHtml(ticketReference($candidate) . ' ' . $candidate['ticket_subject']) ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">Open tickets, and those closed in the last 90 days. Search by number, subject or client.</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="link_tickets" class="btn btn-primary text-bold"><i class="fas fa-link me-2"></i>Link</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,79 @@
<?php
/*
* ITFlow - POST handlers for related tickets (functions/ticket_link.php): the ticket page's
* Link window and the x on each related ticket, and Link together on the tickets list.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
// From a ticket's Link window: this ticket and the ones picked, each a ticket of a client the agent can open
if (isset($_POST['link_tickets'])) {
validateCSRFToken();
$row = ticketForRequest($_POST['ticket_id'] ?? 0, 2);
$ticket_id = intval($row['ticket_id']);
$ids = [$ticket_id];
foreach (array_unique(array_map('intval', (array) ($_POST['related_ticket_ids'] ?? []))) as $related_id) {
$related = $related_id ? ticketRow($related_id) : null;
if ($related && (!intval($related['ticket_client_id']) || hasClientAccess($related['ticket_client_id']))) {
$ids[] = $related_id;
}
}
if (count($ids) < 2) {
flashAlert('Pick the tickets to link it with.', 'error');
redirect();
}
$joined = ticketLinkTogether($ids);
$related_count = count(ticketRelated($ticket_id));
logAudit("Ticket", "Link", "$session_name linked ticket " . escapeSql(ticketReference($row)) . " with " . (count($ids) - 1) . " other ticket(s)", intval($row['ticket_client_id']), $ticket_id);
flashAlert($joined
? "<strong>" . escapeHtml(ticketReference($row)) . "</strong> is related to <strong>$related_count</strong> ticket" . ($related_count === 1 ? '' : 's') . " now"
: 'They were already related.');
redirect();
}
// The x on a related ticket - it comes out of the group, the rest stay related
if (isset($_GET['unlink_ticket'])) {
validateCSRFToken();
$row = ticketForRequest($_GET['unlink_ticket'], 2);
$ticket_id = intval($row['ticket_id']);
if (ticketUnlink($ticket_id)) {
logAudit("Ticket", "Unlink", "$session_name took ticket " . escapeSql(ticketReference($row)) . " out of its related tickets", intval($row['ticket_client_id']), $ticket_id);
flashAlert("<strong>" . escapeHtml(ticketReference($row)) . "</strong> is no longer related to the others");
}
redirect();
}
// Bulk Action > Link together on the tickets list - the tickets ticked, as one group
if (isset($_POST['bulk_link_tickets'])) {
validateCSRFToken();
$rows = ticketsForBulk(2);
if (count($rows) < 2) {
flashAlert('Tick at least two tickets to link together.', 'error');
redirect();
}
$joined = ticketLinkTogether(array_keys($rows));
logAudit("Ticket", "Bulk Link", "$session_name linked " . count($rows) . " tickets together");
flashAlert($joined ? "Linked <strong>" . count($rows) . "</strong> tickets together" : 'They were already related.');
redirect();
}

View File

@@ -217,6 +217,17 @@ if (isset($_GET['ticket_id'])) {
$also_open = empty($ticket['ticket_resolved_at']) && empty($ticket['ticket_closed_at'])
? ticketAlsoOpen($contact_id, intval($ticket['ticket_asset_id']), $ticket_id, 6) : [];
// The tickets it is linked with - the same outage at other clients, say (functions/ticket_link.php)
$related = ticketRelated($ticket_id);
$related_hidden = ticketLinkHidden($ticket_id, count($related));
// This one and the open ones, for one update or resolve to them all
$related_open_ids = array_merge($ticket_is_closed ? [] : [$ticket_id], array_map('intval', array_column(array_filter($related, function ($other) {
return $other['is_open'];
}), 'ticket_id')));
$related_open_query = implode('&amp;', array_map(function ($id) {
return 'ticket_ids[]=' . $id;
}, $related_open_ids));
// Reply counts, one pass - these drive the conversation filter
$reply_counts = array('total' => 0, 'public' => 0, 'internal' => 0);
$sql_reply_counts = mysqli_query(
@@ -668,6 +679,11 @@ if (isset($_GET['ticket_id'])) {
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/ticket/ticket_merge.php?ticket_id=<?= $ticket_id ?>">
<i class="fas fa-fw fa-clone me-2"></i>Merge into another ticket
</a>
<?php if (ticketLinksReady()) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/ticket/ticket_link.php?ticket_id=<?= $ticket_id ?>">
<i class="fas fa-fw fa-link me-2"></i>Link related tickets
</a>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#" id="clientChangeTicketModalLoad" data-modal-url="modals/ticket/ticket_change_client.php?ticket_id=<?= $ticket_id ?>">
<i class="fas fa-fw fa-people-carry me-2"></i>Move to another client
</a>
@@ -1526,6 +1542,56 @@ if (isset($_GET['ticket_id'])) {
</div>
<?php } ?>
<!-- Related tickets - linked with this one, any client's (functions/ticket_link.php) -->
<?php if ($related || $related_hidden) { ?>
<div class="card mb-3" data-related-tickets>
<div class="card-header px-3 py-2">
<h5 class="card-title mt-1"><i class="fas fa-fw fa-link me-2"></i>Related <span class="badge rounded-pill text-bg-secondary ms-1"><?= count($related) + $related_hidden ?></span></h5>
<?php if ($can_edit_ticket) { ?>
<div class="card-tools">
<a class="btn btn-tool ajax-modal" href="#" data-modal-url="modals/ticket/ticket_link.php?ticket_id=<?= $ticket_id ?>" title="Link more tickets"><i class="fas fa-plus"></i></a>
<?php if (count($related_open_ids) > 1) { ?>
<div class="dropdown d-inline-block">
<button class="btn btn-tool" type="button" data-bs-toggle="dropdown" title="To them all"><i class="fas fa-ellipsis-v"></i></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/ticket/ticket_bulk_reply.php?<?= $related_open_query ?>">
<i class="fas fa-fw fa-paper-plane me-2"></i>Reply to all <?= count($related_open_ids) ?> open
</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/ticket/ticket_bulk_resolve.php?<?= $related_open_query ?>">
<i class="fas fa-fw fa-check me-2"></i>Resolve all <?= count($related_open_ids) ?> open
</a>
</div>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<div class="list-group list-group-flush small">
<?php foreach ($related as $other) {
$other_id = intval($other['ticket_id']); ?>
<div class="list-group-item px-3 py-2">
<div class="d-flex align-items-start gap-2">
<div class="text-truncate flex-grow-1"><?= ticketLink($other) ?></div>
<?php if ($can_edit_ticket && (!intval($other['ticket_client_id']) || hasClientAccess($other['ticket_client_id']))) { ?>
<a class="text-body-secondary" href="post.php?unlink_ticket=<?= $other_id ?>&amp;csrf_token=<?= $_SESSION['csrf_token'] ?>" title="No longer related"><i class="fas fa-times"></i></a>
<?php } ?>
</div>
<div class="d-flex align-items-center gap-2 mt-1 text-body-secondary">
<?= ticketStatusHtml($other['ticket_status_name'], $other['ticket_status_color'], 'detail') ?>
<span class="text-truncate"><?= $other['client_name'] !== null ? escapeHtml($other['client_name']) : 'Internal' ?></span>
<span class="ms-auto text-nowrap"><?= $other['user_name'] !== null ? escapeHtml($other['user_name']) : 'Unassigned' ?></span>
</div>
</div>
<?php } ?>
<?php if ($related_hidden) { ?>
<div class="list-group-item px-3 py-2 text-body-secondary">
<i class="fas fa-fw fa-lock me-1"></i><?= $related_hidden ?> more for <?= $related_hidden === 1 ? 'a client' : 'clients' ?> you can't open
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<!-- Also open for the same contact or asset -->
<?php if ($also_open) { ?>
<div class="card mb-3">

View File

@@ -68,6 +68,7 @@ while ($row = mysqli_fetch_assoc($sql)) {
$last_replies = ticketLastReplies(array_keys($tickets));
$tickets_tags = tagsForRecords('ticket', array_keys($tickets));
$task_counts = ticketTaskCounts(array_keys($tickets));
$link_counts = ticketLinkCounts(array_keys($tickets));
// A Due column only when there is something to put in it
$show_due = $sla_in_use || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM tickets WHERE ticket_due_at IS NOT NULL AND ticket_closed_at IS NULL LIMIT 1"));
@@ -191,6 +192,9 @@ $sort_link = function ($column, $label, $class = '') use ($url_query_strings_sor
</span>
<?php } ?>
<?= ticketTasksHtml($task_counts[$ticket_id] ?? null) ?>
<?php if (!empty($link_counts[$ticket_id])) { ?>
<span class="text-nowrap" title="Related to <?= $link_counts[$ticket_id] ?> other ticket<?= $link_counts[$ticket_id] === 1 ? '' : 's' ?>"><i class="fas fa-link me-1"></i><?= $link_counts[$ticket_id] ?></span>
<?php } ?>
</div>
<?php if (!empty($tickets_tags[$ticket_id])) { ?>
<!-- Tags - the + to change them while it is open; tag an untagged one from its page or Bulk Action -->

View File

@@ -387,6 +387,11 @@ $export_extra = [
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/ticket/ticket_bulk_add_project.php" data-bulk="true">
<i class="fas fa-fw fa-project-diagram me-2"></i>Add to a project
</a>
<?php if (ticketLinksReady()) { ?>
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_link_tickets">
<i class="fas fa-fw fa-link me-2"></i>Link together
</button>
<?php } ?>
<?php if ($view === 'list' && ticketReadsReady()) { ?>
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_mark_tickets_read">
<i class="fas fa-fw fa-envelope-open me-2"></i>Mark as read

18
db.sql
View File

@@ -4510,6 +4510,24 @@ CREATE TABLE `ticket_history` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticket_links`
--
DROP TABLE IF EXISTS `ticket_links`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `ticket_links` (
`ticket_id` int(11) NOT NULL,
`link_group` int(11) NOT NULL,
`linked_by` int(11) NOT NULL DEFAULT 0,
`linked_at` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`ticket_id`),
KEY `ticket_links_group` (`link_group`),
CONSTRAINT `ticket_links_ticket` FOREIGN KEY (`ticket_id`) REFERENCES `tickets` (`ticket_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticket_mail_choices`
--

View File

@@ -77,6 +77,7 @@ require_once __DIR__ . '/functions/ticket_fields.php';
require_once __DIR__ . '/functions/by_day.php';
require_once __DIR__ . '/functions/ticket.php';
require_once __DIR__ . '/functions/ticket_helpers.php';
require_once __DIR__ . '/functions/ticket_link.php';
require_once __DIR__ . '/functions/user_timezone.php';
require_once __DIR__ . '/functions/dispatch.php';
require_once __DIR__ . '/functions/project_tickets.php';

View File

@@ -393,6 +393,9 @@ function ticketMergeInto($child, $parent, $comment, $move_replies = false) {
SELECT $parent_id, ticket_tags.tag_id FROM ticket_tags JOIN tags ON tags.tag_id = ticket_tags.tag_id
WHERE ticket_tags.ticket_id = $ticket_id AND tags.tag_archived_at IS NULL");
// So do its related tickets (functions/ticket_link.php)
ticketLinkCarry($ticket_id, $parent_id);
logTicketHistory($ticket_id, "$session_name merged this ticket into $parent_reference and closed it");
logTicketHistory($parent_id, "$session_name merged $child_reference into this ticket");
logAudit("Ticket", "Merge", "$session_name merged ticket $child_reference into $parent_reference", intval($child['ticket_client_id']), $ticket_id);

226
functions/ticket_link.php Normal file
View File

@@ -0,0 +1,226 @@
<?php
/*
* ITFlow - related tickets: tickets about one thing - the same outage at several clients, a
* problem that keeps coming back - linked so each shows the others, and one update or resolve
* can go to them all. The Related tickets card on agent/ticket.php, its Link window
* (agent/modals/ticket/ticket_link.php) and Link together on the tickets list's Bulk Action
* (agent/post/ticket_link.php).
*
* ticket_links (database 4.0.8) puts each linked ticket in a group: every ticket in a group is
* related to every other. Linking a ticket to one in a group brings it into the whole group, and
* linking two groups makes them one. A group's number is the lowest ticket id in it, kept so as
* tickets join and leave - so one number never names two groups. A ticket deleted goes with its
* row (the foreign key), and a group left with one ticket is no group.
*/
/** Whether the 4.0.8 update has run - the ticket_links table. */
function ticketLinksReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '4.0.8', '>=');
}
return $ready;
}
/** A ticket's group, or 0 when it is linked to nothing. */
function ticketLinkGroup($ticket_id) {
global $mysqli;
if (!ticketLinksReady()) {
return 0;
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT link_group FROM ticket_links WHERE ticket_id = " . intval($ticket_id)));
return $row ? intval($row[0]) : 0;
}
/** The tickets in a group - their ids, whoever can see them. */
function ticketLinkMembers($group) {
global $mysqli;
$group = intval($group);
if (!$group) {
return [];
}
$sql = mysqli_query($mysqli, "SELECT ticket_id FROM ticket_links WHERE link_group = $group ORDER BY ticket_id");
return array_map('intval', array_column(mysqli_fetch_all($sql), 0));
}
/** Keep a group numbered by its lowest ticket - and drop it when one ticket is all that's left. */
function ticketLinkTidy($group) {
global $mysqli;
$members = ticketLinkMembers($group);
if (count($members) < 2) {
mysqli_query($mysqli, "DELETE FROM ticket_links WHERE link_group = " . intval($group));
return;
}
if ($members[0] !== intval($group)) {
mysqli_query($mysqli, "UPDATE ticket_links SET link_group = {$members[0]} WHERE link_group = " . intval($group));
}
}
/*
* Link these tickets - and every ticket already related to any of them - into one group.
* Each ticket newly related to others gets a history line naming them. Checks are the caller's:
* the agent's level and their access to each ticket's client. Returns how many tickets were
* related to one they weren't before - 0 when they all already were.
*/
function ticketLinkTogether(array $ticket_ids) {
global $mysqli, $session_user_id, $session_name;
$ticket_ids = array_values(array_unique(array_filter(array_map('intval', $ticket_ids))));
if (!ticketLinksReady() || count($ticket_ids) < 2) {
return 0;
}
$list = implode(',', $ticket_ids);
// The groups they are in now, and everything in those groups
$groups = array_map('intval', array_column(mysqli_fetch_all(mysqli_query($mysqli, "SELECT DISTINCT link_group FROM ticket_links WHERE ticket_id IN ($list)")), 0));
$before = [];
foreach ($groups as $group) {
foreach (ticketLinkMembers($group) as $member) {
$before[$member] = $group;
}
}
$everyone = array_values(array_unique(array_merge(array_keys($before), $ticket_ids)));
$target = min($everyone);
if ($groups) {
mysqli_query($mysqli, "UPDATE ticket_links SET link_group = $target WHERE link_group IN (" . implode(',', $groups) . ")");
}
$user_id = intval($session_user_id);
foreach ($ticket_ids as $ticket_id) {
if (!isset($before[$ticket_id])) {
mysqli_query($mysqli, "INSERT IGNORE INTO ticket_links SET ticket_id = $ticket_id, link_group = $target, linked_by = $user_id");
}
}
// A history line on each ticket for the ones it wasn't related to before
$joined = 0;
$references = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number FROM tickets WHERE ticket_id IN (" . implode(',', $everyone) . ")");
while ($row = mysqli_fetch_assoc($sql)) {
$references[intval($row['ticket_id'])] = ticketReference($row);
}
foreach ($everyone as $ticket_id) {
$new = array_filter($everyone, function ($other) use ($ticket_id, $before) {
return $other !== $ticket_id && (!isset($before[$ticket_id], $before[$other]) || $before[$ticket_id] !== $before[$other]);
});
if (!$new) {
continue;
}
$joined++;
$names = array_map(function ($id) use ($references) {
return $references[$id] ?? '';
}, array_slice(array_values($new), 0, 10));
logTicketHistory($ticket_id, "$session_name linked it with " . escapeSql(implode(', ', array_filter($names)) . (count($new) > 10 ? ' and ' . (count($new) - 10) . ' more' : '')));
}
return $joined;
}
/** Take a ticket out of its group, with a history line on it. True when it was in one. */
function ticketUnlink($ticket_id) {
global $mysqli, $session_name;
$ticket_id = intval($ticket_id);
$group = ticketLinkGroup($ticket_id);
if (!$group) {
return false;
}
mysqli_query($mysqli, "DELETE FROM ticket_links WHERE ticket_id = $ticket_id");
ticketLinkTidy($group);
logTicketHistory($ticket_id, "$session_name took it out of its related tickets");
return true;
}
/*
* The tickets related to this one that the agent can see - open ones first - each with its
* client, status, priority and who has it. Count those they can't see with ticketLinkHidden().
*/
function ticketRelated($ticket_id) {
global $mysqli;
$ticket_id = intval($ticket_id);
$group = ticketLinkGroup($ticket_id);
if (!$group) {
return [];
}
$sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_client_id,
ticket_resolved_at, ticket_closed_at, ticket_assigned_to, ticket_created_at, client_name, user_name, user_avatar,
ticket_status_name, ticket_status_color
FROM ticket_links
JOIN tickets ON tickets.ticket_id = ticket_links.ticket_id
LEFT JOIN clients ON client_id = ticket_client_id
LEFT JOIN users ON user_id = ticket_assigned_to
LEFT JOIN ticket_statuses ON ticket_status_id = ticket_status
WHERE link_group = $group AND tickets.ticket_id <> $ticket_id" . clientScopeSql('ticket_client_id') . "
ORDER BY (ticket_resolved_at IS NULL AND ticket_closed_at IS NULL) DESC, ticket_number DESC");
$rows = [];
while ($row = mysqli_fetch_assoc($sql)) {
$row['is_open'] = ticketIsOpen($row);
$rows[] = $row;
}
return $rows;
}
/** How many of a ticket's related tickets are for clients the agent can't open. */
function ticketLinkHidden($ticket_id, $shown) {
$group = ticketLinkGroup($ticket_id);
return $group ? max(0, count(ticketLinkMembers($group)) - 1 - intval($shown)) : 0;
}
/** For a list of tickets: how many others each is related to that the agent can see - [ticket id => count]. */
function ticketLinkCounts(array $ticket_ids) {
global $mysqli;
$ids = implode(',', array_filter(array_map('intval', $ticket_ids)));
if ($ids === '' || !ticketLinksReady()) {
return [];
}
$sql = mysqli_query($mysqli, "SELECT mine.ticket_id, COUNT(others.ticket_id) FROM ticket_links mine
JOIN ticket_links others ON others.link_group = mine.link_group AND others.ticket_id <> mine.ticket_id
JOIN tickets ON tickets.ticket_id = others.ticket_id
WHERE mine.ticket_id IN ($ids)" . clientScopeSql('tickets.ticket_client_id') . "
GROUP BY mine.ticket_id");
$counts = [];
while ($row = mysqli_fetch_row($sql)) {
$counts[intval($row[0])] = intval($row[1]);
}
return $counts;
}
/*
* The tickets this one could be linked to, for its Link window - any client's the agent can open,
* not this one or those already related to it: open ones, and those closed in the last 90 days
* (a problem back again). Open first, then newest; at most 1000.
*/
function ticketLinkCandidates($ticket_id) {
global $mysqli;
$ticket_id = intval($ticket_id);
$exclude = array_merge([$ticket_id], ticketLinkMembers(ticketLinkGroup($ticket_id)));
$sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_client_id, ticket_resolved_at, ticket_closed_at,
client_name, ticket_status_name, ticket_status_color
FROM tickets
LEFT JOIN clients ON client_id = ticket_client_id
LEFT JOIN ticket_statuses ON ticket_status_id = ticket_status
WHERE tickets.ticket_id NOT IN (" . implode(',', $exclude) . ") AND ticket_archived_at IS NULL
AND (ticket_closed_at IS NULL OR ticket_closed_at > NOW() - INTERVAL 90 DAY)" . clientScopeSql('ticket_client_id') . "
ORDER BY (ticket_resolved_at IS NULL AND ticket_closed_at IS NULL) DESC, tickets.ticket_id DESC
LIMIT 1000");
return mysqli_fetch_all($sql, MYSQLI_ASSOC);
}
/** A merged ticket's related tickets go to the ticket it went into (ticketMergeInto()). */
function ticketLinkCarry($from_id, $to_id) {
global $mysqli;
$from_id = intval($from_id);
$group = ticketLinkGroup($from_id);
if (!$group) {
return;
}
ticketLinkTogether([$to_id, $from_id]);
$group = ticketLinkGroup($from_id);
mysqli_query($mysqli, "DELETE FROM ticket_links WHERE ticket_id = $from_id");
ticketLinkTidy($group);
}