From 533b801a7028882cc65e430286ff40f583d534d5 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Thu, 19 Nov 2026 17:37:25 -0500 Subject: [PATCH] Ticket page: server-side reply drafts with discard and nightly cleanup (db 4.0.1), drop files on the reply box, quick time buttons, no-time prompt on billable replies, split a client reply into a new ticket, copy a ticket, apply a template to an open ticket, keep and read the original email on emailed replies, click-to-zoom pictures --- CHANGELOG.md | 16 +- admin/database_updates/4.0.1.php | 24 ++ agent/ajax.php | 26 ++ agent/js/ticket_reply_extras.js | 349 ++++++++++++++++++ agent/js/tickets_add_modal.js | 5 +- agent/modals/ticket/ticket_add.php | 51 ++- agent/modals/ticket/ticket_apply_template.php | 53 +++ agent/modals/ticket/ticket_email_source.php | 112 ++++++ agent/modals/ticket/ticket_reply_split.php | 102 +++++ agent/post/ticket.php | 161 ++++++++ agent/ticket.php | 55 ++- client/ticket.php | 4 +- cron/nightly_tasks.php | 6 + cron/ticket_email_parser.php | 15 +- css/itflow_custom.css | 7 + db.sql | 17 + functions.php | 1 + functions/ticket_reply_draft.php | 64 ++++ js/pretty_content.js | 66 +++- 19 files changed, 1110 insertions(+), 24 deletions(-) create mode 100644 admin/database_updates/4.0.1.php create mode 100644 agent/js/ticket_reply_extras.js create mode 100644 agent/modals/ticket/ticket_apply_template.php create mode 100644 agent/modals/ticket/ticket_email_source.php create mode 100644 agent/modals/ticket/ticket_reply_split.php create mode 100644 functions/ticket_reply_draft.php diff --git a/CHANGELOG.md b/CHANGELOG.md index f586e83db..59c24c152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-three database changes (3.6.6 to 4.0.0) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, a column on agents' settings for compact rows, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-four database changes (3.6.6 to 4.0.1) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, a column on agents' settings for compact rows, a table for reply drafts, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -142,6 +142,15 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - A list's filters that are on now stand out with a yellow edge, and an x at the end of the search box clears the search and every filter at once. - Shift-click a list's tick boxes to tick, or untick, every row between two clicks. - Compact rows: Your account > Preferences can show lists with tighter rows, so more fit on screen. +- Tickets: what you type in a ticket's reply box is kept as you write. Leave the page, close the browser or get signed out, and it's back next time with a note saying so - pick how to send it to carry on, or discard it. +- Tickets: drop files onto a ticket's reply box to attach them to your reply. +- Tickets: +15m, +30m and +1h beside Time worked add time in one click. The timer stops at the new total. +- Tickets: on a billable ticket, sending a reply with no time asks first - Send without time, or Add time. +- Tickets: Split into a new ticket, in the menu of a client's reply, makes a ticket of its own from a second problem raised in a reply - same client and contact, the reply as its details, its attachments with it. The reply leaves the first ticket, and a note on each points to the other. +- Tickets: Copy as a new ticket, in a ticket's More actions, opens New Ticket with its subject, details, priority, category, billing, contact, asset and tasks - for the same client, or pick another. +- Tickets: Apply a template, in a ticket's More actions, adds a template's tasks to a ticket already open (change them first if you like), asks what the template asks, and adds its tags and due time where the ticket has none. +- Tickets: emailed replies now keep the email as it arrived, as new tickets already did. Read beside it shows who it was from and to, its headers and everything it said - the reply line trims what shows on the ticket - and the .eml downloads from there. The client portal no longer lists these copies. +- Click a picture shrunk to fit in a ticket, document or Knowledge Base article to see it full size - in the client portal too. - Modules: Admin > Settings > Modules has five more switches, to take out of ITFlow what your business doesn't use - Dispatch, which comes with Ticketing; Bookkeeping, Purchasing and Trips, which come with invoicing; and the Calendar. Each part is off while the one it comes with is, and shows faded under it. Switched off, a part leaves the menus, the dashboard, search, the reports and the API, and its pages and windows say it is off. Nothing in it is deleted - switched back on, it is all there. Dispatch, Bookkeeping, Trips and the Calendar start on, as before. - Bookkeeping: switch it off when your books are kept somewhere else. Accounts, Transactions, Transfers, Reconcile and the statement imports go, and nobody picks an account: payments and income go into the default payment account, and expenses come out of the default expense account - both in Admin > Settings > Defaults, or the first account when there's no default. An expense is paid by The business or Paid personally. The dashboard leaves out the account balances, and the Tax Package its Accounts section. - Calendar: switched off, the calendar, its events and the calendar feeds go - a subscribed calendar stops getting them. Tickets are still booked from the ticket and on Dispatch, and booked work still shows on the dashboard. @@ -315,6 +324,11 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Lists: `js/list_filters.js` (every page) reads which filters are applied from the address - the GET form in a card header, its selects, text and search fields, and hidden fields inside its `.collapse` - and gives their fields `.itflow-filter-on`. The x it adds to the search's input group links to the same address without them and `page`. Hidden fields outside the collapse, `show_column`, `view`, `show`, `sort` and `order` are kept. Lists with their own "Clear all" get no x. - Lists: `js/bulk_actions.js` ticks a shift-clicked range of `.bulk-select` boxes within one form, firing `change` on each box it changes. - Database 4.0.0 adds `user_settings.user_config_compact_rows` (`compactRowsReady()` in `functions/user.php`), which puts `itflow-compact` on ``. +- Tickets: database 4.0.1 adds `ticket_reply_drafts` (ticket, agent, body, updated), kept by `functions/ticket_reply_draft.php` (`ticketReplyDraftsReady()`, `ticketReplyDraft()`, `ticketReplyDraftSave()` - purified, and dropped when it has no words or picture - and `ticketReplyDraftDelete()`). `agent/js/ticket_reply_extras.js` posts `ticket_reply_draft` to `agent/ajax.php` 1.5 seconds after typing stops and by `sendBeacon` on `pagehide`, then marks the editor clean so leaving doesn't warn. `add_ticket_reply` drops the draft; the nightly tasks drop drafts untouched for 30 days or on closed tickets. +- Tickets: the same script puts files dropped on the reply card in `#ticket_reply_attachments`, adds `data-time-add-minutes` to the time fields (firing focus, input and change so the timer and work times follow), and, on a form with `data-billable="1"`, holds a reply with words and no time for a SweetAlert2 question - added after the page's own submit checks, so it only asks about a reply that would go. +- Tickets: `split_ticket_reply` (`agent/modals/ticket/ticket_reply_split.php`) makes a ticket from a Client reply - details from the reply, contact from `ticket_reply_by` when it is the client's, category and billable from the ticket - moves the reply's attachment rows and files to it as ticket attachments, archives the reply, and adds an internal note and history on both. `apply_ticket_template` (`ticket_apply_template.php`, the shared template picker and task rows) adds the submitted tasks after the ticket's own and calls `ticketTemplateFinish()` with the fill-in answers and, when ticked, its defaults. `ticket_add.php` takes `copy_ticket_id`, and `agent/js/tickets_add_modal.js` now fills the lists for a client picked as the window opens even when it can be changed. +- Tickets: `cron/ticket_email_parser.php` `addReply()` takes the original message file and keeps it as the reply's `Original-parsed-email.eml` attachment (not a stranger's). `agent/modals/ticket/ticket_email_source.php` reads a kept `.eml` with ImapEngine's `FileMessage` - addresses, date, subject, attachments, the text part (or the HTML as text) and the raw header block - and both attachment lists on the ticket show Read for one. `client/ticket.php` leaves `Original-parsed-email.eml` out, as `guest/guest_view_ticket.php` did. +- `js/pretty_content.js` marks a `.prettyContent` picture shown smaller than it is (not one in a link) `itflow-zoomable` and opens it in a fixed layer on click; Escape closes the layer without closing a window under it. ## [26.11.8] diff --git a/admin/database_updates/4.0.1.php b/admin/database_updates/4.0.1.php new file mode 100644 index 000000000..d588dcffd --- /dev/null +++ b/admin/database_updates/4.0.1.php @@ -0,0 +1,24 @@ + false]); + exit; + } + $draft_ticket = ticketRow(intval($_POST['ticket_id'] ?? 0)); + if (!$draft_ticket || !empty($draft_ticket['ticket_closed_at']) + || (intval($draft_ticket['ticket_client_id']) && !hasClientAccess($draft_ticket['ticket_client_id']))) { + http_response_code(404); + echo json_encode(['ok' => false]); + exit; + } + ticketReplyDraftSave($draft_ticket['ticket_id'], $session_user_id, (string) ($_POST['html'] ?? '')); + $kept = ticketReplyDraft($draft_ticket['ticket_id'], $session_user_id) !== null; + echo json_encode(['ok' => true, 'kept' => $kept, 'time' => date('g:i A', strtotime(timezoneToView(date('Y-m-d H:i:s'))))]); + exit; +} + /* * A reply being written on a ticket, for saving as a canned response (Save * your reply as a canned response - agent/js/canned_response_save.js): made safe, with this diff --git a/agent/js/ticket_reply_extras.js b/agent/js/ticket_reply_extras.js new file mode 100644 index 000000000..4724768a3 --- /dev/null +++ b/agent/js/ticket_reply_extras.js @@ -0,0 +1,349 @@ +/* + * The ticket page's reply form (agent/ticket.php): + * + * - Drafts. What is typed is kept as it is written (agent/ajax.php ticket_reply_draft -> + * functions/ticket_reply_draft.php) - a moment after typing stops, and as the page is left - and + * the page puts it back in the reply box next time. Discard it drops it. Sending drops it too, + * on the server. + * - Files dropped on the reply box go in its Attach files field. + * - +15m, +30m and +1h add to Time worked. The timer stops at the new total, as it does when the + * time is typed. + * - A reply with something in it and no time, on a billable ticket, asks first. + */ +(function () { + 'use strict'; + + var form = document.getElementById('ticketReplyForm'); + if (!form) { + return; + } + var ticketId = form.querySelector('[name="ticket_id"]').value; + var csrf = form.querySelector('[name="csrf_token"]').value; + var composer = document.getElementById('replyComposer'); + var status = form.querySelector('[data-reply-draft-status]'); + + function editor() { + return window.tinymce ? tinymce.get('ticket_reply') : null; + } + + function content() { + var ed = editor(); + if (ed) { + return ed.getContent(); + } + var textarea = document.getElementById('ticket_reply'); + return textarea ? textarea.value : ''; + } + + function hasWords() { + var ed = editor(); + var text = ed ? ed.getContent({ format: 'text' }) : content().replace(/<[^>]*>/g, ''); + return text.replace(/ /g, ' ').trim() !== '' || / 50) { + var textarea = document.getElementById('ticket_reply'); + if (textarea) { + lastSaved = textarea.value; + textarea.addEventListener('input', queueSave); + } + return; + } + setTimeout(waitForEditor, 200); + })(); + + // Leaving with something not yet kept - it goes now + window.addEventListener('pagehide', function () { + if (sending || lastSaved === null || !navigator.sendBeacon) { + return; + } + var html = content(); + if (html === lastSaved) { + return; + } + var data = new FormData(); + data.append('ticket_reply_draft', '1'); + data.append('csrf_token', csrf); + data.append('ticket_id', ticketId); + data.append('html', html); + navigator.sendBeacon('ajax.php', data); + }); + + var discard = form.querySelector('[data-reply-draft-discard]'); + if (discard) { + discard.addEventListener('click', function (e) { + e.preventDefault(); + var drop = function () { + clearTimeout(saveTimer); + itflowPost('ajax.php', { ticket_reply_draft: 1, csrf_token: csrf, ticket_id: ticketId, html: '' }, function () { + var ed = editor(); + if (ed) { + ed.setContent(''); + ed.setDirty(false); + } else if (document.getElementById('ticket_reply')) { + document.getElementById('ticket_reply').value = ''; + } + lastSaved = content(); + var note = form.querySelector('[data-reply-draft-note]'); + if (note) { + note.remove(); + } + setStatus(''); + }); + }; + if (typeof Swal === 'undefined') { + drop(); + return; + } + Swal.fire({ + theme: document.documentElement.getAttribute('data-bs-theme') === 'dark' ? 'dark' : 'light', + title: 'Discard your unsent reply?', + icon: 'warning', + showCancelButton: true, + confirmButtonText: 'Discard', + cancelButtonText: 'Keep it', + reverseButtons: true, + focusCancel: true, + buttonsStyling: false, + customClass: { confirmButton: 'btn btn-danger mx-1', cancelButton: 'btn btn-secondary mx-1' } + }).then(function (result) { + if (result.isConfirmed) { + drop(); + } + }); + }); + } + } + + // ---- Files dropped on the reply box + + var fileInput = document.getElementById('ticket_reply_attachments'); + var dropBox = form.querySelector('.card'); + var filesNote = form.querySelector('[data-reply-files-note]'); + var depth = 0; + + function carriesFiles(e) { + return e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') !== -1; + } + + function showFilesNote() { + if (!filesNote || !fileInput) { + return; + } + var count = fileInput.files.length; + filesNote.hidden = !count || composerOpen(); + filesNote.innerHTML = ''; + filesNote.appendChild(document.createTextNode(count + (count === 1 ? ' file is' : ' files are') + ' ready to attach - pick how to send your reply.')); + } + + if (fileInput && dropBox) { + dropBox.addEventListener('dragenter', function (e) { + if (carriesFiles(e)) { + depth++; + dropBox.classList.add('itflow-reply-drop'); + } + }); + dropBox.addEventListener('dragleave', function (e) { + if (carriesFiles(e)) { + depth = Math.max(0, depth - 1); + if (!depth) { + dropBox.classList.remove('itflow-reply-drop'); + } + } + }); + dropBox.addEventListener('dragover', function (e) { + if (carriesFiles(e)) { + e.preventDefault(); + e.dataTransfer.dropEffect = 'copy'; + } + }); + dropBox.addEventListener('drop', function (e) { + if (!carriesFiles(e)) { + return; + } + e.preventDefault(); + depth = 0; + dropBox.classList.remove('itflow-reply-drop'); + var transfer = new DataTransfer(); + Array.prototype.forEach.call(fileInput.files, function (file) { + transfer.items.add(file); + }); + // A folder comes as an entry with no size and no type - left out + Array.prototype.forEach.call(e.dataTransfer.files, function (file) { + if (file.size || file.type) { + transfer.items.add(file); + } + }); + fileInput.files = transfer.files; + fileInput.dispatchEvent(new Event('change', { bubbles: true })); + showFilesNote(); + }); + if (composer) { + composer.addEventListener('shown.bs.collapse', showFilesNote); + } + } + + // ---- +15m, +30m, +1h + + function pad(value) { + return value < 10 ? '0' + value : String(value); + } + + form.addEventListener('click', function (e) { + var button = e.target.closest('[data-time-add-minutes]'); + if (!button) { + return; + } + var h = document.getElementById('hours'); + var m = document.getElementById('minutes'); + var s = document.getElementById('seconds'); + if (!h || !m || !s) { + return; + } + // The timer stops where it is first, as when the time is typed (agent/js/ticket_time_tracking.js) + m.dispatchEvent(new Event('focus')); + var total = (parseInt(h.value, 10) || 0) * 3600 + (parseInt(m.value, 10) || 0) * 60 + (parseInt(s.value, 10) || 0) + + parseInt(button.dataset.timeAddMinutes, 10) * 60; + total = Math.min(total, 23 * 3600 + 59 * 60 + 59); + h.value = pad(Math.floor(total / 3600)); + m.value = pad(Math.floor((total % 3600) / 60)); + s.value = pad(total % 60); + [h, m, s].forEach(function (field) { + field.dispatchEvent(new Event('input', { bubbles: true })); + field.dispatchEvent(new Event('change', { bubbles: true })); + }); + }); + + // ---- No time on a billable ticket + + function timeWorked() { + var total = 0; + [['hours', 3600], ['minutes', 60], ['seconds', 1]].forEach(function (part) { + var field = document.getElementById(part[0]); + total += field ? (parseInt(field.value, 10) || 0) * part[1] : 0; + }); + return total; + } + + // After the page's own checks (the composer shut, the To line) - they are added as the page is read + function onSubmit(e) { + if (e.defaultPrevented) { + return; + } + if (form.dataset.billable === '1' && form.dataset.noTimeOk !== '1' && composerOpen() && hasWords() && timeWorked() === 0 + && document.getElementById('hours') && typeof Swal !== 'undefined') { + e.preventDefault(); + var submitter = e.submitter || null; + Swal.fire({ + theme: document.documentElement.getAttribute('data-bs-theme') === 'dark' ? 'dark' : 'light', + title: 'No time on this reply', + text: 'This ticket is billable. Send the reply without any time?', + icon: 'question', + showCancelButton: true, + confirmButtonText: 'Send without time', + cancelButtonText: 'Add time', + reverseButtons: true, + focusCancel: true, + returnFocus: false, + buttonsStyling: false, + customClass: { confirmButton: 'btn btn-primary mx-1', cancelButton: 'btn btn-secondary mx-1' } + }).then(function (result) { + if (result.isConfirmed) { + form.dataset.noTimeOk = '1'; + if (typeof form.requestSubmit === 'function') { + form.requestSubmit(submitter); + } else { + form.submit(); + } + } else { + var minutes = document.getElementById('minutes'); + if (minutes) { + minutes.focus(); + } + } + }); + return; + } + // Going, unless something after this holds it back - nothing more to keep as a draft + setTimeout(function () { + if (!e.defaultPrevented) { + sending = true; + clearTimeout(saveTimer); + } + }, 0); + } + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', function () { + form.addEventListener('submit', onSubmit); + }); + } else { + form.addEventListener('submit', onSubmit); + } +})(); diff --git a/agent/js/tickets_add_modal.js b/agent/js/tickets_add_modal.js index 99ac03f43..03b6d71e7 100644 --- a/agent/js/tickets_add_modal.js +++ b/agent/js/tickets_add_modal.js @@ -121,8 +121,9 @@ if (clientSelectDropdown) { - // If the client selector is disabled, we must be on a client-specific page instead. Trigger the lists to update. - if (clientSelectDropdown.disabled) { + // If the client selector is disabled, we must be on a client-specific page instead - or it starts + // with a client picked (a copy of a ticket) that can still be changed. Trigger the lists to update. + if (clientSelectDropdown.disabled || clientSelectDropdown.value) { let client_id = clientSelectDropdown.value; diff --git a/agent/modals/ticket/ticket_add.php b/agent/modals/ticket/ticket_add.php index eed7e6408..deeec711a 100644 --- a/agent/modals/ticket/ticket_add.php +++ b/agent/modals/ticket/ticket_add.php @@ -9,6 +9,10 @@ require_once '../../../includes/modal_header.php'; * in the person it is assigned to and its site. When the person or the asset * already has open tickets, they show under the contact - so a second ticket * for the same problem gets noticed before it is raised. + * + * Copy of a ticket (copy_ticket_id - its More actions > Copy as a new ticket): it starts with + * that ticket's subject, details, priority, category, billing, contact, asset, site, vendor and + * tasks, for the same client - which can be changed, and its lists follow. */ enforceUserPermission('module_support', 2); @@ -40,6 +44,37 @@ if ($client_id) { enforceClientAccess(); } +// A copy of a ticket the agent may reach +$copy = intval($_GET['copy_ticket_id'] ?? 0) ? ticketRow($_GET['copy_ticket_id']) : null; +if ($copy && intval($copy['ticket_client_id']) && !hasClientAccess($copy['ticket_client_id'])) { + $copy = null; +} +$copy_client_id = 0; +$prefill_priority = 'Medium'; +$prefill_category_id = 0; +$prefill_billable = intval($config_ticket_default_billable) === 1; +$existing_tasks = []; +if ($copy) { + $prefill_subject = (string) $copy['ticket_subject']; + $prefill_details_html = (string) $copy['ticket_details']; + $prefill_priority = (string) $copy['ticket_priority']; + $prefill_category_id = intval($copy['ticket_category']); + $prefill_billable = intval($copy['ticket_billable']) === 1; + if (!$client_id) { + $copy_client_id = intval($copy['ticket_client_id']); + } + if ($client_id === intval($copy['ticket_client_id']) || $copy_client_id) { + $contact_id = $contact_id ?: intval($copy['ticket_contact_id']); + $asset_id = $asset_id ?: intval($copy['ticket_asset_id']); + $location_id = $location_id ?: intval($copy['ticket_location_id']); + $vendor_id = $vendor_id ?: intval($copy['ticket_vendor_id']); + } + $sql_copy_tasks = mysqli_query($mysqli, "SELECT task_name, task_completion_estimate FROM tasks WHERE task_ticket_id = " . intval($copy['ticket_id']) . " ORDER BY task_order ASC, task_id ASC"); + while ($task = mysqli_fetch_assoc($sql_copy_tasks)) { + $existing_tasks[] = ['name' => (string) $task['task_name'], 'estimate' => intval($task['task_completion_estimate'])]; + } +} + // Raised about a service (its page's Report a problem) - one of this client's that is not archived $service = intval($_GET['service_id'] ?? 0) ? serviceRow($_GET['service_id']) : null; if ($service && (!$client_id || intval($service['service_client_id']) !== $client_id || $service['service_archived_at'])) { @@ -66,7 +101,7 @@ ob_start(); ?>
@@ -132,7 +167,7 @@ ob_start(); $client_id_select = intval($row['client_id']); $client_name = escapeHtml($row['client_name']); ?> - + @@ -177,10 +212,10 @@ ob_start();
@@ -193,7 +228,7 @@ ob_start(); @@ -281,7 +316,7 @@ ob_start();
- value="1" id="billable" data-template-field="billable"> + value="1" id="billable" data-template-field="billable">
diff --git a/agent/modals/ticket/ticket_apply_template.php b/agent/modals/ticket/ticket_apply_template.php new file mode 100644 index 000000000..cabea7d71 --- /dev/null +++ b/agent/modals/ticket/ticket_apply_template.php @@ -0,0 +1,53 @@ + + + + + + + +
+ + + 'That email is no longer kept.']); + exit; +} +$row = ticketForModal($attachment['ticket_attachment_ticket_id'], 1); +$ticket_id = intval($row['ticket_id']); + +$path = dirname(__DIR__, 3) . "/uploads/tickets/$ticket_id/" . basename((string) $attachment['ticket_attachment_reference_name']); +$too_big = is_file($path) && filesize($path) > 25 * 1024 * 1024; +$raw = is_file($path) && !$too_big ? (string) file_get_contents($path) : ''; + +$fields = []; +$header_text = ''; +$body_text = ''; +$attachment_names = []; +if ($raw !== '') { + require_once dirname(__DIR__, 3) . '/libs/vendor/autoload.php'; // ImapEngine + // The header block as it came - everything before the first blank line, folded lines kept + $split = preg_split("/\r?\n\r?\n/", $raw, 2); + $header_text = $split[0] ?? ''; + try { + $message = new \DirectoryTree\ImapEngine\FileMessage($raw); + $people = function ($addresses) { + return implode(', ', array_map(function ($address) { + $name = trim((string) $address->name()); + return $name !== '' ? "$name <" . $address->email() . '>' : (string) $address->email(); + }, array_filter((array) $addresses))); + }; + $from = $message->from(); + $fields = array_filter([ + 'From' => $from ? $people([$from]) : '', + 'To' => $people($message->to()), + 'Cc' => $people($message->cc()), + 'Date' => $message->date() ? $message->date()->format('Y-m-d H:i:s T') : '', + 'Subject' => (string) $message->subject(), + ], function ($value) { return $value !== ''; }); + $body_text = (string) $message->text(); + if (trim($body_text) === '' && $message->html()) { + $html = preg_replace('/<(style|script|head)\b[^>]*>.*?<\/\1>/is', '', (string) $message->html()); + $html = preg_replace('/<(br|\/p|\/div|\/tr|\/li|\/h[1-6])[^>]*>/i', "\n", $html); + $body_text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8'); + } + $body_text = trim(preg_replace("/\n{3,}/", "\n\n", str_replace("\r", '', $body_text))); + foreach ($message->attachments() as $part) { + $attachment_names[] = (string) $part->filename(); + } + } catch (Throwable $e) { + $body_text = ''; + } +} + +ob_start(); + +?> + + + + + "That reply can't be split off - only a client's reply can."]); + exit; +} +$row = ticketForModal($reply['ticket_reply_ticket_id'], 2, true); +$reference = escapeHtml(ticketReference($row)); + +// What it says, to start the subject with - its first words +$words = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags(preg_replace('/<(br|\/p|\/div)[^>]*>/i', ' ', (string) $reply['ticket_reply'])), ENT_QUOTES, 'UTF-8'))); +$words = preg_replace('/^Email from: .*? at [^:]*:-\s*/u', '', $words); +$suggested = mb_strlen($words) > 80 ? rtrim(mb_substr($words, 0, 77)) . '...' : $words; + +$assigned = intval($row['ticket_assigned_to']); + +ob_start(); + +?> + +
+ + + + +
+ + +" . escapeHtml(ticketReference($row)) . " is closed.", 'error'); + redirect(); + } + $client_id = intval($row['ticket_client_id']); + + $subject_input = trim((string) ($_POST['subject'] ?? '')); + if ($subject_input === '') { + flashAlert('The new ticket needs a subject.', 'error'); + redirect(); + } + $subject = escapeSql(mb_substr($subject_input, 0, 500)); + $priority = escapeSql(ticketPriority($_POST['priority'] ?? $row['ticket_priority'])); + $assigned_to = ticketAgentId($_POST['assigned_to'] ?? 0); + $ticket_status = $assigned_to ? TICKET_STATUS_OPEN : TICKET_STATUS_NEW; + $category_id = intval($row['ticket_category']); + $billable = intval($row['ticket_billable']) ? 1 : 0; + // The person who wrote it, when they are one of this client's contacts + $contact_id = ticketClientOwnedId('contact', $reply['ticket_reply_by'], $client_id); + $details = mysqli_real_escape_string($mysqli, (string) $reply['ticket_reply']); + + mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = LAST_INSERT_ID(config_ticket_next_number), config_ticket_next_number = config_ticket_next_number + 1 WHERE company_id = 1"); + $ticket_number = mysqli_insert_id($mysqli); + $ticket_prefix = escapeSql($config_ticket_prefix); + $url_key = randomString(32); + + mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix', ticket_number = $ticket_number, ticket_source = 'Agent', ticket_category = $category_id, + ticket_subject = '$subject', ticket_details = '$details', ticket_priority = '$priority', ticket_billable = $billable, ticket_status = $ticket_status, + ticket_created_by = $session_user_id, ticket_assigned_to = $assigned_to, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', + ticket_client_id = $client_id, ticket_invoice_id = 0, ticket_project_id = 0, ticket_location_id = 0, ticket_asset_id = 0, ticket_vendor_id = 0"); + $new_id = mysqli_insert_id($mysqli); + applyTicketSla($new_id); + $new = ticketRow($new_id); + $new_reference = escapeSql(ticketReference($new)); + $old_reference = escapeSql(ticketReference($row)); + + // Its attachments go with it, files and all (uploads/tickets//), as the new ticket's own + $sql_attachments = mysqli_query($mysqli, "SELECT ticket_attachment_id, ticket_attachment_reference_name FROM ticket_attachments + WHERE ticket_attachment_reply_id = $ticket_reply_id AND ticket_attachment_ticket_id = $ticket_id"); + if (mysqli_num_rows($sql_attachments)) { + $from_dir = dirname(__DIR__, 2) . "/uploads/tickets/$ticket_id/"; + $to_dir = dirname(__DIR__, 2) . "/uploads/tickets/$new_id/"; + mkdirMissing(dirname(__DIR__, 2) . "/uploads/tickets/"); + mkdirMissing($to_dir); + while ($attachment = mysqli_fetch_assoc($sql_attachments)) { + $from_name = basename((string) $attachment['ticket_attachment_reference_name']); + if ($from_name !== '' && is_file($from_dir . $from_name)) { + rename($from_dir . $from_name, $to_dir . $from_name); + } + mysqli_query($mysqli, "UPDATE ticket_attachments SET ticket_attachment_ticket_id = $new_id, ticket_attachment_reply_id = NULL + WHERE ticket_attachment_id = " . intval($attachment['ticket_attachment_id'])); + } + } + + // The reply leaves this ticket, and a note says where it went + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_archived_at = NOW() WHERE ticket_reply_id = $ticket_reply_id"); + $new_url = escapeSql(ticketUrl($new_id, $client_id)); + $old_url = escapeSql(ticketUrl($ticket_id, $client_id)); + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'A reply from the client was split off into $new_reference - $subject', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Split off from a reply on $old_reference.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $new_id"); + mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); + logTicketHistory($ticket_id, "$session_name split a reply off into $new_reference"); + logTicketHistory($new_id, "$session_name made this ticket from a reply on $old_reference"); + logAudit("Ticket", "Create", "$session_name split a reply on ticket $old_reference into ticket $new_reference - $subject", $client_id, $new_id); + + // The client is told about the new ticket, as for any other + if (intval($config_ticket_client_general_notifications) === 1) { + ticketMailCreated($new_id, 'Ticket Created', []); + } + triggerCustomAction('ticket_create', $new_id); + if ($assigned_to) { + if (ticketTeamNotifyOn('assigned_app')) { + ticketNotifyAgent($assigned_to, $new, "Ticket " . ticketReference($new) . " - Subject: " . $new['ticket_subject'] . " has been assigned to you by $session_name"); + } + ticketMailAssigned($assigned_to, [$new_id], stripslashes($session_name)); + } + ticketStatusMovedByAgent($new_id, TICKET_STATUS_NEW, $ticket_status); + + flashAlert("The reply is now ticket " . escapeHtml(ticketReference($new)) . ""); + + redirect(ticketUrl($new_id, $client_id)); + +} + +/* + * A ticket template applied to a ticket already open - its tasks (as edited in the window), the + * answers to what it asks, and its tags and due time where the ticket has none. The ticket's + * subject, details, category and the rest stay as they are. + */ +if (isset($_POST['apply_ticket_template'])) { + + validateCSRFToken(); + + $row = ticketForRequest($_POST['ticket_id'] ?? 0, 2); + $ticket_id = intval($row['ticket_id']); + if (!empty($row['ticket_closed_at'])) { + flashAlert("Ticket " . escapeHtml(ticketReference($row)) . " is closed.", 'error'); + redirect(); + } + $ticket_template_id = intval($_POST['ticket_template_id'] ?? 0); + $template = $ticket_template_id ? ticketTemplateRow($ticket_template_id) : null; + if (!$template || !empty($template['ticket_template_archived_at'])) { + flashAlert('Pick a template to apply.', 'error'); + redirect(); + } + $answers = ticketFillInAnswers(ticketTemplateFillInsFor($ticket_template_id), $_POST['fill_ins'] ?? [], $fill_in_error); + if ($answers === null) { + flashAlert($fill_in_error, 'error'); + redirect(); + } + + // The tasks as the window left them, after the ticket's own + $added = 0; + if (isset($_POST['tasks_submitted'])) { + $last = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(MAX(task_order), 0) FROM tasks WHERE task_ticket_id = $ticket_id")); + $offset = intval($last[0] ?? 0); + foreach (parseSubmittedTasks() as $task) { + $order = $offset + intval($task['order']) + 1; + mysqli_query($mysqli, "INSERT INTO tasks SET task_name = '{$task['name']}', task_order = $order, task_completion_estimate = {$task['estimate']}, task_ticket_id = $ticket_id"); + $added++; + } + } + + $template_name = escapeSql($template['ticket_template_name']); + ticketTemplateFinish($ticket_id, $ticket_template_id, intval($_POST['template_defaults'] ?? 0) === 1, !isset($_POST['tasks_submitted']), $answers, + "$session_name applied template $template_name"); + mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); + logAudit("Ticket", "Edit", "$session_name applied template $template_name to ticket " . escapeSql(ticketReference($row)), intval($row['ticket_client_id']), $ticket_id); + + flashAlert("Template " . escapeHtml($template['ticket_template_name']) . " applied" . ($added ? " - $added task" . ($added === 1 ? '' : 's') . " added" : '')); + + redirect(); + +} + if (isset($_POST['merge_ticket'])) { validateCSRFToken(); diff --git a/agent/ticket.php b/agent/ticket.php index 02c5b3fc9..cf3356ad4 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -662,6 +662,14 @@ if (isset($_GET['ticket_id'])) { Move to another client + + Copy as a new ticket + + + + Apply a template + + @@ -758,7 +766,11 @@ if (isset($_GET['ticket_id'])) { ?>
- View + + Read + + View + Download = 3) { ?> Delete @@ -809,9 +821,13 @@ if (isset($_GET['ticket_id'])) { - + -
+ @@ -843,6 +859,14 @@ if (isset($_GET['ticket_id'])) {
replied STOP to your texts - they can't be texted until they reply START.
+ +
+ Your unsent reply from is kept - pick how to send it to carry on, or discard it. +
+ + + +
@@ -921,7 +945,7 @@ if (isset($_GET['ticket_id'])) { $mention_attr = ticketMentionAgentsAttr($client_id); ?>
- + @@ -934,7 +958,7 @@ if (isset($_GET['ticket_id'])) {
-
+
@@ -944,6 +968,12 @@ if (isset($_GET['ticket_id'])) {
+ +
+ '+15m', 30 => '+30m', 60 => '+1h'] as $minutes => $label) { ?> + + +
@@ -988,6 +1018,7 @@ if (isset($_GET['ticket_id'])) {
+
@@ -1146,6 +1177,12 @@ if (isset($_GET['ticket_id'])) { Edit + + + Split into a new ticket + + Redact @@ -1179,7 +1216,11 @@ if (isset($_GET['ticket_id'])) { ?>
- View + + Read + + View + Download = 3) { ?> Delete @@ -2020,6 +2061,8 @@ if (!empty($can_edit_ticket) && !empty($ticket_is_open)) { ?> + + = 95) { // Treat as a reply/duplicate - $email_processed = addReply($from_email, $date, $subject, $ticket_number, $message_body, $attachments); + $email_processed = addReply($from_email, $date, $subject, $ticket_number, $message_body, $attachments, $original_message_file); break; } } diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 47dc0cf52..69b5ba443 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -10193,3 +10193,10 @@ input.itflow-filter-on { padding-top: .3rem; padding-bottom: .3rem; } + +/* Files dragged over a ticket's reply box (agent/js/ticket_reply_extras.js) */ +.itflow-reply-drop { + outline: 2px dashed var(--bs-primary); + outline-offset: -2px; + background-color: var(--bs-primary-bg-subtle); +} diff --git a/db.sql b/db.sql index 50d987c2c..b9f17e70c 100644 --- a/db.sql +++ b/db.sql @@ -4509,6 +4509,23 @@ CREATE TABLE `ticket_replies` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `ticket_reply_drafts` +-- + +DROP TABLE IF EXISTS `ticket_reply_drafts`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticket_reply_drafts` ( + `ticket_id` int(11) NOT NULL, + `user_id` int(11) NOT NULL, + `draft_body` longtext NOT NULL, + `draft_updated_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`ticket_id`,`user_id`), + KEY `draft_updated_at` (`draft_updated_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `ticket_reply_mentions` -- diff --git a/functions.php b/functions.php index 91e079284..209832556 100644 --- a/functions.php +++ b/functions.php @@ -119,6 +119,7 @@ require_once __DIR__ . '/functions/rmm_tactical.php'; require_once __DIR__ . '/functions/client_onboarding.php'; require_once __DIR__ . '/functions/ticket_mention.php'; require_once __DIR__ . '/functions/ticket_reply_recipients.php'; +require_once __DIR__ . '/functions/ticket_reply_draft.php'; require_once __DIR__ . '/functions/quick_ticket.php'; require_once __DIR__ . '/functions/getting_started.php'; require_once __DIR__ . '/functions/settings.php'; diff --git a/functions/ticket_reply_draft.php b/functions/ticket_reply_draft.php new file mode 100644 index 000000000..5fe39b4b4 --- /dev/null +++ b/functions/ticket_reply_draft.php @@ -0,0 +1,64 @@ +='); + } + return $ready; +} + +/** An agent's draft on a ticket - ['body' (HTML, as typed), 'updated_at'] - or null. */ +function ticketReplyDraft($ticket_id, $user_id) { + global $mysqli; + if (!ticketReplyDraftsReady()) { + return null; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT draft_body, draft_updated_at FROM ticket_reply_drafts + WHERE ticket_id = " . intval($ticket_id) . " AND user_id = " . intval($user_id) . " LIMIT 1")); + return $row ? ['body' => (string) $row['draft_body'], 'updated_at' => $row['draft_updated_at']] : null; +} + +/** Keep an agent's draft - made safe first. Nothing worth keeping (no words, no picture) drops it. */ +function ticketReplyDraftSave($ticket_id, $user_id, $html) { + global $mysqli; + if (!ticketReplyDraftsReady()) { + return false; + } + $html = documentHtmlPurify((string) $html); + $words = trim(html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8'), " \t\n\r\0\x0B\xC2\xA0"); + if ($words === '' && stripos($html, '