Integrate web_template design system and fix security/quality issues

Security fixes:
- Add HTTP method validation to delete_comment.php (block CSRF via GET)
- Remove $_GET fallback in comment deletion (was CSRF bypass vector)
- Guard session_start() with session_status() check across API files
- Escape json_encode() data attributes with htmlspecialchars in views
- Escape inline APP_TIMEZONE config values in DashboardView/TicketView
- Validate timezone param against DateTimeZone::listIdentifiers() in index.php
- Remove Database::escape() (was using real_escape_string, not safe)
- Fix AttachmentModel hardcoded connection; inject via constructor

Backend fixes:
- Fix CommentModel bind_param type for ticket_id (s→i)
- Fix buildCommentThread orphan parent guard
- Fix StatsModel JOIN→LEFT JOIN so unassigned tickets aren't excluded
- Add ticket ID validation in BulkOperationsModel before implode()
- Add duplicate key retry in TicketModel::createTicket() for race conditions
- Wrap SavedFiltersModel default filter changes in transactions
- Add null result guards in WorkflowModel query methods

Frontend JS:
- Rewrite toast.js as lt.toast shim (base.js dependency)
- Delegate escapeHtml() to lt.escHtml()
- Rewrite keyboard-shortcuts.js using lt.keys.on()
- Migrate settings.js to lt.api.* and lt.modal.open/close()
- Migrate advanced-search.js to lt.api.* and lt.modal.open/close()
- Migrate dashboard.js fetch calls to lt.api.*; update all dynamic
  modals (bulk ops, quick actions, confirm/input) to lt-modal structure
- Migrate ticket.js fetchMentionUsers to lt.api.get()
- Remove console.log/error/warn calls from JS files

Views:
- Add /web_template/base.css and base.js to all 10 view files
- Call lt.keys.initDefaults() in DashboardView, TicketView, admin views
- Migrate all modal HTML from settings-modal/settings-content to
  lt-modal-overlay/lt-modal/lt-modal-header/lt-modal-body/lt-modal-footer
- Replace style="display:none" with aria-hidden="true" on all modals
- Replace modal open/close style.display with lt.modal.open/close()
- Update modal buttons to lt-btn lt-btn-primary/lt-btn-ghost classes
- Remove manual ESC keydown handlers (replaced by lt.keys.initDefaults)
- Fix unescaped timezone values in TicketView inline script

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-17 23:22:24 -04:00
parent d204756cfe
commit 89a685a502
34 changed files with 576 additions and 997 deletions

View File

@@ -30,7 +30,9 @@ try {
require_once dirname(__DIR__) . '/helpers/Database.php'; require_once dirname(__DIR__) . '/helpers/Database.php';
// Check authentication via session // Check authentication via session
session_start(); if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) { if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
throw new Exception("Authentication required"); throw new Exception("Authentication required");
} }

View File

@@ -58,7 +58,7 @@ if (!$attachmentId || !is_numeric($attachmentId)) {
$attachmentId = (int)$attachmentId; $attachmentId = (int)$attachmentId;
try { try {
$attachmentModel = new AttachmentModel(); $attachmentModel = new AttachmentModel(Database::getConnection());
// Get attachment details // Get attachment details
$attachment = $attachmentModel->getAttachment($attachmentId); $attachment = $attachmentModel->getAttachment($attachmentId);

View File

@@ -21,8 +21,19 @@ try {
require_once dirname(__DIR__) . '/models/TicketModel.php'; require_once dirname(__DIR__) . '/models/TicketModel.php';
require_once dirname(__DIR__) . '/models/AuditLogModel.php'; require_once dirname(__DIR__) . '/models/AuditLogModel.php';
// Only allow POST or DELETE — reject GET to prevent CSRF bypass
$method = $_SERVER['REQUEST_METHOD'];
if ($method !== 'POST' && $method !== 'DELETE') {
http_response_code(405);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
exit;
}
// Check authentication via session // Check authentication via session
session_start(); if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) { if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
throw new Exception("Authentication required"); throw new Exception("Authentication required");
} }
@@ -48,9 +59,9 @@ try {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data || !isset($data['comment_id'])) { if (!$data || !isset($data['comment_id'])) {
// Try query params // Also check POST params (no GET fallback — prevents CSRF bypass via URL)
if (isset($_GET['comment_id'])) { if (isset($_POST['comment_id'])) {
$data = ['comment_id' => $_GET['comment_id']]; $data = ['comment_id' => $_POST['comment_id']];
} else { } else {
throw new Exception("Missing required field: comment_id"); throw new Exception("Missing required field: comment_id");
} }

View File

@@ -33,7 +33,7 @@ if (!$attachmentId || !is_numeric($attachmentId)) {
$attachmentId = (int)$attachmentId; $attachmentId = (int)$attachmentId;
try { try {
$attachmentModel = new AttachmentModel(); $attachmentModel = new AttachmentModel(Database::getConnection());
// Get attachment details // Get attachment details
$attachment = $attachmentModel->getAttachment($attachmentId); $attachment = $attachmentModel->getAttachment($attachmentId);

View File

@@ -22,7 +22,9 @@ try {
require_once dirname(__DIR__) . '/models/AuditLogModel.php'; require_once dirname(__DIR__) . '/models/AuditLogModel.php';
// Check authentication via session // Check authentication via session
session_start(); if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) { if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
throw new Exception("Authentication required"); throw new Exception("Authentication required");
} }

View File

@@ -28,7 +28,9 @@ try {
require_once $workflowModelPath; require_once $workflowModelPath;
// Check authentication via session // Check authentication via session
session_start(); if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) { if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
throw new Exception("Authentication required"); throw new Exception("Authentication required");
} }

View File

@@ -46,7 +46,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
} }
try { try {
$attachmentModel = new AttachmentModel(); $attachmentModel = new AttachmentModel(Database::getConnection());
$attachments = $attachmentModel->getAttachments($ticketId); $attachments = $attachmentModel->getAttachments($ticketId);
// Add formatted file size and icon to each attachment // Add formatted file size and icon to each attachment

View File

@@ -7,8 +7,7 @@
function openAdvancedSearch() { function openAdvancedSearch() {
const modal = document.getElementById('advancedSearchModal'); const modal = document.getElementById('advancedSearchModal');
if (modal) { if (modal) {
modal.style.display = 'flex'; lt.modal.open('advancedSearchModal');
document.body.classList.add('modal-open');
loadUsersForSearch(); loadUsersForSearch();
populateCurrentFilters(); populateCurrentFilters();
loadSavedFilters(); loadSavedFilters();
@@ -17,11 +16,7 @@ function openAdvancedSearch() {
// Close advanced search modal // Close advanced search modal
function closeAdvancedSearch() { function closeAdvancedSearch() {
const modal = document.getElementById('advancedSearchModal'); lt.modal.close('advancedSearchModal');
if (modal) {
modal.style.display = 'none';
document.body.classList.remove('modal-open');
}
} }
// Close modal when clicking on backdrop // Close modal when clicking on backdrop
@@ -35,10 +30,7 @@ function closeOnAdvancedSearchBackdropClick(event) {
// Load users for dropdown // Load users for dropdown
async function loadUsersForSearch() { async function loadUsersForSearch() {
try { try {
const response = await fetch('/api/get_users.php', { const data = await lt.api.get('/api/get_users.php');
credentials: 'same-origin'
});
const data = await response.json();
if (data.success && data.users) { if (data.success && data.users) {
const createdBySelect = document.getElementById('adv-created-by'); const createdBySelect = document.getElementById('adv-created-by');
@@ -68,7 +60,7 @@ async function loadUsersForSearch() {
}); });
} }
} catch (error) { } catch (error) {
console.error('Error loading users:', error); lt.toast.error('Error loading users');
} }
} }
@@ -163,30 +155,14 @@ async function saveCurrentFilter() {
const filterCriteria = getCurrentFilterCriteria(); const filterCriteria = getCurrentFilterCriteria();
try { try {
const response = await fetch('/api/saved_filters.php', { await lt.api.post('/api/saved_filters.php', {
method: 'POST', filter_name: filterName.trim(),
credentials: 'same-origin', filter_criteria: filterCriteria
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': window.CSRF_TOKEN
},
body: JSON.stringify({
filter_name: filterName.trim(),
filter_criteria: filterCriteria
})
}); });
lt.toast.success(`Filter "${filterName}" saved successfully!`, 3000);
const result = await response.json(); loadSavedFilters();
if (result.success) {
toast.success(`Filter "${filterName}" saved successfully!`, 3000);
loadSavedFilters();
} else {
toast.error('Failed to save filter: ' + (result.error || 'Unknown error'), 4000);
}
} catch (error) { } catch (error) {
console.error('Error saving filter:', error); lt.toast.error('Error saving filter: ' + (error.message || 'Unknown error'), 4000);
toast.error('Error saving filter', 4000);
} }
} }
); );
@@ -233,16 +209,12 @@ function getCurrentFilterCriteria() {
// Load saved filters // Load saved filters
async function loadSavedFilters() { async function loadSavedFilters() {
try { try {
const response = await fetch('/api/saved_filters.php', { const data = await lt.api.get('/api/saved_filters.php');
credentials: 'same-origin'
});
const data = await response.json();
if (data.success && data.filters) { if (data.success && data.filters) {
populateSavedFiltersDropdown(data.filters); populateSavedFiltersDropdown(data.filters);
} }
} catch (error) { } catch (error) {
console.error('Error loading saved filters:', error); lt.toast.error('Error loading saved filters');
} }
} }
@@ -277,7 +249,7 @@ function loadSavedFilter() {
const criteria = JSON.parse(selectedOption.dataset.criteria); const criteria = JSON.parse(selectedOption.dataset.criteria);
applySavedFilterCriteria(criteria); applySavedFilterCriteria(criteria);
} catch (error) { } catch (error) {
console.error('Error loading filter:', error); lt.toast.error('Error loading filter');
} }
} }
@@ -314,9 +286,7 @@ async function deleteSavedFilter() {
const selectedOption = dropdown.options[dropdown.selectedIndex]; const selectedOption = dropdown.options[dropdown.selectedIndex];
if (!selectedOption || selectedOption.value === '') { if (!selectedOption || selectedOption.value === '') {
if (typeof toast !== 'undefined') { lt.toast.error('Please select a filter to delete');
toast.error('Please select a filter to delete');
}
return; return;
} }
@@ -329,45 +299,21 @@ async function deleteSavedFilter() {
'error', 'error',
async () => { async () => {
try { try {
const response = await fetch('/api/saved_filters.php', { await lt.api.delete('/api/saved_filters.php', { filter_id: filterId });
method: 'DELETE', lt.toast.success('Filter deleted successfully', 3000);
credentials: 'same-origin', loadSavedFilters();
headers: { resetAdvancedSearch();
'Content-Type': 'application/json',
'X-CSRF-Token': window.CSRF_TOKEN
},
body: JSON.stringify({ filter_id: filterId })
});
const result = await response.json();
if (result.success) {
toast.success('Filter deleted successfully', 3000);
loadSavedFilters();
resetAdvancedSearch();
} else {
toast.error('Failed to delete filter', 4000);
}
} catch (error) { } catch (error) {
console.error('Error deleting filter:', error); lt.toast.error('Error deleting filter', 4000);
toast.error('Error deleting filter', 4000);
} }
} }
); );
} }
// Keyboard shortcut (Ctrl+Shift+F) // Keyboard shortcut (Ctrl+Shift+F) — ESC is handled globally by lt.keys.initDefaults()
document.addEventListener('keydown', (e) => { document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.shiftKey && e.key === 'F') { if (e.ctrlKey && e.shiftKey && e.key === 'F') {
e.preventDefault(); e.preventDefault();
openAdvancedSearch(); openAdvancedSearch();
} }
// ESC to close
if (e.key === 'Escape') {
const modal = document.getElementById('advancedSearchModal');
if (modal && modal.style.display === 'flex') {
closeAdvancedSearch();
}
}
}); });

View File

