diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c1674f4a..e3fc2efa6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -108,6 +108,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- 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.
- 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.
### Bug Fixes
@@ -235,6 +236,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- 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.
- Database 3.8.6: `user_settings.user_config_timezone` (NULL is the company's) - `functions/user_timezone.php`: `timezoneUsersReady()`, `timezoneOwn()`, `timezoneOf()`, `timezoneView()`, `timezoneShifted()`, `timezoneConvert()`, `timezoneToView()` and `timezoneFromView()`; `timezoneField()` and `timezoneSave()` (`edit_your_user_preferences`, posting `timezone`). Times go out on the viewer's clock and come back in the company's: `calendar_items` and `calendar_day` turn the days asked for with `timezoneFromView()` and the items with `timezoneItems()`, `calendar_move` takes `timezoneMovePost()`, `add_event` and `edit_event` take `timezoneEventPost()`, `edit_ticket_schedule`, `add_ticket` and `save_ticket_helper` turn `scheduled_date_time` and `schedule` back, and the event form, Schedule window and helper window show `timezoneToView()` with `timezoneFormHint()`. `ticketScheduleShortText()` is on the viewer's clock with `timezoneAbbr()`; `timezoneEventWhenText()` is the quick look's; `agent/calendar.php` has `data-zone` and `timezoneNote()`, and `agent/js/calendar.js` sets `now` from it. `ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start, $end)` and the helper emails give the agent's time with `timezoneWhenFor()`. From Mountaineer IT's build of ITFlow.
+- Dispatch (`agent/dispatch.php`, `agent/js/dispatch.js`, `functions/dispatch.php`): `dispatchCan()` (Support at View), `dispatchCanEdit()` (`calendarCanScheduleTickets()`), `dispatchAgents()` (active agents who are admins or have Support at Modify, with `calendarAgentColor()`), `dispatchState()` / `dispatchStateSave()` (the `dispatch` key of `user_settings.user_config_calendar_state`, which `calendarUserStateSave()` now keeps: `view`, `hidden`, `weekends`), `dispatchBusinessHours()` and `dispatchWorkingDay()` from `getSlaSettings()`, `dispatchQueue($tab, $filters)` (`unassigned`, `unbooked`, `left_behind` via `calendarLeftBehindSql()`, with each tab's count), `dispatchItems($from, $to, $agent_ids)` (the tickets, helper bookings, events and holidays sources per agent, `extendedProps.agent` and `reference` added, only tickets and one-off events editable, through `timezoneItems()`), `dispatchBook()` (`ticketChangeAssignee()`, `ticketMailScheduleAgentCancelled()` for the agent who had it, then `ticketSetSchedule()`), `dispatchUnbook()` (`ticketCancelSchedule()`), `dispatchAssign()` (refused for a booked ticket), `dispatchEventMove()` (a one-off event in time and from one agent to another with `calendarEventSetAgents()`, `calendarSendInvites()` with `update` to those who have it), `dispatchWorkload()` with `dispatchWorkloadFlags()`, and `dispatchWeekStats()` (tickets given this week read from the `assigned the ticket to ` history lines). `agent/ajax.php`: GET `dispatch_queue`, `dispatch_items`, `dispatch_workload`, `dispatch_week`; POST (CSRF) `dispatch_state`, and with `dispatchCanEdit()`, after `timezoneMovePost()`, `dispatch_book`, `dispatch_unbook`, `dispatch_assign` and `dispatch_event_move` - JSON `{ok, message, conflicts}` or `{error}` with 400/403. `ticketSetSchedule()` and `ticketMailSchedule()` take `$tell_client` (default true) to leave the contact and watchers out. Day is a FullCalendar `timeGridDay` per agent in one scroller (`drop` for the queue's `FullCalendar.Interaction.Draggable`, `eventReceive` between columns, `eventDragStop` over the queue to unbook); Week and Workload use SortableJS. From Mountaineer IT's build of ITFlow.
## [26.11.8]
diff --git a/agent/ajax.php b/agent/ajax.php
index ab8a6cc84..cc1a4c562 100644
--- a/agent/ajax.php
+++ b/agent/ajax.php
@@ -2716,6 +2716,96 @@ if (isset($_POST['calendar_move'])) {
exit;
}
+/*
+ * Dispatch (functions/dispatch.php, agent/js/dispatch.js) - JSON:
+ * GET ?dispatch_queue=unassigned|unbooked|left_behind [&client_id &priority &q] the queue and each tab's count
+ * GET ?dispatch_items=1&from=Y-m-d&to=Y-m-d&agents=1,2 the board's bookings, events and holidays
+ * GET ?dispatch_workload=1&agents=1,2&first_day=0|1 each agent's open tickets, SLAs and booked hours
+ * GET ?dispatch_week=1&agents=1,2&first_day=0|1 this week's tickets in and closed, SLAs, each agent's share
+ * POST dispatch_book=1 ticket_id agent_id start minutes onsite tell_client give it to the agent and book it
+ * POST dispatch_unbook=1 ticket_id take its booking off
+ * POST dispatch_assign=1 ticket_id agent_id give it to the agent, not booked
+ * POST dispatch_event_move=1 event_id start end all_day from to a one-off event to another time or agent
+ * POST dispatch_state=1 view hidden weekends what this agent had on Dispatch
+ * Times come and go on the viewer's clock (functions/user_timezone.php). Looking takes
+ * Support at View; changing anything but your own view takes Modify.
+ */
+if (isset($_GET['dispatch_queue']) || isset($_GET['dispatch_items']) || isset($_GET['dispatch_workload']) || isset($_GET['dispatch_week'])
+ || isset($_POST['dispatch_book']) || isset($_POST['dispatch_unbook']) || isset($_POST['dispatch_assign']) || isset($_POST['dispatch_event_move']) || isset($_POST['dispatch_state'])) {
+
+ header('Content-Type: application/json');
+ $fail = function ($message, $code = 400) {
+ http_response_code($code);
+ echo json_encode(['error' => $message]);
+ exit;
+ };
+ if (!dispatchCan()) {
+ $fail('Dispatch takes Support in your role.', 403);
+ }
+ $agent_list = function ($value) {
+ return array_filter(array_map('intval', explode(',', (string) $value)));
+ };
+
+ if (isset($_GET['dispatch_queue'])) {
+ echo json_encode(dispatchQueue((string) $_GET['dispatch_queue'], $_GET));
+ exit;
+ }
+ if (isset($_GET['dispatch_items'])) {
+ $from = calendarIsDate($_GET['from'] ?? '') ? $_GET['from'] : date('Y-m-d');
+ $to = calendarIsDate($_GET['to'] ?? '') ? $_GET['to'] : $from;
+ if ($to < $from || strtotime($to) - strtotime($from) > 86400 * 42) {
+ $to = $from;
+ }
+ echo json_encode(dispatchItems($from, $to, $agent_list($_GET['agents'] ?? '')));
+ exit;
+ }
+ if (isset($_GET['dispatch_workload'])) {
+ echo json_encode(dispatchWorkload($agent_list($_GET['agents'] ?? ''), intval($_GET['first_day'] ?? 0) === 1 ? 1 : 0));
+ exit;
+ }
+ if (isset($_GET['dispatch_week'])) {
+ echo json_encode(dispatchWeekStats($agent_list($_GET['agents'] ?? ''), intval($_GET['first_day'] ?? 0) === 1 ? 1 : 0));
+ exit;
+ }
+
+ validateCSRFToken();
+ if (isset($_POST['dispatch_state'])) {
+ echo json_encode(['ok' => dispatchStateSave($_POST)]);
+ exit;
+ }
+ if (!dispatchCanEdit()) {
+ $fail('Booking and moving tickets takes Support at Modify in your role - you can look, not change.', 403);
+ }
+ // Picked on the viewer's own clock - as the company's clock reads it
+ $_POST = timezoneMovePost($_POST);
+
+ if (isset($_POST['dispatch_book'])) {
+ [$ok, $message, $conflicts] = dispatchBook($_POST['ticket_id'] ?? 0, $_POST['agent_id'] ?? 0, (string) ($_POST['start'] ?? ''),
+ $_POST['minutes'] ?? CALENDAR_TICKET_MINUTES, !empty($_POST['onsite']), !empty($_POST['tell_client']));
+ if (!$ok) {
+ $fail($message);
+ }
+ echo json_encode(['ok' => true, 'message' => $message, 'conflicts' => $conflicts]);
+ exit;
+ }
+ if (isset($_POST['dispatch_unbook'])) {
+ [$ok, $message] = dispatchUnbook($_POST['ticket_id'] ?? 0);
+ $ok ? print(json_encode(['ok' => true, 'message' => $message])) : $fail($message);
+ exit;
+ }
+ if (isset($_POST['dispatch_assign'])) {
+ [$ok, $message] = dispatchAssign($_POST['ticket_id'] ?? 0, $_POST['agent_id'] ?? 0);
+ $ok ? print(json_encode(['ok' => true, 'message' => $message])) : $fail($message);
+ exit;
+ }
+ if (isset($_POST['dispatch_event_move'])) {
+ [$ok, $message] = dispatchEventMove($_POST['event_id'] ?? 0, (string) ($_POST['start'] ?? ''), (string) ($_POST['end'] ?? ''),
+ !empty($_POST['all_day']), $_POST['from'] ?? 0, $_POST['to'] ?? 0);
+ $ok ? print(json_encode(['ok' => true, 'message' => $message])) : $fail($message);
+ exit;
+ }
+}
+
/*
* The calendar's To schedule list: an agent's open tickets with no work booked
* (most urgent first), to drag onto the calendar - in one client, or all.
diff --git a/agent/dispatch.php b/agent/dispatch.php
new file mode 100644
index 000000000..84a0003dd
--- /dev/null
+++ b/agent/dispatch.php
@@ -0,0 +1,238 @@
+ Settings > Modules).', 'error');
+ redirect('/agent/calendar.php');
+}
+
+$agents = dispatchAgents();
+$state = dispatchState();
+$can_edit = dispatchCanEdit();
+$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_config_calendar_first_day FROM user_settings WHERE user_id = $session_user_id"));
+$first_day = intval($row['user_config_calendar_first_day'] ?? 0);
+$clients = mysqli_fetch_all(mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_archived_at IS NULL" . clientScopeSql('client_id') . " ORDER BY client_name"), MYSQLI_ASSOC);
+$tell_client = intval($config_ticket_client_general_notifications) === 1;
+
+?>
+
+
+
+
+
+
+
+
+
+
+
+
+
= $can_edit ? 'Drag a ticket onto an agent and a time. Drag booked work back here to take it off the schedule.' : 'Your role can look at Dispatch, not book from it.' ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/agent/includes/side_nav.php b/agent/includes/side_nav.php
index 3e4a9fb66..3f5f0ab5e 100644
--- a/agent/includes/side_nav.php
+++ b/agent/includes/side_nav.php
@@ -101,6 +101,12 @@
+
+ ">
+
+ Dispatch
+
+
">
diff --git a/agent/js/dispatch.js b/agent/js/dispatch.js
new file mode 100644
index 000000000..4518cbb3c
--- /dev/null
+++ b/agent/js/dispatch.js
@@ -0,0 +1,973 @@
+// Dispatch (agent/dispatch.php, functions/dispatch.php).
+//
+// The queue - tickets nobody has, with an agent and nothing booked, or left
+// behind - beside the board: Day (a time grid per agent), Week (a row per agent,
+// a column per day) or Workload (each agent's load). Dropping a ticket on an
+// agent and a time, or moving a booking, opens the Schedule window and books it
+// as the ticket's own Schedule window does (ajax.php?dispatch_book). A booking
+// dragged back onto the queue is taken off the schedule. Under it, This week.
+// Times come and go on the agent's own clock - the server moves them. The view,
+// the agents shown and weekends are kept to the account (dispatch_state).
+
+(function () {
+ 'use strict';
+
+ const root = document.getElementById('itflowDispatch');
+ if (!root || typeof FullCalendar === 'undefined') {
+ return;
+ }
+
+ const csrf = root.dataset.csrf;
+ const canEdit = root.dataset.canEdit === '1';
+ const agents = JSON.parse(root.dataset.agents || '[]');
+ const firstDay = Number(root.dataset.firstDay) || 0;
+ const defaultMinutes = Number(root.dataset.defaultMinutes) || 60;
+ const lengths = JSON.parse(root.dataset.lengths || '[]');
+ const businessHours = JSON.parse(root.dataset.businessHours || 'null');
+ const zone = root.dataset.zone || '';
+ const queueEl = root.querySelector('[data-dispatch-queue]');
+ const board = root.querySelector('[data-dispatch-board]');
+ const statsEl = root.querySelector('[data-dispatch-stats]');
+ const titleEl = root.querySelector('[data-dispatch-title]');
+ const priorityTones = {Urgent: 'danger', High: 'warning', Medium: 'primary', Low: 'secondary'};
+
+ const saved = JSON.parse(root.dataset.state || '{}');
+ const state = {
+ view: saved.view || 'day',
+ hidden: Array.isArray(saved.hidden) ? saved.hidden.map(Number) : [],
+ weekends: !!saved.weekends,
+ date: parseYmd(root.dataset.initialDate),
+ tab: 'unassigned',
+ filters: {}
+ };
+ let calendars = [];
+ let sortables = [];
+ let queueDraggable = null;
+ let queueTickets = [];
+ let lastItems = [];
+ const expanded = {};
+
+ // ---------- helpers ----------
+
+ function pad(n) {
+ return String(n).padStart(2, '0');
+ }
+ function ymd(date) {
+ return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
+ }
+ function hm(date) {
+ return pad(date.getHours()) + ':' + pad(date.getMinutes());
+ }
+ function parseYmd(text) {
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(text || '');
+ return m ? new Date(+m[1], +m[2] - 1, +m[3]) : new Date();
+ }
+ function parseDateTime(text) {
+ const m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(String(text || ''));
+ return m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]) : null;
+ }
+ function addDays(date, n) {
+ const d = new Date(date.getTime());
+ d.setDate(d.getDate() + n);
+ return d;
+ }
+ function weekStart(date) {
+ return addDays(date, -((date.getDay() - firstDay + 7) % 7));
+ }
+ function esc(text) {
+ const div = document.createElement('div');
+ div.textContent = text == null ? '' : String(text);
+ return div.innerHTML;
+ }
+ function lengthText(minutes) {
+ const h = Math.floor(minutes / 60);
+ const m = minutes % 60;
+ return ((h ? h + (h > 1 ? ' hours' : ' hour') : '') + (m ? ' ' + m + ' min' : '')).trim();
+ }
+ function minutesBetween(start, end) {
+ const a = parseDateTime(start);
+ const b = parseDateTime(end);
+ return a && b ? Math.max(0, Math.round((b - a) / 60000)) : 0;
+ }
+ function toast(message, type) {
+ if (typeof itflowToast === 'function') {
+ itflowToast(message, type || 'success');
+ }
+ }
+ // Now on the agent's own clock, when they work away from the company's
+ function zoneNow() {
+ const parts = {};
+ new Intl.DateTimeFormat('en-CA', {timeZone: zone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'})
+ .formatToParts(new Date()).forEach(function (part) {
+ parts[part.type] = part.value;
+ });
+ return parts.year + '-' + parts.month + '-' + parts.day + 'T' + parts.hour + ':' + parts.minute + ':' + parts.second;
+ }
+ function today() {
+ return zone ? parseYmd(zoneNow()) : new Date();
+ }
+
+ function request(method, params) {
+ const query = new URLSearchParams(params).toString();
+ const options = {method: method, credentials: 'same-origin'};
+ if (method === 'POST') {
+ options.headers = {'Content-Type': 'application/x-www-form-urlencoded'};
+ options.body = query;
+ }
+ return fetch('ajax.php' + (method === 'GET' ? '?' + query : ''), options).then(function (res) {
+ return res.json().catch(function () {
+ return {error: 'Something went wrong - reload the page and try again.'};
+ });
+ }).then(function (json) {
+ if (json && json.error) {
+ throw new Error(json.error);
+ }
+ return json;
+ });
+ }
+ function post(params) {
+ return request('POST', Object.assign({csrf_token: csrf}, params));
+ }
+
+ let saveTimer = null;
+ function saveState() {
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(function () {
+ post({dispatch_state: 1, view: state.view, hidden: state.hidden.join(','), weekends: state.weekends ? 1 : 0}).catch(function () {
+ // Not kept this time - the page still shows it
+ });
+ }, 600);
+ }
+
+ function agentById(id) {
+ return agents.find(function (a) {
+ return a.id === Number(id);
+ });
+ }
+ function shownAgents() {
+ return agents.filter(function (a) {
+ return state.hidden.indexOf(a.id) === -1;
+ });
+ }
+ function dot(color) {
+ return ' ';
+ }
+ function businessStart() {
+ return businessHours && businessHours.startTime && businessHours.startTime !== '00:00' ? businessHours.startTime : '09:00';
+ }
+
+ // ---------- asking: the Schedule window, and taking a booking off ----------
+
+ const scheduleModalEl = document.getElementById('dispatchScheduleModal');
+ const scheduleForm = scheduleModalEl.querySelector('[data-dispatch-schedule]');
+ const scheduleError = scheduleModalEl.querySelector('[data-dispatch-schedule-error]');
+ let scheduling = null;
+
+ // Book a ticket: [ticket] from the queue or the board, at [start] (a Date), for [agentId] - resolves true once booked
+ function schedule(ticket, start, agentId, minutes) {
+ if (!canEdit) {
+ return Promise.resolve(false);
+ }
+ return new Promise(function (resolve) {
+ scheduling = {ticket: ticket, resolve: resolve, done: false};
+ scheduleModalEl.querySelector('[data-dispatch-schedule-ref]').textContent = ticket.reference || '';
+ scheduleModalEl.querySelector('[data-dispatch-schedule-ticket]').innerHTML =
+ ' ' + esc(ticket.reference) + ' ' + esc(ticket.subject) + ' '
+ + '' + esc([ticket.client, ticket.priority, ticket.status, ticket.booked ? 'booked ' + ticket.booked : ''].filter(Boolean).join(' · ')) + '
';
+ const length = minutes || ticket.minutes || defaultMinutes;
+ const list = lengths.indexOf(length) === -1 ? lengths.concat([length]).sort(function (a, b) { return a - b; }) : lengths;
+ scheduleForm.elements.minutes.innerHTML = list.map(function (m) {
+ return '' + esc(lengthText(m)) + ' ';
+ }).join('');
+ scheduleForm.elements.minutes.value = String(length);
+ scheduleForm.elements.agent_id.value = String(agentId || ticket.agent || (agents[0] || {}).id || '');
+ scheduleForm.elements.start.value = ymd(start) + 'T' + hm(start);
+ scheduleForm.elements.onsite.value = ticket.onsite ? '1' : '0';
+ scheduleError.hidden = true;
+ bootstrap.Modal.getOrCreateInstance(scheduleModalEl).show();
+ });
+ }
+
+ scheduleForm.addEventListener('submit', function (e) {
+ e.preventDefault();
+ if (!scheduling) {
+ return;
+ }
+ const button = scheduleForm.querySelector('[type=submit]');
+ button.disabled = true;
+ const tell = scheduleForm.elements.tell_client;
+ post({
+ dispatch_book: 1,
+ ticket_id: scheduling.ticket.id,
+ agent_id: scheduleForm.elements.agent_id.value,
+ start: scheduleForm.elements.start.value.replace('T', ' ') + ':00',
+ minutes: scheduleForm.elements.minutes.value,
+ onsite: scheduleForm.elements.onsite.value,
+ tell_client: tell ? (tell.checked ? 1 : 0) : 1
+ }).then(function (json) {
+ scheduling.done = true;
+ toast(json.message, 'success');
+ if (json.conflicts && json.conflicts.length) {
+ toast('Already booked then: ' + json.conflicts.join('; '), 'warning');
+ }
+ bootstrap.Modal.getOrCreateInstance(scheduleModalEl).hide();
+ reloadAll();
+ }).catch(function (error) {
+ scheduleError.textContent = error.message;
+ scheduleError.hidden = false;
+ }).finally(function () {
+ button.disabled = false;
+ });
+ });
+
+ scheduleModalEl.addEventListener('hidden.bs.modal', function () {
+ if (scheduling) {
+ const done = scheduling.done;
+ scheduling.resolve(done);
+ scheduling = null;
+ if (!done) {
+ refreshBoard(); // anything dragged goes back where it was
+ }
+ }
+ });
+
+ const confirmEl = document.getElementById('dispatchConfirmModal');
+ let confirming = null;
+ function confirmBox(title, text) {
+ return new Promise(function (resolve) {
+ confirming = {resolve: resolve, ok: false};
+ confirmEl.querySelector('[data-dispatch-confirm-title]').textContent = title;
+ confirmEl.querySelector('[data-dispatch-confirm-text]').textContent = text;
+ bootstrap.Modal.getOrCreateInstance(confirmEl).show();
+ });
+ }
+ confirmEl.querySelector('[data-dispatch-confirm-ok]').addEventListener('click', function () {
+ if (confirming) {
+ confirming.ok = true;
+ }
+ bootstrap.Modal.getOrCreateInstance(confirmEl).hide();
+ });
+ confirmEl.addEventListener('hidden.bs.modal', function () {
+ if (confirming) {
+ confirming.resolve(confirming.ok);
+ confirming = null;
+ }
+ });
+
+ function unbook(ticket) {
+ if (!canEdit) {
+ return;
+ }
+ confirmBox('Take ' + (ticket.reference || 'it') + ' off the schedule?', 'The agent - and the contact and watchers, when client emails are on - are sent the cancellation. It goes back to the queue.').then(function (ok) {
+ if (!ok) {
+ refreshBoard();
+ return;
+ }
+ post({dispatch_unbook: 1, ticket_id: ticket.id}).then(function (json) {
+ toast(json.message, 'success');
+ reloadAll();
+ }).catch(function (error) {
+ toast(error.message, 'error');
+ refreshBoard();
+ });
+ });
+ }
+
+ function moveEvent(props, start, end, allDay, from, to) {
+ post({
+ dispatch_event_move: 1, event_id: props.event_id, from: from, to: to, all_day: allDay ? 1 : 0,
+ start: ymd(start) + ' ' + (allDay ? '00:00' : hm(start)) + ':00',
+ end: end && !allDay ? ymd(end) + ' ' + hm(end) + ':00' : ''
+ }).then(function (json) {
+ toast(json.message, 'success');
+ refreshBoard();
+ }).catch(function (error) {
+ toast(error.message, 'error');
+ refreshBoard();
+ });
+ }
+
+ // ---------- the queue ----------
+
+ function ticketFromQueue(el) {
+ return queueTickets.find(function (t) {
+ return t.id === Number(el.dataset.ticket);
+ }) || {id: Number(el.dataset.ticket), reference: el.dataset.reference || ''};
+ }
+ function ticketFromItem(event, props) {
+ return {
+ id: Number(props.ticket_id),
+ reference: props.reference || '',
+ subject: event.title,
+ agent: Number(props.agent),
+ onsite: props.icon === 'fa-car' ? 1 : 0,
+ minutes: event.end && event.start ? Math.round((event.end - event.start) / 60000) : defaultMinutes
+ };
+ }
+
+ function loadQueue() {
+ request('GET', Object.assign({dispatch_queue: state.tab}, state.filters)).then(function (json) {
+ queueTickets = json.tickets || [];
+ Object.keys(json.counts || {}).forEach(function (key) {
+ const badge = root.querySelector('[data-dispatch-count="' + key + '"]');
+ if (badge) {
+ badge.textContent = json.counts[key] ? String(json.counts[key]) : '';
+ }
+ });
+ root.querySelectorAll('[data-dispatch-tab]').forEach(function (tab) {
+ tab.classList.toggle('active', tab.dataset.dispatchTab === state.tab);
+ });
+ if (!queueTickets.length) {
+ queueEl.innerHTML = '' + esc({
+ unassigned: 'Every open ticket has an agent.',
+ unbooked: 'Nothing waiting - every ticket with an agent is booked.',
+ left_behind: 'Nothing left behind - every open ticket booked before today has been moved on or done.'
+ }[state.tab]) + '
';
+ return;
+ }
+ queueEl.innerHTML = queueTickets.map(function (t) {
+ return ''
+ + '
'
+ + '' + esc(t.reference + ' ' + t.subject) + '
'
+ + '
' + esc([t.client, t.agent_name, t.booked ? 'booked ' + t.booked : t.age, t.onsite ? 'Onsite' : ''].filter(Boolean).join(' · ')) + '
';
+ }).join('');
+ }).catch(function (error) {
+ queueEl.innerHTML = '' + esc(error.message) + '
';
+ });
+ }
+
+ queueEl.addEventListener('click', function (e) {
+ const item = e.target.closest('.itflow-dispatch-item');
+ if (item) {
+ openModal('modals/ticket/ticket.php?id=' + Number(item.dataset.ticket));
+ }
+ });
+ root.querySelectorAll('[data-dispatch-tab]').forEach(function (tab) {
+ tab.addEventListener('click', function (e) {
+ e.preventDefault();
+ state.tab = tab.dataset.dispatchTab;
+ loadQueue();
+ });
+ });
+ let filterTimer = null;
+ root.querySelectorAll('[data-dispatch-filter]').forEach(function (input) {
+ input.addEventListener(input.tagName === 'SELECT' ? 'change' : 'input', function () {
+ state.filters[input.dataset.dispatchFilter] = input.value;
+ clearTimeout(filterTimer);
+ filterTimer = setTimeout(loadQueue, input.tagName === 'SELECT' ? 0 : 300);
+ });
+ });
+
+ function openModal(url) {
+ const link = document.createElement('a');
+ link.href = '#';
+ link.className = 'ajax-modal d-none';
+ link.dataset.modalUrl = url;
+ link.dataset.modalSize = 'lg';
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ }
+
+ function overQueue(jsEvent) {
+ const rect = queueEl.getBoundingClientRect();
+ return jsEvent && jsEvent.clientX >= rect.left && jsEvent.clientX <= rect.right && jsEvent.clientY >= rect.top && jsEvent.clientY <= rect.bottom;
+ }
+
+ // ---------- the board ----------
+
+ function range() {
+ if (state.view === 'week') {
+ const start = weekStart(state.date);
+ return [start, addDays(start, 6)];
+ }
+ return [state.date, state.date];
+ }
+
+ function loadItems() {
+ const r = range();
+ return request('GET', {dispatch_items: 1, from: ymd(r[0]), to: ymd(r[1]), agents: shownAgents().map(function (a) {
+ return a.id;
+ }).join(',')}).then(function (items) {
+ lastItems = Array.isArray(items) ? items : [];
+ return lastItems;
+ });
+ }
+
+ function teardown() {
+ calendars.forEach(function (cal) {
+ cal.destroy();
+ });
+ calendars = [];
+ sortables.forEach(function (s) {
+ s.destroy();
+ });
+ sortables = [];
+ if (queueDraggable) {
+ queueDraggable.destroy();
+ queueDraggable = null;
+ }
+ }
+
+ function render() {
+ teardown();
+ root.querySelectorAll('[data-dispatch-view]').forEach(function (b) {
+ b.classList.toggle('active', b.dataset.dispatchView === state.view);
+ });
+ root.querySelectorAll('[data-dispatch-nav], [data-dispatch-date]').forEach(function (el) {
+ el.disabled = state.view === 'workload';
+ });
+ root.querySelector('[data-dispatch-date]').value = ymd(state.date);
+ root.querySelector('[data-dispatch-agent-count]').textContent = '(' + shownAgents().length + '/' + agents.length + ')';
+ const r = range();
+ titleEl.textContent = state.view === 'workload' ? 'Workload - open tickets and the hours booked this week'
+ : (state.view === 'week'
+ ? r[0].toLocaleDateString(undefined, {month: 'short', day: 'numeric'}) + ' - ' + r[1].toLocaleDateString(undefined, {month: 'short', day: 'numeric', year: 'numeric'})
+ : state.date.toLocaleDateString(undefined, {weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'}));
+ if (!shownAgents().length) {
+ board.innerHTML = 'Pick the agents to show under Agents.
';
+ return;
+ }
+ if (state.view === 'day') {
+ renderDay();
+ } else if (state.view === 'week') {
+ renderWeek();
+ } else {
+ renderWorkload();
+ }
+ }
+
+ // [scroll] opens the day at its first hour - a new day; a refresh keeps the place
+ function refreshBoard(scroll) {
+ if (state.view === 'day') {
+ loadItems().then(function (items) {
+ calendars.forEach(function (cal) {
+ cal.removeAllEventSources();
+ cal.addEventSource(items.filter(function (item) {
+ return Number(item.extendedProps.agent) === cal.dispatchAgent;
+ }));
+ });
+ dayTotals(items);
+ if (scroll === true) {
+ requestAnimationFrame(scrollDay);
+ }
+ });
+ } else {
+ render();
+ }
+ }
+
+ function reloadAll() {
+ loadQueue();
+ refreshBoard();
+ loadStats();
+ }
+
+ // An item drawn as on the calendar page: time, icon, title, and where / who
+ function itemContent(arg) {
+ const props = arg.event.extendedProps || {};
+ const wrap = document.createElement('div');
+ wrap.className = 'itflow-cal-event ' + (arg.event.allDay ? 'is-daygrid' : 'is-timegrid');
+ if (arg.timeText && !arg.event.allDay) {
+ const time = document.createElement('span');
+ time.className = 'itflow-cal-time';
+ time.textContent = arg.timeText;
+ wrap.appendChild(time);
+ }
+ if (props.icon) {
+ const icon = document.createElement('i');
+ icon.className = 'fas fa-fw ' + props.icon + ' itflow-cal-icon';
+ wrap.appendChild(icon);
+ }
+ const title = document.createElement('span');
+ title.className = 'itflow-cal-title';
+ title.textContent = arg.event.title;
+ wrap.appendChild(title);
+ if (props.detail && !arg.event.allDay) {
+ const detail = document.createElement('div');
+ detail.className = 'itflow-cal-detail';
+ detail.textContent = props.detail;
+ wrap.appendChild(detail);
+ }
+ return {domNodes: [wrap]};
+ }
+
+ // The hours the day's grid shows - the working day, with room either side
+ function slotRange() {
+ if (zone || !businessHours || businessHours.startTime === '00:00') {
+ return ['00:00:00', '24:00:00'];
+ }
+ const start = businessHours.startTime < '06:00' ? businessHours.startTime : '06:00';
+ const end = businessHours.endTime > '21:00' ? businessHours.endTime : '21:00';
+ return [start + ':00', end === '24:00' ? '24:00:00' : end + ':00'];
+ }
+
+ // Day: a time grid for each agent, side by side
+ function renderDay() {
+ const shown = shownAgents();
+ board.innerHTML = '' + shown.map(function (a) {
+ return '
'
+ + dot(a.color) + esc(a.name) + '
';
+ }).join('') + '
';
+ const slots = slotRange();
+
+ board.querySelectorAll('.itflow-dispatch-col').forEach(function (col, index) {
+ const agentId = Number(col.dataset.agent);
+ const cal = new FullCalendar.Calendar(col.querySelector('[data-dispatch-cal]'), {
+ initialView: 'timeGridDay',
+ initialDate: ymd(state.date),
+ headerToolbar: false,
+ dayHeaders: false,
+ allDaySlot: true,
+ allDayText: '',
+ height: 'auto',
+ slotMinTime: slots[0],
+ slotMaxTime: slots[1],
+ now: zone ? zoneNow : undefined,
+ slotDuration: '00:30:00',
+ snapDuration: '00:15:00',
+ slotEventOverlap: false,
+ nowIndicator: true,
+ editable: canEdit,
+ droppable: canEdit,
+ eventDurationEditable: canEdit,
+ // The company's hours mean nothing on another clock - left unshaded there
+ businessHours: zone ? false : (businessHours || false),
+ // The times down the side once, on the first column - the others keep a blank the
+ // label's height, so the rows line up across
+ slotHeaderContent: function (arg) {
+ return index === 0 ? arg.text : '\u00a0';
+ },
+ eventContent: itemContent,
+ eventDidMount: function (info) {
+ const props = info.event.extendedProps || {};
+ info.el.dataset.kind = props.kind || '';
+ info.el.setAttribute('title', info.event.title + (props.detail ? '\n' + props.detail : ''));
+ },
+ eventClick: function (info) {
+ info.jsEvent.preventDefault();
+ const props = info.event.extendedProps || {};
+ if (props.modal) {
+ openModal(props.modal);
+ }
+ },
+ // From the queue - a booking from another agent's column comes in by eventReceive
+ drop: function (info) {
+ if (!queueEl.contains(info.draggedEl)) {
+ return;
+ }
+ const start = new Date(info.date.getTime());
+ if (info.allDay) {
+ const parts = businessStart().split(':');
+ start.setHours(Number(parts[0]), Number(parts[1]), 0, 0);
+ }
+ schedule(ticketFromQueue(info.draggedEl), start, agentId);
+ },
+ // To another time, the same agent
+ eventDrop: function (info) {
+ const props = info.event.extendedProps || {};
+ if (props.kind === 'event') {
+ moveEvent(props, info.event.start, info.event.end, info.event.allDay, agentId, agentId);
+ return;
+ }
+ schedule(ticketFromItem(info.event, props), info.event.start, agentId);
+ },
+ eventResize: function (info) {
+ const props = info.event.extendedProps || {};
+ if (props.kind === 'event') {
+ moveEvent(props, info.event.start, info.event.end, false, agentId, agentId);
+ return;
+ }
+ const ticket = ticketFromItem(info.event, props);
+ schedule(ticket, info.event.start, agentId, ticket.minutes);
+ },
+ // From another agent's column
+ eventReceive: function (info) {
+ const props = info.event.extendedProps || {};
+ if (props.kind === 'event') {
+ moveEvent(props, info.event.start, info.event.end, info.event.allDay, Number(props.agent), agentId);
+ return;
+ }
+ schedule(ticketFromItem(info.event, props), info.event.start, agentId);
+ },
+ // Back onto the queue
+ eventDragStart: function () {
+ queueEl.classList.add('is-drop-target');
+ },
+ eventDragStop: function (info) {
+ queueEl.classList.remove('is-drop-target');
+ const props = info.event.extendedProps || {};
+ if (props.kind === 'ticket' && overQueue(info.jsEvent)) {
+ unbook(ticketFromItem(info.event, props));
+ }
+ }
+ });
+ cal.dispatchAgent = agentId;
+ cal.render();
+ calendars.push(cal);
+ });
+
+ if (canEdit && FullCalendar.Interaction && FullCalendar.Interaction.Draggable) {
+ queueDraggable = new FullCalendar.Interaction.Draggable(queueEl, {
+ itemSelector: '.itflow-dispatch-item',
+ eventData: function (item) {
+ const minutes = ticketFromQueue(item).minutes || defaultMinutes;
+ return {title: item.dataset.reference, duration: pad(Math.floor(minutes / 60)) + ':' + pad(minutes % 60), create: false, color: '#6c757d'};
+ }
+ });
+ }
+ refreshBoard(true);
+ }
+
+ // The hour to open the day at: the working day's start - or, when the board runs around the clock,
+ // an hour before now today and 8am on other days
+ function scrollHour() {
+ if (slotRange()[0] !== '00:00:00') {
+ return Number(businessStart().split(':')[0]);
+ }
+ if (ymd(state.date) === ymd(today())) {
+ return Math.max(0, (zone ? parseDateTime(zoneNow()) : new Date()).getHours() - 1);
+ }
+ return 8;
+ }
+
+ // One scroller for every column - opened at scrollHour(), once the bookings are in
+ function scrollDay() {
+ const scroller = board.querySelector('.itflow-dispatch-cols');
+ const slot = scroller ? scroller.querySelector('.itflow-dispatch-col [data-time="' + pad(scrollHour()) + ':00:00"]') : null;
+ if (slot) {
+ const head = scroller.querySelector('.itflow-dispatch-col-head');
+ scroller.scrollTop += slot.getBoundingClientRect().top - scroller.getBoundingClientRect().top - (head ? head.offsetHeight : 0) - 4;
+ }
+ }
+
+ function dayTotals(items) {
+ board.querySelectorAll('.itflow-dispatch-col').forEach(function (col) {
+ let minutes = 0;
+ items.forEach(function (item) {
+ if (Number(item.extendedProps.agent) === Number(col.dataset.agent) && ['ticket', 'helper'].indexOf(item.extendedProps.kind) !== -1 && !item.allDay) {
+ minutes += minutesBetween(item.start, item.end);
+ }
+ });
+ col.querySelector('[data-dispatch-booked]').textContent = minutes ? lengthText(minutes) + ' booked' : '';
+ });
+ }
+
+ // Week: a row for each agent, a column for each day
+ function renderWeek() {
+ const start = range()[0];
+ const days = [];
+ for (let i = 0; i < 7; i++) {
+ const d = addDays(start, i);
+ if (state.weekends || (d.getDay() !== 0 && d.getDay() !== 6)) {
+ days.push(d);
+ }
+ }
+ board.innerHTML = 'Loading...
';
+ loadItems().then(function (items) {
+ const now = ymd(today());
+ let html = 'Agent ';
+ days.forEach(function (d) {
+ html += '' + esc(d.toLocaleDateString(undefined, {weekday: 'short', month: 'short', day: 'numeric'})) + ' ';
+ });
+ html += '';
+ shownAgents().forEach(function (a) {
+ // The week's booked hours - weekends too, shown or not, as Workload counts them
+ let week = 0;
+ items.forEach(function (item) {
+ if (Number(item.extendedProps.agent) === a.id && ['ticket', 'helper'].indexOf(item.extendedProps.kind) !== -1 && !item.allDay) {
+ week += minutesBetween(item.start, item.end);
+ }
+ });
+ const cells = days.map(function (d) {
+ const day = ymd(d);
+ const chips = items.filter(function (item) {
+ return Number(item.extendedProps.agent) === a.id && String(item.start).substring(0, 10) === day;
+ }).sort(function (x, y) {
+ return String(x.start).localeCompare(String(y.start));
+ });
+ const off = businessHours && businessHours.daysOfWeek && businessHours.daysOfWeek.indexOf(d.getDay()) === -1;
+ // A box of a fixed height - one that grew as a booking passed over would move the rows under the pointer
+ return '' + chips.map(function (item) {
+ const props = item.extendedProps || {};
+ const minutes = item.allDay ? 0 : minutesBetween(item.start, item.end);
+ const movable = !!item.editable;
+ return '
'
+ + (props.icon ? ' ' : '')
+ + esc((item.allDay ? '' : String(item.start).substring(11, 16) + ' ') + item.title) + '
';
+ }).join('') + '
';
+ }).join('');
+ html += '' + dot(a.color) + esc(a.name)
+ + '' + (week ? esc(lengthText(week)) + ' booked' : '') + '
' + cells + ' ';
+ });
+ board.innerHTML = html + '
';
+
+ board.querySelectorAll('.itflow-dispatch-chip').forEach(function (chip) {
+ chip.addEventListener('click', function () {
+ if (chip.dataset.modal) {
+ openModal(chip.dataset.modal);
+ }
+ });
+ });
+ if (!canEdit || typeof Sortable === 'undefined') {
+ return;
+ }
+ board.querySelectorAll('.itflow-dispatch-cell-list').forEach(function (cell) {
+ sortables.push(Sortable.create(cell, {
+ group: {name: 'dispatch', pull: true, put: true},
+ draggable: '.is-movable',
+ sort: false,
+ onAdd: function (evt) {
+ const el = evt.item;
+ const agentId = Number(cell.dataset.agent);
+ const day = parseYmd(cell.dataset.date);
+ const from = evt.from;
+ el.remove();
+ if (from === queueEl) {
+ // From the queue: the start of the working day
+ const parts = businessStart().split(':');
+ day.setHours(Number(parts[0]), Number(parts[1]), 0, 0);
+ schedule(ticketFromQueue(el), day, agentId);
+ return;
+ }
+ const was = parseDateTime(el.dataset.start) || day;
+ day.setHours(was.getHours(), was.getMinutes(), 0, 0);
+ const fromAgent = Number(from.dataset.agent);
+ if (el.dataset.kind === 'event') {
+ const length = Number(el.dataset.minutes) * 60000;
+ moveEvent({event_id: Number(el.dataset.event)}, day, length ? new Date(day.getTime() + length) : null, el.dataset.allDay === '1', fromAgent, agentId);
+ return;
+ }
+ schedule({id: Number(el.dataset.ticket), reference: el.dataset.reference, subject: el.title.split('\n')[0], onsite: Number(el.dataset.onsite), agent: fromAgent},
+ day, agentId, Number(el.dataset.minutes) || defaultMinutes);
+ }
+ }));
+ });
+ // The queue takes from the board (to take a booking off) and gives to it
+ sortables.push(Sortable.create(queueEl, {
+ group: {name: 'dispatch', pull: 'clone', put: true},
+ draggable: '.itflow-dispatch-item.is-movable, .itflow-dispatch-chip',
+ sort: false,
+ onAdd: function (evt) {
+ const el = evt.item;
+ el.remove();
+ if (el.dataset.kind === 'ticket') {
+ unbook({id: Number(el.dataset.ticket), reference: el.dataset.reference});
+ } else {
+ refreshBoard();
+ }
+ }
+ }));
+ }).catch(function (error) {
+ board.innerHTML = '' + esc(error.message) + '
';
+ });
+ }
+
+ // Workload: each agent's open tickets, SLAs and booked hours - drop a ticket on an agent to give it to them
+ function bar(minutes, capacity) {
+ const pct = capacity ? Math.min(100, Math.round(minutes / capacity * 100)) : 0;
+ const tone = capacity && minutes > capacity ? 'bg-danger' : (pct >= 85 ? 'bg-warning' : 'bg-primary');
+ return '' + esc(lengthText(minutes) || '0 min') + (capacity ? ' of ' + esc(lengthText(capacity)) + ' ' : '') + '
'
+ + '';
+ }
+
+ function renderWorkload() {
+ board.innerHTML = 'Loading...
';
+ request('GET', {dispatch_workload: 1, agents: shownAgents().map(function (a) { return a.id; }).join(','), first_day: firstDay}).then(function (json) {
+ const flagTones = {behind: 'danger', watch: 'warning', overloaded: 'warning', room: 'success'};
+ let html = ''
+ + 'Agent Open SLA Past due Not booked Quiet Booked today Booked this week ';
+ (json.agents || []).forEach(function (a) {
+ html += ''
+ + '' + dot(a.color) + '
' + esc(a.name) + ' '
+ + (a.flags || []).map(function (f) {
+ return '
' + esc(f.text) + ' ';
+ }).join('') + (a.oldest ? '
Oldest ' + esc(a.oldest) + '
' : '') + '
'
+ + '' + a.open + (a.helping ? ' (' + a.helping + ' helping) ' : '') + ' '
+ + '' + (a.sla.breached ? '' + a.sla.breached + ' ' : '0') + ' / ' + (a.sla.at_risk ? '' + a.sla.at_risk + ' ' : '0') + ' '
+ + '' + (a.overdue ? '' + a.overdue + ' ' : '0') + ' '
+ + '' + a.unbooked + ' '
+ + '' + a.quiet + ' '
+ + '' + bar(a.booked_today, a.capacity_today) + ' '
+ + '' + bar(a.booked_week, a.capacity_week) + ' ';
+ html += ''
+ + (a.tickets.length ? '' : 'No open tickets.
') + ' ';
+ });
+ html += '
Team average: ' + esc(json.team.open) + ' open, ' + esc(lengthText(json.team.booked_week) || '0 min') + ' booked this week. Click an agent for their tickets'
+ + (canEdit ? ' - drop a ticket from the queue on one to give it to them.' : '.') + '
';
+ board.innerHTML = html;
+
+ board.querySelectorAll('.itflow-dispatch-workload-row').forEach(function (row) {
+ row.addEventListener('click', function () {
+ const id = Number(row.dataset.agent);
+ expanded[id] = !expanded[id];
+ board.querySelector('[data-tickets-for="' + id + '"]').hidden = !expanded[id];
+ });
+ });
+ if (!canEdit || typeof Sortable === 'undefined') {
+ return;
+ }
+ board.querySelectorAll('.itflow-dispatch-drop').forEach(function (drop) {
+ sortables.push(Sortable.create(drop, {
+ group: {name: 'dispatch', pull: false, put: true},
+ sort: false,
+ onAdd: function (evt) {
+ const ticket = ticketFromQueue(evt.item);
+ evt.item.remove();
+ post({dispatch_assign: 1, ticket_id: ticket.id, agent_id: drop.dataset.agent}).then(function (json) {
+ toast(json.message, 'success');
+ reloadAll();
+ }).catch(function (error) {
+ toast(error.message, 'error');
+ });
+ }
+ }));
+ });
+ sortables.push(Sortable.create(queueEl, {
+ group: {name: 'dispatch', pull: 'clone', put: false},
+ draggable: '.itflow-dispatch-item.is-movable',
+ sort: false,
+ onStart: function () {
+ board.classList.add('is-dragging');
+ },
+ onEnd: function () {
+ board.classList.remove('is-dragging');
+ }
+ }));
+ }).catch(function (error) {
+ board.innerHTML = '' + esc(error.message) + '
';
+ });
+ }
+
+ // ---------- This week ----------
+
+ let statsChart = null;
+ function loadStats() {
+ request('GET', {dispatch_week: 1, agents: shownAgents().map(function (a) { return a.id; }).join(','), first_day: firstDay}).then(function (json) {
+ const t = json.totals;
+ const s = json.sla;
+ const from = parseYmd(json.week[0]);
+ const to = parseYmd(json.week[1]);
+ root.querySelector('[data-dispatch-week]').textContent = from.toLocaleDateString(undefined, {month: 'short', day: 'numeric'}) + ' - ' + to.toLocaleDateString(undefined, {month: 'short', day: 'numeric'});
+ const tile = function (label, value, sub) {
+ return '' + esc(label) + '
' + esc(value) + '
' + sub + '
';
+ };
+ const signed = function (n) {
+ return (n > 0 ? '+' : '') + n;
+ };
+ let html = ''
+ + tile('In', t.inbound, esc('Last week ' + t.last_inbound))
+ + tile('Closed', t.closed, esc('Last week ' + t.last_closed + ' · 4-week average ' + t.avg_closed))
+ + tile('In minus closed', signed(t.net), esc(t.net > 0 ? 'The queue grew' : (t.net < 0 ? 'The queue shrank' : 'Even')))
+ + tile('Open now', t.open, esc((s.breached_now || 0) + ' SLA breached · ' + (s.at_risk_now || 0) + ' close to it'))
+ + tile('First responses', (s.response_met || 0) + ' met', esc((s.response_missed || 0) + ' missed this week'))
+ + tile('Resolutions', (s.resolution_met || 0) + ' met', esc((s.resolution_missed || 0) + ' missed this week'))
+ + '
'
+ + '
Agent Given Closed Open SLA missed '
+ + (json.agents || []).map(function (a) {
+ return '' + dot(a.color) + esc(a.name) + ' ' + a.assigned + ' ' + a.closed + ' ' + a.open + ' '
+ + (a.sla_missed ? '' + a.sla_missed + ' ' : '0') + ' ';
+ }).join('') + '
';
+ statsEl.innerHTML = html;
+ if (statsChart) {
+ statsChart.destroy();
+ statsChart = null;
+ }
+ if (typeof Chart === 'undefined') {
+ return;
+ }
+ const css = getComputedStyle(document.documentElement);
+ const v = function (name, fallback) {
+ return (css.getPropertyValue(name) || '').trim() || fallback;
+ };
+ const base = typeof itflowChartDefaults === 'function' ? itflowChartDefaults() : {grid: 'rgba(0,0,0,.1)'};
+ statsChart = new Chart(statsEl.querySelector('canvas'), {
+ type: 'bar',
+ data: {
+ labels: json.days.map(function (d) { return d.label; }),
+ datasets: [
+ {label: 'In', data: json.days.map(function (d) { return d.future ? null : d.inbound; }), backgroundColor: v('--itflow-accent', '#007bff'), borderRadius: 4, maxBarThickness: 18},
+ {label: 'Closed', data: json.days.map(function (d) { return d.future ? null : d.closed; }), backgroundColor: v('--bs-success', '#198754'), borderRadius: 4, maxBarThickness: 18}
+ ]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ interaction: {mode: 'index', intersect: false},
+ plugins: {legend: {position: 'bottom', labels: {boxWidth: 12}}},
+ scales: {
+ x: {grid: {display: false}},
+ y: {beginAtZero: true, ticks: {precision: 0}, grid: {color: base.grid}}
+ }
+ }
+ });
+ }).catch(function (error) {
+ statsEl.innerHTML = '' + esc(error.message) + '
';
+ });
+ }
+
+ // ---------- the toolbar ----------
+
+ root.querySelectorAll('[data-dispatch-view]').forEach(function (button) {
+ button.addEventListener('click', function () {
+ state.view = button.dataset.dispatchView;
+ saveState();
+ render();
+ });
+ });
+ root.querySelectorAll('[data-dispatch-nav]').forEach(function (button) {
+ button.addEventListener('click', function () {
+ const step = Number(button.dataset.dispatchNav);
+ state.date = step === 0 ? today() : addDays(state.date, step * (state.view === 'week' ? 7 : 1));
+ render();
+ });
+ });
+ root.querySelector('[data-dispatch-date]').addEventListener('change', function (e) {
+ if (e.target.value) {
+ state.date = parseYmd(e.target.value);
+ render();
+ }
+ });
+ root.querySelectorAll('[data-dispatch-agent]').forEach(function (box) {
+ box.addEventListener('change', function () {
+ const id = Number(box.value);
+ state.hidden = state.hidden.filter(function (h) { return h !== id; });
+ if (!box.checked) {
+ state.hidden.push(id);
+ }
+ saveState();
+ render();
+ loadStats();
+ });
+ });
+ root.querySelector('[data-dispatch-weekends]').addEventListener('change', function (e) {
+ state.weekends = e.target.checked;
+ saveState();
+ if (state.view === 'week') {
+ render();
+ }
+ });
+ // The ticket's quick look can resolve, reassign or book a ticket
+ document.addEventListener('hidden.bs.modal', function (e) {
+ if (e.target !== scheduleModalEl && e.target !== confirmEl) {
+ reloadAll();
+ }
+ });
+
+ loadQueue();
+ render();
+ loadStats();
+
+})();
diff --git a/css/itflow_custom.css b/css/itflow_custom.css
index f63499dfd..95182dc93 100644
--- a/css/itflow_custom.css
+++ b/css/itflow_custom.css
@@ -5713,6 +5713,186 @@ img.itflow-contact-avatar {
gap: 1rem;
}
+/* --- Dispatch (agent/dispatch.php, agent/js/dispatch.js) ------------------- */
+.itflow-dispatch-cal {
+ --fc-classic-background: var(--bs-body-bg);
+ --fc-classic-foreground: var(--bs-body-color);
+ --fc-classic-muted-foreground: var(--bs-secondary-color);
+ --fc-classic-border: var(--bs-border-color);
+ --fc-classic-strong-border: var(--bs-border-color);
+ --fc-classic-primary: var(--itflow-accent, #007bff);
+ --fc-classic-event: var(--itflow-accent, #007bff);
+}
+.itflow-dispatch-dot {
+ display: inline-block;
+ width: .6rem;
+ height: .6rem;
+ border-radius: 50%;
+ flex-shrink: 0;
+ vertical-align: baseline;
+}
+.itflow-dispatch-agents {
+ min-width: 14rem;
+ max-height: 60vh;
+ overflow-y: auto;
+}
+/* The queue - tickets to give out, dragged onto the board */
+.itflow-dispatch-queue {
+ min-height: 8rem;
+ max-height: 26rem;
+ overflow-y: auto;
+ transition: background-color .15s;
+}
+@media (min-width: 992px) {
+ .itflow-dispatch-queue {
+ max-height: max(22rem, calc(100vh - 27rem));
+ }
+}
+.itflow-dispatch-queue.is-drop-target {
+ background: color-mix(in srgb, var(--bs-danger) 8%, transparent);
+ outline: 2px dashed var(--bs-danger);
+ outline-offset: -4px;
+}
+.itflow-dispatch-item {
+ padding: .35rem .5rem;
+ margin-bottom: .25rem;
+ border: 1px solid var(--bs-border-color);
+ border-radius: var(--bs-border-radius);
+ background: var(--bs-body-bg);
+ cursor: pointer;
+ user-select: none;
+}
+.itflow-dispatch-item.is-movable {
+ cursor: grab;
+}
+.itflow-dispatch-item:hover {
+ background: var(--bs-tertiary-bg);
+}
+/* Day - a column per agent, in one scroller: down the day together, and sideways when more than fit */
+.itflow-dispatch-cols {
+ display: flex;
+ overflow: auto;
+ max-height: max(30rem, calc(100vh - 17rem));
+}
+.itflow-dispatch-col {
+ flex: 1 0 13rem;
+ min-width: 13rem;
+ border-left: 1px solid var(--bs-border-color);
+}
+.itflow-dispatch-col:first-child {
+ flex-basis: 16rem;
+ min-width: 16rem;
+ border-left: 0;
+}
+.itflow-dispatch-col-head {
+ position: sticky;
+ top: 0;
+ z-index: 5;
+ display: flex;
+ align-items: center;
+ padding: .4rem .5rem;
+ border-bottom: 1px solid var(--bs-border-color);
+ background: var(--bs-tertiary-bg);
+}
+/* Week - a row per agent, a column per day */
+.itflow-dispatch-week {
+ table-layout: fixed;
+ min-width: 46rem;
+}
+.itflow-dispatch-week thead th {
+ background: var(--bs-tertiary-bg);
+}
+.itflow-dispatch-week-agent {
+ width: 11rem;
+ vertical-align: top;
+}
+.itflow-dispatch-cell {
+ vertical-align: top;
+ padding: 0 !important;
+}
+.itflow-dispatch-cell-list {
+ height: 6.5rem;
+ padding: .25rem;
+ overflow-y: auto;
+}
+.itflow-dispatch-cell.is-off {
+ background: var(--bs-tertiary-bg);
+}
+.itflow-dispatch-chip {
+ margin-bottom: .2rem;
+ padding: .1rem .35rem;
+ border-radius: .25rem;
+ color: #fff;
+ font-size: .75rem;
+ line-height: 1.35;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ cursor: pointer;
+}
+.itflow-dispatch-chip.is-movable {
+ cursor: grab;
+}
+.itflow-dispatch-chip[data-kind="helper"] {
+ background-image: repeating-linear-gradient(135deg, rgba(255, 255, 255, .18) 0 4px, transparent 4px 8px);
+}
+.itflow-dispatch-chip[data-kind="holiday"] {
+ opacity: .8;
+}
+/* Workload - drop a ticket on an agent to give it to them */
+.itflow-dispatch-workload-row {
+ cursor: pointer;
+}
+.itflow-dispatch-drop {
+ min-width: 11rem;
+ padding: .15rem .25rem;
+ border-radius: var(--bs-border-radius);
+}
+.itflow-dispatch-drop > .itflow-dispatch-item {
+ display: none;
+}
+[data-dispatch-board].is-dragging .itflow-dispatch-drop {
+ outline: 2px dashed var(--bs-border-color);
+}
+[data-dispatch-board].is-dragging .itflow-dispatch-drop:hover {
+ outline-color: var(--itflow-accent, #007bff);
+ background: color-mix(in srgb, var(--itflow-accent, #007bff) 10%, transparent);
+}
+.itflow-dispatch-bar {
+ height: .4rem;
+}
+/* This week */
+.itflow-dispatch-tiles {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
+ gap: .75rem;
+}
+.itflow-dispatch-tile {
+ padding: .6rem .75rem;
+ border: 1px solid var(--bs-border-color);
+ border-radius: var(--bs-border-radius);
+}
+.itflow-dispatch-tile-label {
+ font-size: .75rem;
+ letter-spacing: .03em;
+ text-transform: uppercase;
+ color: var(--bs-secondary-color);
+}
+.itflow-dispatch-tile-value {
+ font-size: 1.5rem;
+ font-weight: 600;
+ line-height: 1.2;
+ font-variant-numeric: tabular-nums;
+}
+.itflow-dispatch-tile-sub {
+ font-size: .75rem;
+ color: var(--bs-secondary-color);
+}
+.itflow-dispatch-chart {
+ position: relative;
+ height: 15rem;
+}
+
/* ---------- Networks and asset interfaces ---------- */
/* A tile small enough for a line of text - networkLink(), interfaceAssetRef() (a vendor's has its own, .itflow-vendor-tile-xs) */
diff --git a/functions.php b/functions.php
index fa77fcf6e..4425a1af1 100644
--- a/functions.php
+++ b/functions.php
@@ -72,6 +72,7 @@ require_once __DIR__ . '/functions/by_day.php';
require_once __DIR__ . '/functions/ticket.php';
require_once __DIR__ . '/functions/ticket_helpers.php';
require_once __DIR__ . '/functions/user_timezone.php';
+require_once __DIR__ . '/functions/dispatch.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 4379577d0..31813be81 100644
--- a/functions/calendar.php
+++ b/functions/calendar.php
@@ -1768,7 +1768,7 @@ function calendarUserStateSave($user_id, $page, array $state) {
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_config_calendar_state FROM user_settings WHERE user_id = $user_id"));
$saved = json_decode((string) ($row[0] ?? ''), true);
- $saved = is_array($saved) ? array_intersect_key($saved, ['all' => 1, 'client' => 1]) : [];
+ $saved = is_array($saved) ? array_intersect_key($saved, ['all' => 1, 'client' => 1, 'dispatch' => 1]) : [];
$saved[$page === 'client' ? 'client' : 'all'] = calendarCleanState($state);
$json = mysqli_real_escape_string($mysqli, json_encode($saved));
return (bool) mysqli_query($mysqli, "INSERT INTO user_settings SET user_id = $user_id, user_config_calendar_state = '$json' ON DUPLICATE KEY UPDATE user_config_calendar_state = '$json'");
diff --git a/functions/dispatch.php b/functions/dispatch.php
new file mode 100644
index 000000000..17e06917f
--- /dev/null
+++ b/functions/dispatch.php
@@ -0,0 +1,706 @@
+= 1;
+}
+
+/** May they book, move and assign there? */
+function dispatchCanEdit() {
+ return calendarCanScheduleTickets();
+}
+
+/** The agents who can be dispatched to - active, and able to work tickets (Support at Modify, or an admin): user_id => [id, name, color]. */
+function dispatchAgents() {
+ global $mysqli;
+ static $agents = null;
+ if ($agents !== null) {
+ return $agents;
+ }
+ $support_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT module_id FROM modules WHERE module_name = 'module_support' LIMIT 1"))[0] ?? 0);
+ $sql = mysqli_query($mysqli, "SELECT user_id, user_name, role_is_admin,
+ COALESCE((SELECT user_role_permission_level FROM user_role_permissions WHERE user_role_permissions.user_role_id = users.user_role_id AND module_id = $support_id LIMIT 1), 0) AS support_level
+ FROM users LEFT JOIN user_roles ON role_id = user_role_id
+ WHERE user_type = 1" . serviceAccountsOutSql() . " AND user_status = 1 AND user_archived_at IS NULL ORDER BY user_name");
+ $agents = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ if (intval($row['role_is_admin']) === 1 || intval($row['support_level']) >= 2) {
+ $agents[intval($row['user_id'])] = ['id' => intval($row['user_id']), 'name' => $row['user_name'], 'color' => calendarAgentColor($row['user_id'])];
+ }
+ }
+ return $agents;
+}
+
+/** What the signed-in agent last had on Dispatch: view (day, week, workload), hidden (agent ids) and weekends. */
+function dispatchState() {
+ global $mysqli, $session_user_id;
+ $state = [];
+ if (calendarAgentSettingsReady()) {
+ $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_config_calendar_state FROM user_settings WHERE user_id = " . intval($session_user_id)));
+ $saved = json_decode((string) ($row[0] ?? ''), true);
+ $state = is_array($saved['dispatch'] ?? null) ? $saved['dispatch'] : [];
+ }
+ return [
+ 'view' => in_array($state['view'] ?? '', ['week', 'workload'], true) ? $state['view'] : 'day',
+ 'hidden' => array_values(array_filter(array_map('intval', (array) ($state['hidden'] ?? [])))),
+ 'weekends' => !empty($state['weekends']),
+ ];
+}
+
+/** Keep what Dispatch showed, with the calendar's. */
+function dispatchStateSave(array $post) {
+ global $mysqli, $session_user_id;
+ $user_id = intval($session_user_id);
+ if (!$user_id || !calendarAgentSettingsReady()) {
+ return false;
+ }
+ $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_config_calendar_state FROM user_settings WHERE user_id = $user_id"));
+ $saved = json_decode((string) ($row[0] ?? ''), true);
+ $saved = is_array($saved) ? array_intersect_key($saved, ['all' => 1, 'client' => 1, 'dispatch' => 1]) : [];
+ $saved['dispatch'] = [
+ 'view' => in_array($post['view'] ?? '', ['week', 'workload'], true) ? $post['view'] : 'day',
+ 'hidden' => array_slice(array_values(array_filter(array_map('intval', explode(',', (string) ($post['hidden'] ?? ''))))), 0, 500),
+ 'weekends' => !empty($post['weekends']),
+ ];
+ $json = mysqli_real_escape_string($mysqli, json_encode($saved));
+ return (bool) mysqli_query($mysqli, "INSERT INTO user_settings SET user_id = $user_id, user_config_calendar_state = '$json' ON DUPLICATE KEY UPDATE user_config_calendar_state = '$json'");
+}
+
+/** No business days or hours in Admin > SLA - the SLA clocks run around the clock, and so does the board. */
+function dispatchAroundTheClock() {
+ $sla = getSlaSettings();
+ return empty($sla['business_days']) || empty($sla['business_hours_start']) || empty($sla['business_hours_end'])
+ || $sla['business_hours_start'] >= $sla['business_hours_end'];
+}
+
+/** The board's working hours, from Admin > SLA - FullCalendar's businessHours. */
+function dispatchBusinessHours() {
+ if (dispatchAroundTheClock()) {
+ return ['daysOfWeek' => [0, 1, 2, 3, 4, 5, 6], 'startTime' => '00:00', 'endTime' => '24:00'];
+ }
+ $sla = getSlaSettings();
+ return [
+ // ISO weekdays (Monday 1 to Sunday 7) as FullCalendar's (Sunday 0 to Saturday 6)
+ 'daysOfWeek' => array_values(array_map(function ($day) {
+ return $day % 7;
+ }, $sla['business_days'])),
+ 'startTime' => substr((string) $sla['business_hours_start'], 0, 5),
+ 'endTime' => substr((string) $sla['business_hours_end'], 0, 5),
+ ];
+}
+
+/** Working minutes a day and the working weekdays (ISO), from Admin > SLA - around the clock is still an 8-hour weekday for one person. */
+function dispatchWorkingDay() {
+ if (dispatchAroundTheClock()) {
+ return [480, [1, 2, 3, 4, 5]];
+ }
+ $sla = getSlaSettings();
+ [$sh, $sm] = array_map('intval', explode(':', substr((string) $sla['business_hours_start'], 0, 5)));
+ [$eh, $em] = array_map('intval', explode(':', substr((string) $sla['business_hours_end'], 0, 5)));
+ return [max(60, ($eh * 60 + $em) - ($sh * 60 + $sm)), $sla['business_days']];
+}
+
+/*
+ * ---------- the queue and the board ----------
+ */
+
+/*
+ * The queue: open tickets nobody has ('unassigned'), with an agent and nothing
+ * booked ('unbooked'), or left behind ('left_behind', longest first) - most
+ * urgent and oldest first. $filters: client_id, priority, q. With each tab's count.
+ */
+function dispatchQueue($tab, array $filters = []) {
+ global $mysqli;
+ $where = TICKET_OPEN_SQL . " AND ticket_archived_at IS NULL" . clientScopeSql('ticket_client_id');
+ $client_id = intval($filters['client_id'] ?? 0);
+ if ($client_id && hasClientAccess($client_id)) {
+ $where .= " AND ticket_client_id = $client_id";
+ }
+ $priority = (string) ($filters['priority'] ?? '');
+ if (in_array($priority, TICKET_PRIORITIES, true)) {
+ $where .= " AND ticket_priority = '" . escapeSql($priority) . "'";
+ }
+ $q = trim((string) ($filters['q'] ?? ''));
+ if ($q !== '') {
+ $like = escapeSql(mb_substr($q, 0, 100));
+ $where .= " AND (ticket_subject LIKE '%$like%' OR client_name LIKE '%$like%' OR CONCAT(ticket_prefix, ticket_number) LIKE '%$like%' OR ticket_number = " . intval($q) . ")";
+ }
+ $tabs = [
+ 'unassigned' => 'ticket_assigned_to = 0',
+ 'unbooked' => 'ticket_assigned_to > 0 AND ticket_schedule IS NULL',
+ 'left_behind' => calendarLeftBehindSql(),
+ ];
+ $tab = isset($tabs[$tab]) ? $tab : 'unassigned';
+ $counts = [];
+ foreach ($tabs as $key => $condition) {
+ $counts[$key] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM tickets LEFT JOIN clients ON client_id = ticket_client_id WHERE $where AND $condition"))[0]);
+ }
+ $sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_onsite, ticket_client_id, ticket_created_at,
+ ticket_schedule, " . (ticketScheduleEndReady() ? 'ticket_schedule_end' : 'NULL AS ticket_schedule_end') . ", ticket_assigned_to, client_name, user_name, ticket_status_name
+ FROM tickets
+ 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 $where AND {$tabs[$tab]}
+ ORDER BY " . ($tab === 'left_behind' ? 'ticket_schedule ASC, ' : '') . "FIELD(ticket_priority, 'Urgent', 'High', 'Medium', 'Low'), ticket_created_at ASC
+ LIMIT 200");
+ $tickets = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $tickets[] = [
+ 'id' => intval($row['ticket_id']),
+ 'reference' => ticketReference($row),
+ 'subject' => $row['ticket_subject'],
+ 'client' => $row['client_name'] ?: 'Internal',
+ 'priority' => (string) $row['ticket_priority'],
+ 'status' => (string) $row['ticket_status_name'],
+ 'onsite' => intval($row['ticket_onsite']),
+ 'agent' => intval($row['ticket_assigned_to']),
+ 'agent_name' => (string) $row['user_name'],
+ 'age' => timeAgo($row['ticket_created_at']),
+ 'minutes' => ticketScheduleMinutes($row['ticket_schedule'], $row['ticket_schedule_end']),
+ 'booked' => $row['ticket_schedule'] ? date('D M j', strtotime(timezoneToView($row['ticket_schedule']))) : '',
+ ];
+ }
+ return ['tab' => $tab, 'counts' => $counts, 'tickets' => $tickets];
+}
+
+/*
+ * The board's items from $from to $to (Y-m-d, on the viewer's clock) for these
+ * agents: their booked tickets - leading or helping - the events they are on,
+ * and the holidays, each with 'agent' set. Tickets they lead and one-off events
+ * move; the rest is there to book around. Times on the viewer's clock.
+ */
+function dispatchItems($from, $to, array $agent_ids) {
+ $agents = dispatchAgents();
+ $sources = calendarSources();
+ $calendar_ids = array_keys(calendarList());
+ $can_edit = dispatchCanEdit();
+ [$q_from, $q_to] = [timezoneFromView("$from 00:00:00"), timezoneFromView("$to 23:59:59")];
+ $holidays = isset($sources['holidays']) ? calendarSourceItems('holidays', "$from 00:00:00", "$to 23:59:59") : [];
+ $items = [];
+ $ticket_ids = [];
+ foreach (array_unique(array_map('intval', $agent_ids)) as $agent_id) {
+ if (!isset($agents[$agent_id])) {
+ continue;
+ }
+ $opts = ['client_id' => 0, 'user_id' => $agent_id];
+ $found = array_merge(
+ isset($sources['tickets']) ? calendarSourceItems('tickets', $q_from, $q_to, $opts) : [],
+ calendarEventItems($calendar_ids, $q_from, $q_to, $opts),
+ $holidays
+ );
+ foreach ($found as $item) {
+ $kind = $item['extendedProps']['kind'] ?? '';
+ $ticket_ids[] = intval($item['extendedProps']['ticket_id'] ?? 0);
+ // The same event or holiday on more than one agent's line
+ $item['id'] = ($item['id'] ?? '') . ($kind === 'ticket' || $kind === 'helper' ? '' : "-a$agent_id");
+ $item['extendedProps']['agent'] = $agent_id;
+ $item['editable'] = $can_edit && in_array($kind, ['ticket', 'event'], true) && !empty($item['editable']);
+ $item['durationEditable'] = $item['editable'];
+ $items[] = $item;
+ }
+ }
+ // Each booking's ticket reference, for the Schedule window's title
+ $ticket_ids = array_values(array_filter(array_unique($ticket_ids)));
+ if ($ticket_ids) {
+ $references = [];
+ $sql = mysqli_query($GLOBALS['mysqli'], "SELECT ticket_id, ticket_prefix, ticket_number FROM tickets WHERE ticket_id IN (" . implode(',', $ticket_ids) . ")");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $references[intval($row['ticket_id'])] = ticketReference($row);
+ }
+ foreach ($items as &$item) {
+ $item['extendedProps']['reference'] = $references[intval($item['extendedProps']['ticket_id'] ?? 0)] ?? '';
+ }
+ unset($item);
+ }
+ return timezoneItems($items);
+}
+
+/*
+ * ---------- booking ----------
+ */
+
+/*
+ * Give a ticket to an agent (when it's someone new) and book it for $start (on
+ * the company's clock) for $minutes, onsite or remote. $tell_client false keeps
+ * the contact and watchers out of it - the agent is always told.
+ * [ok, message, conflicts].
+ */
+function dispatchBook($ticket_id, $agent_id, $start, $minutes, $onsite, $tell_client = true) {
+ global $session_user_id;
+ $row = ticketRow($ticket_id);
+ if (!$row || !empty($row['ticket_archived_at'])) {
+ return [false, 'That ticket no longer exists.', []];
+ }
+ if (intval($row['ticket_client_id']) && !hasClientAccess($row['ticket_client_id'])) {
+ return [false, 'You do not have access to that client.', []];
+ }
+ if (!ticketIsOpen($row)) {
+ return [false, 'Ticket ' . ticketReference($row) . ' is resolved or closed - reopen it to schedule work.', []];
+ }
+ $start = ticketScheduleValue($start);
+ if ($start === '') {
+ return [false, 'Pick the date and time.', []];
+ }
+ $agent_id = intval($agent_id);
+ $agents = dispatchAgents();
+ if (!isset($agents[$agent_id])) {
+ return [false, 'Pick an agent.', []];
+ }
+ if (!isset(ticketMentionAgents($row['ticket_client_id'])[$agent_id])) {
+ return [false, $agents[$agent_id]['name'] . ' cannot open tickets of this client.', []];
+ }
+ if ($agent_id !== intval($row['ticket_assigned_to'])) {
+ [$assigned_ok, $assigned_message] = ticketChangeAssignee($row['ticket_id'], $agent_id);
+ if (!$assigned_ok) {
+ return [false, strip_tags($assigned_message), []];
+ }
+ // The agent who had the booking has it taken off their calendar
+ ticketMailScheduleAgentCancelled($row);
+ $row = ticketRow($ticket_id);
+ }
+ $end = date('Y-m-d H:i:s', strtotime($start) + max(15, min(1440, intval($minutes))) * 60);
+ $result = ticketSetSchedule($row, $start, $onsite ? 1 : 0, $end, (bool) $tell_client);
+ return [true, ticketReference($row) . ' scheduled with ' . $agents[$agent_id]['name'] . ' for ' . timezoneWhenFor($start, $end, $session_user_id), $result['conflicts']];
+}
+
+/** Take a ticket's booking off - dragged back onto the queue. [ok, message]. */
+function dispatchUnbook($ticket_id) {
+ $row = ticketRow($ticket_id);
+ if (!$row || (intval($row['ticket_client_id']) && !hasClientAccess($row['ticket_client_id']))) {
+ return [false, 'That ticket no longer exists.'];
+ }
+ if (empty($row['ticket_schedule'])) {
+ return [false, ticketReference($row) . ' has nothing booked.'];
+ }
+ ticketCancelSchedule($row);
+ return [true, ticketReference($row) . ' taken off the schedule - it is back in the queue'];
+}
+
+/** Give a ticket to another agent without booking it - Workload. A booked one is moved on the board instead. [ok, message]. */
+function dispatchAssign($ticket_id, $agent_id) {
+ $row = ticketRow($ticket_id);
+ if (!$row || !empty($row['ticket_archived_at'])) {
+ return [false, 'That ticket no longer exists.'];
+ }
+ if (intval($row['ticket_client_id']) && !hasClientAccess($row['ticket_client_id'])) {
+ return [false, 'You do not have access to that client.'];
+ }
+ if (!ticketIsOpen($row)) {
+ return [false, 'Ticket ' . ticketReference($row) . ' is resolved or closed.'];
+ }
+ $agent_id = intval($agent_id);
+ $agents = dispatchAgents();
+ if (!isset($agents[$agent_id])) {
+ return [false, 'Pick an agent.'];
+ }
+ if (!isset(ticketMentionAgents($row['ticket_client_id'])[$agent_id])) {
+ return [false, $agents[$agent_id]['name'] . ' cannot open tickets of this client.'];
+ }
+ if ($agent_id === intval($row['ticket_assigned_to'])) {
+ return [true, ticketReference($row) . ' is already theirs.'];
+ }
+ if (!empty($row['ticket_schedule'])) {
+ return [false, ticketReference($row) . ' is booked - move the booking on the board instead, so the new agent gets the calendar file.'];
+ }
+ [$ok, $message] = ticketChangeAssignee($row['ticket_id'], $agent_id);
+ return [$ok, $ok ? ticketReference($row) . ' given to ' . $agents[$agent_id]['name'] : strip_tags($message)];
+}
+
+/*
+ * A one-off event dragged to another time and/or from one agent's line to
+ * another's ($from, $to - the same for a move in time). Those who have the
+ * invitation are sent the update. [ok, message].
+ */
+function dispatchEventMove($event_id, $start, $end, $all_day, $from, $to) {
+ global $mysqli, $session_name;
+ $event = calendarEventRow($event_id);
+ if (!$event || !empty($event['event_archived_at'])) {
+ return [false, 'That event no longer exists.'];
+ }
+ if (intval($event['event_client_id']) && !hasClientAccess($event['event_client_id'])) {
+ return [false, 'You do not have access to that client.'];
+ }
+ if (!calendarEventCan($event, 'edit')) {
+ return [false, permissionRefusedText('module_client', 2, intval(lookupUserPermission('module_client')))];
+ }
+ if (calendarEventRepeats($event)) {
+ return [false, 'A repeating event is moved from Edit, so the whole series moves together.'];
+ }
+ $event_id = intval($event['event_id']);
+ $from = intval($from);
+ $to = intval($to);
+ if ($from !== $to && !isset(dispatchAgents()[$to])) {
+ return [false, 'Pick an agent.'];
+ }
+ $start = ticketScheduleValue($start);
+ if ($start === '') {
+ return [false, 'That is not a date and time.'];
+ }
+ if ($all_day) {
+ $days = $event['event_all_day'] ? max(0, intval((strtotime(substr($event['event_end'] ?: $event['event_start'], 0, 10)) - strtotime(substr($event['event_start'], 0, 10))) / 86400)) : 0;
+ $start = substr($start, 0, 10) . ' 00:00:00';
+ $end = date('Y-m-d 00:00:00', strtotime(substr($start, 0, 10) . " +$days day"));
+ } else {
+ $end = ticketScheduleValue($end);
+ if ($end === '' || $end <= $start) {
+ $length = $event['event_all_day'] ? 3600 : max(900, strtotime($event['event_end'] ?: $event['event_start']) - strtotime($event['event_start']));
+ $end = date('Y-m-d H:i:s', strtotime($start) + $length);
+ }
+ }
+ $all_day = $all_day ? 1 : 0;
+ $moved = $start !== $event['event_start'] || $end !== (string) $event['event_end'] || $all_day !== intval($event['event_all_day']);
+ if ($moved) {
+ mysqli_query($mysqli, "UPDATE calendar_events SET event_start = '" . escapeSql($start) . "', event_end = '" . escapeSql($end) . "', event_all_day = $all_day,
+ event_sequence = event_sequence + 1 WHERE event_id = $event_id");
+ }
+ $event = calendarEventRow($event_id);
+ $sent = 0;
+ if ($moved) {
+ // Those who have it get the new time - not an agent being taken off, who is sent the cancellation
+ $sent += calendarSendInvites($event, 'update', array_values(array_filter(calendarInvitedAttendees($event_id), function ($attendee) use ($from, $to) {
+ return $from === $to || intval($attendee['attendee_user_id']) !== $from;
+ })));
+ }
+ $words = '';
+ if ($from !== $to) {
+ $agents = array_keys(calendarEventAgents([$event_id])[$event_id] ?? []);
+ $agents = array_values(array_unique(array_merge(array_diff($agents, [$from]), [$to])));
+ [$added, $removed, $mailed] = calendarEventSetAgents($event, $agents);
+ $sent += $mailed;
+ $words = calendarEventAgentsText($added, $removed);
+ }
+ $what = trim(($moved ? 'moved to ' . timezoneEventWhenText($event, $event['event_start'], $event['event_end']) : '') . ($moved && $words ? ', ' : '') . $words);
+ logAudit("Calendar Event", "Edit", "$session_name (Dispatch) " . escapeSql($what ?: 'left') . " the event " . escapeSql($event['event_title']), intval($event['event_client_id']), $event_id);
+ return [true, $event['event_title'] . ($what ? " $what" : '') . ($sent ? " - emailed to $sent " . ($sent === 1 ? 'person' : 'people') : '')];
+}
+
+/*
+ * ---------- Workload ----------
+ */
+
+/** The week $date is in, from the agent's first day - [from, to] as Y-m-d. */
+function dispatchWeek($first_day, $date = null) {
+ $ts = $date ? strtotime($date) : time();
+ $offset = (intval(date('w', $ts)) - intval($first_day) + 7) % 7;
+ $from = date('Y-m-d', strtotime("-$offset days", $ts));
+ return [$from, date('Y-m-d', strtotime("$from +6 days"))];
+}
+
+/*
+ * Each agent's load: their open tickets as lead or helper, ITFlow's SLA state
+ * for each, due dates passed, tickets not booked and gone quiet, and the hours
+ * booked today and this week against the working hours in Admin > SLA - with
+ * flags (dispatchWorkloadFlags()). $first_day 0 is a week from Sunday, 1 from
+ * Monday. [agents => [...], team => averages, week => [from, to]].
+ */
+function dispatchWorkload(array $agent_ids, $first_day = 0) {
+ global $mysqli;
+ $agents = dispatchAgents();
+ $agent_ids = array_values(array_filter(array_unique(array_map('intval', $agent_ids)), function ($id) use ($agents) {
+ return isset($agents[$id]);
+ }));
+ [$week_from, $week_to] = dispatchWeek($first_day);
+ $today = date('Y-m-d');
+ [$day_minutes, $work_days] = dispatchWorkingDay();
+ $week_days = 0;
+ for ($i = 0; $i < 7; $i++) {
+ $week_days += in_array(intval(date('N', strtotime("$week_from +$i days"))), $work_days, true) ? 1 : 0;
+ }
+ $works_today = in_array(intval(date('N')), $work_days, true);
+
+ $rows = [];
+ foreach ($agent_ids as $id) {
+ $rows[$id] = [
+ 'id' => $id, 'name' => $agents[$id]['name'], 'color' => $agents[$id]['color'],
+ 'open' => 0, 'lead' => 0, 'helping' => 0,
+ 'sla' => ['breached' => 0, 'at_risk' => 0, 'running' => 0, 'paused' => 0, 'none' => 0],
+ 'overdue' => 0, 'unbooked' => 0, 'quiet' => 0, 'oldest' => '',
+ 'booked_today' => 0, 'booked_week' => 0,
+ 'capacity_today' => $works_today ? $day_minutes : 0, 'capacity_week' => $week_days * $day_minutes,
+ 'flags' => [], 'tickets' => [],
+ ];
+ }
+ if (!$agent_ids) {
+ return ['agents' => [], 'team' => ['open' => 0, 'booked_week' => 0], 'week' => [$week_from, $week_to]];
+ }
+ $in = implode(',', $agent_ids);
+ $helpers = ticketHelpersReady();
+
+ $sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_status,
+ ticket_sla_id, ticket_response_sla_alert_stage, ticket_resolution_sla_alert_stage, ticket_response_sla_met, ticket_resolution_sla_met,
+ ticket_first_response_at, ticket_response_due_at, ticket_resolution_due_at, ticket_due_at, ticket_resolved_at, ticket_closed_at,
+ ticket_schedule, " . (ticketScheduleEndReady() ? 'ticket_schedule_end' : 'NULL AS ticket_schedule_end') . ", ticket_onsite, ticket_created_at,
+ ticket_assigned_to, ticket_client_id, client_name, ticket_status_name, ticket_status_pauses_sla,
+ " . ($helpers ? 'th.user_id' : '0') . " AS helper_id,
+ (SELECT MAX(ticket_reply_created_at) FROM ticket_replies WHERE ticket_reply_ticket_id = tickets.ticket_id AND ticket_reply_type <> 'Client') AS last_reply_at
+ FROM tickets
+ LEFT JOIN clients ON client_id = ticket_client_id
+ LEFT JOIN ticket_statuses ON ticket_status_id = ticket_status
+ " . ($helpers ? "LEFT JOIN ticket_helpers th ON th.ticket_id = tickets.ticket_id AND th.user_id IN ($in)" : '') . "
+ WHERE " . TICKET_OPEN_SQL . " AND ticket_archived_at IS NULL" . clientScopeSql('ticket_client_id') . "
+ AND (ticket_assigned_to IN ($in)" . ($helpers ? ' OR th.user_id IS NOT NULL' : '') . ")");
+ $order = ['breached' => 0, 'at_risk' => 1, 'running' => 2, 'paused' => 3, 'none' => 4];
+ $quiet_before = time() - DISPATCH_QUIET_DAYS * 86400;
+ $seen = [];
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $lead = intval($row['ticket_assigned_to']);
+ $helper = intval($row['helper_id']);
+ $owners = [];
+ if (isset($rows[$lead])) {
+ $owners[$lead] = 'lead';
+ }
+ if ($helper && isset($rows[$helper]) && $helper !== $lead) {
+ $owners[$helper] = 'helper';
+ }
+ $sla = ticketSlaState($row);
+ $due = ticketDueState($row);
+ $last = max(strtotime($row['ticket_created_at']), $row['last_reply_at'] ? strtotime($row['last_reply_at']) : 0);
+ $quiet = $last < $quiet_before && $sla['key'] !== 'paused';
+ foreach ($owners as $agent_id => $role) {
+ if (isset($seen[$row['ticket_id'] . '-' . $agent_id])) {
+ continue;
+ }
+ $seen[$row['ticket_id'] . '-' . $agent_id] = true;
+ $r = &$rows[$agent_id];
+ $r['open']++;
+ $r[$role === 'lead' ? 'lead' : 'helping']++;
+ $r['sla'][in_array($sla['key'], ['met', 'missed'], true) ? 'none' : $sla['key']]++;
+ $r['overdue'] += ($due['key'] ?? '') === 'overdue' ? 1 : 0;
+ $r['unbooked'] += $role === 'lead' && empty($row['ticket_schedule']) ? 1 : 0;
+ $r['quiet'] += $quiet ? 1 : 0;
+ if ($r['oldest'] === '' || $row['ticket_created_at'] < $r['oldest']) {
+ $r['oldest'] = $row['ticket_created_at'];
+ }
+ $r['tickets'][] = [
+ 'id' => intval($row['ticket_id']),
+ 'reference' => ticketReference($row),
+ 'subject' => (string) $row['ticket_subject'],
+ 'client' => $row['client_name'] ?: 'Internal',
+ 'priority' => (string) $row['ticket_priority'],
+ 'status' => (string) $row['ticket_status_name'],
+ 'role' => $role,
+ 'sla' => $sla['key'],
+ 'sla_due' => $sla['due'] ?? '',
+ 'sla_html' => ticketSlaPill($sla),
+ 'due_html' => in_array($due['key'] ?? '', ['overdue', 'soon'], true) ? ticketDuePill($due) : '',
+ 'overdue' => ($due['key'] ?? '') === 'overdue',
+ 'quiet' => $quiet,
+ 'last' => timeAgo(date('Y-m-d H:i:s', $last)),
+ 'scheduled' => $row['ticket_schedule'] ? ticketScheduleShortText($row['ticket_schedule'], $row['ticket_schedule_end']) : '',
+ 'url' => ticketUrl($row['ticket_id'], $row['ticket_client_id']),
+ ];
+ unset($r);
+ }
+ }
+
+ // Booked time this week - their tickets and helper bookings
+ foreach (dispatchItems($week_from, $week_to, $agent_ids) as $item) {
+ $kind = $item['extendedProps']['kind'] ?? '';
+ $agent_id = intval($item['extendedProps']['agent'] ?? 0);
+ if (!isset($rows[$agent_id]) || !in_array($kind, ['ticket', 'helper'], true) || empty($item['start']) || empty($item['end'])) {
+ continue;
+ }
+ $start = strtotime($item['start']);
+ $minutes = max(0, intval((strtotime($item['end']) - $start) / 60));
+ $rows[$agent_id]['booked_week'] += $minutes;
+ if (date('Y-m-d', $start) === substr(timezoneToView(date('Y-m-d H:i:s')), 0, 10)) {
+ $rows[$agent_id]['booked_today'] += $minutes;
+ }
+ }
+
+ // Most urgent first: the SLA, a due date passed, the clock that runs out first, then the oldest
+ foreach ($rows as &$r) {
+ usort($r['tickets'], function ($a, $b) use ($order) {
+ return [$order[$a['sla']] ?? 9, $a['overdue'] ? 0 : 1, $a['sla_due'] ?: '9999', $a['id']] <=> [$order[$b['sla']] ?? 9, $b['overdue'] ? 0 : 1, $b['sla_due'] ?: '9999', $b['id']];
+ });
+ $r['oldest'] = $r['oldest'] !== '' ? timeAgo($r['oldest']) : '';
+ }
+ unset($r);
+
+ $team = dispatchWorkloadFlags($rows);
+ return ['agents' => array_values($rows), 'team' => $team, 'week' => [$week_from, $week_to], 'today' => $today];
+}
+
+/*
+ * Each agent's flags: behind (an SLA breached or a due date passed), watch (an
+ * SLA close to it), overloaded (well above the team in open tickets or booked
+ * hours, or booked past their working week) or room (well below it). The team
+ * averages: [open, booked_week].
+ */
+function dispatchWorkloadFlags(array &$rows) {
+ $count = count($rows);
+ $avg_open = $count ? array_sum(array_column($rows, 'open')) / $count : 0;
+ $avg_booked = $count ? array_sum(array_column($rows, 'booked_week')) / $count : 0;
+ foreach ($rows as &$r) {
+ $flags = [];
+ if ($r['sla']['breached'] || $r['overdue']) {
+ $parts = array_filter([$r['sla']['breached'] ? $r['sla']['breached'] . ' SLA breached' : '', $r['overdue'] ? $r['overdue'] . ' past due' : '']);
+ $flags[] = ['key' => 'behind', 'text' => 'Falling behind', 'why' => implode(', ', $parts)];
+ } elseif ($r['sla']['at_risk']) {
+ $flags[] = ['key' => 'watch', 'text' => 'Watch', 'why' => $r['sla']['at_risk'] . ' close to the SLA'];
+ }
+ $why = [];
+ if ($count > 1 && $r['open'] >= 1.5 * $avg_open && $r['open'] - $avg_open >= 3) {
+ $why[] = $r['open'] . ' open (team average ' . round($avg_open, 1) . ')';
+ }
+ if ($count > 1 && $r['booked_week'] >= 1.5 * $avg_booked && $r['booked_week'] - $avg_booked >= 240) {
+ $why[] = round($r['booked_week'] / 60, 1) . ' h booked this week (team average ' . round($avg_booked / 60, 1) . ' h)';
+ }
+ if ($r['capacity_week'] && $r['booked_week'] > $r['capacity_week']) {
+ $why[] = 'booked past their working week';
+ }
+ if ($why) {
+ $flags[] = ['key' => 'overloaded', 'text' => 'Overloaded', 'why' => implode('; ', $why)];
+ } elseif ($count > 1 && $avg_open >= 2 && $r['open'] <= 0.5 * $avg_open && $r['booked_week'] <= 0.5 * max($avg_booked, 1) && !$r['sla']['breached']) {
+ $flags[] = ['key' => 'room', 'text' => 'Has room', 'why' => $r['open'] . ' open (team average ' . round($avg_open, 1) . ')'];
+ }
+ $r['flags'] = $flags;
+ }
+ unset($r);
+ return ['open' => round($avg_open, 1), 'booked_week' => intval(round($avg_booked))];
+}
+
+/*
+ * ---------- This week ----------
+ */
+
+/** SQL: done between two SQL datetimes - resolved, or closed without resolving. */
+function dispatchDoneIn($from, $to, $to_op = '<=') {
+ return "(tickets.ticket_resolved_at >= $from AND tickets.ticket_resolved_at $to_op $to
+ OR (tickets.ticket_resolved_at IS NULL AND tickets.ticket_closed_at >= $from AND tickets.ticket_closed_at $to_op $to))";
+}
+
+/*
+ * The week's numbers: tickets in and closed each day, closed against last week
+ * and the four weeks before, the week's SLA results, and for each agent the
+ * tickets given to them this week (raised for them, or the ticket's "assigned
+ * the ticket to" history) against those they closed. $first_day as Workload's.
+ */
+function dispatchWeekStats(array $agent_ids, $first_day = 0) {
+ global $mysqli;
+ [$from, $to] = dispatchWeek($first_day);
+ $start = "'$from 00:00:00'";
+ $end = "'$to 23:59:59'";
+ $scope = "tickets.ticket_archived_at IS NULL" . clientScopeSql('tickets.ticket_client_id');
+ $one = function ($sql) use ($mysqli) {
+ return intval(mysqli_fetch_row(mysqli_query($mysqli, $sql))[0] ?? 0);
+ };
+
+ $days = [];
+ for ($i = 0; $i < 7; $i++) {
+ $date = date('Y-m-d', strtotime("$from +$i days"));
+ $days[$date] = ['date' => $date, 'label' => date('D j', strtotime($date)), 'inbound' => 0, 'closed' => 0, 'future' => $date > date('Y-m-d')];
+ }
+ $sql = mysqli_query($mysqli, "SELECT DATE(ticket_created_at), COUNT(*) FROM tickets WHERE $scope AND ticket_created_at BETWEEN $start AND $end GROUP BY 1");
+ while ($row = mysqli_fetch_row($sql)) {
+ if (isset($days[$row[0]])) {
+ $days[$row[0]]['inbound'] = intval($row[1]);
+ }
+ }
+ $sql = mysqli_query($mysqli, "SELECT DATE(COALESCE(tickets.ticket_resolved_at, tickets.ticket_closed_at)), COUNT(*) FROM tickets WHERE $scope AND " . dispatchDoneIn($start, $end) . " GROUP BY 1");
+ while ($row = mysqli_fetch_row($sql)) {
+ if (isset($days[$row[0]])) {
+ $days[$row[0]]['closed'] = intval($row[1]);
+ }
+ }
+ $inbound = array_sum(array_column($days, 'inbound'));
+ $closed = array_sum(array_column($days, 'closed'));
+
+ $last_from = date('Y-m-d', strtotime("$from -7 days"));
+ $four_from = date('Y-m-d', strtotime("$from -28 days"));
+ $totals = [
+ 'inbound' => $inbound,
+ 'closed' => $closed,
+ 'net' => $inbound - $closed,
+ 'open' => $one("SELECT COUNT(*) FROM tickets WHERE $scope AND " . TICKET_OPEN_SQL),
+ 'last_inbound' => $one("SELECT COUNT(*) FROM tickets WHERE $scope AND ticket_created_at >= '$last_from' AND ticket_created_at < '$from'"),
+ 'last_closed' => $one("SELECT COUNT(*) FROM tickets WHERE $scope AND " . dispatchDoneIn("'$last_from'", "'$from'", '<')),
+ 'avg_closed' => round($one("SELECT COUNT(*) FROM tickets WHERE $scope AND " . dispatchDoneIn("'$four_from'", "'$from'", '<')) / 4, 1),
+ ];
+
+ // SLA results: responses due this week, and resolutions due or done this week - the ones judged
+ $response = "tickets.ticket_sla_id > 0 AND tickets.ticket_response_due_at BETWEEN $start AND $end";
+ $done_week = dispatchDoneIn($start, $end);
+ $resolution = "tickets.ticket_sla_id > 0 AND (tickets.ticket_resolution_due_at BETWEEN $start AND $end OR $done_week)";
+ $sla = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT
+ SUM($response AND ticket_response_sla_met = 1) AS response_met,
+ SUM($response AND ticket_response_sla_met = 0) AS response_missed,
+ SUM($resolution AND ticket_resolution_sla_met = 1) AS resolution_met,
+ SUM($resolution AND ticket_resolution_sla_met = 0) AS resolution_missed,
+ SUM(" . TICKET_OPEN_SQL . " AND ticket_sla_id > 0 AND GREATEST(ticket_response_sla_alert_stage, ticket_resolution_sla_alert_stage) = 2) AS breached_now,
+ SUM(" . TICKET_OPEN_SQL . " AND ticket_sla_id > 0 AND GREATEST(ticket_response_sla_alert_stage, ticket_resolution_sla_alert_stage) = 1) AS at_risk_now
+ FROM tickets WHERE $scope AND (tickets.ticket_response_due_at BETWEEN $start AND $end
+ OR tickets.ticket_resolution_due_at BETWEEN $start AND $end OR $done_week OR " . TICKET_OPEN_SQL . ")"));
+ $sla = array_map('intval', $sla ?: []);
+
+ // Given to each agent this week: raised for them, or the history's "assigned the ticket to " - the longest name that fits
+ $agents = dispatchAgents();
+ $ids = array_values(array_filter(array_unique(array_map('intval', $agent_ids)), function ($id) use ($agents) {
+ return isset($agents[$id]);
+ }));
+ $given = array_fill_keys($ids, []);
+ if ($ids) {
+ $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_assigned_to FROM tickets WHERE $scope AND ticket_created_at BETWEEN $start AND $end AND ticket_assigned_to IN (" . implode(',', $ids) . ")");
+ while ($row = mysqli_fetch_row($sql)) {
+ $given[intval($row[1])][intval($row[0])] = true;
+ }
+ $by_name = [];
+ foreach ($ids as $id) {
+ $by_name[$id] = (string) $agents[$id]['name'];
+ }
+ uasort($by_name, function ($a, $b) {
+ return mb_strlen($b) <=> mb_strlen($a);
+ });
+ $sql = mysqli_query($mysqli, "SELECT ticket_history_ticket_id, ticket_history_description FROM ticket_history
+ JOIN tickets ON tickets.ticket_id = ticket_history_ticket_id
+ WHERE $scope AND ticket_history_created_at BETWEEN $start AND $end AND ticket_history_description LIKE '%assigned the ticket to %'");
+ while ($row = mysqli_fetch_row($sql)) {
+ foreach ($by_name as $id => $name) {
+ if ($name !== '' && preg_match('/assigned the ticket to ' . preg_quote($name, '/') . '( |$)/iu', (string) $row[1])) {
+ $given[$id][intval($row[0])] = true;
+ break;
+ }
+ }
+ }
+ }
+ $rows = [];
+ foreach ($ids as $id) {
+ $rows[] = [
+ 'id' => $id,
+ 'name' => $agents[$id]['name'],
+ 'color' => $agents[$id]['color'],
+ 'assigned' => count($given[$id]),
+ 'closed' => $one("SELECT COUNT(*) FROM tickets WHERE $scope AND ticket_assigned_to = $id AND " . dispatchDoneIn($start, $end)),
+ 'open' => $one("SELECT COUNT(*) FROM tickets WHERE $scope AND ticket_assigned_to = $id AND " . TICKET_OPEN_SQL),
+ 'sla_missed' => $one("SELECT COUNT(*) FROM tickets WHERE $scope AND ticket_assigned_to = $id
+ AND (($response AND ticket_response_sla_met = 0) OR ($resolution AND ticket_resolution_sla_met = 0))"),
+ ];
+ }
+ return ['week' => [$from, $to], 'days' => array_values($days), 'totals' => $totals, 'sla' => $sla, 'agents' => $rows];
+}
diff --git a/functions/ticket.php b/functions/ticket.php
index 24178fc7b..781bee9d5 100644
--- a/functions/ticket.php
+++ b/functions/ticket.php
@@ -2248,9 +2248,10 @@ function ticketScheduleValue($input) {
* cancellation: to the agent doing the work, and when client notifications
* are on (Admin > Ticket) to the contact and the watchers. $row has the
* ticket's id and, for a booking, location_address. With the booking's $start
- * and $end, the agent's email has the time on their own clock.
+ * and $end, the agent's email has the time on their own clock. $tell_client
+ * false leaves the contact and watchers out of it (Dispatch).
*/
-function ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start = null, $end = null) {
+function ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start = null, $end = null, $tell_client = true) {
global $config_ticket_client_general_notifications;
$ticket = ticketRow($row['ticket_id']);
if (!$ticket || !emailReady()) {
@@ -2263,7 +2264,7 @@ function ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start = nul
emailQueue([$agent + ['footnote' => "You get this as the agent $reference is assigned to."]], $subject,
ticketAgentEmailContent($ticket, 'scheduled', ['when' => $start ? timezoneWhenFor($start, $end, $ticket['ticket_assigned_to']) : $when_text] + $opts), ['from' => ticketEmailFrom(), 'cal_str' => $cal_str]);
}
- if (intval($config_ticket_client_general_notifications) === 1) {
+ if ($tell_client && intval($config_ticket_client_general_notifications) === 1) {
ticketMailSend($ticket['ticket_id'], $subject, ticketEmailContent($ticket, 'scheduled', $opts), ['cal_str' => $cal_str]);
}
}
@@ -2455,11 +2456,12 @@ 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. 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())].
+ * who follow the lead are sent the new time. $tell_client false leaves the
+ * contact and watchers out of it. 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) {
+function ticketSetSchedule(array $row, $schedule, $onsite, $end = null, $tell_client = true) {
global $mysqli, $session_user_id, $session_name;
$ticket_id = intval($row['ticket_id']);
$client_id = intval($row['ticket_client_id']);
@@ -2476,7 +2478,7 @@ function ticketSetSchedule(array $row, $schedule, $onsite, $end = null) {
$mail_row = ticketScheduleRow($ticket_id);
$cal_str = ticketScheduleIcs($mail_row, $schedule, $end);
$when_text = ticketScheduleWhenText($schedule, $end);
- ticketMailSchedule($mail_row, $cal_str, false, $when_text, $schedule, $end);
+ ticketMailSchedule($mail_row, $cal_str, false, $when_text, $schedule, $end, $tell_client);
// 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));