Files
Ticketsystem/public/ticketview/ticket-user.js
T
2026-02-26 16:29:28 +01:00

210 lines
7.8 KiB
JavaScript

import {
fetchTicket, fetchComments, fetchHistory,
createComment,
formatDateTime, formatMinutes, getHistoryIcon
} from './ticket-shared.js';
document.addEventListener('DOMContentLoaded', () => {
document.body.classList.add('user-view');
const ticketId = new URLSearchParams(window.location.search).get('id');
if (!ticketId) return window.location.href = '/';
// DOM elements
const ticketTitle = document.getElementById('ticket-title-text');
const ticketIdElem = document.getElementById('ticket-id-val');
const ticketStatus = document.getElementById('ticket-status-badge');
const ticketPriority = document.getElementById('priority-text');
const ticketDescription = document.getElementById('ticket-description-text');
const ticketRequester = document.getElementById('ticket-requester');
const ticketCreated = document.getElementById('ticket-created');
const ticketUpdated = document.getElementById('ticket-updated');
const ticketCategory = document.getElementById('ticket-category');
const commentsContainer = document.getElementById('comments-container');
const historyContainer = document.getElementById('history-container');
const commentForm = document.getElementById('comment-form');
const tabBtns = document.querySelectorAll('.tab-btn');
const totalTimeDisplay = document.getElementById('total-time');
let webhookConfig = null;
// Fetch Webhook Configuration
async function loadWebhookConfig() {
try {
const response = await fetch('/api/webhooks');
if (response.ok) {
webhookConfig = await response.json();
console.log('Webhook configuration loaded:', webhookConfig.configured);
} else {
console.warn('Failed to load webhook configuration');
webhookConfig = { admin: null, user: null, configured: { admin: false, user: false } };
}
} catch (error) {
console.error('Error loading webhook configuration:', error);
webhookConfig = { admin: null, user: null, configured: { admin: false, user: false } };
}
}
// Send Webhook Notification
async function sendAdminWebhook(message) {
if (!webhookConfig?.admin) {
console.log('Admin webhook not configured, skipping notification');
return;
}
try {
const res = await fetch(webhookConfig.admin, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: message })
});
if (!res.ok) {
console.error('Admin webhook failed:', res.statusText);
}
} catch (err) {
console.error('Error sending admin webhook:', err);
}
}
// Links automatically convert to clickable
function linkify(text) {
const urlPattern = /(\bhttps?:\/\/[^\s<]+)/g;
return text.replace(urlPattern, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
}
let originalStatus = '';
let originalPriority = '';
async function loadTicketDetails() {
const ticket = await fetchTicket(ticketId);
if (!ticket) return alert('Ticket not found');
ticketTitle.textContent = ticket.title;
ticketIdElem.textContent = ticket.id;
ticketStatus.textContent = ticket.status;
ticketDescription.innerHTML = linkify(ticket.description || '');
ticketRequester.textContent = ticket.requester;
ticketCreated.textContent = formatDateTime(ticket.created_at);
ticketUpdated.textContent = formatDateTime(ticket.updated_at);
ticketPriority.textContent = ticket.priority;
if (ticketCategory) {
ticketCategory.textContent = ticket.category || '—';
}
ticketStatus.className = `ticket-status status-${ticket.status.replace(/ /g, '-')}`;
const totalTimeDisplay = document.getElementById('total-time');
if (totalTimeDisplay) {
totalTimeDisplay.textContent = formatMinutes(ticket.total_time || 0);
}
originalStatus = ticket.status;
originalPriority = ticket.priority;
}
async function loadComments() {
const comments = await fetchComments(ticketId);
commentsContainer.innerHTML = comments.map(comment => {
const role = comment.role ? comment.role.toLowerCase() : 'user';
let avatarUrl = '/assets/user.jpg';
if (role === 'admin') avatarUrl = '/assets/admin.jpg';
else if (role === 'moderator') avatarUrl = '/assets/moderator.jpg';
// Comment content is linkified
const linkedContent = linkify(comment.content || '');
return `
<div class="comment">
<img class="comment-avatar" src="${avatarUrl}" alt="${role.charAt(0).toUpperCase() + role.slice(1)} Avatar">
<div class="comment-content">
<div class="comment-header">
<span class="comment-author">${comment.author}</span>
<span class="comment-date">${formatDateTime(comment.date)}</span>
</div>
<div class="comment-text">${linkedContent}</div>
</div>
</div>
`;
}).join('');
}
async function loadHistory() {
const history = await fetchHistory(ticketId);
historyContainer.innerHTML = history.map(h => `
<div class="history-item">
<div class="history-icon"><i class="fas fa-${getHistoryIcon(h.action)}"></i></div>
<div class="history-content">
<div class="history-action">${h.action}</div>
<div class="history-details">${h.message || h.details || ''}</div>
<div class="history-meta">
<span class="history-actor">By ${h.author || h.actor || 'unknown'}</span>
<span class="history-date">${formatDateTime(h.date)}</span>
</div>
</div>
</div>
`).join('');
}
if (commentForm) {
commentForm.addEventListener('submit', async (e) => {
e.preventDefault();
const author = document.getElementById('comment-author')?.value || 'Unknown';
const content = document.getElementById('comment-content')?.value;
if (!content?.trim()) return alert('Please enter a comment');
const timestamp = new Date().toISOString();
try {
await createComment(ticketId, { author, content, timestamp });
document.getElementById('comment-content').value = '';
await loadComments();
await loadHistory();
await sendAdminWebhook(`New comment added by ${author}: "${content}" on ticket #${ticketId}`);
} catch (err) {
console.error('Failed to create comment:', err);
alert('Failed to submit comment. Please try again.');
}
});
}
async function checkForChanges() {
const ticket = await fetchTicket(ticketId);
if (!ticket) return;
// Update UI if status or priority changes server-side
if (ticket.status !== originalStatus) {
originalStatus = ticket.status;
ticketStatus.textContent = ticket.status;
ticketStatus.className = `ticket-status status-${ticket.status.replace(/ /g, '-')}`;
}
if (ticket.priority !== originalPriority) {
originalPriority = ticket.priority;
ticketPriority.textContent = ticket.priority;
}
// Check and update category if necessary
if (ticketCategory && ticket.category !== ticketCategory.textContent) {
ticketCategory.textContent = ticket.category || '—';
}
}
tabBtns.forEach(btn => btn.addEventListener('click', () => {
tabBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.getElementById(`${btn.dataset.tab}-tab`).classList.add('active');
}));
// Initial load
loadWebhookConfig().then(() => {
loadTicketDetails();
loadComments();
loadHistory();
});
// Periodic updates
setInterval(checkForChanges, 30000);
});