@@ -60,7 +60,6 @@ function renderASCIIBanner(bannerId, containerSelector, speed = 5, addGlow = tru
const container = document.querySelector(containerSelector); const container = document.querySelector(containerSelector);
if (!container || !banner) { if (!container || !banner) {
console.error('ASCII Banner: Container or banner not found', { bannerId, containerSelector });
return; return;
} }

View File

@@ -504,7 +504,6 @@ function initStatusFilter() {
function quickSave() { function quickSave() {
if (!window.ticketData) { if (!window.ticketData) {
console.error('No ticket data available');
return; return;
} }
@@ -512,7 +511,6 @@ function quickSave() {
const prioritySelect = document.getElementById('priority-select'); const prioritySelect = document.getElementById('priority-select');
if (!statusSelect || !prioritySelect) { if (!statusSelect || !prioritySelect) {
console.error('Status or priority select not found');
return; return;
} }
@@ -568,12 +566,10 @@ function quickSave() {
} }
} else { } else {
console.error('Error updating ticket:', result.error || 'Unknown error');
toast.error('Error updating ticket: ' + (result.error || 'Unknown error'), 5000); toast.error('Error updating ticket: ' + (result.error || 'Unknown error'), 5000);
} }
}) })
.catch(error => { .catch(error => {
console.error('Error updating ticket:', error);
toast.error('Error updating ticket: ' + error.message, 5000); toast.error('Error updating ticket: ' + error.message, 5000);
}); });
} }
@@ -611,7 +607,12 @@ function saveTicket() {
statusDisplay.className = `status-${data.status}`; statusDisplay.className = `status-${data.status}`;
statusDisplay.textContent = data.status; statusDisplay.textContent = data.status;
} }
} else {
lt.toast.error('Error saving ticket: ' + (data.error || 'Unknown error'));
} }
})
.catch(error => {
lt.toast.error('Error saving ticket: ' + error.message);
}); });
} }
/** /**
@@ -670,12 +671,10 @@ function loadTemplate() {
document.getElementById('priority').value = template.default_priority; document.getElementById('priority').value = template.default_priority;
} }
} else { } else {
console.error('Failed to load template:', data.error);
toast.error('Failed to load template: ' + (data.error || 'Unknown error'), 4000); toast.error('Failed to load template: ' + (data.error || 'Unknown error'), 4000);
} }
}) })
.catch(error => { .catch(error => {
console.error('Error loading template:', error);
toast.error('Error loading template: ' + error.message, 4000); toast.error('Error loading template: ' + error.message, 4000);
}); });
} }
@@ -793,7 +792,6 @@ function performBulkCloseAction(ticketIds) {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error performing bulk close:', error);
toast.error('Bulk close failed: ' + error.message, 5000); toast.error('Bulk close failed: ' + error.message, 5000);
}); });
} }
@@ -808,44 +806,31 @@ function showBulkAssignModal() {
// Create modal HTML // Create modal HTML
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="bulkAssignModal"> <div class="lt-modal-overlay" id="bulkAssignModal" aria-hidden="true">
<div class="modal-content ascii-frame-outer"> <div class="lt-modal">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">Assign ${ticketIds.length} Ticket(s)</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header">Assign ${ticketIds.length} Ticket(s)</div>
<div class="ascii-content">
<div class="ascii-frame-inner">
<div class="modal-body">
<label for="bulkAssignUser">Assign to:</label>
<select id="bulkAssignUser" class="editable">
<option value="">Select User...</option>
<!-- Users will be loaded dynamically -->
</select>
</div>
</div>
</div> </div>
<div class="lt-modal-body">
<div class="ascii-divider"></div> <label for="bulkAssignUser">Assign to:</label>
<select id="bulkAssignUser" class="lt-select" style="width:100%;margin-top:0.5rem;">
<div class="ascii-content"> <option value="">Select User...</option>
<div class="modal-footer"> </select>
<button data-action="perform-bulk-assign" class="btn btn-bulk">Assign</button> </div>
<button data-action="close-bulk-assign-modal" class="btn btn-secondary">Cancel</button> <div class="lt-modal-footer">
</div> <button data-action="perform-bulk-assign" class="lt-btn lt-btn-primary">Assign</button>
<button data-action="close-bulk-assign-modal" class="lt-btn lt-btn-ghost">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
`; `;
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
lt.modal.open('bulkAssignModal');
// Fetch users for the dropdown // Fetch users for the dropdown
fetch('/api/get_users.php', { lt.api.get('/api/get_users.php')
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => { .then(data => {
if (data.success && data.users) { if (data.success && data.users) {
const select = document.getElementById('bulkAssignUser'); const select = document.getElementById('bulkAssignUser');
@@ -857,16 +842,13 @@ function showBulkAssignModal() {
}); });
} }
}) })
.catch(error => { .catch(() => lt.toast.error('Error loading users'));
console.error('Error loading users:', error);
});
} }
function closeBulkAssignModal() { function closeBulkAssignModal() {
lt.modal.close('bulkAssignModal');
const modal = document.getElementById('bulkAssignModal'); const modal = document.getElementById('bulkAssignModal');
if (modal) { if (modal) setTimeout(() => modal.remove(), 300);
modal.remove();
}
} }
function performBulkAssign() { function performBulkAssign() {
@@ -906,7 +888,6 @@ function performBulkAssign() {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error performing bulk assign:', error);
toast.error('Bulk assign failed: ' + error.message, 5000); toast.error('Bulk assign failed: ' + error.message, 5000);
}); });
} }
@@ -920,49 +901,39 @@ function showBulkPriorityModal() {
} }
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="bulkPriorityModal"> <div class="lt-modal-overlay" id="bulkPriorityModal" aria-hidden="true">
<div class="modal-content ascii-frame-outer"> <div class="lt-modal">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">Change Priority for ${ticketIds.length} Ticket(s)</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header">Change Priority for ${ticketIds.length} Ticket(s)</div>
<div class="ascii-content">
<div class="ascii-frame-inner">
<div class="modal-body">
<label for="bulkPriority">Priority:</label>
<select id="bulkPriority" class="editable">
<option value="">Select Priority...</option>
<option value="1">P1 - Critical Impact</option>
<option value="2">P2 - High Impact</option>
<option value="3">P3 - Medium Impact</option>
<option value="4">P4 - Low Impact</option>
<option value="5">P5 - Minimal Impact</option>
</select>
</div>
</div>
</div> </div>
<div class="lt-modal-body">
<div class="ascii-divider"></div> <label for="bulkPriority">Priority:</label>
<select id="bulkPriority" class="lt-select" style="width:100%;margin-top:0.5rem;">
<div class="ascii-content"> <option value="">Select Priority...</option>
<div class="modal-footer"> <option value="1">P1 - Critical Impact</option>
<button data-action="perform-bulk-priority" class="btn btn-bulk">Update</button> <option value="2">P2 - High Impact</option>
<button data-action="close-bulk-priority-modal" class="btn btn-secondary">Cancel</button> <option value="3">P3 - Medium Impact</option>
</div> <option value="4">P4 - Low Impact</option>
<option value="5">P5 - Minimal Impact</option>
</select>
</div>
<div class="lt-modal-footer">
<button data-action="perform-bulk-priority" class="lt-btn lt-btn-primary">Update</button>
<button data-action="close-bulk-priority-modal" class="lt-btn lt-btn-ghost">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
`; `;
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
lt.modal.open('bulkPriorityModal');
} }
function closeBulkPriorityModal() { function closeBulkPriorityModal() {
lt.modal.close('bulkPriorityModal');
const modal = document.getElementById('bulkPriorityModal'); const modal = document.getElementById('bulkPriorityModal');
if (modal) { if (modal) setTimeout(() => modal.remove(), 300);
modal.remove();
}
} }
function performBulkPriority() { function performBulkPriority() {
@@ -1002,7 +973,6 @@ function performBulkPriority() {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error performing bulk priority update:', error);
toast.error('Bulk priority update failed: ' + error.message, 5000); toast.error('Bulk priority update failed: ' + error.message, 5000);
}); });
} }
@@ -1056,48 +1026,38 @@ function showBulkStatusModal() {
} }
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="bulkStatusModal"> <div class="lt-modal-overlay" id="bulkStatusModal" aria-hidden="true">
<div class="modal-content ascii-frame-outer"> <div class="lt-modal">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">Change Status for ${ticketIds.length} Ticket(s)</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header">Change Status for ${ticketIds.length} Ticket(s)</div>
<div class="ascii-content">
<div class="ascii-frame-inner">
<div class="modal-body">
<label for="bulkStatus">New Status:</label>
<select id="bulkStatus" class="editable">
<option value="">Select Status...</option>
<option value="Open">Open</option>
<option value="Pending">Pending</option>
<option value="In Progress">In Progress</option>
<option value="Closed">Closed</option>
</select>
</div>
</div>
</div> </div>
<div class="lt-modal-body">
<div class="ascii-divider"></div> <label for="bulkStatus">New Status:</label>
<select id="bulkStatus" class="lt-select" style="width:100%;margin-top:0.5rem;">
<div class="ascii-content"> <option value="">Select Status...</option>
<div class="modal-footer"> <option value="Open">Open</option>
<button data-action="perform-bulk-status" class="btn btn-bulk">Update</button> <option value="Pending">Pending</option>
<button data-action="close-bulk-status-modal" class="btn btn-secondary">Cancel</button> <option value="In Progress">In Progress</option>
</div> <option value="Closed">Closed</option>
</select>
</div>
<div class="lt-modal-footer">
<button data-action="perform-bulk-status" class="lt-btn lt-btn-primary">Update</button>
<button data-action="close-bulk-status-modal" class="lt-btn lt-btn-ghost">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
`; `;
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
lt.modal.open('bulkStatusModal');
} }
function closeBulkStatusModal() { function closeBulkStatusModal() {
lt.modal.close('bulkStatusModal');
const modal = document.getElementById('bulkStatusModal'); const modal = document.getElementById('bulkStatusModal');
if (modal) { if (modal) setTimeout(() => modal.remove(), 300);
modal.remove();
}
} }
function performBulkStatusChange() { function performBulkStatusChange() {
@@ -1137,7 +1097,6 @@ function performBulkStatusChange() {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error performing bulk status change:', error);
toast.error('Bulk status change failed: ' + error.message, 5000); toast.error('Bulk status change failed: ' + error.message, 5000);
}); });
} }
@@ -1152,47 +1111,32 @@ function showBulkDeleteModal() {
} }
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="bulkDeleteModal"> <div class="lt-modal-overlay" id="bulkDeleteModal" aria-hidden="true">
<div class="modal-content ascii-frame-outer"> <div class="lt-modal">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header" style="color: var(--status-closed);">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">⚠ Delete ${ticketIds.length} Ticket(s)</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header" style="color: var(--status-closed);">⚠ Delete ${ticketIds.length} Ticket(s)</div>
<div class="ascii-content">
<div class="ascii-frame-inner">
<div class="modal-body" style="text-align: center; padding: 2rem;">
<p style="color: var(--terminal-amber); font-size: 1.1rem; margin-bottom: 1rem;">
This action cannot be undone!
</p>
<p style="color: var(--terminal-green);">
You are about to permanently delete ${ticketIds.length} ticket(s).<br>
All associated comments and history will be lost.
</p>
</div>
</div>
</div> </div>
<div class="lt-modal-body" style="text-align:center;">
<div class="ascii-divider"></div> <p style="color: var(--terminal-amber); font-size: 1.1rem; margin-bottom: 1rem;">This action cannot be undone!</p>
<p style="color: var(--terminal-green);">You are about to permanently delete ${ticketIds.length} ticket(s).<br>All associated comments and history will be lost.</p>
<div class="ascii-content"> </div>
<div class="modal-footer"> <div class="lt-modal-footer">
<button data-action="perform-bulk-delete" class="btn btn-bulk" style="background: var(--status-closed); border-color: var(--status-closed);">Delete Permanently</button> <button data-action="perform-bulk-delete" class="lt-btn lt-btn-primary" style="background: var(--status-closed); border-color: var(--status-closed);">Delete Permanently</button>
<button data-action="close-bulk-delete-modal" class="btn btn-secondary">Cancel</button> <button data-action="close-bulk-delete-modal" class="lt-btn lt-btn-ghost">Cancel</button>
</div>
</div> </div>
</div> </div>
</div> </div>
`; `;
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
lt.modal.open('bulkDeleteModal');
} }
function closeBulkDeleteModal() { function closeBulkDeleteModal() {
lt.modal.close('bulkDeleteModal');
const modal = document.getElementById('bulkDeleteModal'); const modal = document.getElementById('bulkDeleteModal');
if (modal) { if (modal) setTimeout(() => modal.remove(), 300);
modal.remove();
}
} }
function performBulkDelete() { function performBulkDelete() {
@@ -1221,7 +1165,6 @@ function performBulkDelete() {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error performing bulk delete:', error);
toast.error('Bulk delete failed: ' + error.message, 5000); toast.error('Bulk delete failed: ' + error.message, 5000);
}); });
} }
@@ -1262,32 +1205,18 @@ function showConfirmModal(title, message, type = 'warning', onConfirm, onCancel
const safeMessage = escapeHtml(message); const safeMessage = escapeHtml(message);
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="${modalId}"> <div class="lt-modal-overlay" id="${modalId}" aria-hidden="true">
<div class="modal-content ascii-frame-outer" style="max-width: 500px;"> <div class="lt-modal" style="max-width: 500px;">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header" style="color: ${color};">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">${icon} ${safeTitle}</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header" style="color: ${color};">
${icon} ${safeTitle}
</div> </div>
<div class="lt-modal-body" style="text-align: center;">
<div class="ascii-content"> <p style="color: var(--terminal-green); white-space: pre-line;">${safeMessage}</p>
<div class="ascii-frame-inner">
<div class="modal-body" style="padding: 1.5rem; text-align: center;">
<p style="color: var(--terminal-green); white-space: pre-line;">
${safeMessage}
</p>
</div>
</div>
</div> </div>
<div class="lt-modal-footer">
<div class="ascii-divider"></div> <button class="lt-btn lt-btn-primary" id="${modalId}_confirm">Confirm</button>
<button class="lt-btn lt-btn-ghost" id="${modalId}_cancel">Cancel</button>
<div class="ascii-content">
<div class="modal-footer">
<button class="btn btn-primary" id="${modalId}_confirm">Confirm</button>
<button class="btn btn-secondary" id="${modalId}_cancel">Cancel</button>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -1296,28 +1225,17 @@ function showConfirmModal(title, message, type = 'warning', onConfirm, onCancel
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
const modal = document.getElementById(modalId); const modal = document.getElementById(modalId);
const confirmBtn = document.getElementById(`${modalId}_confirm`); lt.modal.open(modalId);
const cancelBtn = document.getElementById(`${modalId}_cancel`);
confirmBtn.addEventListener('click', () => { const cleanup = (cb) => {
modal.remove(); lt.modal.close(modalId);
if (onConfirm) onConfirm(); setTimeout(() => modal.remove(), 300);
}); if (cb) cb();
cancelBtn.addEventListener('click', () => {
modal.remove();
if (onCancel) onCancel();
});
// ESC key to cancel
const escHandler = (e) => {
if (e.key === 'Escape') {
modal.remove();
if (onCancel) onCancel();
document.removeEventListener('keydown', escHandler);
}
}; };
document.addEventListener('keydown', escHandler);
document.getElementById(`${modalId}_confirm`).addEventListener('click', () => cleanup(onConfirm));
document.getElementById(`${modalId}_cancel`).addEventListener('click', () => cleanup(onCancel));
modal.querySelector('[data-modal-close]').addEventListener('click', () => cleanup(onCancel));
} }
/** /**
@@ -1338,39 +1256,19 @@ function showInputModal(title, label, placeholder = '', onSubmit, onCancel = nul
const safePlaceholder = escapeHtml(placeholder); const safePlaceholder = escapeHtml(placeholder);
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="${modalId}"> <div class="lt-modal-overlay" id="${modalId}" aria-hidden="true">
<div class="modal-content ascii-frame-outer" style="max-width: 500px;"> <div class="lt-modal" style="max-width: 500px;">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">${safeTitle}</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header">
${safeTitle}
</div> </div>
<div class="lt-modal-body">
<div class="ascii-content"> <label for="${inputId}" style="display: block; margin-bottom: 0.5rem; color: var(--terminal-green);">${safeLabel}</label>
<div class="ascii-frame-inner"> <input type="text" id="${inputId}" class="lt-input" placeholder="${safePlaceholder}" style="width: 100%;" />
<div class="modal-body" style="padding: 1.5rem;">
<label for="${inputId}" style="display: block; margin-bottom: 0.5rem; color: var(--terminal-green);">
${safeLabel}
</label>
<input
type="text"
id="${inputId}"
class="terminal-input"
placeholder="${safePlaceholder}"
style="width: 100%; padding: 0.5rem; background: var(--bg-primary); border: 1px solid var(--terminal-green); color: var(--terminal-green); font-family: var(--font-mono);"
/>
</div>
</div>
</div> </div>
<div class="lt-modal-footer">
<div class="ascii-divider"></div> <button class="lt-btn lt-btn-primary" id="${modalId}_submit">Save</button>
<button class="lt-btn lt-btn-ghost" id="${modalId}_cancel">Cancel</button>
<div class="ascii-content">
<div class="modal-footer">
<button class="btn btn-primary" id="${modalId}_submit">Save</button>
<button class="btn btn-secondary" id="${modalId}_cancel">Cancel</button>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -1380,41 +1278,22 @@ function showInputModal(title, label, placeholder = '', onSubmit, onCancel = nul
const modal = document.getElementById(modalId); const modal = document.getElementById(modalId);
const input = document.getElementById(inputId); const input = document.getElementById(inputId);
const submitBtn = document.getElementById(`${modalId}_submit`); lt.modal.open(modalId);
const cancelBtn = document.getElementById(`${modalId}_cancel`);
// Focus input
setTimeout(() => input.focus(), 100); setTimeout(() => input.focus(), 100);
const handleSubmit = () => { const cleanup = (cb) => {
const value = input.value.trim(); lt.modal.close(modalId);
modal.remove(); setTimeout(() => modal.remove(), 300);
if (onSubmit) onSubmit(value); if (cb) cb();
}; };
submitBtn.addEventListener('click', handleSubmit); const handleSubmit = () => cleanup(() => onSubmit && onSubmit(input.value.trim()));
// Enter key to submit document.getElementById(`${modalId}_submit`).addEventListener('click', handleSubmit);
input.addEventListener('keypress', (e) => { input.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleSubmit(); });
if (e.key === 'Enter') { document.getElementById(`${modalId}_cancel`).addEventListener('click', () => cleanup(onCancel));
handleSubmit(); modal.querySelector('[data-modal-close]').addEventListener('click', () => cleanup(onCancel));
}
});
cancelBtn.addEventListener('click', () => {
modal.remove();
if (onCancel) onCancel();
});
// ESC key to cancel
const escHandler = (e) => {
if (e.key === 'Escape') {
modal.remove();
if (onCancel) onCancel();
document.removeEventListener('keydown', escHandler);
}
};
document.addEventListener('keydown', escHandler);
} }
// ======================================== // ========================================
@@ -1429,44 +1308,36 @@ function quickStatusChange(ticketId, currentStatus) {
const otherStatuses = statuses.filter(s => s !== currentStatus); const otherStatuses = statuses.filter(s => s !== currentStatus);
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="quickStatusModal"> <div class="lt-modal-overlay" id="quickStatusModal" aria-hidden="true">
<div class="modal-content ascii-frame-outer" style="max-width: 400px;"> <div class="lt-modal" style="max-width:400px;">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">Quick Status Change</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header">Quick Status Change</div>
<div class="ascii-content">
<div class="ascii-frame-inner">
<div class="modal-body" style="padding: 1rem;">
<p style="margin-bottom: 1rem;">Ticket #${escapeHtml(ticketId)}</p>
<p style="margin-bottom: 0.5rem; color: var(--terminal-amber);">Current: ${escapeHtml(currentStatus)}</p>
<label for="quickStatusSelect">New Status:</label>
<select id="quickStatusSelect" class="editable" style="width: 100%; margin-top: 0.5rem;">
${otherStatuses.map(s => `<option value="${s}">${s}</option>`).join('')}
</select>
</div>
</div>
</div> </div>
<div class="lt-modal-body">
<div class="ascii-divider"></div> <p style="margin-bottom:0.5rem;">Ticket #${escapeHtml(ticketId)}</p>
<p style="margin-bottom:0.5rem;color:var(--terminal-amber);">Current: ${escapeHtml(currentStatus)}</p>
<div class="ascii-content"> <label for="quickStatusSelect">New Status:</label>
<div class="modal-footer"> <select id="quickStatusSelect" class="lt-select" style="width:100%;margin-top:0.5rem;">
<button data-action="perform-quick-status" data-ticket-id="${ticketId}" class="btn btn-primary">Update</button> ${otherStatuses.map(s => `<option value="${s}">${s}</option>`).join('')}
<button data-action="close-quick-status-modal" class="btn btn-secondary">Cancel</button> </select>
</div> </div>
<div class="lt-modal-footer">
<button data-action="perform-quick-status" data-ticket-id="${ticketId}" class="lt-btn lt-btn-primary">Update</button>
<button data-action="close-quick-status-modal" class="lt-btn lt-btn-ghost">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
`; `;
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
lt.modal.open('quickStatusModal');
} }
function closeQuickStatusModal() { function closeQuickStatusModal() {
lt.modal.close('quickStatusModal');
const modal = document.getElementById('quickStatusModal'); const modal = document.getElementById('quickStatusModal');
if (modal) modal.remove(); if (modal) setTimeout(() => modal.remove(), 300);
} }
function performQuickStatusChange(ticketId) { function performQuickStatusChange(ticketId) {
@@ -1496,7 +1367,6 @@ function performQuickStatusChange(ticketId) {
}) })
.catch(error => { .catch(error => {
closeQuickStatusModal(); closeQuickStatusModal();
console.error('Error:', error);
toast.error('Error updating status', 4000); toast.error('Error updating status', 4000);
}); });
} }
@@ -1506,44 +1376,32 @@ function performQuickStatusChange(ticketId) {
*/ */
function quickAssign(ticketId) { function quickAssign(ticketId) {
const modalHtml = ` const modalHtml = `
<div class="modal-overlay" id="quickAssignModal"> <div class="lt-modal-overlay" id="quickAssignModal" aria-hidden="true">
<div class="modal-content ascii-frame-outer" style="max-width: 400px;"> <div class="lt-modal" style="max-width:400px;">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title">Quick Assign</span>
<button class="lt-modal-close" data-modal-close>✕</button>
<div class="ascii-section-header">Quick Assign</div>
<div class="ascii-content">
<div class="ascii-frame-inner">
<div class="modal-body" style="padding: 1rem;">
<p style="margin-bottom: 1rem;">Ticket #${escapeHtml(ticketId)}</p>
<label for="quickAssignSelect">Assign to:</label>
<select id="quickAssignSelect" class="editable" style="width: 100%; margin-top: 0.5rem;">
<option value="">Unassigned</option>
</select>
</div>
</div>
</div> </div>
<div class="lt-modal-body">
<div class="ascii-divider"></div> <p style="margin-bottom:0.5rem;">Ticket #${escapeHtml(ticketId)}</p>
<label for="quickAssignSelect">Assign to:</label>
<div class="ascii-content"> <select id="quickAssignSelect" class="lt-select" style="width:100%;margin-top:0.5rem;">
<div class="modal-footer"> <option value="">Unassigned</option>
<button data-action="perform-quick-assign" data-ticket-id="${ticketId}" class="btn btn-primary">Assign</button> </select>
<button data-action="close-quick-assign-modal" class="btn btn-secondary">Cancel</button> </div>
</div> <div class="lt-modal-footer">
<button data-action="perform-quick-assign" data-ticket-id="${ticketId}" class="lt-btn lt-btn-primary">Assign</button>
<button data-action="close-quick-assign-modal" class="lt-btn lt-btn-ghost">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
`; `;
document.body.insertAdjacentHTML('beforeend', modalHtml); document.body.insertAdjacentHTML('beforeend', modalHtml);
lt.modal.open('quickAssignModal');
// Load users // Load users
fetch('/api/get_users.php', { lt.api.get('/api/get_users.php')
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => { .then(data => {
if (data.success && data.users) { if (data.success && data.users) {
const select = document.getElementById('quickAssignSelect'); const select = document.getElementById('quickAssignSelect');
@@ -1555,12 +1413,13 @@ function quickAssign(ticketId) {
}); });
} }
}) })
.catch(error => console.error('Error loading users:', error)); .catch(() => lt.toast.error('Error loading users'));
} }
function closeQuickAssignModal() { function closeQuickAssignModal() {
lt.modal.close('quickAssignModal');
const modal = document.getElementById('quickAssignModal'); const modal = document.getElementById('quickAssignModal');
if (modal) modal.remove(); if (modal) setTimeout(() => modal.remove(), 300);
} }
function performQuickAssign(ticketId) { function performQuickAssign(ticketId) {
@@ -1590,7 +1449,6 @@ function performQuickAssign(ticketId) {
}) })
.catch(error => { .catch(error => {
closeQuickAssignModal(); closeQuickAssignModal();
console.error('Error:', error);
toast.error('Error updating assignment', 4000); toast.error('Error updating assignment', 4000);
}); });
} }

