diff --git a/CHANGELOG.md b/CHANGELOG.md
index 247ed2066..2a97c61bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
### Upgrading
-Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's eighteen database changes (3.6.6 to 3.8.4) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one 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, and two columns on agents' settings for their calendar color and what their calendar shows, and change nothing that is there. Nothing else is required. This release has eleven 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 nineteen database changes (3.6.6 to 3.8.5) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one 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, two columns on agents' settings for their calendar color and what their calendar shows, and a table for the agents helping on a ticket, and change nothing that is there. Nothing else is required. This release has eleven 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,8 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- Calendar: a 7 days view shows seven days from any day, and its arrows move a day at a time, so a booking can be dragged across a weekend without leaving the view. Bookings at the same time now sit side by side instead of on top of each other. From Mountaineer IT's build of ITFlow.
- 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: 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.
### Bug Fixes
@@ -230,6 +232,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- Database 3.8.2: `tickets.ticket_schedule_end` (NULL is `CALENDAR_TICKET_MINUTES` after the start) and `recurring_tickets.recurring_ticket_schedule_minutes` (default 60) - `ticketScheduleEndReady()`. `ticketSetSchedule($row, $schedule, $onsite, $end = null)` keeps the end (cancelling clears it) and `ticketScheduleIcs()` and `createiCalStr(..., $uid, $end)` write it as DTEND. `ticketScheduleEnd()`, `ticketScheduleMinutes()`, `ticketScheduleMinutesValue()` (15 to 1440), `ticketScheduleLengths()`, `ticketScheduleLengthText()`, `ticketScheduleWhenText()` and `ticketScheduleShortText()` word it; `ticketScheduleOverlapSql($from, $to)` finds bookings running into a range, used by the calendar's tickets source, the agent feed and `ticketScheduleConflicts()` (overlapping tickets and timed calendar events of the agent). `edit_ticket_schedule` takes `schedule_tech` (one of `ticketMentionAgents()`, given the ticket with `ticketChangeAssignee()`, the old agent sent `ticketMailScheduleAgentCancelled()`) and `schedule_minutes`; `add_ticket` and the recurring ticket handlers take `schedule_minutes`, and `recurringTicketBook()` books that long. `calendar_move` (`agent/ajax.php`) takes an `end` from a resize, or keeps the length on a move; ticket items are `durationEditable`. From Mountaineer IT's build of ITFlow.
- Database 3.8.3: `recurring_tickets.recurring_ticket_by_day` and `calendar_events.event_repeat_by_day`, an RFC 5545 BYDAY value (`3WE`, `-1FR`; NULL is the same date) - `byDayReady()` and the helpers in `functions/by_day.php`: `byDayRule()`, `byDayDate($year, $month, $rule)`, `byDayText()`, `byDayOptions($date)` (the rules a date can take), `byDayForDate()` (a posted rule, kept when the date takes it), `byDayFollow()` (a rule carried to a moved date) and `byDayField()`, the Repeats on picker filled by `js/repeat_on.js`, which posts `repeat_on` with `repeat_on_field`. `recurringTicketNextRun()` takes `$by_day` for month-based frequencies, passed by every caller, and `recurringTicketByDaySql()` saves it for `add_recurring_ticket`, `edit_recurring_ticket`, the bulk next run and `recurring_tickets/create` and `update` (`repeat_on`). `calendarEventFormSet()` saves `event_repeat_by_day` from `repeat_on`, or follows `repeat_on_current`; `expandRecurringEvent()`, `calendarRepeatText()` and `icsRepeatToRrule($repeat, $interval, $until, $all_day, $timezone, $by_day, $start)` (BYDAY, with BYMONTH for yearly) use it, through `calendarEventByDay()`. `events/create` and `update` take `event_repeat_by_day`. From Mountaineer IT's build of ITFlow.
- Database 3.8.4: `user_settings.user_config_calendar_color` (NULL is `calendarAgentDefaultColor()`, one of `CALENDAR_AGENT_COLORS` by user id) and `user_config_calendar_state` (JSON, `all` and `client`) - `calendarAgentSettingsReady()`. `calendarAgentColor()`, `calendarAgentColors()`, `calendarFirstName()`; `calendarAgentColorField()` (Account > Preferences, Admin > Users' Edit) posts `calendar_color` and `calendar_color_auto`, saved by `calendarAgentColorSave()` in `edit_your_user_preferences` and `edit_user`. The tickets source colors each booking by `ticket_assigned_to` and adds `agent_name` and `agent_full` (the name leaves `detail`); `calendarEventItems()` ends with `calendarEventItemsAgents()`, which colors an event by its attendee agents and leaves out of one agent's calendar an event assigned only to others. `calendarEventAgents()`, `calendarEventAgentChoices()`, `calendarEventDefaultAgents()` (New Event's `agent_id`), `calendarEventSetAgents()` and `calendarEventAgentsText()`; `assign_event` (`agent/post/event.php`) is the quick look's. `calendarLeftBehindSql()` and `calendarLeftBehindTickets()` behind `ajax.php?calendar_left_behind`, and items left behind get `itflow-cal-left-behind`. `ajax.php` `calendar_state` saves through `calendarUserStateSave()` and `calendarCleanState()` (`CALENDAR_VIEWS`); `agent/calendar.php` reads `calendarUserState()` into `data-saved-state`, which `agent/js/calendar.js` prefers to `localStorage`. `calendar_unscheduled` takes `user_id` 0 as everyone's, with `agent`. The `holidays` source reads `business_holidays`. The `timeGridSevenDays` view and `slotEventOverlap: false`. From Mountaineer IT's build of ITFlow.
+- Database 3.8.5: `ticket_helpers` (`ticket_id`, `user_id`, `follows_lead`, `schedule_start`, `schedule_end`, `added_by`, `added_at`; the lead stays `ticket_assigned_to`) - `functions/ticket_helpers.php`: `ticketHelpersReady()`, `ticketHelpers()`, `ticketHelperNames()`, `ticketHelpersTidy()` (a row for whoever is now the lead is cleared once a request, its booking cancelled and `ticketHelperLeadInvite()` sent), `ticketAssignedSql()` (Mine, the assigned filter and the dashboard's My tickets), `ticketHelperSave()`, `ticketHelperRemove()`, `ticketHelperMail()` (`ticketAgentEmailContent()`'s new `helper` kind; its own UID, `ticketHelperUid()`), `ticketHelpersLeadMoved()` from `ticketSetSchedule()` (their clashes join its conflicts), `ticketHelpersLeadCancelled()` from `ticketCancelSchedule()`, `ticketHelpersMailReplied()` from `ticketMailAssigneeReplied()`, `ticketHelperCalendarItems()` (kind `helper`, in the tickets source), `ticketHelperFeedItems()`, `ticketHelperDashboardItems()` and `ticketHelperConflicts()` (in `ticketScheduleConflicts()`). Helpers are `ticketMentionAgents()`. `agent/modals/ticket/ticket_helper.php`, `agent/post/ticket_helper.php` (`save_ticket_helper`, `remove_ticket_helper`), `ticketHelpersBadge()` in the list and board, and `calendar_move` with `kind` `helper` (their own time). From Mountaineer IT's build of ITFlow.
## [26.11.8]
diff --git a/admin/database_updates/3.8.5.php b/admin/database_updates/3.8.5.php
new file mode 100644
index 000000000..3eac3d7ca
--- /dev/null
+++ b/admin/database_updates/3.8.5.php
@@ -0,0 +1,29 @@
+ 86400) {
+ $end = date('Y-m-d H:i:s', strtotime($start) + ($helper['start'] !== '' ? ticketScheduleMinutes($helper['start'], $helper['end']) : CALENDAR_TICKET_MINUTES) * 60);
+ }
+ [$ok, $message, $conflicts] = ticketHelperSave($row, $helper['user_id'], 'own', $start, $end);
+ if (!$ok) {
+ $fail($message);
+ }
+ echo json_encode(['ok' => true, 'message' => $helper['user_name'] . ' booked on ' . ticketReference($row) . ' for ' . ticketScheduleWhenText($start, $end), 'conflicts' => $conflicts]);
+ exit;
+ }
+
$event = calendarEventRow($_POST['id'] ?? 0);
if (!$event) {
$fail('That event no longer exists.', 404);
@@ -2788,7 +2823,8 @@ if (isset($_GET['calendar_day'])) {
$day = [];
foreach ($items as $item) {
- if ($item['id'] === $skip_ticket) {
+ // The ticket being booked - the lead's booking, and the agents helping on it
+ if ($item['id'] === $skip_ticket || strpos($item['id'], 'helper-' . intval($_GET['ticket_id'] ?? 0) . '-') === 0) {
continue;
}
$all_day = !empty($item['allDay']);
diff --git a/agent/js/calendar.js b/agent/js/calendar.js
index 93553658e..215edda44 100644
--- a/agent/js/calendar.js
+++ b/agent/js/calendar.js
@@ -200,7 +200,7 @@
function saved(json) {
itflowToast(json.message, 'success');
if (json.conflicts && json.conflicts.length) {
- itflowToast('The same agent already has work then: ' + json.conflicts.join('; '), 'warning');
+ itflowToast('Already booked then - the agent, or those helping: ' + json.conflicts.join('; '), 'warning');
}
}
@@ -390,6 +390,30 @@
return;
}
+ // An agent helping on a ticket - moved or stretched, it becomes a time of their own
+ if (props.kind === 'helper') {
+ confirmDialog({
+ title: resized && end
+ ? 'Book ' + event.title.split(' ')[0] + ' for this agent until ' + end.toLocaleTimeString([], {hour: 'numeric', minute: '2-digit'}) + '?'
+ : 'Move ' + event.title.split(' ')[0] + ' for this agent to ' + words(start, false) + '?',
+ text: props.follows_lead ? 'It becomes a time of their own - no longer moving with the lead. They are emailed the new time.' : 'They are emailed the new time.',
+ confirmButtonText: resized ? 'Change it' : 'Move it'
+ }).then(function (result) {
+ if (!result.isConfirmed) {
+ info.revert();
+ return;
+ }
+ post({kind: 'helper', id: props.ticket_id, user_id: props.user_id, start: ymdhm(start), end: end && !event.allDay ? ymdhm(end) : '', all_day: event.allDay ? 1 : 0}, function (json) {
+ saved(json);
+ calendar.refetchEvents();
+ }, function (error) {
+ itflowToast(error, 'error');
+ info.revert();
+ });
+ });
+ return;
+ }
+
if (props.kind !== 'event') {
info.revert();
return;
diff --git a/agent/modals/ticket/ticket_helper.php b/agent/modals/ticket/ticket_helper.php
new file mode 100644
index 000000000..5156303eb
--- /dev/null
+++ b/agent/modals/ticket/ticket_helper.php
@@ -0,0 +1,168 @@
+ 'The database update for additional agents has not run yet.']);
+ exit;
+}
+$helpers = ticketHelpers($ticket_id);
+$edit_user_id = intval($_GET['user_id'] ?? 0);
+$helper = $helpers[$edit_user_id] ?? null;
+$is_open = ticketIsOpen($row);
+
+// Booked with the lead, at a time of their own, or not at all
+$mode = $helper ? (intval($helper['follows_lead']) === 1 ? 'lead' : ($helper['start'] !== '' ? 'own' : 'none')) : 'lead';
+$own_start = $mode === 'own' ? $helper['start'] : (string) ($row['ticket_schedule'] ?? '');
+$own_minutes = $mode === 'own' ? ticketScheduleMinutes($helper['start'], $helper['end'])
+ : ticketScheduleMinutes($row['ticket_schedule'], $row['ticket_schedule_end'] ?? null);
+$lead_when = $row['ticket_schedule'] ? ticketScheduleWhenText($row['ticket_schedule'], $row['ticket_schedule_end'] ?? null) : '';
+
+// Who can be added: the agents who can open the ticket, but the lead and those on it already
+$agents = [];
+if (!$helper) {
+ foreach (ticketMentionAgents($row['ticket_client_id']) as $user_id => $agent) {
+ if ($user_id !== $lead_id && !isset($helpers[$user_id])) {
+ $agents[$user_id] = $agent;
+ }
+ }
+}
+$day_user = $helper ? $edit_user_id : intval(array_key_first($agents) ?? 0);
+$day_name = $helper ? $helper['user_name'] : ($agents[$day_user]['name'] ?? '');
+
+ob_start();
+
+?>
+
+
+
+
+
+
+
+" . escapeHtml($row['user_name']) . "" : '');
if ($result['conflicts']) {
- flashAlert("$scheduled.
The same agent already has work at that time:
" . implode(",
", array_map('escapeHtml', $result['conflicts'])), 'warning');
+ flashAlert("$scheduled.
Already booked at that time - the agent, or those helping:
" . implode(",
", array_map('escapeHtml', $result['conflicts'])), 'warning');
} else {
flashAlert($scheduled);
}
diff --git a/agent/post/ticket_helper.php b/agent/post/ticket_helper.php
new file mode 100644
index 000000000..609f7fb8e
--- /dev/null
+++ b/agent/post/ticket_helper.php
@@ -0,0 +1,60 @@
+" . escapeHtml(ticketReference($row)) . " is resolved or closed - reopen it to add agents.", 'error');
+ redirect();
+ }
+
+ $mode = (string) ($_POST['helper_mode'] ?? 'lead');
+ $start = $end = '';
+ if ($mode === 'own') {
+ $start = ticketScheduleValue($_POST['scheduled_date_time'] ?? '');
+ $end = $start !== '' ? date('Y-m-d H:i:s', strtotime($start) + ticketScheduleMinutesValue($_POST['schedule_minutes'] ?? 0) * 60) : '';
+ }
+
+ [$ok, $message, $conflicts] = ticketHelperSave($row, intval($_POST['user_id'] ?? 0), $mode, $start, $end);
+ if (!$ok) {
+ flashAlert(escapeHtml($message), 'error');
+ redirect();
+ }
+
+ if ($conflicts) {
+ flashAlert(escapeHtml($message) . ".
They already have work at that time:
" . implode(",
", array_map('escapeHtml', $conflicts)), 'warning');
+ } else {
+ flashAlert(escapeHtml($message));
+ }
+
+ redirect();
+
+}
+
+if (isset($_GET['remove_ticket_helper'])) {
+
+ validateCSRFToken();
+
+ $row = ticketForRequest($_GET['remove_ticket_helper'], 2);
+
+ $name = ticketHelperRemove($row, intval($_GET['user_id'] ?? 0));
+ if ($name === false) {
+ flashAlert('That agent is not on this ticket.', 'error');
+ redirect();
+ }
+
+ flashAlert(escapeHtml($name) . ' taken off the ticket');
+
+ redirect();
+
+}
diff --git a/agent/ticket.php b/agent/ticket.php
index d6837d9eb..659cb72fe 100644
--- a/agent/ticket.php
+++ b/agent/ticket.php
@@ -1235,6 +1235,36 @@ if (isset($_GET['ticket_id'])) {
+ = 2;
+ if ($helpers || ($can_change_helpers && ticketIsOpen($ticket))) { ?>
+
+
+
- = $can_edit ? quickPick('assignee', $ticket_id, (string) intval($row['ticket_assigned_to']), $assignee) : $assignee ?>
+ = $can_edit ? quickPick('assignee', $ticket_id, (string) intval($row['ticket_assigned_to']), $assignee) : $assignee ?>= ticketHelpersBadge($ticket_id) ?>
diff --git a/agent/ticket_list.php b/agent/ticket_list.php
index 38a1e983a..ef699b316 100644
--- a/agent/ticket_list.php
+++ b/agent/ticket_list.php
@@ -227,6 +227,7 @@ $sort_link = function ($column, $label, $class = '') use ($url_query_strings_sor
= $assignee ?>
+ = ticketHelpersBadge($ticket_id) ?>
diff --git a/agent/tickets.php b/agent/tickets.php
index e6e232671..c65a1a18c 100644
--- a/agent/tickets.php
+++ b/agent/tickets.php
@@ -107,7 +107,8 @@ if ($assigned_filter === 'unassigned') {
$filter_sql[] = 'AND ticket_assigned_to = 0';
} elseif (intval($assigned_filter)) {
$assigned_filter = intval($assigned_filter);
- $filter_sql[] = "AND ticket_assigned_to = $assigned_filter";
+ // The lead, or helping (functions/ticket_helpers.php)
+ $filter_sql[] = "AND " . ticketAssignedSql($assigned_filter);
} else {
$assigned_filter = '';
}
@@ -214,7 +215,7 @@ $base_sql = $view === 'kanban' ? 'tickets.ticket_closed_at IS NULL' : $open_sql;
$shows = [
'open' => ['label' => $view === 'kanban' ? 'On the board' : 'Open', 'where' => $base_sql,
'title' => $view === 'kanban' ? 'Everything not closed yet' : 'Neither resolved nor closed'],
- 'mine' => ['label' => 'Mine', 'icon' => 'fa-user-check', 'where' => "$base_sql AND ticket_assigned_to = " . intval($session_user_id)],
+ 'mine' => ['label' => 'Mine', 'icon' => 'fa-user-check', 'where' => "$base_sql AND " . ticketAssignedSql($session_user_id)],
'unassigned' => ['label' => 'Unassigned', 'icon' => 'fa-user-slash', 'where' => "$base_sql AND ticket_assigned_to = 0", 'alarm' => 'warning'],
'reply' => ['label' => 'Needs reply', 'icon' => 'fa-reply', 'where' => ticketNeedsReplySql(), 'alarm' => 'warning',
'title' => 'The client spoke last, or nobody has replied yet'],
diff --git a/db.sql b/db.sql
index 9398382f1..d10f5b980 100644
--- a/db.sql
+++ b/db.sql
@@ -4059,6 +4059,28 @@ CREATE TABLE `ticket_fill_ins` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `ticket_helpers`
+--
+
+DROP TABLE IF EXISTS `ticket_helpers`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8mb4 */;
+CREATE TABLE `ticket_helpers` (
+ `ticket_id` int(11) NOT NULL,
+ `user_id` int(11) NOT NULL,
+ `follows_lead` tinyint(1) NOT NULL DEFAULT 1,
+ `schedule_start` datetime DEFAULT NULL,
+ `schedule_end` datetime DEFAULT NULL,
+ `added_by` int(11) NOT NULL DEFAULT 0,
+ `added_at` datetime NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`ticket_id`,`user_id`),
+ KEY `ticket_helpers_user` (`user_id`),
+ CONSTRAINT `ticket_helpers_ticket` FOREIGN KEY (`ticket_id`) REFERENCES `tickets` (`ticket_id`) ON DELETE CASCADE,
+ CONSTRAINT `ticket_helpers_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_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_history`
--
diff --git a/functions.php b/functions.php
index ef06b1e34..8825169e9 100644
--- a/functions.php
+++ b/functions.php
@@ -70,6 +70,7 @@ require_once __DIR__ . '/functions/database_collation.php';
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_status.php';
require_once __DIR__ . '/functions/ticket_template.php';
require_once __DIR__ . '/functions/ticket_template_transfer.php';
diff --git a/functions/calendar.php b/functions/calendar.php
index ebc8a8f78..4379577d0 100644
--- a/functions/calendar.php
+++ b/functions/calendar.php
@@ -690,6 +690,8 @@ function calendarSourceItems($key, $from, $to, array $opts = []) {
'detail' => implode(' · ', array_filter([$left_behind ? 'Left behind' : '', $agent === '' ? 'Unassigned' : '', $row['ticket_status_name']]))],
] + $base;
}
+ // The agents helping, at the lead's time or their own (functions/ticket_helpers.php)
+ $items = array_merge($items, ticketHelperCalendarItems($from, $to, $client_id, $user_id, $can_move));
} elseif ($key === 'projects') {
$sql = mysqli_query($mysqli, "SELECT project_id, project_prefix, project_number, project_name, project_start, project_due, project_client_id, client_name
FROM projects LEFT JOIN clients ON client_id = project_client_id
@@ -1368,6 +1370,8 @@ function calendarUserFeedItems(array $feed, $from, $to) {
'busy' => $busy,
];
}
+ // And the tickets they are helping on (functions/ticket_helpers.php)
+ $items = array_merge($items, ticketHelperFeedItems($feed, $from, $to));
}
if (!empty($feed['feed_events'])) {
diff --git a/functions/dashboard.php b/functions/dashboard.php
index ba885762f..5424f09dc 100644
--- a/functions/dashboard.php
+++ b/functions/dashboard.php
@@ -397,7 +397,8 @@ function dashboardMyTickets($limit = 8) {
global $mysqli, $session_user_id;
$user_id = intval($session_user_id);
- $where = "ticket_assigned_to = $user_id AND ticket_resolved_at IS NULL " . clientScopeSql('ticket_client_id');
+ // Mine - leading it, or helping (functions/ticket_helpers.php)
+ $where = ticketAssignedSql($user_id) . " AND ticket_resolved_at IS NULL " . clientScopeSql('ticket_client_id');
$sql = mysqli_query($mysqli, "
SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_client_id,
@@ -463,6 +464,9 @@ function dashboardSchedule($days = 7, $limit = 30) {
];
}
+ // Tickets I am helping on, booked
+ $items = array_merge($items, ticketHelperDashboardItems($from, $to));
+
// Projects I manage, starting or due - all day
$sql = mysqli_query($mysqli, "
SELECT project_id, project_prefix, project_number, project_name, project_start, project_due, project_client_id, client_name
diff --git a/functions/ticket.php b/functions/ticket.php
index ebe5b233d..e30fbb0c6 100644
--- a/functions/ticket.php
+++ b/functions/ticket.php
@@ -877,6 +877,8 @@ function ticketMailAgent($user_id) {
* mentioned an internal note mentions them - by (who), message (the note, HTML), reply_id (the note, to open)
* sla an SLA alert - track: response or resolution, breached: true once missed, due (when)
* scheduled the work was booked - when, where, or cancelled: true (handed_over: true, it went to someone else)
+ * helper helping on it (functions/ticket_helpers.php) - when and where they are booked, lead (the lead's
+ * name), or cancelled: true, or added: true (on it, not booked - by, who added them)
* paid the invoice it waits on was paid - invoice (its number), amount, reopened (On Hold to Open)
*/
function ticketAgentEmailContent(array $row, $kind, array $opts = []) {
@@ -933,6 +935,24 @@ function ticketAgentEmailContent(array $row, $kind, array $opts = []) {
$email['summary'] += ['When' => (string) $opts['when'], 'Where' => !empty($row['ticket_onsite']) ? (trim((string) ($opts['where'] ?? '')) !== '' ? (string) $opts['where'] : 'Onsite') : 'Remote'];
$email['history'] = ticketEmailHistory($row, ['limit' => 2, 'label' => 'What it is about']);
}
+ } elseif ($kind === 'helper') {
+ $lead = trim((string) ($opts['lead'] ?? ''));
+ $lead_line = $lead !== '' ? " $lead is the lead agent." : '';
+ if (!empty($opts['cancelled'])) {
+ $email['kind'] = 'Visit cancelled';
+ $email['tone'] = 'secondary';
+ $email['intro'] = ["Your time helping on $reference is cancelled - the calendar file with this email takes it out of your calendar."];
+ } elseif (!empty($opts['added'])) {
+ $email['kind'] = 'Helping';
+ $email['intro'] = [($by !== '' ? $by : 'Someone') . " added you to help on $reference.$lead_line It isn't booked on your calendar."];
+ $email['message'] = ['html' => (string) $row['ticket_details'], 'label' => 'Details'];
+ $email['history'] = ticketEmailHistory($row, ['request' => false, 'label' => 'Replies so far']);
+ } else {
+ $email['kind'] = 'Work booked';
+ $email['intro'] = ["You're booked to help on $reference for " . $opts['when'] . " - the calendar file with this email adds it to your calendar.$lead_line"];
+ $email['summary'] += ['When' => (string) $opts['when'], 'Where' => !empty($row['ticket_onsite']) ? (trim((string) ($opts['where'] ?? '')) !== '' ? (string) $opts['where'] : 'Onsite') : 'Remote'];
+ $email['history'] = ticketEmailHistory($row, ['limit' => 2, 'label' => 'What it is about']);
+ }
} elseif ($kind === 'sla') {
$track = ($opts['track'] ?? 'response') === 'resolution' ? 'resolution' : 'response';
$due = !empty($opts['due']) ? date('D j M, g:i A', strtotime($opts['due'])) : '';
@@ -970,7 +990,7 @@ function ticketMailNewTicketAddress($ticket_id, $how) {
$subject, ticketAgentEmailContent($row, 'new', ['how' => $how]));
}
-/** Tell the agent a ticket is assigned to that the client replied - $how portal or email, $reply its HTML, $by who. */
+/** Tell the agent a ticket is assigned to that the client replied - and the agents helping on it - $how portal or email, $reply its HTML, $by who. */
function ticketMailAssigneeReplied($ticket_id, $how, $reply, $by) {
global $config_app_name;
$row = ticketRow($ticket_id);
@@ -980,7 +1000,8 @@ function ticketMailAssigneeReplied($ticket_id, $how, $reply, $by) {
}
return ticketMailAgents([$agent + ['footnote' => 'You get this as the agent ' . ticketReference($row) . ' is assigned to.']],
($config_app_name ?: 'ITFlow') . " - Ticket updated - [" . ticketReference($row) . "] " . $row['ticket_subject'],
- ticketAgentEmailContent($row, 'replied', ['how' => $how, 'message' => (string) $reply, 'by' => (string) $by]));
+ ticketAgentEmailContent($row, 'replied', ['how' => $how, 'message' => (string) $reply, 'by' => (string) $by]))
+ + ticketHelpersMailReplied($row, $agent, $how, $reply, $by);
}
/*
@@ -2377,7 +2398,8 @@ function ticketScheduleOverlapSql($from, $to) {
/*
* An agent's other open work that overlaps $start - $end, as plain text lines:
- * their booked tickets, and the timed calendar events they are on. A ticket for
+ * their booked tickets, the timed calendar events they are on, and their
+ * bookings helping on other tickets. A ticket for
* a client the agent booking it can't see is only said to be there.
*/
function ticketScheduleConflicts($user_id, $start, $end, $ticket_id = 0) {
@@ -2406,7 +2428,8 @@ function ticketScheduleConflicts($user_id, $start, $end, $ticket_id = 0) {
}
}
}
- return $conflicts;
+ // Tickets they are helping on (functions/ticket_helpers.php)
+ return array_merge($conflicts, ticketHelperConflicts($user_id, $start, $end, $ticket_id));
}
/*
@@ -2426,8 +2449,9 @@ function ticketScheduleIcs(array $row, $schedule, $end = null) {
/**
* Book the work on a ticket for $schedule ('Y-m-d H:i:s') to $end (the usual
* length when none), onsite or remote: the agent, the contact and the watchers
- * are emailed with the calendar file, and it is noted on the ticket. Returns
- * ['when_text' => ..., 'conflicts' => the same agent's other work at that
+ * are emailed with the calendar file, and it is noted on the ticket. Helpers
+ * who follow the lead are sent the new time. Returns ['when_text' => ...,
+ * 'conflicts' => the same agent's - and those helpers' - other work at that
* time, as plain text (ticketScheduleConflicts())].
*/
function ticketSetSchedule(array $row, $schedule, $onsite, $end = null) {
@@ -2449,6 +2473,9 @@ function ticketSetSchedule(array $row, $schedule, $onsite, $end = null) {
$when_text = ticketScheduleWhenText($schedule, $end);
ticketMailSchedule($mail_row, $cal_str, false, $when_text);
+ // The agents helping at the same time move with it, and are sent the new time (functions/ticket_helpers.php)
+ $conflicts = array_merge($conflicts, ticketHelpersLeadMoved($ticket_id));
+
// Note it on the ticket
$note = escapeSql("Ticket scheduled for $when_text " . ($onsite ? '(onsite).' : '(remote).'));
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$note', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = " . intval($session_user_id) . ", ticket_reply_ticket_id = $ticket_id");
@@ -2479,6 +2506,7 @@ function ticketCancelSchedule(array $row) {
$cal_subject = intval($mail_row['ticket_number']) . ": " . $mail_row['client_name'] . " - " . $mail_row['ticket_subject'];
$cal_str = createiCalStrCancel($old_schedule, $cal_subject, getTicketCalendarUid($ticket_id));
ticketMailSchedule($mail_row, $cal_str, true, '');
+ ticketHelpersLeadCancelled($ticket_id, $old_schedule);
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket schedule cancelled.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = " . intval($session_user_id) . ", ticket_reply_ticket_id = $ticket_id");
diff --git a/functions/ticket_helpers.php b/functions/ticket_helpers.php
new file mode 100644
index 000000000..6fab191cc
--- /dev/null
+++ b/functions/ticket_helpers.php
@@ -0,0 +1,514 @@
+=');
+ }
+ return $ready;
+}
+
+/*
+ * A helper who has since become the lead is no longer a helper - cleared once a
+ * request, before helpers are read. A booking they had as a helper is cancelled,
+ * and as the lead they are sent the ticket's own, unless that just went to them.
+ */
+function ticketHelpersTidy() {
+ global $mysqli;
+ static $done = false;
+ if ($done || !ticketHelpersReady()) {
+ return;
+ }
+ $done = true;
+ $sql = mysqli_query($mysqli, "SELECT th.ticket_id, th.user_id, " . TICKET_HELPER_START_SQL . " AS start FROM ticket_helpers th
+ JOIN tickets ON tickets.ticket_id = th.ticket_id WHERE th.user_id = tickets.ticket_assigned_to");
+ $rows = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $rows[] = $row;
+ }
+ if (!$rows) {
+ return;
+ }
+ mysqli_query($mysqli, "DELETE th FROM ticket_helpers th JOIN tickets ON tickets.ticket_id = th.ticket_id WHERE th.user_id = tickets.ticket_assigned_to");
+ foreach ($rows as $row) {
+ if (!empty($row['start'])) {
+ ticketHelperMail($row['ticket_id'], $row['user_id'], $row['start'], null, 'cancelled');
+ ticketHelperLeadInvite($row['ticket_id']);
+ }
+ }
+}
+
+/** A ticket's helpers (not the lead), by name, with their booking: user_id => row, start and end '' when not booked. */
+function ticketHelpers($ticket_id) {
+ global $mysqli;
+ $ticket_id = intval($ticket_id);
+ if (!$ticket_id || !ticketHelpersReady()) {
+ return [];
+ }
+ ticketHelpersTidy();
+ $sql = mysqli_query($mysqli, "SELECT th.ticket_id, th.user_id, th.follows_lead, th.schedule_start, th.schedule_end, th.added_by, th.added_at,
+ user_name, user_email, user_avatar, " . TICKET_HELPER_START_SQL . " AS start, " . TICKET_HELPER_END_SQL . " AS end
+ FROM ticket_helpers th
+ JOIN tickets ON tickets.ticket_id = th.ticket_id
+ JOIN users ON users.user_id = th.user_id
+ WHERE th.ticket_id = $ticket_id AND th.user_id <> tickets.ticket_assigned_to AND users.user_archived_at IS NULL
+ ORDER BY user_name");
+ $helpers = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $row['end'] = $row['start'] ? ticketScheduleEnd($row['start'], $row['end']) : '';
+ $row['start'] = (string) $row['start'];
+ $helpers[intval($row['user_id'])] = $row;
+ }
+ return $helpers;
+}
+
+/** Every ticket's helpers, ticket_id => [user_id => name] - read once a page, for the lists. */
+function ticketHelperNames() {
+ global $mysqli;
+ static $names = null;
+ if ($names === null) {
+ $names = [];
+ if (ticketHelpersReady()) {
+ ticketHelpersTidy();
+ $sql = mysqli_query($mysqli, "SELECT th.ticket_id, th.user_id, user_name FROM ticket_helpers th
+ JOIN tickets ON tickets.ticket_id = th.ticket_id
+ JOIN users ON users.user_id = th.user_id
+ WHERE th.user_id <> tickets.ticket_assigned_to AND users.user_archived_at IS NULL ORDER BY user_name");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $names[intval($row['ticket_id'])][intval($row['user_id'])] = $row['user_name'];
+ }
+ }
+ }
+ return $names;
+}
+
+/** SQL: the ticket is this agent's - the lead, or helping. $id_column is how the query names the ticket's id. */
+function ticketAssignedSql($user_id, $id_column = 'tickets.ticket_id') {
+ $user_id = intval($user_id);
+ if (!ticketHelpersReady()) {
+ return "ticket_assigned_to = $user_id";
+ }
+ return "(ticket_assigned_to = $user_id OR $id_column IN (SELECT th.ticket_id FROM ticket_helpers th WHERE th.user_id = $user_id))";
+}
+
+/** A helper's booking in words: "Same time as the lead", a time, or "Not booked". */
+function ticketHelperWhenText(array $helper) {
+ if (intval($helper['follows_lead']) === 1) {
+ return $helper['start'] !== '' ? 'Same time as the lead' : 'With the lead - not booked yet';
+ }
+ return $helper['start'] !== '' ? ticketScheduleShortText($helper['start'], $helper['end']) : 'Not booked';
+}
+
+/** The tickets list's assignee cell: "+2" after the lead - "Helping" when you are one of them. */
+function ticketHelpersBadge($ticket_id) {
+ global $session_user_id;
+ $names = ticketHelperNames()[intval($ticket_id)] ?? [];
+ if (!$names) {
+ return '';
+ }
+ $mine = isset($names[intval($session_user_id)]);
+ return ' '
+ . ($mine ? 'Helping' : '+' . count($names)) . '';
+}
+
+/*
+ * ---------- adding, changing and taking off ----------
+ */
+
+/*
+ * Add a helper, or change their booking. $mode: lead (the lead's time), own
+ * ($start to $end) or none. They are emailed their booking, its cancellation, or
+ * that they are on it, and it is noted on the ticket. [ok, message (plain text),
+ * conflicts - their other work at that time].
+ */
+function ticketHelperSave(array $ticket, $user_id, $mode, $start = '', $end = '') {
+ global $mysqli, $session_user_id, $session_name;
+ $ticket_id = intval($ticket['ticket_id']);
+ $user_id = intval($user_id);
+ $who = stripslashes((string) $session_name);
+ if (!ticketHelpersReady()) {
+ return [false, 'The database update for additional agents has not run yet.', []];
+ }
+ $agents = ticketMentionAgents($ticket['ticket_client_id']);
+ if (!isset($agents[$user_id])) {
+ return [false, 'Pick an agent who can open this ticket.', []];
+ }
+ $name = $agents[$user_id]['name'];
+ if ($user_id === intval($ticket['ticket_assigned_to'])) {
+ return [false, "$name is the lead agent on this ticket.", []];
+ }
+ $mode = in_array($mode, ['lead', 'own', 'none'], true) ? $mode : 'lead';
+ if ($mode === 'own' && ($start === '' || $end === '' || $end <= $start)) {
+ return [false, "Pick the date and time for $name.", []];
+ }
+
+ $before = ticketHelpers($ticket_id)[$user_id] ?? null;
+ $follows = $mode === 'lead' ? 1 : 0;
+ $start_sql = $mode === 'own' ? "'" . escapeSql($start) . "'" : 'NULL';
+ $end_sql = $mode === 'own' ? "'" . escapeSql($end) . "'" : 'NULL';
+ mysqli_query($mysqli, "INSERT INTO ticket_helpers SET ticket_id = $ticket_id, user_id = $user_id, follows_lead = $follows,
+ schedule_start = $start_sql, schedule_end = $end_sql, added_by = " . intval($session_user_id) . "
+ ON DUPLICATE KEY UPDATE follows_lead = $follows, schedule_start = $start_sql, schedule_end = $end_sql");
+ $after = ticketHelpers($ticket_id)[$user_id] ?? null;
+
+ $when = $after && $after['start'] !== '' ? ticketScheduleWhenText($after['start'], $after['end']) : '';
+ $conflicts = $when !== '' ? ticketScheduleConflicts($user_id, $after['start'], $after['end'], $ticket_id) : [];
+
+ // Tell them - their booking, new or moved; its cancellation; or that they are on it
+ $was_booked = $before && $before['start'] !== '';
+ $changed = !$before || $before['start'] !== ($after['start'] ?? '') || $before['end'] !== ($after['end'] ?? '');
+ if ($when !== '' && $changed) {
+ ticketHelperMail($ticket_id, $user_id, $after['start'], $after['end'], 'booked');
+ } elseif ($when === '' && $was_booked) {
+ ticketHelperMail($ticket_id, $user_id, $before['start'], $before['end'], 'cancelled');
+ } elseif (!$before) {
+ ticketHelperMail($ticket_id, $user_id, '', '', 'added');
+ }
+
+ $what = $mode === 'lead' ? 'at the same time as the lead' . ($when !== '' ? " ($when)" : '') : ($mode === 'own' ? "for $when" : 'not booked');
+ $note = $before ? "$name's booking changed - $what." : "$name added as an additional agent - $what.";
+ mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . escapeSql($note) . "', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = " . intval($session_user_id) . ", ticket_reply_ticket_id = $ticket_id");
+ logTicketHistory($ticket_id, escapeSql("$who " . ($before ? "changed $name's booking - $what" : "added $name as an additional agent - $what")));
+ logAudit("Ticket", "Edit", escapeSql("$who " . ($before ? "changed $name's booking on " : "added $name to ") . ticketReference($ticket)), intval($ticket['ticket_client_id']), $ticket_id);
+
+ // Told in ITFlow too, when someone else added them
+ if (!$before && $user_id !== intval($session_user_id)) {
+ mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '" . escapeSql('Ticket ' . ticketReference($ticket) . ' - ' . $ticket['ticket_subject'] . " - $who added you to help") . "',
+ notification_action = '/agent/" . escapeSql(ticketUrl($ticket_id, $ticket['ticket_client_id'])) . "', notification_client_id = " . intval($ticket['ticket_client_id']) . ", notification_user_id = $user_id");
+ }
+
+ return [true, $before ? "$name's booking is saved" : "$name added to the ticket", $conflicts];
+}
+
+/** Take a helper off a ticket - a booking they had is cancelled. Their name, or false when they weren't on it. */
+function ticketHelperRemove(array $ticket, $user_id) {
+ global $mysqli, $session_user_id, $session_name;
+ $ticket_id = intval($ticket['ticket_id']);
+ $user_id = intval($user_id);
+ $who = stripslashes((string) $session_name);
+ $helper = ticketHelpers($ticket_id)[$user_id] ?? null;
+ if (!$helper) {
+ return false;
+ }
+ mysqli_query($mysqli, "DELETE FROM ticket_helpers WHERE ticket_id = $ticket_id AND user_id = $user_id");
+ if ($helper['start'] !== '') {
+ ticketHelperMail($ticket_id, $user_id, $helper['start'], $helper['end'], 'cancelled');
+ }
+ $name = $helper['user_name'];
+ mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . escapeSql("$name taken off the ticket.") . "', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = " . intval($session_user_id) . ", ticket_reply_ticket_id = $ticket_id");
+ logTicketHistory($ticket_id, escapeSql("$who took $name off the ticket"));
+ logAudit("Ticket", "Edit", escapeSql("$who took $name off " . ticketReference($ticket)), intval($ticket['ticket_client_id']), $ticket_id);
+ return $name;
+}
+
+/*
+ * ---------- the lead's booking (ticketSetSchedule(), ticketCancelSchedule()) ----------
+ */
+
+/** The lead's booking moved: helpers who follow it are sent the new time. Their clashes, "Name: ..." lines. */
+function ticketHelpersLeadMoved($ticket_id) {
+ $conflicts = [];
+ foreach (ticketHelpers($ticket_id) as $user_id => $helper) {
+ if (intval($helper['follows_lead']) === 1 && $helper['start'] !== '') {
+ ticketHelperMail($ticket_id, $user_id, $helper['start'], $helper['end'], 'booked');
+ foreach (ticketScheduleConflicts($user_id, $helper['start'], $helper['end'], $ticket_id) as $line) {
+ $conflicts[] = $helper['user_name'] . ': ' . $line;
+ }
+ }
+ }
+ return $conflicts;
+}
+
+/** The lead's booking cancelled: helpers who followed it are sent the cancellation. */
+function ticketHelpersLeadCancelled($ticket_id, $old_start) {
+ if (!$old_start) {
+ return;
+ }
+ foreach (ticketHelpers($ticket_id) as $user_id => $helper) {
+ if (intval($helper['follows_lead']) === 1) {
+ ticketHelperMail($ticket_id, $user_id, $old_start, '', 'cancelled');
+ }
+ }
+}
+
+/*
+ * ---------- emails ----------
+ */
+
+/** A helper's booking's calendar UID - their own, so it never replaces the lead's. */
+function ticketHelperUid($ticket_id, $user_id) {
+ return 'ticket-' . intval($ticket_id) . '-helper-' . intval($user_id) . '@' . ($_SERVER['SERVER_NAME'] ?? 'itflow');
+}
+
+/*
+ * Email a helper - $kind booked (with the calendar file), cancelled (its
+ * cancellation) or added (on it, not booked). Nothing new goes to one who can
+ * no longer open the ticket; a cancellation still does, to clear their calendar.
+ */
+function ticketHelperMail($ticket_id, $user_id, $start, $end, $kind) {
+ global $session_name;
+ if (!emailReady()) {
+ return;
+ }
+ $ticket = ticketRow($ticket_id);
+ $agent = ticketMailAgent($user_id);
+ if (!$ticket || !$agent) {
+ return;
+ }
+ if ($kind !== 'cancelled' && !isset(ticketMentionAgents($ticket['ticket_client_id'])[intval($user_id)])) {
+ return;
+ }
+ $reference = ticketReference($ticket);
+ $mail_row = ticketScheduleRow($ticket_id);
+ $title = intval($ticket['ticket_number']) . ": " . $ticket['client_name'] . " - " . $ticket['ticket_subject'];
+ $opts = ['lead' => (string) ($ticket['user_name'] ?? ''), 'by' => stripslashes((string) $session_name)];
+ $cal_str = '';
+ if ($kind === 'booked') {
+ $opts['when'] = ticketScheduleWhenText($start, $end);
+ $opts['where'] = (string) ($mail_row['location_address'] ?? '');
+ $subject = "Ticket Scheduled - [$reference] - " . $ticket['ticket_subject'];
+ $cal_str = createiCalStr($start, $title, mb_substr(strip_tags((string) $ticket['ticket_details']), 0, 100) . ' - ' . ticketAgentUrl($ticket),
+ (string) ($mail_row['location_address'] ?? ''), ticketHelperUid($ticket_id, $user_id), ticketScheduleEnd($start, $end));
+ } elseif ($kind === 'cancelled') {
+ $opts['cancelled'] = true;
+ $subject = "Ticket Schedule Cancelled - [$reference] - " . $ticket['ticket_subject'];
+ $cal_str = createiCalStrCancel($start, $title, ticketHelperUid($ticket_id, $user_id));
+ } else {
+ $opts['added'] = true;
+ $subject = "Ticket - [$reference] - " . $ticket['ticket_subject'];
+ }
+ emailQueue([$agent + ['footnote' => "You get this as an agent helping on $reference."]], $subject,
+ ticketAgentEmailContent($ticket, 'helper', $opts), ['from' => ticketEmailFrom()] + ($cal_str !== '' ? ['cal_str' => $cal_str] : []));
+}
+
+/*
+ * The ticket's own booking, to its lead alone - a helper who became the lead
+ * (ticketHelpersTidy()) - unless it went to them in the last 10 minutes.
+ */
+function ticketHelperLeadInvite($ticket_id) {
+ global $mysqli;
+ $ticket = ticketRow($ticket_id);
+ $agent = $ticket ? ticketMailAgent($ticket['ticket_assigned_to']) : null;
+ if (!$ticket || !$agent || empty($ticket['ticket_schedule']) || !ticketIsOpen($ticket) || !emailReady()) {
+ return;
+ }
+ $reference = ticketReference($ticket);
+ $subject = "Ticket Scheduled - [$reference] - " . $ticket['ticket_subject'];
+ if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM email_queue WHERE email_recipient = '" . escapeSql($agent['email']) . "' AND email_subject = '" . escapeSql($subject) . "'
+ AND email_queued_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND email_cal_str LIKE '%UID:" . escapeSql(getTicketCalendarUid($ticket['ticket_id'])) . "%' LIMIT 1"))) {
+ return;
+ }
+ $mail_row = ticketScheduleRow($ticket['ticket_id']);
+ $end = ticketScheduleEnd($ticket['ticket_schedule'], $ticket['ticket_schedule_end'] ?? null);
+ emailQueue([$agent + ['footnote' => "You get this as the agent $reference is assigned to."]], $subject,
+ ticketAgentEmailContent($ticket, 'scheduled', ['when' => ticketScheduleWhenText($ticket['ticket_schedule'], $end), 'where' => (string) ($mail_row['location_address'] ?? '')]),
+ ['from' => ticketEmailFrom(), 'cal_str' => ticketScheduleIcs($mail_row, $ticket['ticket_schedule'], $end)]);
+}
+
+/*
+ * A client replied (ticketMailAssigneeReplied()): the same email the lead gets,
+ * to each helper who can open the ticket. As for the lead, a ticket nobody
+ * leads mails nobody. How many went.
+ */
+function ticketHelpersMailReplied(array $row, array $lead, $how, $reply, $by) {
+ global $config_app_name;
+ if (!ticketHelpersReady()) {
+ return 0;
+ }
+ $agents = ticketMentionAgents($row['ticket_client_id']);
+ $recipients = [];
+ foreach (ticketHelpers($row['ticket_id']) as $user_id => $helper) {
+ if (!isset($agents[$user_id]) || !filter_var($helper['user_email'], FILTER_VALIDATE_EMAIL) || strcasecmp($helper['user_email'], $lead['email']) === 0) {
+ continue;
+ }
+ $recipients[] = ['email' => $helper['user_email'], 'name' => $helper['user_name'], 'footnote' => 'You get this as an agent helping on ' . ticketReference($row) . '.'];
+ }
+ if (!$recipients) {
+ return 0;
+ }
+ return ticketMailAgents($recipients, ($config_app_name ?: 'ITFlow') . " - Ticket updated - [" . ticketReference($row) . "] " . $row['ticket_subject'],
+ ticketAgentEmailContent($row, 'replied', ['how' => $how, 'message' => (string) $reply, 'by' => (string) $by]));
+}
+
+/*
+ * ---------- calendar, dashboard and clashes ----------
+ */
+
+/*
+ * Helpers' bookings for the calendar (the tickets source) - in the helper's
+ * colour, with their name. $user_id: only that agent's (0 for everyone's).
+ */
+function ticketHelperCalendarItems($from, $to, $client_id, $user_id, $can_move) {
+ global $mysqli;
+ if (!ticketHelpersReady()) {
+ return [];
+ }
+ ticketHelpersTidy();
+ $from = escapeSql($from);
+ $to = escapeSql($to);
+ $client_id = intval($client_id);
+ $user_id = intval($user_id);
+ $start = TICKET_HELPER_START_SQL;
+ $end = TICKET_HELPER_END_SQL;
+ $sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_onsite, ticket_client_id,
+ ticket_resolved_at, ticket_closed_at, client_name, ticket_status_name, th.user_id, th.follows_lead, helper.user_name, lead.user_name AS lead_name,
+ $start AS start, $end AS end
+ FROM ticket_helpers th
+ JOIN tickets ON tickets.ticket_id = th.ticket_id
+ JOIN users helper ON helper.user_id = th.user_id
+ LEFT JOIN users lead ON lead.user_id = ticket_assigned_to
+ LEFT JOIN clients ON client_id = ticket_client_id
+ LEFT JOIN ticket_statuses ON ticket_status_id = ticket_status
+ WHERE $start BETWEEN DATE_SUB('$from', INTERVAL 1 DAY) AND '$to'
+ AND COALESCE(IF($end > $start, $end, NULL), DATE_ADD($start, INTERVAL " . intval(CALENDAR_TICKET_MINUTES) . " MINUTE)) > '$from'
+ AND ticket_archived_at IS NULL AND th.user_id <> ticket_assigned_to AND helper.user_archived_at IS NULL
+ " . ($client_id ? "AND ticket_client_id = $client_id" : '') . "
+ " . ($user_id ? "AND th.user_id = $user_id" : '') . "
+ " . clientScopeSql('ticket_client_id'));
+ $items = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $open = ticketIsOpen($row);
+ $ticket_id = intval($row['ticket_id']);
+ $items[] = [
+ 'id' => "helper-$ticket_id-" . intval($row['user_id']),
+ 'title' => calendarTicketTitle($row, !$client_id) . ' (helping)',
+ 'start' => $row['start'],
+ 'end' => ticketScheduleEnd($row['start'], $row['end']),
+ 'allDay' => false,
+ 'editable' => $can_move && $open,
+ 'durationEditable' => $can_move && $open,
+ 'color' => calendarAgentColor($row['user_id']),
+ 'className' => $open ? '' : 'itflow-cal-done',
+ 'extendedProps' => ['kind' => 'helper', 'ticket_id' => $ticket_id, 'user_id' => intval($row['user_id']), 'follows_lead' => intval($row['follows_lead']),
+ 'client_id' => intval($row['ticket_client_id']),
+ 'icon' => intval($row['ticket_onsite']) ? 'fa-car' : 'fa-headset',
+ 'modal' => "modals/ticket/ticket.php?id=$ticket_id",
+ 'agent_name' => calendarFirstName($row['user_name']), 'agent_full' => $row['user_name'],
+ 'detail' => implode(' · ', array_filter([$row['lead_name'] ? 'Helping ' . $row['lead_name'] : 'Helping', $row['ticket_status_name']]))],
+ ];
+ }
+ return $items;
+}
+
+/* Helpers' bookings for a calendar link (calendarUserFeedItems()) - theirs, or everyone's for a feed set to everyone. */
+function ticketHelperFeedItems(array $feed, $from, $to) {
+ global $mysqli;
+ if (!ticketHelpersReady()) {
+ return [];
+ }
+ $user_id = intval($feed['feed_user_id']);
+ $everyone = ($feed['feed_scope'] ?? 'mine') === 'everyone';
+ $host = calendarHost();
+ $from = escapeSql($from);
+ $to = escapeSql($to);
+ $start = TICKET_HELPER_START_SQL;
+ $sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_onsite, ticket_client_id,
+ ticket_created_at, ticket_updated_at, ticket_resolved_at, ticket_closed_at, client_name, th.user_id, helper.user_name,
+ location_name, location_address, location_city, location_state, location_zip,
+ $start AS start, " . TICKET_HELPER_END_SQL . " AS end
+ FROM ticket_helpers th
+ JOIN tickets ON tickets.ticket_id = th.ticket_id
+ JOIN users helper ON helper.user_id = th.user_id
+ LEFT JOIN clients ON client_id = ticket_client_id
+ LEFT JOIN contacts ON contact_id = ticket_contact_id AND ticket_contact_id > 0
+ LEFT JOIN locations ON location_id = IF(ticket_location_id > 0, ticket_location_id, contacts.contact_location_id)
+ WHERE $start BETWEEN '$from' AND '$to' AND ticket_archived_at IS NULL AND th.user_id <> ticket_assigned_to
+ " . ($everyone ? '' : "AND th.user_id = $user_id") . "
+ " . clientScopeSql('ticket_client_id'));
+ $items = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $ticket_id = intval($row['ticket_id']);
+ $link = "https://$host/agent/" . ticketUrl($ticket_id, $row['ticket_client_id']);
+ $items[] = [
+ 'uid' => "itflow-ticket-$ticket_id-helper-" . intval($row['user_id']) . "@$host",
+ 'start' => $row['start'],
+ 'end' => ticketScheduleEnd($row['start'], $row['end']),
+ 'summary' => calendarTicketTitle($row) . ' (' . ($everyone ? $row['user_name'] . ' ' : '') . 'helping)' . (ticketIsOpen($row) ? '' : ' [done]'),
+ 'location' => implode(', ', array_filter([$row['location_address'], $row['location_city'], trim($row['location_state'] . ' ' . $row['location_zip'])])),
+ 'description' => implode("\n", array_filter([$row['client_name'] ? 'Client: ' . $row['client_name'] : '', $row['location_name'] ? 'Site: ' . $row['location_name'] : '', 'Helping: ' . $row['user_name'], $link])),
+ 'url' => $link,
+ 'stamp' => $row['ticket_updated_at'] ?: $row['ticket_created_at'],
+ 'categories' => intval($row['ticket_onsite']) ? 'Onsite' : 'Remote',
+ 'busy' => !empty($feed['feed_busy_only']),
+ ];
+ }
+ return $items;
+}
+
+/** The dashboard's My schedule: the open tickets I am helping on, booked in the window, in its item shape. */
+function ticketHelperDashboardItems($from, $to) {
+ global $session_user_id;
+ $items = [];
+ foreach (ticketHelperCalendarItems($from, $to, 0, $session_user_id, false) as $item) {
+ if (strpos((string) ($item['className'] ?? ''), 'itflow-cal-done') !== false) {
+ continue;
+ }
+ $props = $item['extendedProps'];
+ $items[] = [
+ 'when' => $item['start'], 'all_day' => false, 'ongoing' => false,
+ 'title' => $item['title'], 'ref' => '', 'detail' => $props['detail'],
+ 'onsite' => $props['icon'] === 'fa-car', 'color' => null,
+ 'url' => '/agent/' . ticketUrl($props['ticket_id'], $props['client_id']),
+ ];
+ }
+ return $items;
+}
+
+/** An agent's open helper bookings that overlap $start - $end (ticketScheduleConflicts()), as text lines. */
+function ticketHelperConflicts($user_id, $start, $end, $ticket_id = 0) {
+ global $mysqli;
+ if (!ticketHelpersReady()) {
+ return [];
+ }
+ $user_id = intval($user_id);
+ $ticket_id = intval($ticket_id);
+ $start = escapeSql($start);
+ $end = escapeSql($end);
+ $s = TICKET_HELPER_START_SQL;
+ $e = TICKET_HELPER_END_SQL;
+ $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_client_id, $s AS start, $e AS end FROM ticket_helpers th
+ JOIN tickets ON tickets.ticket_id = th.ticket_id
+ WHERE th.user_id = $user_id AND th.ticket_id <> $ticket_id AND th.user_id <> ticket_assigned_to
+ AND ticket_resolved_at IS NULL AND ticket_closed_at IS NULL AND ticket_archived_at IS NULL
+ AND $s IS NOT NULL AND $s < '$end'
+ AND COALESCE(IF($e > $s, $e, NULL), DATE_ADD($s, INTERVAL " . intval(CALENDAR_TICKET_MINUTES) . " MINUTE)) > '$start'
+ ORDER BY start");
+ $lines = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $hidden = !empty($GLOBALS['session_user_id']) && intval($row['ticket_client_id']) && !hasClientAccess($row['ticket_client_id']);
+ $what = $hidden ? 'Another booking (a client you can\'t see)' : ticketReference($row) . ' - ' . $row['ticket_subject'];
+ $lines[] = "$what (helping) @ " . date('g:ia', strtotime($row['start'])) . '-' . date('g:ia', strtotime(ticketScheduleEnd($row['start'], $row['end'])));
+ }
+ return $lines;
+}