From ec205ca6333eb5e4dc18214c84f03f6ee1c05a0c Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 13 Oct 2026 13:56:47 -0400 Subject: [PATCH] Agent picker for project managers and recurring tickets: pick the manager on the project page and projects list, and the agent on recurring tickets, inline like ticket assignees --- agent/ajax.php | 170 +++++++++ agent/modals/ticket/ticket_assign.php | 82 ---- agent/modals/ticket/ticket_billable.php | 60 --- agent/modals/ticket/ticket_priority.php | 64 ---- agent/post/ticket.php | 191 ---------- agent/project.php | 11 +- agent/projects.php | 9 +- agent/recurring_tickets.php | 3 + agent/ticket.php | 53 +-- agent/ticket_list.php | 41 +- css/itflow_custom.css | 43 +++ functions.php | 1 + functions/format.php | 4 +- functions/ticket_fields.php | 405 ++++++++++++++++++++ includes/footer.php | 1 + js/quick_pick.js | 486 ++++++++++++++++++++++++ 16 files changed, 1145 insertions(+), 479 deletions(-) delete mode 100644 agent/modals/ticket/ticket_assign.php delete mode 100644 agent/modals/ticket/ticket_billable.php delete mode 100644 agent/modals/ticket/ticket_priority.php create mode 100644 functions/ticket_fields.php create mode 100644 js/quick_pick.js diff --git a/agent/ajax.php b/agent/ajax.php index 1d2a0499a..ba6962307 100644 --- a/agent/ajax.php +++ b/agent/ajax.php @@ -179,6 +179,176 @@ if (isset($_POST['tag_picker_set']) || isset($_POST['tag_picker_create'])) { exit(); } +/* + * Quick pickers (js/quick_pick.js) - a ticket's status, priority, assignee + * and billable, a project's manager and a recurring ticket's assignee, + * changed in place instead of through a modal. GET lists the choices; POST makes the change through the same + * functions the post.php handlers use (functions/ticket_fields.php) and sends + * back the redrawn values. + */ +if (isset($_GET['quick_pick_options'])) { + + header('Content-Type: application/json'); + enforceUserPermission('module_support', 2); + + $field = (string) ($_GET['field'] ?? ''); + $options = []; + + if ($field === 'priority') { + $colors = ['Urgent' => 'var(--bs-emphasis-color)', 'High' => 'var(--bs-danger)', 'Medium' => 'var(--bs-warning)', 'Low' => 'var(--bs-info)']; + foreach (TICKET_PRIORITIES as $priority) { + $options[] = ['value' => $priority, 'label' => $priority, 'color' => $colors[$priority]]; + } + } elseif ($field === 'status') { + foreach (ticketPickableStatuses() as $status_id => $status) { + $options[] = ['value' => (string) $status_id, 'label' => $status['ticket_status_name'], 'color' => preg_match('/^(#[0-9a-f]{3,8}|[a-z]{3,24})$/i', (string) $status['ticket_status_color']) ? $status['ticket_status_color'] : '']; + } + } elseif ($field === 'billable') { + $options[] = ['value' => '1', 'label' => 'Billable', 'icon' => 'fas fa-dollar-sign', 'description' => 'Shows on the Unbilled Tickets report until invoiced']; + $options[] = ['value' => '0', 'label' => 'Not billable', 'icon' => 'fas fa-minus']; + } elseif ($field === 'assignee' || $field === 'recurring_assignee') { + $options = quickPickAgents(); + } elseif ($field === 'project_manager') { + $options = quickPickAgents('No manager'); + } else { + http_response_code(400); + echo json_encode(['error' => 'Unknown field']); + exit(); + } + + echo json_encode(['options' => $options]); + exit(); +} + +if (isset($_POST['quick_pick_set'])) { + + validateCSRFToken(); + + header('Content-Type: application/json'); + + $field = (string) ($_POST['field'] ?? ''); + $value = (string) ($_POST['value'] ?? ''); + $ticket_ids = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['ids'] ?? []))))); + + // A project's manager or a recurring ticket's assignee - open projects + // and recurring tickets of clients this agent can reach, like their edit modals + if ($field === 'project_manager' || $field === 'recurring_assignee') { + $is_project = $field === 'project_manager'; + $allowed = lookupUserPermission('module_support') >= 2 && $ticket_ids; + foreach ($allowed ? $ticket_ids : [] as $id) { + $row = mysqli_fetch_assoc(mysqli_query($mysqli, $is_project + ? "SELECT project_client_id AS client_id, project_completed_at IS NULL AND project_archived_at IS NULL AS is_open FROM projects WHERE project_id = $id" + : "SELECT recurring_ticket_client_id AS client_id, 1 AS is_open FROM recurring_tickets WHERE recurring_ticket_id = $id" + )); + if (!$row || !$row['is_open'] || (intval($row['client_id']) && !hasClientAccess($row['client_id']))) { + $allowed = false; + break; + } + } + if (!$allowed) { + http_response_code(403); + echo json_encode(['error' => 'You cannot change that here.']); + exit(); + } + + $response = ['records' => []]; + foreach ($ticket_ids as $id) { + [$ok, $message] = $is_project ? projectChangeManager($id, intval($value)) : recurringTicketChangeAssignee($id, intval($value)); + if (!$ok) { + http_response_code(422); + echo json_encode(['error' => $message]); + exit(); + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, $is_project + ? "SELECT project_manager AS user_id, user_name, user_avatar FROM projects LEFT JOIN users ON user_id = project_manager WHERE project_id = $id" + : "SELECT recurring_ticket_assigned_to AS user_id, user_name, user_avatar FROM recurring_tickets LEFT JOIN users ON user_id = recurring_ticket_assigned_to WHERE recurring_ticket_id = $id" + )); + $html = formatAssignee($row['user_id'], $row['user_name'], $row['user_avatar'], false, $is_project ? 'No manager' : 'Unassigned'); + $response['records'][$id] = ['current' => (string) intval($row['user_id']), 'html' => ['list' => $html, 'detail' => $html]]; + } + $response['message'] = $message; + echo json_encode($response); + exit(); + } + + $allowed = lookupUserPermission('module_support') >= 2 + && in_array($field, ['priority', 'assignee', 'billable', 'status'], true) + && ($field !== 'billable' || lookupUserPermission('module_sales') >= 2) + && $ticket_ids; + + // Every ticket has to be one this agent can reach, and still open + // for priority and assignee - the same tickets the pickers are shown on + if ($allowed) { + foreach ($ticket_ids as $ticket_id) { + $row = ticketFieldsRow($ticket_id); + if (!$row || (intval($row['ticket_client_id']) && !hasClientAccess($row['ticket_client_id'])) + || ($field !== 'billable' && $row['ticket_closed_at'])) { + $allowed = false; + break; + } + } + } + if (!$allowed) { + http_response_code(403); + echo json_encode(['error' => 'You cannot change that on these tickets.']); + exit(); + } + + $message = ''; + $response = ['records' => []]; + foreach ($ticket_ids as $ticket_id) { + if ($field === 'priority') { + [$ok, $message] = ticketChangePriority($ticket_id, $value); + } elseif ($field === 'assignee') { + [$ok, $message] = ticketChangeAssignee($ticket_id, intval($value)); + } elseif ($field === 'status') { + [$ok, $message] = ticketChangeStatus($ticket_id, intval($value)); + } else { + [$ok, $message] = ticketChangeBillable($ticket_id, intval($value)); + } + if (!$ok) { + http_response_code(422); + echo json_encode(['error' => strip_tags($message)]); + exit(); + } + + // Redraw what changed, in both looks, plus the status (assigning a New ticket opens it) + $row = mysqli_fetch_assoc(mysqli_query($mysqli, + "SELECT ticket_priority, ticket_assigned_to, ticket_billable, ticket_closed_at, ticket_resolved_at, ticket_status, + ticket_status_name, ticket_status_color, user_name, user_avatar + FROM tickets + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + LEFT JOIN users ON user_id = ticket_assigned_to + WHERE ticket_id = $ticket_id" + )); + $is_open = empty($row['ticket_resolved_at']) && empty($row['ticket_closed_at']); + if ($field === 'priority') { + $current = $row['ticket_priority']; + $html = ['list' => ticketPriorityHtml($current, 'list'), 'detail' => ticketPriorityHtml($current, 'detail')]; + } elseif ($field === 'assignee') { + $current = (string) intval($row['ticket_assigned_to']); + $assignee = formatAssignee($row['ticket_assigned_to'], $row['user_name'], $row['user_avatar'], $is_open); + $html = ['list' => $assignee, 'detail' => $assignee]; + } elseif ($field === 'status') { + $current = (string) intval($row['ticket_status']); + $html = ['list' => ticketStatusHtml($row['ticket_status_name'], $row['ticket_status_color'], 'list'), 'detail' => ticketStatusHtml($row['ticket_status_name'], $row['ticket_status_color'], 'detail')]; + } else { + $current = (string) intval($row['ticket_billable']); + $html = ['list' => ticketBillableHtml($current, 'list'), 'detail' => ticketBillableHtml($current, 'detail')]; + } + $response['records'][$ticket_id] = [ + 'current' => $current, + 'html' => $html, + 'status_id' => intval($row['ticket_status']), + 'status' => ['list' => ticketStatusHtml($row['ticket_status_name'], $row['ticket_status_color'], 'list'), 'detail' => ticketStatusHtml($row['ticket_status_name'], $row['ticket_status_color'], 'detail')] + ]; + } + + $response['message'] = count($ticket_ids) === 1 ? strip_tags($message) : 'Updated ' . count($ticket_ids) . ' tickets'; + echo json_encode($response); + exit(); +} + if (isset($_POST['client_set_notes'])) { validateCSRFToken(); diff --git a/agent/modals/ticket/ticket_assign.php b/agent/modals/ticket/ticket_assign.php deleted file mode 100644 index 45357f65d..000000000 --- a/agent/modals/ticket/ticket_assign.php +++ /dev/null @@ -1,82 +0,0 @@ - - - - -
- - - - - - - -
- - - - -
- - - - -
- - - - -
- - - - - - - -
- -$original_priority to $priority"); - - redirect(); - -} - if (isset($_POST['edit_ticket_sla'])) { validateCSRFToken(); @@ -844,118 +800,6 @@ if (isset($_POST['edit_ticket_vendor'])) { } -if (isset($_POST['assign_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $ticket_id = intval($_POST['ticket_id']); - $assigned_to = intval($_POST['assigned_to']); - $ticket_status = intval($_POST['ticket_status']); - - // New > Open as assigned - if ($ticket_status == 1 && $assigned_to !== 0) { - $ticket_status = 2; - } - - // Allow for un-assigning tickets - if ($assigned_to == 0) { - $ticket_reply = "Ticket unassigned."; - $agent_name = "No One"; - } else { - // Get & verify assigned agent details - $agent_details_sql = mysqli_query($mysqli, "SELECT user_name, user_email FROM users WHERE users.user_id = $assigned_to"); - $agent_details = mysqli_fetch_assoc($agent_details_sql); - - $agent_name = escapeSql($agent_details['user_name']); - $agent_email = escapeSql($agent_details['user_email']); - $ticket_reply = "Ticket re-assigned to $agent_name."; - - if (!$agent_name) { - flashAlert("Invalid agent!", 'error'); - redirect(); - } - } - - // Get & verify ticket details - $ticket_details_sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_client_id, client_name FROM tickets LEFT JOIN clients ON ticket_client_id = client_id WHERE ticket_id = '$ticket_id' AND ticket_status != 5"); - $ticket_details = mysqli_fetch_assoc($ticket_details_sql); - - $ticket_prefix = escapeSql($ticket_details['ticket_prefix']); - $ticket_number = intval($ticket_details['ticket_number']); - $ticket_subject = escapeSql($ticket_details['ticket_subject']); - $client_id = intval($ticket_details['ticket_client_id']); - $client_name = escapeSql($ticket_details['client_name']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - if (!$ticket_subject) { - flashAlert("Invalid ticket!", 'error'); - redirect(); - } - - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - // Update ticket & insert reply - mysqli_query($mysqli, "UPDATE tickets SET ticket_assigned_to = $assigned_to, ticket_status = '$ticket_status' WHERE ticket_id = $ticket_id"); - syncTicketSlaClock($ticket_id); - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logTicketHistory($ticket_id, "$session_name assigned the ticket to $agent_name"); - - logAudit("Ticket", "Edit", "$session_name reassigned $ticket_prefix$ticket_number to $agent_name", $client_id, $ticket_id); - - // Notification - if ($session_user_id != $assigned_to && $assigned_to != 0) { - - // App Notification - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = 'Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject has been assigned to you by $session_name', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $assigned_to"); - - // Email Notification - if (!empty($config_smtp_provider)) { - - // Sanitize Config vars from get_settings.php - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $company_name = escapeSql($session_company_name); - - $subject = "$config_app_name - Ticket $ticket_prefix$ticket_number assigned to you - $ticket_subject"; - $body = "Hi $agent_name,

A ticket has been assigned to you!

Client: $client_name
Ticket Number: $ticket_prefix$ticket_number
Subject: $ticket_subject

https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri

Thanks,
$session_name
$company_name"; - - // Email Ticket Agent - // Queue Mail - $data = [ - [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $agent_email, - 'recipient_name' => $agent_name, - 'subject' => $subject, - 'body' => $body, - ] - ]; - addToMailQueue($data); - } - } - - triggerCustomAction('ticket_assign', $ticket_id); - - flashAlert("Ticket $ticket_prefix$ticket_number assigned to $agent_name"); - - redirect(); - -} - if (isset($_GET['delete_ticket'])) { validateCSRFToken(); @@ -2975,41 +2819,6 @@ if (isExportRequest('export_tickets')) { } -if (isset($_POST['edit_ticket_billable_status'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - enforceUserPermission('module_sales', 2); - - $ticket_id = intval($_POST['ticket_id']); - $billable_status = intval($_POST['billable_status']); - if ($billable_status == 0 ) { - $billable_wording = "Not"; - } - - // Get ticket details for logging - $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli,"UPDATE tickets SET ticket_billable = $billable_status WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name marked ticket $ticket_prefix$ticket_number as $billable_wording Billable", $client_id, $ticket_id); - - flashAlert("Ticket marked $billable_wording Billable"); - - redirect(); - -} - if (isset($_POST['edit_ticket_schedule'])) { validateCSRFToken(); diff --git a/agent/project.php b/agent/project.php index 5e504ce50..a63a53a84 100644 --- a/agent/project.php +++ b/agent/project.php @@ -28,7 +28,7 @@ if (isset($_GET['project_id'])) { $mysqli, "SELECT client_id, client_name, project_archived_at, project_completed_at, project_created_at, project_description, project_due, project_id, project_name, project_number, project_prefix, - project_updated_at, user_id, user_name FROM projects + project_updated_at, user_id, user_name, user_avatar FROM projects LEFT JOIN clients ON project_client_id = client_id LEFT JOIN users ON project_manager = user_id WHERE project_id = $project_id @@ -64,12 +64,11 @@ if (isset($_GET['project_id'])) { } $project_manager = intval($row['user_id']); - $project_manager_name = escapeHtml($row['user_name']); - if ($project_manager) { - $project_manager_display = "
$project_manager_name
"; - } else { - $project_manager_display = "-"; + $project_manager_display = formatAssignee($project_manager, $row['user_name'], $row['user_avatar'], false, 'No manager'); + if (lookupUserPermission('module_support') >= 2 && !$project_completed_at && !$project_archived_at) { + $project_manager_display = quickPick('project_manager', $project_id, $project_manager, $project_manager_display); } + $project_manager_display = "
$project_manager_display
"; if ($project_completed_at) { $project_status_display = "Closed"; diff --git a/agent/projects.php b/agent/projects.php index 27730ae78..594becd84 100644 --- a/agent/projects.php +++ b/agent/projects.php @@ -33,7 +33,7 @@ $sql_projects = mysqli_query( $mysqli, "SELECT SQL_CALC_FOUND_ROWS client_id, client_name, project_archived_at, project_completed_at, project_created_at, project_description, project_due, project_id, project_name, project_number, project_prefix, - project_updated_at, user_id, user_name FROM projects + project_updated_at, user_id, user_name, user_avatar FROM projects LEFT JOIN clients ON client_id = project_client_id LEFT JOIN users ON user_id = project_manager WHERE DATE(project_created_at) BETWEEN '$dtf' AND '$dtt' @@ -179,10 +179,9 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); } $project_manager = intval($row['user_id']); - if ($project_manager) { - $project_manager_display = escapeHtml($row['user_name']); - } else { - $project_manager_display = "-"; + $project_manager_display = formatAssignee($project_manager, $row['user_name'], $row['user_avatar'], false, 'No manager'); + if (lookupUserPermission('module_support') >= 2 && !$project_completed_at && !$project_archived_at) { + $project_manager_display = quickPick('project_manager', $project_id, $project_manager, $project_manager_display); } diff --git a/agent/recurring_tickets.php b/agent/recurring_tickets.php index 01222d392..a7c4735da 100644 --- a/agent/recurring_tickets.php +++ b/agent/recurring_tickets.php @@ -296,6 +296,9 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); $recurring_ticket_category = escapeHtml($row['category_name']) ?: '-'; $recurring_ticket_client_name = escapeHtml($row['client_name']); $assigned_to = formatAssignee($row['recurring_ticket_assigned_to'], $row['user_name'], $row['user_avatar'], false); + if (lookupUserPermission('module_support') >= 2) { + $assigned_to = quickPick('recurring_assignee', $recurring_ticket_id, intval($row['recurring_ticket_assigned_to']), $assigned_to); + } $recurring_ticket_template_name = escapeHtml($row['ticket_template_name']); $recurring_ticket_task_count = intval($row['recurring_ticket_task_count']); ?> diff --git a/agent/ticket.php b/agent/ticket.php index b586d77e4..d073f8243 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -967,38 +967,10 @@ if (isset($_GET['ticket_id'])) {
Status
- - + + + + @@ -1011,10 +983,7 @@ if (isset($_GET['ticket_id'])) {
Priority
- - - - + @@ -1025,10 +994,7 @@ if (isset($_GET['ticket_id'])) {
Assigned to
- - - - + @@ -1128,11 +1094,8 @@ if (isset($_GET['ticket_id'])) { Quoted on - - - Not billable" ?> - - + = 2) { ?> + Not billable" ?> diff --git a/agent/ticket_list.php b/agent/ticket_list.php index 928574a00..804c0f080 100644 --- a/agent/ticket_list.php +++ b/agent/ticket_list.php @@ -367,33 +367,29 @@ if ($tickets) { Quoted - - - - - - - + - = 2 && empty($ticket_closed_at)) { ?> - class="ajax-modal" - data-modal-url="modals/ticket/ticket_priority.php?id=" - - > - - + = 2 && empty($ticket_closed_at)) { ?> + + + + - + + = 2 && $ticket_is_open) { ?> + + + + +
@@ -430,14 +426,11 @@ if ($tickets) { - = 2 && empty($ticket_closed_at)) { ?> - class="ajax-modal" - data-modal-url="modals/ticket/ticket_assign.php?id=" - - > + = 2 && empty($ticket_closed_at)) { ?> + + - + diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 72ea34ddf..51b81f3d6 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -2864,6 +2864,49 @@ a.itflow-dash-rail-item:focus-visible { --bs-table-bg-state: var(--bs-primary-bg-subtle); } +/* Quick pickers - js/quick_pick.js. A ticket's priority, assignee or billing + badge is a button that opens a small menu under it; the menu itself is the + select picker's panel. On the ticket page the button also carries + .ticket-prop-edit, so it looks like the other properties there. */ +.itflow-quick-pick { + padding: 0; + border: 0; + border-radius: 2rem; + font: inherit; + color: inherit; + background: none; + cursor: pointer; + transition: opacity .15s; +} +.itflow-quick-pick-list:hover .badge, +.itflow-quick-pick-list:focus-visible .badge, +.itflow-quick-pick-list[aria-expanded="true"] .badge { + box-shadow: 0 0 0 .2rem color-mix(in srgb, var(--itflow-accent, #0d6efd) 30%, transparent); +} +.itflow-quick-pick:focus-visible { + outline: 0; +} +.itflow-quick-pick-detail { + border-radius: var(--bs-border-radius); +} +.itflow-quick-pick.is-saving { + opacity: .5; + pointer-events: none; +} +/* A brief ring on the value that just changed */ +.itflow-quick-pick.is-saved .badge { + animation: itflowQuickSaved .9s ease-out; +} +@keyframes itflowQuickSaved { + from { box-shadow: 0 0 0 .3rem color-mix(in srgb, var(--bs-success) 45%, transparent); } + to { box-shadow: 0 0 0 .3rem transparent; } +} +@media (prefers-reduced-motion: reduce) { + .itflow-quick-pick.is-saved .badge { + animation: none; + } +} + /* Client side nav - agent/includes/client_side_nav.php: the client's initials and name at the top, under the "All clients" link */ /* Same width, corners and left padding as the menu links below it, so the diff --git a/functions.php b/functions.php index f0c4c1793..c1f0e902f 100644 --- a/functions.php +++ b/functions.php @@ -32,3 +32,4 @@ require_once __DIR__ . '/functions/notifications.php'; require_once __DIR__ . '/functions/dashboard.php'; require_once __DIR__ . '/functions/client_overview.php'; require_once __DIR__ . '/functions/tags.php'; +require_once __DIR__ . '/functions/ticket_fields.php'; diff --git a/functions/format.php b/functions/format.php index 2d2e50443..b4f57564c 100644 --- a/functions/format.php +++ b/functions/format.php @@ -232,14 +232,14 @@ function formatAddress($address, $city, $state, $zip, $country = '', $separator * doesn't. Takes the RAW user columns and escapes them itself. * Bootstrap 5.3 utilities and Font Awesome only - no custom CSS. */ -function formatAssignee($user_id, $user_name, $user_avatar, $highlight_unassigned = true) { +function formatAssignee($user_id, $user_name, $user_avatar, $highlight_unassigned = true, $none_label = 'Unassigned') { $pill = "badge rounded-pill d-inline-flex align-items-center align-middle gap-1 p-1 pe-2"; $user_id = intval($user_id); if (!$user_id) { $tone = $highlight_unassigned ? 'danger' : 'secondary'; $colors = $highlight_unassigned ? 'text-danger-emphasis bg-danger-subtle' : 'text-body-secondary bg-body-secondary'; - return "Unassigned"; + return "" . escapeHtml($none_label) . ""; } $user_avatar = escapeHtml($user_avatar); diff --git a/functions/ticket_fields.php b/functions/ticket_fields.php new file mode 100644 index 000000000..9e8f0192f --- /dev/null +++ b/functions/ticket_fields.php @@ -0,0 +1,405 @@ + 'dark', 'High' => 'danger', 'Medium' => 'warning', 'Low' => 'info']; + return $colors[$priority] ?? 'info'; +} + +/* The ticket row the change functions work from, or null. */ +function ticketFieldsRow($ticket_id) { + global $mysqli; + + $ticket_id = intval($ticket_id); + return mysqli_fetch_assoc(mysqli_query($mysqli, + "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_assigned_to, + ticket_status, ticket_billable, ticket_client_id, ticket_resolved_at, ticket_closed_at, ticket_status_name, client_name + FROM tickets + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + LEFT JOIN clients ON client_id = ticket_client_id + WHERE ticket_id = $ticket_id" + )) ?: null; +} + +/* Change the priority. Returns [ok, message]. */ +function ticketChangePriority($ticket_id, $priority) { + global $mysqli, $session_name; + + $ticket_id = intval($ticket_id); + $row = ticketFieldsRow($ticket_id); + if (!$row) { + return [false, 'That ticket no longer exists.']; + } + if (!in_array($priority, TICKET_PRIORITIES, true)) { + return [false, 'That is not a priority.']; + } + + $original_priority = escapeSql($row['ticket_priority']); + if ($row['ticket_priority'] === $priority) { + return [true, "Priority is already $priority"]; + } + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status = escapeSql($row['ticket_status_name']); + $client_id = intval($row['ticket_client_id']); + $priority_sql = escapeSql($priority); + + mysqli_query($mysqli, "UPDATE tickets SET ticket_priority = '$priority_sql' WHERE ticket_id = $ticket_id"); + applyTicketSla($ticket_id); + + mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status', ticket_history_description = '$session_name changed priority from $original_priority to $priority_sql', ticket_history_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name changed priority from $original_priority to $priority_sql for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + + return [true, "Priority updated from $original_priority to $priority_sql"]; +} + +/* + * Assign to an agent, or to no one with 0. A New ticket that gets an agent + * becomes Open. Returns [ok, message]. + */ +function ticketChangeAssignee($ticket_id, $assigned_to) { + global $mysqli, $session_name, $session_user_id, $session_company_name, + $config_smtp_provider, $config_ticket_from_name, $config_ticket_from_email, $config_app_name, $config_base_url; + + $ticket_id = intval($ticket_id); + $assigned_to = intval($assigned_to); + + $row = ticketFieldsRow($ticket_id); + if (!$row || intval($row['ticket_status']) == 5) { + return [false, 'Invalid ticket!']; + } + + // New > Open as assigned + $ticket_status = intval($row['ticket_status']); + if ($ticket_status == 1 && $assigned_to !== 0) { + $ticket_status = 2; + } + + // Allow for un-assigning tickets + if ($assigned_to == 0) { + $ticket_reply = "Ticket unassigned."; + $agent_name = "No One"; + } else { + $agent_details = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_name, user_email FROM users WHERE user_id = $assigned_to AND user_type = 1 AND user_archived_at IS NULL")); + if (!$agent_details) { + return [false, 'Invalid agent!']; + } + $agent_name = escapeSql($agent_details['user_name']); + $agent_email = escapeSql($agent_details['user_email']); + $ticket_reply = "Ticket re-assigned to $agent_name."; + } + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $client_id = intval($row['ticket_client_id']); + $client_name = escapeSql($row['client_name']); + $client_uri = $client_id ? "&client_id=$client_id" : ''; + + // Update ticket & insert reply + mysqli_query($mysqli, "UPDATE tickets SET ticket_assigned_to = $assigned_to, ticket_status = '$ticket_status' WHERE ticket_id = $ticket_id"); + syncTicketSlaClock($ticket_id); + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logTicketHistory($ticket_id, "$session_name assigned the ticket to $agent_name"); + + logAudit("Ticket", "Edit", "$session_name reassigned $ticket_prefix$ticket_number to $agent_name", $client_id, $ticket_id); + + // Notification + if ($session_user_id != $assigned_to && $assigned_to != 0) { + + // App Notification + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = 'Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject has been assigned to you by $session_name', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $assigned_to"); + + // Email Notification + if (!empty($config_smtp_provider)) { + + // Sanitize Config vars from get_settings.php + $from_name = escapeSql($config_ticket_from_name); + $from_email = escapeSql($config_ticket_from_email); + $company_name = escapeSql($session_company_name); + + $subject = "$config_app_name - Ticket $ticket_prefix$ticket_number assigned to you - $ticket_subject"; + $body = "Hi $agent_name,

A ticket has been assigned to you!

Client: $client_name
Ticket Number: $ticket_prefix$ticket_number
Subject: $ticket_subject

https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri

Thanks,
$session_name
$company_name"; + + addToMailQueue([ + [ + 'from' => $from_email, + 'from_name' => $from_name, + 'recipient' => $agent_email, + 'recipient_name' => $agent_name, + 'subject' => $subject, + 'body' => $body, + ] + ]); + } + } + + triggerCustomAction('ticket_assign', $ticket_id); + + return [true, "Ticket $ticket_prefix$ticket_number assigned to $agent_name"]; +} + +/* + * The statuses an agent can move an open ticket to by hand: the active ones + * except New and Closed (the system sets those) and Resolved (the Resolve + * button does that, because it also emails the client). + */ +function ticketPickableStatuses() { + global $mysqli; + + $statuses = []; + $sql = mysqli_query($mysqli, "SELECT ticket_status_id, ticket_status_name, ticket_status_color FROM ticket_statuses + WHERE ticket_status_id NOT IN (1, 4, 5) AND ticket_status_active = 1 + ORDER BY ticket_status_order, ticket_status_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $statuses[intval($row['ticket_status_id'])] = $row; + } + return $statuses; +} + +/* + * Change the status of an open ticket - what the ticket page's status menu + * did through the reply form's status-only path. Returns [ok, message]. + */ +function ticketChangeStatus($ticket_id, $status_id) { + global $mysqli, $session_name; + + $ticket_id = intval($ticket_id); + $status_id = intval($status_id); + + $row = ticketFieldsRow($ticket_id); + if (!$row || $row['ticket_closed_at'] || $row['ticket_resolved_at']) { + return [false, 'Invalid ticket!']; + } + $statuses = ticketPickableStatuses(); + if (!isset($statuses[$status_id])) { + return [false, 'That status cannot be set here.']; + } + if (intval($row['ticket_status']) === $status_id) { + return [true, "Status is already " . escapeHtml($statuses[$status_id]['ticket_status_name']) . ""]; + } + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $client_id = intval($row['ticket_client_id']); + $status_name = escapeSql($statuses[$status_id]['ticket_status_name']); + + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $status_id, ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); + syncTicketSlaClock($ticket_id); + + logTicketHistory($ticket_id, "$session_name set the status to $status_name"); + + logAudit("Ticket", "Edit", "$session_name set the status of $ticket_prefix$ticket_number to $status_name", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + + return [true, "Status set to $status_name"]; +} + +/* Mark billable (1) or not (0). Returns [ok, message]. */ +function ticketChangeBillable($ticket_id, $billable) { + global $mysqli, $session_name; + + $ticket_id = intval($ticket_id); + $billable = intval($billable) ? 1 : 0; + + $row = ticketFieldsRow($ticket_id); + if (!$row) { + return [false, 'That ticket no longer exists.']; + } + + $billable_wording = $billable ? '' : 'Not'; + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $client_id = intval($row['ticket_client_id']); + + mysqli_query($mysqli, "UPDATE tickets SET ticket_billable = $billable WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name marked ticket $ticket_prefix$ticket_number as $billable_wording Billable", $client_id, $ticket_id); + + return [true, "Ticket marked $billable_wording Billable"]; +} + +/* + * What each value looks like. $style is 'list' (the ticket list's padded + * pills) or 'detail' (the ticket page's properties panel). + */ +function ticketPriorityHtml($priority, $style = 'list') { + $priority = in_array($priority, TICKET_PRIORITIES, true) ? $priority : 'Low'; + return '' . $priority . ''; +} + +function ticketBillableHtml($billable, $style = 'list') { + if ($style === 'detail') { + return $billable ? 'Billable' : "Not billable"; + } + return $billable + ? '' + : ''; +} + +function ticketStatusHtml($status_name, $status_color, $style = 'list') { + $color = preg_match('/^(#[0-9a-f]{3,8}|[a-z]{3,24})$/i', (string) $status_color) ? $status_color : 'var(--bs-secondary)'; + return '' . escapeHtml($status_name) . ''; +} + +/* + * The button that opens a quick picker (js/quick_pick.js) for one record's + * field, wrapped round how the value looks now. $id is the ticket, project + * or recurring ticket, depending on the field. + */ +function quickPick($field, $id, $current, $inner, $style = 'list', $status_id = 0) { + $labels = [ + 'priority' => 'Change priority', 'assignee' => 'Change who it is assigned to', 'billable' => 'Change billing', 'status' => 'Change status', + 'project_manager' => 'Change the project manager', 'recurring_assignee' => 'Change who it is assigned to' + ]; + // On the ticket page it looks like the other editable properties there (agent/css/ticket.css) + $class = 'itflow-quick-pick itflow-quick-pick-' . $style . ($style === 'detail' ? ' ticket-prop-edit' : ''); + return ''; +} + +/* The agents a picker offers: none first, then me, then everyone else by name. */ +function quickPickAgents($none_label = 'Unassigned') { + global $mysqli, $session_user_id; + + $options = [['value' => '0', 'label' => $none_label, 'icon' => 'fas fa-user-slash', 'none' => true]]; + $sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar FROM users WHERE user_type = 1 AND user_archived_at IS NULL ORDER BY user_name ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $user_id = intval($row['user_id']); + $option = ['value' => (string) $user_id, 'label' => $row['user_name'] . ($user_id == $session_user_id ? ' (me)' : '')]; + if ($row['user_avatar']) { + $option['image'] = "/uploads/users/$user_id/" . rawurlencode($row['user_avatar']); + } else { + $option['initials'] = personInitials($row['user_name']); + } + if ($user_id == $session_user_id) { + array_splice($options, 1, 0, [$option]); + } else { + $options[] = $option; + } + } + + return $options; +} + +/* An active agent's name and email, or null. */ +function quickPickAgent($user_id) { + global $mysqli; + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_name, user_email FROM users WHERE user_id = " . intval($user_id) . " AND user_type = 1 AND user_archived_at IS NULL")) ?: null; +} + +/* + * A project's manager - what Edit Project did with just that field. The + * caller checks the project is open and the agent may reach its client. + */ +function projectChangeManager($project_id, $manager_id) { + global $mysqli, $session_name; + + $project_id = intval($project_id); + $manager_id = intval($manager_id); + + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT project_prefix, project_number, project_name, project_client_id FROM projects WHERE project_id = $project_id")); + if (!$row) { + return [false, 'Invalid project!']; + } + if ($manager_id) { + $agent = quickPickAgent($manager_id); + if (!$agent) { + return [false, 'Invalid agent!']; + } + $manager_name = escapeSql($agent['user_name']); + } else { + $manager_name = 'No One'; + } + + $project = escapeSql($row['project_prefix'] . $row['project_number'] . ' - ' . $row['project_name']); + + mysqli_query($mysqli, "UPDATE projects SET project_manager = $manager_id WHERE project_id = $project_id"); + + logAudit("Project", "Edit", "$session_name set the manager of project $project to $manager_name", intval($row['project_client_id']), $project_id); + + return [true, $manager_id ? "Project manager set to $manager_name" : 'Project manager removed']; +} + +/* + * Who a recurring ticket's tickets go to - what Bulk Assign did for one + * recurring ticket, notification and email included. The caller checks + * client access. + */ +function recurringTicketChangeAssignee($recurring_ticket_id, $assigned_to) { + global $mysqli, $session_name, $session_user_id, $session_company_name, + $config_smtp_provider, $config_ticket_from_name, $config_ticket_from_email, $config_app_name; + + $recurring_ticket_id = intval($recurring_ticket_id); + $assigned_to = intval($assigned_to); + + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT recurring_ticket_subject, recurring_ticket_client_id FROM recurring_tickets WHERE recurring_ticket_id = $recurring_ticket_id")); + if (!$row) { + return [false, 'Invalid recurring ticket!']; + } + if ($assigned_to) { + $agent = quickPickAgent($assigned_to); + if (!$agent) { + return [false, 'Invalid agent!']; + } + $agent_name = escapeSql($agent['user_name']); + $agent_email = escapeSql($agent['user_email']); + } else { + $agent_name = 'No One'; + } + + $subject = escapeSql($row['recurring_ticket_subject']); + $client_id = intval($row['recurring_ticket_client_id']); + + mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_assigned_to = $assigned_to WHERE recurring_ticket_id = $recurring_ticket_id"); + + logAudit("Recurring Ticket", "Edit", "$session_name reassigned recurring ticket $subject to $agent_name", $client_id, $recurring_ticket_id); + + if ($assigned_to && $assigned_to != $session_user_id) { + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Recurring Ticket', notification = 'Recurring ticket $subject has been assigned to you by $session_name', notification_action = 'recurring_tickets.php?assigned=$assigned_to', notification_client_id = $client_id, notification_user_id = $assigned_to"); + + if (!empty($config_smtp_provider)) { + $company_name = escapeSql($session_company_name); + addToMailQueue([ + [ + 'from' => escapeSql($config_ticket_from_email), + 'from_name' => escapeSql($config_ticket_from_name), + 'recipient' => $agent_email, + 'recipient_name' => $agent_name, + 'subject' => "$config_app_name - Recurring ticket $subject assigned to you", + 'body' => "Hi $agent_name,

$session_name assigned the recurring ticket $subject to you - the tickets it opens will be yours.

Thanks,
$session_name
$company_name", + ] + ]); + } + } + + return [true, $assigned_to ? "Recurring ticket assigned to $agent_name" : 'Recurring ticket unassigned']; +} diff --git a/includes/footer.php b/includes/footer.php index 56b958f20..94ee1148d 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -78,6 +78,7 @@ + diff --git a/js/quick_pick.js b/js/quick_pick.js new file mode 100644 index 000000000..2370bd379 --- /dev/null +++ b/js/quick_pick.js @@ -0,0 +1,486 @@ +/* + * Quick pickers - a ticket's status, priority, assignee and billable, a + * project's manager and a recurring ticket's assignee, changed where you see + * them (ticket list and page, projects and project page, recurring tickets) + * instead of in a modal. + * + * Click the value and a small menu opens under it (a sheet from the bottom + * on a phone): statuses and priorities with their colours, agents with their + * pictures and a search box, or Billable / Not billable. Pick one and it saves straight + * away through agent/ajax.php, which runs the same code as the old modals + * (functions/ticket_fields.php - history, audit log, SLA, notifications) and + * sends back the redrawn value. Assigning a New ticket opens it, so the + * ticket's status redraws too, wherever it is marked with + * data-ticket-status-for="". + * + * Markup comes from quickPick() in functions/ticket_fields.php. Styled + * with the select picker's panel classes, like the tag picker. + */ +(function () { + 'use strict'; + + if (window.itflowQuickPick) { + return; // re-run by an ajax modal - the listeners are already in place + } + + var sheetMedia = window.matchMedia('(max-width: 575.98px)'); + var finePointer = window.matchMedia('(pointer: fine)'); + var titles = { priority: 'Priority', assignee: 'Assign to', billable: 'Billing', status: 'Status', project_manager: 'Project manager', recurring_assignee: 'Assign to' }; + var agentFields = ['assignee', 'project_manager', 'recurring_assignee']; + var cache = {}; + var open = null; + + function make(tag, className, text) { + var node = document.createElement(tag); + if (className) { + node.className = className; + } + if (text) { + node.textContent = text; + } + return node; + } + + function fold(text) { + return String(text || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase(); + } + + function lead(option) { + var node; + if (option.image) { + node = make('img', 'itflow-select-avatar'); + node.src = option.image; + node.alt = ''; + } else if (option.initials) { + node = make('span', 'itflow-select-avatar text-bg-secondary', option.initials); + } else if (option.color) { + node = make('span', 'itflow-select-dot'); + node.style.setProperty('--itflow-select-color', option.color); + } else if (option.icon) { + node = make('span', 'itflow-select-icon'); + node.appendChild(make('i', option.icon)); + } else { + return null; + } + node.setAttribute('aria-hidden', 'true'); + return node; + } + + function options(field, done, failed) { + if (cache[field]) { + done(cache[field]); + return; + } + itflowGet('ajax.php', { quick_pick_options: 1, field: field }, function (text) { + try { + cache[field] = JSON.parse(text).options; + } catch (e) { + failed(); + return; + } + done(cache[field]); + }, failed); + } + + function Picker(button) { + this.button = button; + this.field = button.dataset.quickPick; + this.ids = [button.dataset.quickId]; + this.current = button.dataset.quickCurrent; + this.csrf = button.dataset.csrf || ''; + this.query = ''; + this.rows = []; + this.active = -1; + } + + Picker.prototype.show = function () { + var self = this; + open = this; + + var panel = this.panel = make('div', 'itflow-select-panel itflow-quick-panel'); + panel.setAttribute('role', 'dialog'); + panel.setAttribute('aria-label', titles[this.field] || 'Change'); + + var head = make('div', 'itflow-select-sheet-head'); + head.appendChild(make('span', 'itflow-select-sheet-title', titles[this.field] || 'Change')); + var done = make('button', 'btn btn-sm btn-link itflow-select-done', 'Cancel'); + done.type = 'button'; + done.addEventListener('click', function () { + self.close(false); + }); + head.appendChild(done); + panel.appendChild(head); + + var search = this.searchRow = make('div', 'itflow-select-search'); + search.hidden = true; + search.appendChild(make('i', 'fas fa-search')); + var input = this.input = make('input'); + input.type = 'text'; + input.autocomplete = 'off'; + input.spellcheck = false; + input.placeholder = 'Search'; + input.setAttribute('aria-label', 'Search'); + input.addEventListener('input', function () { + self.query = input.value; + self.draw(); + }); + input.addEventListener('keydown', function (e) { + self.key(e); + }); + search.appendChild(input); + panel.appendChild(search); + + var list = this.list = make('div', 'itflow-select-list'); + list.setAttribute('role', 'listbox'); + list.setAttribute('aria-label', titles[this.field] || 'Choices'); + list.appendChild(make('div', 'itflow-select-empty', 'Loading...')); + list.addEventListener('click', function (e) { + var node = e.target.closest('[data-row]'); + if (node) { + self.pick(parseInt(node.getAttribute('data-row'), 10)); + } + }); + list.addEventListener('mousemove', function (e) { + var node = e.target.closest('[data-row]'); + if (node) { + self.setActive(parseInt(node.getAttribute('data-row'), 10), false); + } + }); + panel.appendChild(list); + + panel.addEventListener('mousedown', function (e) { + if (e.target !== input && !e.target.closest('a, button')) { + e.preventDefault(); + } + }); + // With no search box, the keys work on the button that opened it + this.onButtonKey = function (e) { + self.key(e); + }; + this.button.addEventListener('keydown', this.onButtonKey); + + this.sheet = sheetMedia.matches; + panel.classList.toggle('is-sheet', this.sheet); + this.backdrop = make('div', 'itflow-select-backdrop'); + var host = this.button.closest('.modal, .offcanvas') || document.body; + if (this.sheet) { + host.appendChild(this.backdrop); + } + host.appendChild(panel); + this.button.setAttribute('aria-expanded', 'true'); + this.place(); + + options(this.field, function (list) { + if (open !== self) { + return; + } + self.options = list; + self.searchRow.hidden = list.length < 8; + self.draw(); + if (!self.searchRow.hidden && finePointer.matches) { + self.input.focus({ preventScroll: true }); + } + }, function () { + self.fail('Could not load the choices.'); + self.close(false); + }); + }; + + Picker.prototype.close = function (refocus) { + if (open !== this) { + return; + } + open = null; + this.panel.remove(); + this.backdrop.remove(); + this.button.removeEventListener('keydown', this.onButtonKey); + this.button.setAttribute('aria-expanded', 'false'); + if (refocus && this.button.isConnected) { + this.button.focus({ preventScroll: true }); + } + }; + + Picker.prototype.fail = function (message) { + if (typeof itflowToast === 'function') { + itflowToast(message, 'error'); + } + }; + + Picker.prototype.place = function () { + if (this.sheet || open !== this) { + return; + } + if (!this.button.isConnected) { + this.close(false); + return; + } + var rect = this.button.getBoundingClientRect(); + var viewWidth = document.documentElement.clientWidth; + var viewHeight = window.innerHeight; + var width = Math.min(agentFields.indexOf(this.field) !== -1 ? 264 : 224, viewWidth - 16); + var panel = this.panel; + panel.style.width = width + 'px'; + panel.style.left = Math.min(Math.max(8, rect.left), viewWidth - width - 8) + 'px'; + this.list.style.maxHeight = ''; + var height = panel.offsetHeight; + var below = viewHeight - rect.bottom - 12; + var above = rect.top - 12; + var up = height > below && above > below; + var room = up ? above : below; + if (height > room) { + this.list.style.maxHeight = Math.max(96, this.list.offsetHeight - (height - room)) + 'px'; + height = panel.offsetHeight; + } + panel.style.top = (up ? rect.top - 4 - height : rect.bottom + 4) + 'px'; + panel.classList.toggle('is-above', up); + }; + + Picker.prototype.draw = function () { + var self = this; + var terms = fold(this.query.trim()).split(/\s+/).filter(Boolean); + var list = this.list; + list.textContent = ''; + this.rows = []; + + this.options.forEach(function (option) { + var label = fold(option.label); + if (terms.length && !terms.every(function (t) { return label.indexOf(t) !== -1; })) { + return; + } + var selected = String(option.value) === String(self.current); + var index = self.rows.length; + var node = make('div', 'itflow-select-option' + (selected ? ' is-selected' : '') + (option.none ? ' is-none' : '')); + node.id = 'itflow-quick-option-' + index; + node.setAttribute('role', 'option'); + node.setAttribute('data-row', index); + node.setAttribute('aria-selected', selected ? 'true' : 'false'); + var visual = lead(option); + if (visual) { + node.appendChild(visual); + } + var text = make('span', 'itflow-select-text'); + text.appendChild(make('span', 'itflow-select-label', option.label)); + if (option.description) { + text.appendChild(make('span', 'itflow-select-description', option.description)); + } + node.appendChild(text); + node.appendChild(make('i', 'fas fa-check itflow-select-tick')); + list.appendChild(node); + self.rows.push({ node: node, option: option }); + }); + + if (!this.rows.length) { + list.appendChild(make('div', 'itflow-select-empty', 'No matches')); + } + + var active = 0; + this.rows.forEach(function (row, i) { + if (!terms.length && String(row.option.value) === String(self.current)) { + active = i; + } + }); + this.setActive(this.rows.length ? active : -1, true); + this.place(); + }; + + Picker.prototype.setActive = function (index, scroll) { + var old = this.rows[this.active]; + if (old) { + old.node.classList.remove('is-active'); + } + this.active = index; + var row = this.rows[index]; + var owner = this.searchRow.hidden ? this.button : this.input; + if (!row) { + owner.removeAttribute('aria-activedescendant'); + return; + } + row.node.classList.add('is-active'); + owner.setAttribute('aria-activedescendant', row.node.id); + if (scroll) { + row.node.scrollIntoView({ block: 'nearest' }); + } + }; + + Picker.prototype.key = function (e) { + switch (e.key) { + case 'ArrowDown': + e.preventDefault(); + this.setActive(Math.min(this.active + 1, this.rows.length - 1), true); + break; + case 'ArrowUp': + e.preventDefault(); + this.setActive(Math.max(this.active - 1, 0), true); + break; + case 'Enter': + case ' ': + if (e.key === ' ' && e.target === this.input) { + return; + } + e.preventDefault(); + this.pick(this.active); + break; + case 'Escape': + // Stop here, or a modal behind the picker closes too + e.preventDefault(); + e.stopPropagation(); + this.close(true); + break; + case 'Tab': + this.close(true); + break; + } + }; + + /* Save the pick, close, and redraw the value from what the server says. */ + Picker.prototype.pick = function (index) { + var self = this; + var row = this.rows[index]; + if (!row) { + return; + } + var value = String(row.option.value); + this.close(true); + if (value === String(this.current)) { + return; + } + + var button = this.button; + var field = this.field; + button.classList.add('is-saving'); + + itflowPost('ajax.php', { + quick_pick_set: 1, + csrf_token: this.csrf, + field: field, + value: value, + ids: this.ids + }, function (text) { + button.classList.remove('is-saving'); + var result; + try { + result = JSON.parse(text); + } catch (e) { + result = null; + } + if (!result || !result.records) { + self.fail((result && result.error) || 'That change was not saved - try again.'); + return; + } + Object.keys(result.records).forEach(function (id) { + var record = result.records[id]; + document.querySelectorAll('[data-quick-pick="' + field + '"][data-quick-id="' + id + '"]').forEach(function (spot) { + var style = spot.dataset.quickStyle === 'detail' ? 'detail' : 'list'; + spot.dataset.quickCurrent = record.current; + var holder = spot.querySelector('.itflow-quick-pick-value'); + if (holder) { + holder.innerHTML = record.html[style]; + } + spot.classList.add('is-saved'); + setTimeout(function () { + spot.classList.remove('is-saved'); + }, 900); + }); + if (record.status_id === undefined) { + return; // not a ticket + } + // The status shows elsewhere too (assigning a New ticket opens it). + // Where the status is its own picker, redraw inside the picker + document.querySelectorAll('[data-ticket-status-for="' + id + '"]').forEach(function (spot) { + var style = spot.dataset.quickStyle === 'detail' ? 'detail' : 'list'; + if (spot.dataset.statusId === String(record.status_id)) { + return; + } + spot.dataset.statusId = record.status_id; + var statusPick = spot.querySelector('[data-quick-pick="status"]'); + if (statusPick) { + statusPick.dataset.quickCurrent = record.status_id; + statusPick.querySelector('.itflow-quick-pick-value').innerHTML = record.status[style]; + } else { + spot.innerHTML = record.status[style]; + } + }); + }); + // On the ticket page billing decides the Quote / Invoice buttons, and + // assigning a New ticket opens it - both show elsewhere on the page, + // so load it again rather than leave those out of date + var statusChanged = Object.keys(result.records).some(function (id) { + return String(result.records[id].status_id) !== String(button.dataset.statusId || result.records[id].status_id); + }); + if (button.dataset.quickStyle === 'detail' && (field === 'billable' || (field === 'assignee' && statusChanged))) { + window.location.reload(); + return; + } + if (typeof itflowToast === 'function' && result.message) { + itflowToast(result.message, 'success'); + } + }, function () { + button.classList.remove('is-saving'); + self.fail('That change was not saved - try again.'); + }); + }; + + /* ---------- wiring ---------- */ + + document.addEventListener('click', function (e) { + var button = e.target.closest('[data-quick-pick]'); + if (!button) { + return; + } + e.preventDefault(); + e.stopPropagation(); + var wasOpen = open && open.button === button; + if (open) { + open.close(false); + } + if (!wasOpen) { + new Picker(button).show(); + } + }); + + // Clicking off the menu closes it - and that click does nothing else + var swallow = false; + function outside(e) { + if (open && !open.panel.contains(e.target) && !e.target.closest('[data-quick-pick]')) { + open.close(false); + swallow = true; + } + } + document.addEventListener('mousedown', outside, true); + document.addEventListener('touchstart', outside, { capture: true, passive: true }); + document.addEventListener('click', function (e) { + if (swallow) { + swallow = false; + e.preventDefault(); + e.stopPropagation(); + } + }, true); + document.addEventListener('pointerdown', function (e) { + if (!open && !e.target.closest('[data-quick-pick]')) { + swallow = false; + } + }, true); + + var placing = false; + function replace() { + if (!open || placing) { + return; + } + placing = true; + requestAnimationFrame(function () { + placing = false; + if (open) { + open.place(); + } + }); + } + window.addEventListener('resize', replace); + document.addEventListener('scroll', function (e) { + if (open && open.panel.contains(e.target)) { + return; + } + replace(); + }, true); + + window.itflowQuickPick = true; +})();