View File

@@ -1,173 +1,9 @@
/** /**
* Keyboard shortcuts for power users * Keyboard shortcuts for power users.
* App-specific shortcuts registered via lt.keys.on() from web_template/base.js.
* ESC, Ctrl+K, and ? are handled by lt.keys.initDefaults().
*/ */
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('keydown', function(e) {
// ESC: Close modals, cancel edit mode, blur inputs
if (e.key === 'Escape') {
// Close any open modals first
const openModals = document.querySelectorAll('.modal-overlay');
let closedModal = false;
openModals.forEach(modal => {
if (modal.style.display !== 'none' && modal.offsetParent !== null) {
modal.remove();
document.body.classList.remove('modal-open');
closedModal = true;
}
});
// Close settings modal if open
const settingsModal = document.getElementById('settingsModal');
if (settingsModal && settingsModal.style.display !== 'none') {
settingsModal.style.display = 'none';
document.body.classList.remove('modal-open');
closedModal = true;
}
// Close advanced search modal if open
const searchModal = document.getElementById('advancedSearchModal');
if (searchModal && searchModal.style.display !== 'none') {
searchModal.style.display = 'none';
document.body.classList.remove('modal-open');
closedModal = true;
}
// If we closed a modal, stop here
if (closedModal) {
e.preventDefault();
return;
}
// Blur any focused input
if (e.target.tagName === 'INPUT' ||
e.target.tagName === 'TEXTAREA' ||
e.target.isContentEditable) {
e.target.blur();
}
// Cancel edit mode on ticket pages
const editButton = document.getElementById('editButton');
if (editButton && editButton.classList.contains('active')) {
window.location.reload();
}
return;
}
// Skip other shortcuts if user is typing in an input/textarea
if (e.target.tagName === 'INPUT' ||
e.target.tagName === 'TEXTAREA' ||
e.target.isContentEditable) {
return;
}
// Ctrl/Cmd + E: Toggle edit mode (on ticket pages)
if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
e.preventDefault();
const editButton = document.getElementById('editButton');
if (editButton) {
editButton.click();
toast.info('Edit mode ' + (editButton.classList.contains('active') ? 'enabled' : 'disabled'));
}
}
// Ctrl/Cmd + S: Save ticket (on ticket pages)
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
const editButton = document.getElementById('editButton');
if (editButton && editButton.classList.contains('active')) {
editButton.click();
toast.success('Saving ticket...');
}
}
// Ctrl/Cmd + K: Focus search (on dashboard)
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
const searchBox = document.querySelector('.search-box');
if (searchBox) {
searchBox.focus();
searchBox.select();
}
}
// ? : Show keyboard shortcuts help (requires Shift on most keyboards)
if (e.key === '?') {
e.preventDefault();
showKeyboardHelp();
}
// J: Move to next row in table (Gmail-style)
if (e.key === 'j') {
e.preventDefault();
navigateTableRow('next');
}
// K: Move to previous row in table (Gmail-style)
if (e.key === 'k') {
e.preventDefault();
navigateTableRow('prev');
}
// Enter: Open selected ticket
if (e.key === 'Enter') {
const selectedRow = document.querySelector('tbody tr.keyboard-selected');
if (selectedRow) {
e.preventDefault();
const ticketLink = selectedRow.querySelector('a[href*="/ticket/"]');
if (ticketLink) {
window.location.href = ticketLink.href;
}
}
}
// N: Create new ticket (on dashboard)
if (e.key === 'n') {
e.preventDefault();
const newTicketBtn = document.querySelector('a[href*="/create"]');
if (newTicketBtn) {
window.location.href = newTicketBtn.href;
}
}
// C: Focus comment textarea (on ticket page)
if (e.key === 'c') {
const commentBox = document.getElementById('newComment');
if (commentBox) {
e.preventDefault();
commentBox.focus();
commentBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
// G then D: Go to Dashboard (vim-style)
if (e.key === 'g') {
window._pendingG = true;
setTimeout(() => { window._pendingG = false; }, 1000);
}
if (e.key === 'd' && window._pendingG) {
e.preventDefault();
window._pendingG = false;
window.location.href = '/';
}
// 1-4: Quick status change on ticket page
if (['1', '2', '3', '4'].includes(e.key)) {
const statusSelect = document.getElementById('statusSelect');
if (statusSelect && !document.querySelector('.modal-overlay')) {
const statusMap = { '1': 'Open', '2': 'Pending', '3': 'In Progress', '4': 'Closed' };
const targetStatus = statusMap[e.key];
const option = Array.from(statusSelect.options).find(opt => opt.value === targetStatus);
if (option && !option.disabled) {
e.preventDefault();
statusSelect.value = targetStatus;
statusSelect.dispatchEvent(new Event('change'));
}
}
}
});
});
// Track currently selected row for J/K navigation // Track currently selected row for J/K navigation
let currentSelectedRowIndex = -1; let currentSelectedRowIndex = -1;
@@ -175,7 +11,6 @@ function navigateTableRow(direction) {
const rows = document.querySelectorAll('tbody tr'); const rows = document.querySelectorAll('tbody tr');
if (rows.length === 0) return; if (rows.length === 0) return;
// Remove current selection
rows.forEach(row => row.classList.remove('keyboard-selected')); rows.forEach(row => row.classList.remove('keyboard-selected'));
if (direction === 'next') { if (direction === 'next') {
@@ -184,7 +19,6 @@ function navigateTableRow(direction) {
currentSelectedRowIndex = Math.max(currentSelectedRowIndex - 1, 0); currentSelectedRowIndex = Math.max(currentSelectedRowIndex - 1, 0);
} }
// Add selection to new row
const selectedRow = rows[currentSelectedRowIndex]; const selectedRow = rows[currentSelectedRowIndex];
if (selectedRow) { if (selectedRow) {
selectedRow.classList.add('keyboard-selected'); selectedRow.classList.add('keyboard-selected');
@@ -193,59 +27,135 @@ function navigateTableRow(direction) {
} }
function showKeyboardHelp() { function showKeyboardHelp() {
// Check if help is already showing if (document.getElementById('keyboardHelpModal')) return;
if (document.getElementById('keyboardHelpModal')) {
return;
}
const modal = document.createElement('div'); const modal = document.createElement('div');
modal.id = 'keyboardHelpModal'; modal.id = 'keyboardHelpModal';
modal.className = 'modal-overlay'; modal.className = 'lt-modal-overlay';
modal.setAttribute('aria-hidden', 'true');
modal.innerHTML = ` modal.innerHTML = `
<div class="modal-content ascii-frame-outer" style="max-width: 500px;"> <div class="lt-modal" style="max-width: 500px;">
<div class="ascii-frame"> <div class="lt-modal-header">
<div class="ascii-content"> <span class="lt-modal-title">KEYBOARD SHORTCUTS</span>
<h3 style="margin: 0 0 1rem 0; color: var(--terminal-green);">KEYBOARD SHORTCUTS</h3> <button class="lt-modal-close" data-modal-close aria-label="Close">✕</button>
<div class="modal-body" style="padding: 0;"> </div>
<h4 style="color: var(--terminal-amber); margin: 0.5rem 0; font-size: 0.9rem;">Navigation</h4> <div class="lt-modal-body">
<table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;"> <h4 style="color: var(--terminal-amber); margin: 0 0 0.5rem 0; font-size: 0.9rem;">Navigation</h4>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>J</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Next ticket in list</td></tr> <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>K</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Previous ticket in list</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>J</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Next ticket in list</td></tr>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>Enter</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Open selected ticket</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>K</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Previous ticket in list</td></tr>
<tr><td style="padding: 0.4rem;"><kbd>G</kbd> then <kbd>D</kbd></td><td style="padding: 0.4rem;">Go to Dashboard</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>Enter</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Open selected ticket</td></tr>
</table> <tr><td style="padding: 0.4rem;"><kbd>G</kbd> then <kbd>D</kbd></td><td style="padding: 0.4rem;">Go to Dashboard</td></tr>
<h4 style="color: var(--terminal-amber); margin: 0.5rem 0; font-size: 0.9rem;">Actions</h4> </table>
<table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;"> <h4 style="color: var(--terminal-amber); margin: 0 0 0.5rem 0; font-size: 0.9rem;">Actions</h4>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>N</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">New ticket</td></tr> <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>C</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Focus comment box</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>N</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">New ticket</td></tr>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>Ctrl/Cmd + E</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Toggle Edit Mode</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>C</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Focus comment box</td></tr>
<tr><td style="padding: 0.4rem;"><kbd>Ctrl/Cmd + S</kbd></td><td style="padding: 0.4rem;">Save Changes</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>Ctrl/Cmd+E</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Toggle Edit Mode</td></tr>
</table> <tr><td style="padding: 0.4rem;"><kbd>Ctrl/Cmd+S</kbd></td><td style="padding: 0.4rem;">Save Changes</td></tr>
<h4 style="color: var(--terminal-amber); margin: 0.5rem 0; font-size: 0.9rem;">Quick Status (Ticket Page)</h4> </table>
<table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;"> <h4 style="color: var(--terminal-amber); margin: 0 0 0.5rem 0; font-size: 0.9rem;">Quick Status (Ticket Page)</h4>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>1</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Set Open</td></tr> <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>2</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Set Pending</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>1</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Set Open</td></tr>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>3</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Set In Progress</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>2</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Set Pending</td></tr>
<tr><td style="padding: 0.4rem;"><kbd>4</kbd></td><td style="padding: 0.4rem;">Set Closed</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>3</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Set In Progress</td></tr>
</table> <tr><td style="padding: 0.4rem;"><kbd>4</kbd></td><td style="padding: 0.4rem;">Set Closed</td></tr>
<h4 style="color: var(--terminal-amber); margin: 0.5rem 0; font-size: 0.9rem;">Other</h4> </table>
<table style="width: 100%; border-collapse: collapse;"> <h4 style="color: var(--terminal-amber); margin: 0 0 0.5rem 0; font-size: 0.9rem;">Other</h4>
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>Ctrl/Cmd + K</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Focus Search</td></tr> <table style="width: 100%; border-collapse: collapse;">
<tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>ESC</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Close Modal / Cancel</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>Ctrl/Cmd+K</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Focus Search</td></tr>
<tr><td style="padding: 0.4rem;"><kbd>?</kbd></td><td style="padding: 0.4rem;">Show This Help</td></tr> <tr><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);"><kbd>ESC</kbd></td><td style="padding: 0.4rem; border-bottom: 1px solid var(--border-color);">Close Modal / Cancel</td></tr>
</table> <tr><td style="padding: 0.4rem;"><kbd>?</kbd></td><td style="padding: 0.4rem;">Show This Help</td></tr>
</div> </table>
<div class="modal-footer" style="margin-top: 1rem;"> </div>
<button class="btn btn-secondary" data-action="close-shortcuts-modal">Close</button> <div class="lt-modal-footer">
</div> <button class="lt-btn lt-btn-ghost" data-modal-close>Close</button>
</div>
</div> </div>
</div> </div>
`; `;
document.body.appendChild(modal); document.body.appendChild(modal);
lt.modal.open('keyboardHelpModal');
// Add event listener for the close button
modal.querySelector('[data-action="close-shortcuts-modal"]').addEventListener('click', function() {
modal.remove();
});
} }
document.addEventListener('DOMContentLoaded', function() {
// Ctrl+E: Toggle edit mode (ticket pages)
lt.keys.on('ctrl+e', function() {
const editButton = document.getElementById('editButton');
if (editButton) {
editButton.click();
lt.toast.info('Edit mode ' + (editButton.classList.contains('active') ? 'enabled' : 'disabled'));
}
});
// Ctrl+S: Save ticket (ticket pages)
lt.keys.on('ctrl+s', function() {
const editButton = document.getElementById('editButton');
if (editButton && editButton.classList.contains('active')) {
editButton.click();
lt.toast.success('Saving ticket...');
}
});
// ?: Show keyboard shortcuts help (lt.keys.initDefaults also handles this, but we override to show our modal)
lt.keys.on('?', function() {
showKeyboardHelp();
});
// J: Next row
lt.keys.on('j', () => navigateTableRow('next'));
// K: Previous row
lt.keys.on('k', () => navigateTableRow('prev'));
// Enter: Open selected ticket
lt.keys.on('enter', function() {
const selectedRow = document.querySelector('tbody tr.keyboard-selected');
if (selectedRow) {
const ticketLink = selectedRow.querySelector('a[href*="/ticket/"]');
if (ticketLink) window.location.href = ticketLink.href;
}
});
// N: New ticket
lt.keys.on('n', function() {
const newTicketBtn = document.querySelector('a[href*="/create"]');
if (newTicketBtn) window.location.href = newTicketBtn.href;
});
// C: Focus comment box
lt.keys.on('c', function() {
const commentBox = document.getElementById('newComment');
if (commentBox) {
commentBox.focus();
commentBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
});
// G then D: Go to Dashboard (vim-style)
lt.keys.on('g', function() {
window._pendingG = true;
setTimeout(() => { window._pendingG = false; }, 1000);
});
lt.keys.on('d', function() {
if (window._pendingG) {
window._pendingG = false;
window.location.href = '/';
}
});
// 1-4: Quick status change on ticket page
['1', '2', '3', '4'].forEach(key => {
lt.keys.on(key, function() {
const statusSelect = document.getElementById('statusSelect');
if (statusSelect && !document.querySelector('.lt-modal-overlay[aria-hidden="false"]')) {
const statusMap = { '1': 'Open', '2': 'Pending', '3': 'In Progress', '4': 'Closed' };
const targetStatus = statusMap[key];
const option = Array.from(statusSelect.options).find(opt => opt.value === targetStatus);
if (option && !option.disabled) {
statusSelect.value = targetStatus;
statusSelect.dispatchEvent(new Event('change'));
}
}
});
});
});

View File

@@ -8,16 +8,13 @@ let userPreferences = {};
// Load preferences on page load // Load preferences on page load
async function loadUserPreferences() { async function loadUserPreferences() {
try { try {
const response = await fetch('/api/user_preferences.php', { const data = await lt.api.get('/api/user_preferences.php');
credentials: 'same-origin'
});
const data = await response.json();
if (data.success) { if (data.success) {
userPreferences = data.preferences; userPreferences = data.preferences;
applyPreferences(); applyPreferences();
} }
} catch (error) { } catch (error) {
console.error('Error loading preferences:', error); lt.toast.error('Error loading preferences');
} }
} }
@@ -94,34 +91,12 @@ async function saveSettings() {
}; };
try { try {
// Batch save all preferences in one request await lt.api.post('/api/user_preferences.php', { preferences: prefs });
const response = await fetch('/api/user_preferences.php', { lt.toast.success('Preferences saved successfully!');
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': window.CSRF_TOKEN
},
body: JSON.stringify({ preferences: prefs })
});
const result = await response.json();
if (!result.success) {
throw new Error('Failed to save preferences');
}
if (typeof toast !== 'undefined') {
toast.success('Preferences saved successfully!');
}
closeSettingsModal(); closeSettingsModal();
// Reload page to apply new preferences
setTimeout(() => window.location.reload(), 1000); setTimeout(() => window.location.reload(), 1000);
} catch (error) { } catch (error) {
if (typeof toast !== 'undefined') { lt.toast.error('Error saving preferences');
toast.error('Error saving preferences');
}
console.error('Error saving preferences:', error);
} }
} }
@@ -129,24 +104,18 @@ async function saveSettings() {
function openSettingsModal() { function openSettingsModal() {
const modal = document.getElementById('settingsModal'); const modal = document.getElementById('settingsModal');
if (modal) { if (modal) {
modal.style.display = 'flex'; lt.modal.open('settingsModal');
document.body.classList.add('modal-open');
loadUserPreferences(); loadUserPreferences();
} }
} }
function closeSettingsModal() { function closeSettingsModal() {
const modal = document.getElementById('settingsModal'); lt.modal.close('settingsModal');
if (modal) {
modal.style.display = 'none';
document.body.classList.remove('modal-open');
}
} }
// Close modal when clicking on backdrop (outside the settings content) // Close modal when clicking on backdrop (outside the settings content)
function closeOnBackdropClick(event) { function closeOnBackdropClick(event) {
const modal = document.getElementById('settingsModal'); const modal = document.getElementById('settingsModal');
// Only close if clicking directly on the modal backdrop, not on content
if (event.target === modal) { if (event.target === modal) {
closeSettingsModal(); closeSettingsModal();
} }
@@ -158,14 +127,7 @@ document.addEventListener('keydown', (e) => {
e.preventDefault(); e.preventDefault();
openSettingsModal(); openSettingsModal();
} }
// ESC is handled globally by lt.keys.initDefaults()
// ESC to close modal
if (e.key === 'Escape') {
const modal = document.getElementById('settingsModal');
if (modal && modal.style.display !== 'none' && modal.style.display !== '') {
closeSettingsModal();
}
}
}); });
// Initialize on page load // Initialize on page load

