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

This commit is contained in:
johnnyq
2026-10-13 13:56:47 -04:00
parent 67e511a914
commit ec205ca633
16 changed files with 1145 additions and 479 deletions

View File

@@ -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();

View File

@@ -1,82 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$ticket_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT client_name, ticket_assigned_to, ticket_client_id, ticket_closed_at, ticket_number,
ticket_prefix, ticket_status FROM tickets
LEFT JOIN clients ON client_id = ticket_client_id
WHERE ticket_id = $ticket_id
LIMIT 1"
);
$row = mysqli_fetch_assoc($sql);
$ticket_prefix = escapeHtml($row['ticket_prefix']);
$ticket_number = intval($row['ticket_number']);
$ticket_assigned_to = intval($row['ticket_assigned_to']);
$ticket_status = intval($row['ticket_status']);
$ticket_closed_at = escapeHtml($row['ticket_closed_at']);
$client_name = escapeHtml($row['client_name']);
$client_id = intval($row['ticket_client_id']);
if ($client_id) {
enforceClientAccess();
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class='fa fa-fw fa-user-check me-2'></i>Assign ticket <small class="ms-1 opacity-75"><?= "$ticket_prefix$ticket_number" ?></small></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<input type="hidden" name="ticket_status" value="<?= $ticket_status ?>">
<div class="modal-body">
<div class="mb-3">
<label>Technician</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user-check"></i></span>
<select class="form-select select2" name="assigned_to">
<option value="0">Unassigned</option>
<?php
$sql_users_select = 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_users_select)) {
$user_id_select = intval($row['user_id']);
$user_name_select = escapeHtml($row['user_name']);
?>
<option value="<?= $user_id_select ?>" <?php if ($user_id_select == $ticket_assigned_to) { echo "selected"; } ?><?= selectOptionUser($row['user_id'], $row['user_name'], $row['user_avatar'] ?? '') ?>><?= $user_name_select ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="assign_ticket" class="btn btn-primary text-bold">
<i class="fa fa-check me-2"></i>Assign
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal">
<i class="fa fa-times me-2"></i>Cancel
</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,60 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$ticket_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT ticket_billable, ticket_client_id, ticket_number, ticket_prefix FROM tickets WHERE ticket_id = $ticket_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$ticket_prefix = escapeHtml($row['ticket_prefix']);
$ticket_number = intval($row['ticket_number']);
$ticket_billable = intval($row['ticket_billable']);
$client_id = intval($row['ticket_client_id']);
enforceClientAccess();
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title">
<i class="fa fa-fw fa-money-bill me-2"></i>Billing <small class="ms-1 opacity-75"><?= "$ticket_prefix$ticket_number" ?></small>
</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<div class="modal-body">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<div class="mb-3">
<label>This ticket is</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-bill"></i></span>
<select class="form-select" name="billable_status">
<option <?php if ($ticket_billable == 1) { echo "selected"; } ?> value="1">Billable</option>
<option <?php if ($ticket_billable == 0) { echo "selected"; } ?> value="0">Not billable</option>
</select>
</div>
<small class="text-muted">Billable tickets show in the Unbilled Tickets report until they are invoiced.</small>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="edit_ticket_billable_status" class="btn btn-primary text-bold">
<i class="fa fa-check me-2"></i>Save
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal">
<i class="fa fa-times me-2"></i>Cancel
</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,64 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$ticket_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT client_name, ticket_client_id, ticket_number, ticket_prefix, ticket_priority FROM tickets
LEFT JOIN clients ON client_id = ticket_client_id
WHERE ticket_id = $ticket_id
LIMIT 1"
);
$row = mysqli_fetch_assoc($sql);
$ticket_prefix = escapeHtml($row['ticket_prefix']);
$ticket_number = intval($row['ticket_number']);
$ticket_priority = escapeHtml($row['ticket_priority']);
$client_name = escapeHtml($row['client_name']);
$client_id = intval($row['ticket_client_id']);
if ($client_id) {
enforceClientAccess();
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-thermometer-half me-2"></i>Change priority <small class="ms-1 opacity-75"><?= "$ticket_prefix$ticket_number" ?></small></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<div class="modal-body">
<div class="mb-3">
<label>Priority</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-thermometer-half"></i></span>
<select class="form-select select2" name="priority" required>
<option <?php if ($ticket_priority == 'Low') { echo "selected"; } ?> data-color="var(--bs-info)">Low</option>
<option <?php if ($ticket_priority == 'Medium') { echo "selected"; } ?> data-color="var(--bs-warning)">Medium</option>
<option <?php if ($ticket_priority == 'High') { echo "selected"; } ?> data-color="var(--bs-danger)">High</option>
<option <?php if ($ticket_priority == 'Urgent') { echo "selected"; } ?> data-color="var(--bs-emphasis-color)">Urgent</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="edit_ticket_priority" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -352,50 +352,6 @@ if (isset($_POST['edit_ticket'])) {
}
if (isset($_POST['edit_ticket_priority'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$ticket_id = intval($_POST['ticket_id']);
$priority = escapeSql($_POST['priority']);
// Get ticket details before updating
$sql = mysqli_query($mysqli, "SELECT
ticket_prefix, ticket_number, ticket_priority, ticket_status_name, ticket_client_id
FROM tickets
LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
WHERE ticket_id = $ticket_id"
);
$row = mysqli_fetch_assoc($sql);
$ticket_prefix = escapeSql($row['ticket_prefix']);
$ticket_number = intval($row['ticket_number']);
$original_priority = escapeSql($row['ticket_priority']);
$ticket_status = escapeSql($row['ticket_status_name']);
$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_priority = '$priority' WHERE ticket_id = $ticket_id");
applyTicketSla($ticket_id);
// Update Ticket History
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', ticket_history_ticket_id = $ticket_id");
logAudit("Ticket", "Edit", "$session_name changed priority from $original_priority to $priority for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id);
triggerCustomAction('ticket_update', $ticket_id);
flashAlert("Priority updated from <strong>$original_priority</strong> to <strong>$priority</strong>");
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, <br><br>A ticket has been assigned to you!<br><br>Client: $client_name<br>Ticket Number: $ticket_prefix$ticket_number<br> Subject: $ticket_subject<br><br>https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri <br><br>Thanks, <br>$session_name<br>$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 <strong>$ticket_prefix$ticket_number</strong> assigned to <strong>$agent_name</strong>");
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 <strong>$billable_wording Billable</strong>");
redirect();
}
if (isset($_POST['edit_ticket_schedule'])) {
validateCSRFToken();

View File

@@ -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 = "<div class='text-secondary'><i class='fas fa-fw fa-user-tie me-2'></i>$project_manager_name</div>";
} 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 = "<div class='d-flex align-items-center text-secondary my-1' title='Project manager'><i class='fas fa-fw fa-user-tie me-2'></i>$project_manager_display</div>";
if ($project_completed_at) {
$project_status_display = "<span class='badge rounded-pill bg-dark ms-2'>Closed</span>";

View File

@@ -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);
}

View File

@@ -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']);
?>

View File

@@ -967,38 +967,10 @@ if (isset($_GET['ticket_id'])) {
<dt>Status</dt>
<dd>
<?php if ($ticket_status_options) { ?>
<!--
Changing status without writing a reply. Posts the same
handler the reply form uses with no reply text, which is
already its status-only path. Resolved is left out - the
Resolve button does that, and it also emails the client.
-->
<form action="post.php" method="post" class="dropdown">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<input type="hidden" name="add_ticket_reply" value="1">
<input type="hidden" name="public_reply_type" value="0">
<input type="hidden" name="ticket_reply" value="">
<input type="hidden" name="hours" value="0">
<input type="hidden" name="minutes" value="0">
<input type="hidden" name="seconds" value="0">
<button type="button" class="ticket-prop-edit" data-bs-toggle="dropdown" aria-expanded="false" title="Change status">
<span class="badge rounded-pill text-light" style="background-color: <?= $ticket_status_color ?>"><?= $ticket_status_name ?></span>
<i class="fas fa-caret-down ticket-prop-edit-icon"></i>
</button>
<div class="dropdown-menu">
<?php foreach ($ticket_status_options as $status_option) {
$status_option_id = intval($status_option['ticket_status_id']);
if ($status_option_id == 4) {
continue;
}
?>
<button type="submit" name="status" value="<?= $status_option_id ?>" class="dropdown-item<?= $status_option_id == $ticket_status ? ' active' : '' ?>">
<i class="fas fa-fw fa-circle me-2" style="color: <?= escapeHtml($status_option['ticket_status_color']) ?>"></i><?= escapeHtml($status_option['ticket_status_name']) ?>
</button>
<?php } ?>
</div>
</form>
<?php /* Resolved is not offered - the Resolve button does that, and it also emails the client */ ?>
<span class="d-block" data-ticket-status-for="<?= $ticket_id ?>" data-quick-style="detail" data-status-id="<?= intval($ticket_status) ?>">
<?= quickPick('status', $ticket_id, (string) intval($ticket_status), ticketStatusHtml($ticket['ticket_status_name'], $ticket['ticket_status_color'], 'detail'), 'detail') ?>
</span>
<?php } else { ?>
<span class="ticket-prop-static">
<span class="badge rounded-pill text-light" style="background-color: <?= $ticket_status_color ?>"><?= $ticket_status_name ?></span>
@@ -1011,10 +983,7 @@ if (isset($_GET['ticket_id'])) {
<dt>Priority</dt>
<dd>
<?php if ($can_change_fields) { ?>
<a href="#" class="ticket-prop-edit ajax-modal" data-modal-url="modals/ticket/ticket_priority.php?id=<?= $ticket_id ?>" title="Change priority">
<span class="badge rounded-pill text-bg-<?= $ticket_priority_color ?>"><?= $ticket_priority ?></span>
<i class="fas fa-pen ticket-prop-edit-icon"></i>
</a>
<?= quickPick('priority', $ticket_id, $ticket_priority, ticketPriorityHtml($ticket_priority, 'detail'), 'detail') ?>
<?php } else { ?>
<span class="ticket-prop-static"><span class="badge rounded-pill text-bg-<?= $ticket_priority_color ?>"><?= $ticket_priority ?></span></span>
<?php } ?>
@@ -1025,10 +994,7 @@ if (isset($_GET['ticket_id'])) {
<dt>Assigned to</dt>
<dd>
<?php if ($can_change_fields) { ?>
<a href="#" class="ticket-prop-edit ajax-modal" data-modal-url="modals/ticket/ticket_assign.php?id=<?= $ticket_id ?>" title="Change who it is assigned to">
<?= $ticket_assigned_to_display ?>
<i class="fas fa-pen ticket-prop-edit-icon"></i>
</a>
<?= quickPick('assignee', $ticket_id, (string) intval($ticket['ticket_assigned_to']), $ticket_assigned_to_display, 'detail', $ticket['ticket_status']) ?>
<?php } else { ?>
<span class="ticket-prop-static"><?= $ticket_assigned_to_display ?></span>
<?php } ?>
@@ -1128,11 +1094,8 @@ if (isset($_GET['ticket_id'])) {
<a href="quote.php?quote_id=<?= $quote_id ?>" class="ticket-prop-edit" title="Open the quote">
<span><i class="fa fa-fw fa-comment-dollar text-secondary me-1"></i>Quoted on <?= $quote_reference ?></span>
</a>
<?php } elseif ($can_edit_ticket) { ?>
<a href="#" class="ticket-prop-edit ajax-modal" data-modal-url="modals/ticket/ticket_billable.php?id=<?= $ticket_id ?>" title="Change billing">
<span><?= $ticket_billable ? 'Billable' : "<span class='text-muted'>Not billable</span>" ?></span>
<i class="fas fa-pen ticket-prop-edit-icon"></i>
</a>
<?php } elseif ($can_edit_ticket && lookupUserPermission("module_sales") >= 2) { ?>
<?= quickPick('billable', $ticket_id, $ticket_billable ? '1' : '0', ticketBillableHtml($ticket_billable, 'detail'), 'detail') ?>
<?php } else { ?>
<span class="ticket-prop-static"><?= $ticket_billable ? 'Billable' : "<span class='text-muted'>Not billable</span>" ?></span>
<?php } ?>

View File

@@ -367,33 +367,29 @@ if ($tickets) {
<?php } elseif ($ticket_quote_id) { ?>
<a href="quote.php?client_id=<?= $client_id ?>&quote_id=<?= $ticket_quote_id ?>"><span class="badge rounded-pill bg-primary p-2">Quoted</span></a>
<?php } else { ?>
<a href="#" class="ajax-modal" data-modal-url="modals/ticket/ticket_billable.php?id=<?= $ticket_id ?>"
title="<?= $ticket_billable ? 'Billable - click to change' : 'Not billable - click to change' ?>">
<?php if ($ticket_billable) { ?>
<span class="badge rounded-pill bg-success p-2"><i class="fas fa-fw fa-dollar-sign"></i></span>
<?php } else { ?>
<span class="badge rounded-pill bg-secondary p-2"><i class="fas fa-fw fa-minus"></i></span>
<?php } ?>
</a>
<?= quickPick('billable', $ticket_id, $ticket_billable ? '1' : '0', ticketBillableHtml($ticket_billable, 'list')) ?>
<?php } ?>
</td>
<?php } ?>
<!-- Ticket Priority -->
<td>
<a href="#"
<?php if (lookupUserPermission("module_support") >= 2 && empty($ticket_closed_at)) { ?>
class="ajax-modal"
data-modal-url="modals/ticket/ticket_priority.php?id=<?= $ticket_id ?>"
<?php } ?>
>
<span class="p-2 badge rounded-pill text-bg-<?= $ticket_priority_color ?>"><?= $ticket_priority ?></span>
</a>
<?php if (lookupUserPermission("module_support") >= 2 && empty($ticket_closed_at)) { ?>
<?= quickPick('priority', $ticket_id, $ticket_priority, ticketPriorityHtml($ticket_priority, 'list')) ?>
<?php } else { ?>
<?= ticketPriorityHtml($ticket_priority, 'list') ?>
<?php } ?>
</td>
<!-- Ticket Status -->
<td>
<span class="badge rounded-pill text-light p-2" style="background-color: <?= $ticket_status_color ?>"><?= $ticket_status_name ?></span>
<span data-ticket-status-for="<?= $ticket_id ?>" data-status-id="<?= intval($row['ticket_status']) ?>">
<?php if (lookupUserPermission("module_support") >= 2 && $ticket_is_open) { ?>
<?= quickPick('status', $ticket_id, (string) intval($row['ticket_status']), ticketStatusHtml($row['ticket_status_name'], $row['ticket_status_color'], 'list')) ?>
<?php } else { ?>
<?= ticketStatusHtml($row['ticket_status_name'], $row['ticket_status_color'], 'list') ?>
<?php } ?>
</span>
<?php if (!empty($ticket_scheduled_for)) { ?>
<div class="mt-1"><small class="text-secondary"><i class="fas fa-fw fa-calendar-check me-1"></i><?= $ticket_scheduled_for ?></small></div>
<?php } ?>
@@ -430,14 +426,11 @@ if ($tickets) {
<!-- Ticket Assigned agent -->
<td>
<a href="#"
<?php if (lookupUserPermission("module_support") >= 2 && empty($ticket_closed_at)) { ?>
class="ajax-modal"
data-modal-url="modals/ticket/ticket_assign.php?id=<?= $ticket_id ?>"
<?php } ?>
>
<?php if (lookupUserPermission("module_support") >= 2 && empty($ticket_closed_at)) { ?>
<?= quickPick('assignee', $ticket_id, (string) intval($row['ticket_assigned_to']), $ticket_assigned_to_display) ?>
<?php } else { ?>
<?= $ticket_assigned_to_display ?>
</a>
<?php } ?>
</td>
<!-- Ticket Last Response -->

View File

@@ -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

View File

@@ -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';

View File

@@ -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 "<span class='$pill $colors'><span class='position-relative d-inline-flex' aria-hidden='true'><i class='fas fa-circle fs-5 text-$tone'></i><i class='fas fa-user-slash position-absolute top-50 start-50 translate-middle small text-white'></i></span>Unassigned</span>";
return "<span class='$pill $colors'><span class='position-relative d-inline-flex' aria-hidden='true'><i class='fas fa-circle fs-5 text-$tone'></i><i class='fas fa-user-slash position-absolute top-50 start-50 translate-middle small text-white'></i></span>" . escapeHtml($none_label) . "</span>";
}
$user_avatar = escapeHtml($user_avatar);

405
functions/ticket_fields.php Normal file
View File

@@ -0,0 +1,405 @@
<?php
/*
* Ticket priority, assignee and billable - changing them, and drawing them.
* Also a project's manager and a recurring ticket's assignee, which use the
* same agent picker.
*
* The change functions are what the old Change priority / Assign ticket /
* Billing modals' post handlers did (history, audit log, SLA, notifications,
* custom actions), moved here for the inline pickers on the ticket list and
* ticket page (js/quick_pick.js, via agent/ajax.php), which replaced those
* modals. They assume the caller has checked module rights and client access.
*
* The draw functions are the one markup for each value, used by those pages
* and by the ajax reply that redraws them after a change.
*/
const TICKET_PRIORITIES = ['Low', 'Medium', 'High', 'Urgent'];
/* The badge colour for a priority - the same everywhere. */
function ticketPriorityColor($priority) {
$colors = ['Urgent' => '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 <strong>$priority</strong>"];
}
$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 <strong>$original_priority</strong> to <strong>$priority_sql</strong>"];
}
/*
* 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, <br><br>A ticket has been assigned to you!<br><br>Client: $client_name<br>Ticket Number: $ticket_prefix$ticket_number<br> Subject: $ticket_subject<br><br>https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri <br><br>Thanks, <br>$session_name<br>$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 <strong>$ticket_prefix$ticket_number</strong> assigned to <strong>$agent_name</strong>"];
}
/*
* 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 <strong>" . escapeHtml($statuses[$status_id]['ticket_status_name']) . "</strong>"];
}
$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 <strong>$status_name</strong>"];
}
/* 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 <strong>$billable_wording Billable</strong>"];
}
/*
* 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 '<span class="badge rounded-pill text-bg-' . ticketPriorityColor($priority) . ($style === 'list' ? ' p-2' : '') . '">' . $priority . '</span>';
}
function ticketBillableHtml($billable, $style = 'list') {
if ($style === 'detail') {
return $billable ? '<span>Billable</span>' : "<span class='text-muted'>Not billable</span>";
}
return $billable
? '<span class="badge rounded-pill bg-success p-2"><i class="fas fa-fw fa-dollar-sign"></i></span>'
: '<span class="badge rounded-pill bg-secondary p-2"><i class="fas fa-fw fa-minus"></i></span>';
}
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 '<span class="badge rounded-pill text-light' . ($style === 'list' ? ' p-2' : '') . '" style="background-color: ' . $color . '">' . escapeHtml($status_name) . '</span>';
}
/*
* 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 '<button type="button" class="' . $class . '" data-quick-pick="' . $field . '" data-quick-id="' . intval($id) . '"'
. ' data-quick-current="' . escapeHtml($current) . '" data-quick-style="' . $style . '"' . ($status_id ? ' data-status-id="' . intval($status_id) . '"' : '') . ' data-csrf="' . escapeHtml($_SESSION['csrf_token'] ?? '') . '"'
. ' title="' . $labels[$field] . '" aria-haspopup="listbox" aria-expanded="false">'
. '<span class="itflow-quick-pick-value">' . $inner . '</span>'
. ($style === 'detail' ? '<i class="fas fa-chevron-down ticket-prop-edit-icon" aria-hidden="true"></i>' : '')
. '</button>';
}
/* 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, <br><br>$session_name assigned the recurring ticket $subject to you - the tickets it opens will be yours.<br><br>Thanks, <br>$session_name<br>$company_name",
]
]);
}
}
return [true, $assigned_to ? "Recurring ticket assigned to $agent_name" : 'Recurring ticket unassigned'];
}

View File

@@ -78,6 +78,7 @@
<script src="/js/autocomplete.js"></script>
<script src="/js/app.js"></script>
<script src="/js/tag_picker.js"></script>
<script src="/js/quick_pick.js"></script>
<script src="/js/ajax_modal.js"></script>
<script src="/js/confirm_modal.js"></script>
<script src="/js/date_filter.js"></script>

486
js/quick_pick.js Normal file
View File

@@ -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="<ticket id>".
*
* 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;
})();