View File

@@ -24,7 +24,6 @@ function saveTicket() {
const ticketId = getTicketIdFromUrl(); const ticketId = getTicketIdFromUrl();
if (!ticketId) { if (!ticketId) {
console.error('Could not determine ticket ID');
return; return;
} }
@@ -66,7 +65,6 @@ function saveTicket() {
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
return response.text().then(text => { return response.text().then(text => {
console.error('Server response:', text);
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
}); });
} }
@@ -81,11 +79,9 @@ function saveTicket() {
} }
toast.success('Ticket updated successfully'); toast.success('Ticket updated successfully');
} else { } else {
console.error('Error in API response:', data.error || 'Unknown error');
} }
}) })
.catch(error => { .catch(error => {
console.error('Error updating ticket:', error);
}); });
} }
@@ -140,14 +136,12 @@ function toggleEditMode() {
function addComment() { function addComment() {
const commentText = document.getElementById('newComment').value; const commentText = document.getElementById('newComment').value;
if (!commentText.trim()) { if (!commentText.trim()) {
console.error('Comment text cannot be empty');
return; return;
} }
const ticketId = getTicketIdFromUrl(); const ticketId = getTicketIdFromUrl();
if (!ticketId) { if (!ticketId) {
console.error('Could not determine ticket ID');
return; return;
} }
@@ -169,7 +163,6 @@ function addComment() {
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
return response.text().then(text => { return response.text().then(text => {
console.error('Server response:', text);
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
}); });
} }
@@ -224,11 +217,9 @@ function addComment() {
commentsList.insertBefore(commentDiv, commentsList.firstChild); commentsList.insertBefore(commentDiv, commentsList.firstChild);
} else { } else {
console.error('Error adding comment:', data.error || 'Unknown error');
} }
}) })
.catch(error => { .catch(error => {
console.error('Error adding comment:', error);
}); });
} }
@@ -327,11 +318,9 @@ function handleAssignmentChange() {
.then(data => { .then(data => {
if (!data.success) { if (!data.success) {
toast.error('Error updating assignment'); toast.error('Error updating assignment');
console.error(data.error);
} }
}) })
.catch(error => { .catch(error => {
console.error('Error updating assignment:', error);
toast.error('Error updating assignment: ' + error.message); toast.error('Error updating assignment: ' + error.message);
}); });
}); });
@@ -365,7 +354,6 @@ function handleMetadataChanges() {
.then(data => { .then(data => {
if (!data.success) { if (!data.success) {
toast.error(`Error updating ${fieldName}`); toast.error(`Error updating ${fieldName}`);
console.error(data.error);
} else { } else {
// Update window.ticketData // Update window.ticketData
window.ticketData[fieldName] = fieldName === 'priority' ? parseInt(newValue) : newValue; window.ticketData[fieldName] = fieldName === 'priority' ? parseInt(newValue) : newValue;
@@ -387,7 +375,6 @@ function handleMetadataChanges() {
} }
}) })
.catch(error => { .catch(error => {
console.error(`Error updating ${fieldName}:`, error);
toast.error(`Error updating ${fieldName}: ` + error.message); toast.error(`Error updating ${fieldName}: ` + error.message);
}); });
} }
@@ -472,7 +459,6 @@ function performStatusChange(statusSelect, selectedOption, newStatus) {
const text = await response.text(); const text = await response.text();
if (!response.ok) { if (!response.ok) {
console.error('Server error response:', text);
try { try {
const data = JSON.parse(text); const data = JSON.parse(text);
throw new Error(data.error || 'Server returned an error'); throw new Error(data.error || 'Server returned an error');
@@ -484,7 +470,6 @@ function performStatusChange(statusSelect, selectedOption, newStatus) {
try { try {
return JSON.parse(text); return JSON.parse(text);
} catch (parseError) { } catch (parseError) {
console.error('Failed to parse JSON:', text);
throw new Error('Invalid JSON response from server'); throw new Error('Invalid JSON response from server');
} }
}) })
@@ -507,14 +492,12 @@ function performStatusChange(statusSelect, selectedOption, newStatus) {
window.location.reload(); window.location.reload();
}, 500); }, 500);
} else { } else {
console.error('Error updating status:', data.error || 'Unknown error');
toast.error('Error updating status: ' + (data.error || 'Unknown error')); toast.error('Error updating status: ' + (data.error || 'Unknown error'));
// Reset to current status // Reset to current status
statusSelect.selectedIndex = 0; statusSelect.selectedIndex = 0;
} }
}) })
.catch(error => { .catch(error => {
console.error('Error updating status:', error);
toast.error('Error updating status: ' + error.message); toast.error('Error updating status: ' + error.message);
// Reset to current status // Reset to current status
statusSelect.selectedIndex = 0; statusSelect.selectedIndex = 0;
@@ -530,7 +513,6 @@ function showTab(tabName) {
const activityTab = document.getElementById('activity-tab'); const activityTab = document.getElementById('activity-tab');
if (!descriptionTab || !commentsTab) { if (!descriptionTab || !commentsTab) {
console.error('Tab elements not found');
return; return;
} }
@@ -592,12 +574,10 @@ function loadDependencies() {
renderDependencies(data.dependencies); renderDependencies(data.dependencies);
renderDependents(data.dependents); renderDependents(data.dependents);
} else { } else {
console.error('Error loading dependencies:', data.error);
showDependencyError(data.error || 'Failed to load dependencies'); showDependencyError(data.error || 'Failed to load dependencies');
} }
}) })
.catch(error => { .catch(error => {
console.error('Error loading dependencies:', error);
showDependencyError('Failed to load dependencies. The feature may not be available.'); showDependencyError('Failed to load dependencies. The feature may not be available.');
}); });
} }
@@ -720,7 +700,6 @@ function addDependency() {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error adding dependency:', error);
toast.error('Error adding dependency', 4000); toast.error('Error adding dependency', 4000);
}); });
} }
@@ -751,7 +730,6 @@ function removeDependency(dependencyId) {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error removing dependency:', error);
toast.error('Error removing dependency', 4000); toast.error('Error removing dependency', 4000);
}); });
} }
@@ -910,7 +888,6 @@ function loadAttachments() {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error loading attachments:', error);
container.innerHTML = '<p style="color: var(--terminal-green-dim);">Error loading attachments.</p>'; container.innerHTML = '<p style="color: var(--terminal-green-dim);">Error loading attachments.</p>';
}); });
} }
@@ -998,7 +975,6 @@ function deleteAttachment(attachmentId) {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error deleting attachment:', error);
toast.error('Error deleting attachment', 4000); toast.error('Error deleting attachment', 4000);
}); });
} }
@@ -1042,18 +1018,13 @@ function initMentionAutocomplete() {
* Fetch available users for mentions * Fetch available users for mentions
*/ */
function fetchMentionUsers() { function fetchMentionUsers() {
fetch('/api/get_users.php', { lt.api.get('/api/get_users.php')
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => { .then(data => {
if (data.success && data.users) { if (data.success && data.users) {
mentionUsers = data.users; mentionUsers = data.users;
} }
}) })
.catch(error => { .catch(() => { /* silently ignore mention user fetch failures */ });
console.error('Error fetching users for mentions:', error);
});
} }
/** /**
@@ -1380,7 +1351,6 @@ function saveEditComment(commentId) {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error updating comment:', error);
showToast('Failed to update comment', 'error'); showToast('Failed to update comment', 'error');
}); });
} }
@@ -1434,7 +1404,6 @@ function deleteComment(commentId) {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error deleting comment:', error);
showToast('Failed to delete comment', 'error'); showToast('Failed to delete comment', 'error');
}); });
} }
@@ -1596,7 +1565,6 @@ function submitReply(parentCommentId) {
} }
}) })
.catch(error => { .catch(error => {
console.error('Error adding reply:', error);
showToast('Failed to add reply', 'error'); showToast('Failed to add reply', 'error');
}); });
} }

View File

@@ -1,94 +1,22 @@
/** /**
* Terminal-style toast notification system with queuing * Deprecated: use lt.toast.* directly (from web_template/base.js).
* This shim maintains backwards compatibility while callers are migrated.
*/ */
// Toast queue management // showToast() shim — used by inline view scripts
let toastQueue = []; function showToast(message, type = 'info', duration = 3500) {
let currentToast = null; switch (type) {
case 'success': lt.toast.success(message, duration); break;
function showToast(message, type = 'info', duration = 3000) { case 'error': lt.toast.error(message, duration); break;
// Queue if a toast is already showing case 'warning': lt.toast.warning(message, duration); break;
if (currentToast) { default: lt.toast.info(message, duration); break;
toastQueue.push({ message, type, duration });
return;
} }
displayToast(message, type, duration);
} }
function displayToast(message, type, duration) { // window.toast.* shim — used by JS files
// Create toast element
const toast = document.createElement('div');
toast.className = `terminal-toast toast-${type}`;
currentToast = toast;
// Icon based on type
const icons = {
success: '✓',
error: '✗',
info: '',
warning: '⚠'
};
const iconSpan = document.createElement('span');
iconSpan.className = 'toast-icon';
iconSpan.textContent = `[${icons[type] || ''}]`;
const msgSpan = document.createElement('span');
msgSpan.className = 'toast-message';
msgSpan.textContent = message;
const closeSpan = document.createElement('span');
closeSpan.className = 'toast-close';
closeSpan.style.cssText = 'margin-left: auto; cursor: pointer; opacity: 0.7; padding-left: 1rem;';
closeSpan.textContent = '[×]';
toast.appendChild(iconSpan);
toast.appendChild(msgSpan);
toast.appendChild(closeSpan);
// Add to document
document.body.appendChild(toast);
// Trigger animation
setTimeout(() => toast.classList.add('show'), 10);
// Manual dismiss handler
const closeBtn = toast.querySelector('.toast-close');
closeBtn.addEventListener('click', () => dismissToast(toast));
// Auto-remove after duration
const timeoutId = setTimeout(() => {
dismissToast(toast);
}, duration);
// Store timeout ID for manual dismiss
toast.timeoutId = timeoutId;
}
function dismissToast(toast) {
// Clear auto-dismiss timeout
if (toast.timeoutId) {
clearTimeout(toast.timeoutId);
}
toast.classList.remove('show');
setTimeout(() => {
toast.remove();
currentToast = null;
// Show next toast in queue
if (toastQueue.length > 0) {
const next = toastQueue.shift();
displayToast(next.message, next.type, next.duration);
}
}, 300);
}
// Convenience functions
window.toast = { window.toast = {
success: (msg, duration) => showToast(msg, 'success', duration), success: (msg, dur) => lt.toast.success(msg, dur),
error: (msg, duration) => showToast(msg, 'error', duration), error: (msg, dur) => lt.toast.error(msg, dur),
info: (msg, duration) => showToast(msg, 'info', duration), warning: (msg, dur) => lt.toast.warning(msg, dur),
warning: (msg, duration) => showToast(msg, 'warning', duration) info: (msg, dur) => lt.toast.info(msg, dur),
}; };

View File

@@ -1,8 +1,6 @@
// XSS prevention helper // XSS prevention helper — delegates to lt.escHtml() from web_template/base.js
function escapeHtml(text) { function escapeHtml(text) {
const div = document.createElement('div'); return lt.escHtml(text);
div.textContent = text;
return div.innerHTML;
} }
// Get ticket ID from URL (handles both /ticket/123 and ?id=123 formats) // Get ticket ID from URL (handles both /ticket/123 and ?id=123 formats)

View File

@@ -162,13 +162,5 @@ class Database {
return self::getConnection()->insert_id; return self::getConnection()->insert_id;
} }
/** // escape() removed — use prepared statements with bind_param() instead
* Escape a string for use in queries (prefer prepared statements)
*
* @param string $string String to escape
* @return string Escaped string
*/
public static function escape(string $string): string {
return self::getConnection()->real_escape_string($string);
}
} }

View File

@@ -42,8 +42,8 @@ if (!str_starts_with($requestPath, '/api/')) {
require_once 'models/UserPreferencesModel.php'; require_once 'models/UserPreferencesModel.php';
$prefsModel = new UserPreferencesModel($conn); $prefsModel = new UserPreferencesModel($conn);
$userTimezone = $prefsModel->getPreference($currentUser['user_id'], 'timezone', null); $userTimezone = $prefsModel->getPreference($currentUser['user_id'], 'timezone', null);
if ($userTimezone) { if ($userTimezone && in_array($userTimezone, DateTimeZone::listIdentifiers())) {
// Override system timezone with user preference // Override system timezone with user preference (validated against known identifiers)
date_default_timezone_set($userTimezone); date_default_timezone_set($userTimezone);
$GLOBALS['config']['TIMEZONE'] = $userTimezone; $GLOBALS['config']['TIMEZONE'] = $userTimezone;
$now = new DateTime('now', new DateTimeZone($userTimezone)); $now = new DateTime('now', new DateTimeZone($userTimezone));

View File

@@ -3,22 +3,11 @@
* AttachmentModel - Handles ticket file attachments * AttachmentModel - Handles ticket file attachments
*/ */
require_once __DIR__ . '/../config/config.php';
class AttachmentModel { class AttachmentModel {
private $conn; private $conn;
public function __construct() { public function __construct($conn) {
$this->conn = new mysqli( $this->conn = $conn;
$GLOBALS['config']['DB_HOST'],
$GLOBALS['config']['DB_USER'],
$GLOBALS['config']['DB_PASS'],
$GLOBALS['config']['DB_NAME']
);
if ($this->conn->connect_error) {
throw new Exception('Database connection failed: ' . $this->conn->connect_error);
}
} }
/** /**
@@ -204,9 +193,4 @@ class AttachmentModel {
return in_array($mimeType, $allowedTypes); return in_array($mimeType, $allowedTypes);
} }
public function __destruct() {
if ($this->conn) {
$this->conn->close();
}
}
} }

View File

@@ -19,6 +19,14 @@ class BulkOperationsModel {
* @return int|false Operation ID or false on failure * @return int|false Operation ID or false on failure
*/ */
public function createBulkOperation($type, $ticketIds, $userId, $parameters = null) { public function createBulkOperation($type, $ticketIds, $userId, $parameters = null) {
// Validate ticket IDs to prevent injection via implode
$ticketIds = array_values(array_filter(
array_map('strval', $ticketIds),
fn($id) => preg_match('/^[0-9]+$/', $id)
));
if (empty($ticketIds)) {
return false;
}
$ticketIdsStr = implode(',', $ticketIds); $ticketIdsStr = implode(',', $ticketIds);
$totalTickets = count($ticketIds); $totalTickets = count($ticketIds);
$parametersJson = $parameters ? json_encode($parameters) : null; $parametersJson = $parameters ? json_encode($parameters) : null;

View File

@@ -71,7 +71,7 @@ class CommentModel {
} }
$stmt = $this->conn->prepare($sql); $stmt = $this->conn->prepare($sql);
$stmt->bind_param("s", $ticketId); $stmt->bind_param("i", $ticketId);
$stmt->execute(); $stmt->execute();
$result = $stmt->get_result(); $result = $stmt->get_result();
@@ -126,7 +126,8 @@ class CommentModel {
private function buildCommentThread($comment, &$allComments) { private function buildCommentThread($comment, &$allComments) {
$comment['replies'] = []; $comment['replies'] = [];
foreach ($allComments as $c) { foreach ($allComments as $c) {
if ($c['parent_comment_id'] == $comment['comment_id']) { if ($c['parent_comment_id'] == $comment['comment_id']
&& isset($allComments[$c['comment_id']])) {
$comment['replies'][] = $this->buildCommentThread($c, $allComments); $comment['replies'][] = $this->buildCommentThread($c, $allComments);
} }
} }

View File

@@ -54,29 +54,36 @@ class SavedFiltersModel {
* Save a new filter * Save a new filter
*/ */
public function saveFilter($userId, $filterName, $filterCriteria, $isDefault = false) { public function saveFilter($userId, $filterName, $filterCriteria, $isDefault = false) {
// If this is set as default, unset all other defaults for this user $this->conn->begin_transaction();
if ($isDefault) { try {
$this->clearDefaultFilters($userId); // If this is set as default, unset all other defaults for this user
if ($isDefault) {
$this->clearDefaultFilters($userId);
}
$sql = "INSERT INTO saved_filters (user_id, filter_name, filter_criteria, is_default)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
filter_criteria = VALUES(filter_criteria),
is_default = VALUES(is_default),
updated_at = CURRENT_TIMESTAMP";
$stmt = $this->conn->prepare($sql);
$criteriaJson = json_encode($filterCriteria);
$stmt->bind_param("issi", $userId, $filterName, $criteriaJson, $isDefault);
if ($stmt->execute()) {
$filterId = $stmt->insert_id ?: $this->getFilterIdByName($userId, $filterName);
$this->conn->commit();
return ['success' => true, 'filter_id' => $filterId];
}
$error = $this->conn->error;
$this->conn->rollback();
return ['success' => false, 'error' => $error];
} catch (Exception $e) {
$this->conn->rollback();
return ['success' => false, 'error' => $e->getMessage()];
} }
$sql = "INSERT INTO saved_filters (user_id, filter_name, filter_criteria, is_default)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
filter_criteria = VALUES(filter_criteria),
is_default = VALUES(is_default),
updated_at = CURRENT_TIMESTAMP";
$stmt = $this->conn->prepare($sql);
$criteriaJson = json_encode($filterCriteria);
$stmt->bind_param("issi", $userId, $filterName, $criteriaJson, $isDefault);
if ($stmt->execute()) {
return [
'success' => true,
'filter_id' => $stmt->insert_id ?: $this->getFilterIdByName($userId, $filterName)
];
}
return ['success' => false, 'error' => $this->conn->error];
} }
/** /**
@@ -126,18 +133,25 @@ class SavedFiltersModel {
* Set a filter as default * Set a filter as default
*/ */
public function setDefaultFilter($filterId, $userId) { public function setDefaultFilter($filterId, $userId) {
// First, clear all defaults $this->conn->begin_transaction();
$this->clearDefaultFilters($userId); try {
$this->clearDefaultFilters($userId);
// Then set this one as default $sql = "UPDATE saved_filters SET is_default = 1 WHERE filter_id = ? AND user_id = ?";
$sql = "UPDATE saved_filters SET is_default = 1 WHERE filter_id = ? AND user_id = ?"; $stmt = $this->conn->prepare($sql);
$stmt = $this->conn->prepare($sql); $stmt->bind_param("ii", $filterId, $userId);
$stmt->bind_param("ii", $filterId, $userId);
if ($stmt->execute()) { if ($stmt->execute()) {
return ['success' => true]; $this->conn->commit();
return ['success' => true];
}
$error = $this->conn->error;
$this->conn->rollback();
return ['success' => false, 'error' => $error];
} catch (Exception $e) {
$this->conn->rollback();
return ['success' => false, 'error' => $e->getMessage()];
} }
return ['success' => false, 'error' => $this->conn->error];
} }
/** /**

View File

@@ -134,7 +134,7 @@ class StatsModel {
u.username, u.username,
COUNT(t.ticket_id) as ticket_count COUNT(t.ticket_id) as ticket_count
FROM tickets t FROM tickets t
JOIN users u ON t.assigned_to = u.user_id LEFT JOIN users u ON t.assigned_to = u.user_id
WHERE t.status != 'Closed' WHERE t.status != 'Closed'
GROUP BY t.assigned_to GROUP BY t.assigned_to
ORDER BY ticket_count DESC ORDER BY ticket_count DESC

View File

@@ -422,6 +422,34 @@ class TicketModel {
'ticket_id' => $ticket_id 'ticket_id' => $ticket_id
]; ];
} else { } else {
// Handle duplicate key (errno 1062) caused by race condition between
// the uniqueness SELECT above and this INSERT — regenerate and retry once
if ($this->conn->errno === 1062) {
$stmt->close();
try {
$ticket_id = sprintf('%09d', random_int(100000000, 999999999));
} catch (Exception $e) {
$ticket_id = sprintf('%09d', mt_rand(100000000, 999999999));
}
$stmt = $this->conn->prepare($sql);
$stmt->bind_param(
"sssssssiiss",
$ticket_id,
$ticketData['title'],
$ticketData['description'],
$status,
$priority,
$category,
$type,
$createdBy,
$assignedTo,
$visibility,
$visibilityGroups
);
if ($stmt->execute()) {
return ['success' => true, 'ticket_id' => $ticket_id];
}
}
return [ return [
'success' => false, 'success' => false,
'error' => $this->conn->error 'error' => $this->conn->error

View File

@@ -27,6 +27,10 @@ class WorkflowModel {
WHERE is_active = TRUE"; WHERE is_active = TRUE";
$result = $this->conn->query($sql); $result = $this->conn->query($sql);
if (!$result) {
return [];
}
$transitions = []; $transitions = [];
while ($row = $result->fetch_assoc()) { while ($row = $result->fetch_assoc()) {
$from = $row['from_status']; $from = $row['from_status'];
@@ -102,6 +106,10 @@ class WorkflowModel {
ORDER BY status"; ORDER BY status";
$result = $this->conn->query($sql); $result = $this->conn->query($sql);
if (!$result) {
return [];
}
$statuses = []; $statuses = [];
while ($row = $result->fetch_assoc()) { while ($row = $result->fetch_assoc()) {
$statuses[] = $row['status']; $statuses[] = $row['status'];

View File

@@ -11,8 +11,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create New Ticket</title> <title>Create New Ticket</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css?v=20260126c"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css?v=20260126c">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css?v=20260124e"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css?v=20260124e">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/utils.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/utils.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/dashboard.js?v=20260205"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/dashboard.js?v=20260205"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
@@ -61,7 +63,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<div class="ascii-content"> <div class="ascii-content">
<div class="ascii-frame-inner"> <div class="ascii-frame-inner">
<div class="error-message" style="color: var(--priority-1); border: 2px solid var(--priority-1); padding: 1rem; background: rgba(231, 76, 60, 0.1);"> <div class="error-message" style="color: var(--priority-1); border: 2px solid var(--priority-1); padding: 1rem; background: rgba(231, 76, 60, 0.1);">
<strong>⚠ Error:</strong> <?php echo $error; ?> <strong>⚠ Error:</strong> <?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -12,7 +12,9 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ticket Dashboard</title> <title>Ticket Dashboard</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css?v=20260131e"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css?v=20260131e">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/ascii-banner.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/ascii-banner.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/toast.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/toast.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/utils.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/utils.js"></script>
@@ -22,12 +24,12 @@ $nonce = SecurityHeadersMiddleware::getNonce();
// CSRF Token for AJAX requests // CSRF Token for AJAX requests
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';
// Timezone configuration (from server) // Timezone configuration (from server)
window.APP_TIMEZONE = '<?php echo $GLOBALS['config']['TIMEZONE']; ?>'; window.APP_TIMEZONE = '<?php echo htmlspecialchars($GLOBALS['config']['TIMEZONE'] ?? 'UTC', ENT_QUOTES, 'UTF-8'); ?>';
window.APP_TIMEZONE_OFFSET = <?php echo $GLOBALS['config']['TIMEZONE_OFFSET']; ?>; // minutes from UTC window.APP_TIMEZONE_OFFSET = <?php echo (int)($GLOBALS['config']['TIMEZONE_OFFSET'] ?? 0); ?>; // minutes from UTC
window.APP_TIMEZONE_ABBREV = '<?php echo $GLOBALS['config']['TIMEZONE_ABBREV']; ?>'; window.APP_TIMEZONE_ABBREV = '<?php echo htmlspecialchars($GLOBALS['config']['TIMEZONE_ABBREV'] ?? 'UTC', ENT_QUOTES, 'UTF-8'); ?>';
</script> </script>
</head> </head>
<body data-categories='<?php echo json_encode($categories); ?>' data-types='<?php echo json_encode($types); ?>'> <body data-categories='<?php echo htmlspecialchars(json_encode($categories), ENT_QUOTES, 'UTF-8'); ?>' data-types='<?php echo htmlspecialchars(json_encode($types), ENT_QUOTES, 'UTF-8'); ?>'>
<!-- Terminal Boot Sequence --> <!-- Terminal Boot Sequence -->
<div id="boot-sequence" class="boot-overlay"> <div id="boot-sequence" class="boot-overlay">
@@ -573,17 +575,14 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</section> </section>
<!-- Settings Modal --> <!-- Settings Modal -->
<div class="settings-modal" id="settingsModal" style="display: none;" data-action="close-settings-backdrop" role="dialog" aria-modal="true" aria-labelledby="settingsModalTitle"> <div class="lt-modal-overlay" id="settingsModal" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="settingsModalTitle">
<div class="settings-content"> <div class="lt-modal">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title" id="settingsModalTitle">⚙ System Preferences</span>
<button class="lt-modal-close" data-modal-close aria-label="Close settings">✕</button>
<div class="settings-header">
<h3 id="settingsModalTitle">⚙ System Preferences</h3>
<button class="close-settings" data-action="close-settings" aria-label="Close settings">✗</button>
</div> </div>
<div class="settings-body"> <div class="lt-modal-body">
<!-- Display Preferences --> <!-- Display Preferences -->
<div class="settings-section"> <div class="settings-section">
<h4>╔══ Display Preferences ══╗</h4> <h4>╔══ Display Preferences ══╗</h4>
@@ -724,23 +723,23 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button class="btn btn-primary" data-action="save-settings">Save Preferences</button> <button class="lt-btn lt-btn-primary" data-action="save-settings">Save Preferences</button>
<button class="btn btn-secondary" data-action="close-settings">Cancel</button> <button class="lt-btn lt-btn-ghost" data-action="close-settings">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
<!-- Advanced Search Modal --> <!-- Advanced Search Modal -->
<div class="settings-modal" id="advancedSearchModal" style="display: none;" data-action="close-advanced-search-backdrop" role="dialog" aria-modal="true" aria-labelledby="advancedSearchModalTitle"> <div class="lt-modal-overlay" id="advancedSearchModal" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="advancedSearchModalTitle">
<div class="settings-content"> <div class="lt-modal">
<div class="settings-header"> <div class="lt-modal-header">
<h3 id="advancedSearchModalTitle">🔍 Advanced Search</h3> <span class="lt-modal-title" id="advancedSearchModalTitle">🔍 Advanced Search</span>
<button class="close-settings" data-action="close-advanced-search" aria-label="Close advanced search"></button> <button class="lt-modal-close" data-modal-close aria-label="Close advanced search"></button>
</div> </div>
<form id="advancedSearchForm"> <form id="advancedSearchForm">
<div class="settings-body"> <div class="lt-modal-body">
<!-- Saved Filters --> <!-- Saved Filters -->
<div class="settings-section"> <div class="settings-section">
<h4>╔══ Saved Filters ══╗</h4> <h4>╔══ Saved Filters ══╗</h4>
@@ -841,10 +840,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button type="submit" class="btn btn-primary">Search</button> <button type="submit" class="lt-btn lt-btn-primary">Search</button>
<button type="button" class="btn btn-secondary" data-action="reset-advanced-search">Reset</button> <button type="button" class="lt-btn lt-btn-ghost" data-action="reset-advanced-search">Reset</button>
<button type="button" class="btn btn-secondary" data-action="close-advanced-search">Cancel</button> <button type="button" class="lt-btn lt-btn-ghost" data-action="close-advanced-search">Cancel</button>
</div> </div>
</form> </form>
</div> </div>
@@ -854,6 +853,8 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/keyboard-shortcuts.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/keyboard-shortcuts.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/advanced-search.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/advanced-search.js"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
// Initialize lt keyboard defaults (ESC closes modals, Ctrl+K focuses search, ? shows help)
lt.keys.initDefaults();
// Event delegation for all data-action handlers // Event delegation for all data-action handlers
document.addEventListener('click', function(event) { document.addEventListener('click', function(event) {
const target = event.target.closest('[data-action]'); const target = event.target.closest('[data-action]');
@@ -882,10 +883,6 @@ $nonce = SecurityHeadersMiddleware::getNonce();
closeSettingsModal(); closeSettingsModal();
break; break;
case 'close-settings-backdrop':
if (event.target === target) closeSettingsModal();
break;
case 'save-settings': case 'save-settings':
saveSettings(); saveSettings();
break; break;
@@ -906,10 +903,6 @@ $nonce = SecurityHeadersMiddleware::getNonce();
closeAdvancedSearch(); closeAdvancedSearch();
break; break;
case 'close-advanced-search-backdrop':
if (event.target === target) closeAdvancedSearch();
break;
case 'reset-advanced-search': case 'reset-advanced-search':
resetAdvancedSearch(); resetAdvancedSearch();
break; break;

View File

@@ -50,8 +50,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ticket #<?php echo $ticket['ticket_id']; ?></title> <title>Ticket #<?php echo $ticket['ticket_id']; ?></title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css?v=20260131e"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css?v=20260131e">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css?v=20260131e"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css?v=20260131e">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/toast.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/toast.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/utils.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/utils.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/markdown.js?v=20260131e"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/markdown.js?v=20260131e"></script>
@@ -61,9 +63,9 @@ $nonce = SecurityHeadersMiddleware::getNonce();
// CSRF Token for AJAX requests // CSRF Token for AJAX requests
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';
// Timezone configuration (from server) // Timezone configuration (from server)
window.APP_TIMEZONE = '<?php echo $GLOBALS['config']['TIMEZONE']; ?>'; window.APP_TIMEZONE = '<?php echo htmlspecialchars($GLOBALS['config']['TIMEZONE'] ?? 'UTC', ENT_QUOTES, 'UTF-8'); ?>';
window.APP_TIMEZONE_OFFSET = <?php echo $GLOBALS['config']['TIMEZONE_OFFSET']; ?>; // minutes from UTC window.APP_TIMEZONE_OFFSET = <?php echo (int)($GLOBALS['config']['TIMEZONE_OFFSET'] ?? 0); ?>; // minutes from UTC
window.APP_TIMEZONE_ABBREV = '<?php echo $GLOBALS['config']['TIMEZONE_ABBREV']; ?>'; window.APP_TIMEZONE_ABBREV = '<?php echo htmlspecialchars($GLOBALS['config']['TIMEZONE_ABBREV'] ?? 'UTC', ENT_QUOTES, 'UTF-8'); ?>';
</script> </script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
// Store ticket data in a global variable (using json_encode for XSS safety) // Store ticket data in a global variable (using json_encode for XSS safety)
@@ -653,15 +655,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
}); });
} }
// Settings modal backdrop click // Settings modal backdrop click (lt-modal-overlay handles this via data-modal-close)
var settingsModal = document.getElementById('settingsModal');
if (settingsModal) {
settingsModal.addEventListener('click', function(e) {
if (e.target.classList.contains('settings-modal')) {
if (typeof closeSettingsModal === 'function') closeSettingsModal();
}
});
}
// Handle change events for data-action // Handle change events for data-action
document.addEventListener('change', function(e) { document.addEventListener('change', function(e) {
@@ -688,17 +682,14 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</script> </script>
<!-- Settings Modal (same as dashboard) --> <!-- Settings Modal (same as dashboard) -->
<div class="settings-modal" id="settingsModal" style="display: none;" role="dialog" aria-modal="true" aria-labelledby="ticketSettingsTitle"> <div class="lt-modal-overlay" id="settingsModal" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="ticketSettingsTitle">
<div class="settings-content"> <div class="lt-modal">
<span class="bottom-left-corner">╚</span> <div class="lt-modal-header">
<span class="bottom-right-corner">╝</span> <span class="lt-modal-title" id="ticketSettingsTitle">⚙ System Preferences</span>
<button class="lt-modal-close" data-modal-close aria-label="Close settings">✕</button>
<div class="settings-header">
<h3 id="ticketSettingsTitle">⚙ System Preferences</h3>
<button class="close-settings" id="closeSettingsBtn" aria-label="Close settings">✗</button>
</div> </div>
<div class="settings-body"> <div class="lt-modal-body">
<!-- Display Preferences --> <!-- Display Preferences -->
<div class="settings-section"> <div class="settings-section">
<h4>╔══ Display Preferences ══╗</h4> <h4>╔══ Display Preferences ══╗</h4>
@@ -816,13 +807,15 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button class="btn btn-primary" id="saveSettingsBtn">Save Preferences</button> <button class="lt-btn lt-btn-primary" id="saveSettingsBtn">Save Preferences</button>
<button class="btn btn-secondary" id="cancelSettingsBtn">Cancel</button> <button class="lt-btn lt-btn-ghost" id="cancelSettingsBtn">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/keyboard-shortcuts.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/settings.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/settings.js"></script>
<script nonce="<?php echo $nonce; ?>">lt.keys.initDefaults();</script>
</body> </body>
</html> </html>

View File

@@ -12,8 +12,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Keys - Admin</title> <title>API Keys - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/toast.js"></script> <script nonce="<?php echo $nonce; ?>" src="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/js/toast.js"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';

View File

@@ -9,8 +9,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audit Log - Admin</title> <title>Audit Log - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script src="/web_template/base.js"></script>
</head> </head>
<body> <body>
<div class="user-header"> <div class="user-header">

View File

@@ -12,8 +12,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Fields - Admin</title> <title>Custom Fields - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';
</script> </script>
@@ -92,15 +94,15 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
<!-- Create/Edit Modal --> <!-- Create/Edit Modal -->
<div class="settings-modal" id="fieldModal" style="display: none;" data-action="close-modal-backdrop"> <div class="lt-modal-overlay" id="fieldModal" aria-hidden="true">
<div class="settings-content" style="max-width: 500px;"> <div class="lt-modal" style="max-width: 500px;">
<div class="settings-header"> <div class="lt-modal-header">
<h3 id="modalTitle">Create Custom Field</h3> <span class="lt-modal-title" id="modalTitle">Create Custom Field</span>
<button class="close-settings" data-action="close-modal">×</button> <button class="lt-modal-close" data-modal-close>✕</button>
</div> </div>
<form id="fieldForm"> <form id="fieldForm">
<input type="hidden" id="field_id" name="field_id"> <input type="hidden" id="field_id" name="field_id">
<div class="settings-body"> <div class="lt-modal-body">
<div class="setting-row"> <div class="setting-row">
<label for="field_name">Field Name * (internal)</label> <label for="field_name">Field Name * (internal)</label>
<input type="text" id="field_name" name="field_name" required pattern="[a-z_]+" placeholder="e.g., server_name"> <input type="text" id="field_name" name="field_name" required pattern="[a-z_]+" placeholder="e.g., server_name">
@@ -146,9 +148,9 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<label><input type="checkbox" id="is_active" name="is_active" checked> Active</label> <label><input type="checkbox" id="is_active" name="is_active" checked> Active</label>
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button type="submit" class="btn btn-primary">Save</button> <button type="submit" class="lt-btn lt-btn-primary">Save</button>
<button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button> <button type="button" class="lt-btn lt-btn-ghost" data-modal-close>Cancel</button>
</div> </div>
</form> </form>
</div> </div>
@@ -162,11 +164,11 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('field_id').value = ''; document.getElementById('field_id').value = '';
document.getElementById('is_active').checked = true; document.getElementById('is_active').checked = true;
toggleOptionsField(); toggleOptionsField();
document.getElementById('fieldModal').style.display = 'flex'; lt.modal.open('fieldModal');
} }
function closeModal() { function closeModal() {
document.getElementById('fieldModal').style.display = 'none'; lt.modal.close('fieldModal');
} }
// Event delegation for data-action handlers // Event delegation for data-action handlers
@@ -179,12 +181,6 @@ $nonce = SecurityHeadersMiddleware::getNonce();
case 'show-create-modal': case 'show-create-modal':
showCreateModal(); showCreateModal();
break; break;
case 'close-modal':
closeModal();
break;
case 'close-modal-backdrop':
if (event.target === target) closeModal();
break;
case 'edit-field': case 'edit-field':
editField(target.dataset.id); editField(target.dataset.id);
break; break;
@@ -208,12 +204,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
saveField(e); saveField(e);
}); });
// Close modal on ESC key lt.keys.initDefaults();
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeModal();
}
});
function toggleOptionsField() { function toggleOptionsField() {
const type = document.getElementById('field_type').value; const type = document.getElementById('field_type').value;
@@ -255,7 +246,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
if (result.success) { if (result.success) {
window.location.reload(); window.location.reload();
} else { } else {
toast.error(result.error || 'Failed to save'); lt.toast.error(result.error || 'Failed to save');
} }
}); });
} }
@@ -279,7 +270,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('field_options').value = f.field_options.options.join('\n'); document.getElementById('field_options').value = f.field_options.options.join('\n');
} }
document.getElementById('modalTitle').textContent = 'Edit Custom Field'; document.getElementById('modalTitle').textContent = 'Edit Custom Field';
document.getElementById('fieldModal').style.display = 'flex'; lt.modal.open('fieldModal');
} }
}); });
} }

View File

@@ -12,8 +12,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recurring Tickets - Admin</title> <title>Recurring Tickets - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';
</script> </script>
@@ -107,15 +109,15 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
<!-- Create/Edit Modal --> <!-- Create/Edit Modal -->
<div class="settings-modal" id="recurringModal" style="display: none;" data-action="close-modal-backdrop"> <div class="lt-modal-overlay" id="recurringModal" aria-hidden="true">
<div class="settings-content" style="max-width: 800px; width: 90%;"> <div class="lt-modal" style="max-width: 800px; width: 90%;">
<div class="settings-header"> <div class="lt-modal-header">
<h3 id="modalTitle">Create Recurring Ticket</h3> <span class="lt-modal-title" id="modalTitle">Create Recurring Ticket</span>
<button class="close-settings" data-action="close-modal">×</button> <button class="lt-modal-close" data-modal-close>✕</button>
</div> </div>
<form id="recurringForm"> <form id="recurringForm">
<input type="hidden" id="recurring_id" name="recurring_id"> <input type="hidden" id="recurring_id" name="recurring_id">
<div class="settings-body"> <div class="lt-modal-body">
<div class="setting-row"> <div class="setting-row">
<label for="title_template">Title Template *</label> <label for="title_template">Title Template *</label>
<input type="text" id="title_template" name="title_template" required style="width: 100%;" placeholder="Use {{date}}, {{month}}, etc."> <input type="text" id="title_template" name="title_template" required style="width: 100%;" placeholder="Use {{date}}, {{month}}, etc.">
@@ -181,9 +183,9 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button type="submit" class="btn btn-primary">Save</button> <button type="submit" class="lt-btn lt-btn-primary">Save</button>
<button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button> <button type="button" class="lt-btn lt-btn-ghost" data-modal-close>Cancel</button>
</div> </div>
</form> </form>
</div> </div>
@@ -196,11 +198,11 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('recurringForm').reset(); document.getElementById('recurringForm').reset();
document.getElementById('recurring_id').value = ''; document.getElementById('recurring_id').value = '';
updateScheduleOptions(); updateScheduleOptions();
document.getElementById('recurringModal').style.display = 'flex'; lt.modal.open('recurringModal');
} }
function closeModal() { function closeModal() {
document.getElementById('recurringModal').style.display = 'none'; lt.modal.close('recurringModal');
} }
// Event delegation for data-action handlers // Event delegation for data-action handlers
@@ -213,12 +215,6 @@ $nonce = SecurityHeadersMiddleware::getNonce();
case 'show-create-modal': case 'show-create-modal':
showCreateModal(); showCreateModal();
break; break;
case 'close-modal':
closeModal();
break;
case 'close-modal-backdrop':
if (event.target === target) closeModal();
break;
case 'edit-recurring': case 'edit-recurring':
editRecurring(target.dataset.id); editRecurring(target.dataset.id);
break; break;
@@ -245,12 +241,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
saveRecurring(e); saveRecurring(e);
}); });
// Close modal on ESC key lt.keys.initDefaults();
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeModal();
}
});
function updateScheduleOptions() { function updateScheduleOptions() {
const type = document.getElementById('schedule_type').value; const type = document.getElementById('schedule_type').value;
@@ -296,7 +287,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
if (data.success) { if (data.success) {
window.location.reload(); window.location.reload();
} else { } else {
toast.error(data.error || 'Failed to save'); lt.toast.error(data.error || 'Failed to save');
} }
}); });
} }
@@ -342,7 +333,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('priority').value = rt.priority || 4; document.getElementById('priority').value = rt.priority || 4;
document.getElementById('assigned_to').value = rt.assigned_to || ''; document.getElementById('assigned_to').value = rt.assigned_to || '';
document.getElementById('modalTitle').textContent = 'Edit Recurring Ticket'; document.getElementById('modalTitle').textContent = 'Edit Recurring Ticket';
document.getElementById('recurringModal').style.display = 'flex'; lt.modal.open('recurringModal');
} }
}); });
} }

View File

@@ -12,8 +12,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Template Management - Admin</title> <title>Template Management - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';
</script> </script>
@@ -92,15 +94,15 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
<!-- Create/Edit Modal --> <!-- Create/Edit Modal -->
<div class="settings-modal" id="templateModal" style="display: none;" data-action="close-modal-backdrop"> <div class="lt-modal-overlay" id="templateModal" aria-hidden="true">
<div class="settings-content" style="max-width: 800px; width: 90%;"> <div class="lt-modal" style="max-width: 800px; width: 90%;">
<div class="settings-header"> <div class="lt-modal-header">
<h3 id="modalTitle">Create Template</h3> <span class="lt-modal-title" id="modalTitle">Create Template</span>
<button class="close-settings" data-action="close-modal">×</button> <button class="lt-modal-close" data-modal-close>✕</button>
</div> </div>
<form id="templateForm"> <form id="templateForm">
<input type="hidden" id="template_id" name="template_id"> <input type="hidden" id="template_id" name="template_id">
<div class="settings-body"> <div class="lt-modal-body">
<div class="setting-row"> <div class="setting-row">
<label for="template_name">Template Name *</label> <label for="template_name">Template Name *</label>
<input type="text" id="template_name" name="template_name" required style="width: 100%;"> <input type="text" id="template_name" name="template_name" required style="width: 100%;">
@@ -152,9 +154,9 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<label><input type="checkbox" id="is_active" name="is_active" checked> Active</label> <label><input type="checkbox" id="is_active" name="is_active" checked> Active</label>
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button type="submit" class="btn btn-primary">Save</button> <button type="submit" class="lt-btn lt-btn-primary">Save</button>
<button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button> <button type="button" class="lt-btn lt-btn-ghost" data-modal-close>Cancel</button>
</div> </div>
</form> </form>
</div> </div>
@@ -169,11 +171,11 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('templateForm').reset(); document.getElementById('templateForm').reset();
document.getElementById('template_id').value = ''; document.getElementById('template_id').value = '';
document.getElementById('is_active').checked = true; document.getElementById('is_active').checked = true;
document.getElementById('templateModal').style.display = 'flex'; lt.modal.open('templateModal');
} }
function closeModal() { function closeModal() {
document.getElementById('templateModal').style.display = 'none'; lt.modal.close('templateModal');
} }
// Event delegation for data-action handlers // Event delegation for data-action handlers
@@ -186,12 +188,6 @@ $nonce = SecurityHeadersMiddleware::getNonce();
case 'show-create-modal': case 'show-create-modal':
showCreateModal(); showCreateModal();
break; break;
case 'close-modal':
closeModal();
break;
case 'close-modal-backdrop':
if (event.target === target) closeModal();
break;
case 'edit-template': case 'edit-template':
editTemplate(target.dataset.id); editTemplate(target.dataset.id);
break; break;
@@ -206,12 +202,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
saveTemplate(e); saveTemplate(e);
}); });
// Close modal on ESC key lt.keys.initDefaults();
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeModal();
}
});
function saveTemplate(e) { function saveTemplate(e) {
e.preventDefault(); e.preventDefault();
@@ -242,7 +233,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
if (result.success) { if (result.success) {
window.location.reload(); window.location.reload();
} else { } else {
toast.error(result.error || 'Failed to save'); lt.toast.error(result.error || 'Failed to save');
} }
}); });
} }
@@ -260,7 +251,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('priority').value = tpl.default_priority || 4; document.getElementById('priority').value = tpl.default_priority || 4;
document.getElementById('is_active').checked = (tpl.is_active ?? 1) == 1; document.getElementById('is_active').checked = (tpl.is_active ?? 1) == 1;
document.getElementById('modalTitle').textContent = 'Edit Template'; document.getElementById('modalTitle').textContent = 'Edit Template';
document.getElementById('templateModal').style.display = 'flex'; lt.modal.open('templateModal');
} }
function deleteTemplate(id) { function deleteTemplate(id) {

View File

@@ -9,8 +9,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Activity - Admin</title> <title>User Activity - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script src="/web_template/base.js"></script>
</head> </head>
<body> <body>
<div class="user-header"> <div class="user-header">

View File

@@ -12,8 +12,10 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Workflow Designer - Admin</title> <title>Workflow Designer - Admin</title>
<link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png"> <link rel="icon" type="image/png" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/images/favicon.png">
<link rel="stylesheet" href="/web_template/base.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/dashboard.css">
<link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css"> <link rel="stylesheet" href="<?php echo $GLOBALS['config']['ASSETS_URL']; ?>/css/ticket.css">
<script nonce="<?php echo $nonce; ?>" src="/web_template/base.js"></script>
<script nonce="<?php echo $nonce; ?>"> <script nonce="<?php echo $nonce; ?>">
window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>'; window.CSRF_TOKEN = '<?php echo CsrfMiddleware::getToken(); ?>';
</script> </script>
@@ -132,15 +134,15 @@ $nonce = SecurityHeadersMiddleware::getNonce();
</div> </div>
<!-- Create/Edit Modal --> <!-- Create/Edit Modal -->
<div class="settings-modal" id="workflowModal" style="display: none;" data-action="close-modal-backdrop"> <div class="lt-modal-overlay" id="workflowModal" aria-hidden="true">
<div class="settings-content" style="max-width: 450px;"> <div class="lt-modal" style="max-width: 450px;">
<div class="settings-header"> <div class="lt-modal-header">
<h3 id="modalTitle">Create Transition</h3> <span class="lt-modal-title" id="modalTitle">Create Transition</span>
<button class="close-settings" data-action="close-modal">×</button> <button class="lt-modal-close" data-modal-close>✕</button>
</div> </div>
<form id="workflowForm"> <form id="workflowForm">
<input type="hidden" id="transition_id" name="transition_id"> <input type="hidden" id="transition_id" name="transition_id">
<div class="settings-body"> <div class="lt-modal-body">
<div class="setting-row"> <div class="setting-row">
<label for="from_status">From Status *</label> <label for="from_status">From Status *</label>
<select id="from_status" name="from_status" required> <select id="from_status" name="from_status" required>
@@ -169,9 +171,9 @@ $nonce = SecurityHeadersMiddleware::getNonce();
<label><input type="checkbox" id="is_active" name="is_active" checked> Active</label> <label><input type="checkbox" id="is_active" name="is_active" checked> Active</label>
</div> </div>
</div> </div>
<div class="settings-footer"> <div class="lt-modal-footer">
<button type="submit" class="btn btn-primary">Save</button> <button type="submit" class="lt-btn lt-btn-primary">Save</button>
<button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button> <button type="button" class="lt-btn lt-btn-ghost" data-modal-close>Cancel</button>
</div> </div>
</form> </form>
</div> </div>
@@ -186,11 +188,11 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('workflowForm').reset(); document.getElementById('workflowForm').reset();
document.getElementById('transition_id').value = ''; document.getElementById('transition_id').value = '';
document.getElementById('is_active').checked = true; document.getElementById('is_active').checked = true;
document.getElementById('workflowModal').style.display = 'flex'; lt.modal.open('workflowModal');
} }
function closeModal() { function closeModal() {
document.getElementById('workflowModal').style.display = 'none'; lt.modal.close('workflowModal');
} }
// Event delegation for data-action handlers // Event delegation for data-action handlers
@@ -203,12 +205,6 @@ $nonce = SecurityHeadersMiddleware::getNonce();
case 'show-create-modal': case 'show-create-modal':
showCreateModal(); showCreateModal();
break; break;
case 'close-modal':
closeModal();
break;
case 'close-modal-backdrop':
if (event.target === target) closeModal();
break;
case 'edit-transition': case 'edit-transition':
editTransition(target.dataset.id); editTransition(target.dataset.id);
break; break;
@@ -223,12 +219,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
saveTransition(e); saveTransition(e);
}); });
// Close modal on ESC key lt.keys.initDefaults();
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeModal();
}
});
function saveTransition(e) { function saveTransition(e) {
e.preventDefault(); e.preventDefault();
@@ -257,7 +248,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
if (result.success) { if (result.success) {
window.location.reload(); window.location.reload();
} else { } else {
toast.error(result.error || 'Failed to save'); lt.toast.error(result.error || 'Failed to save');
} }
}); });
} }
@@ -273,7 +264,7 @@ $nonce = SecurityHeadersMiddleware::getNonce();
document.getElementById('requires_admin').checked = wf.requires_admin == 1; document.getElementById('requires_admin').checked = wf.requires_admin == 1;
document.getElementById('is_active').checked = wf.is_active == 1; document.getElementById('is_active').checked = wf.is_active == 1;
document.getElementById('modalTitle').textContent = 'Edit Transition'; document.getElementById('modalTitle').textContent = 'Edit Transition';
document.getElementById('workflowModal').style.display = 'flex'; lt.modal.open('workflowModal');
} }
function deleteTransition(id) { function deleteTransition(id) {