Current Version
This commit is contained in:
1 parent
aef8a08dd8
commit
cb5d091be2
9 files changed
+1424
-3
No files matched your search
@@ -0,0 +1,86 @@
|
||||
export async function fetchTicket(id) {
|
||||
const res = await fetch(`/api/tickets/${id}`);
|
||||
if (!res.ok) return null;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchComments(id) {
|
||||
const res = await fetch(`/api/tickets/${id}/comments`);
|
||||
if (!res.ok) return [];
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchHistory(id) {
|
||||
const res = await fetch(`/api/tickets/${id}/history`);
|
||||
if (!res.ok) return [];
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function logTime(id, timeLog) {
|
||||
// timeLog = { minutes: Number, comment: String, author: String }
|
||||
const res = await fetch(`/api/tickets/${id}/time`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(timeLog),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// Flexible Update-Funktion für beliebige Felder, z.B. {status, priority, category, actor, ...}
|
||||
export async function updateTicket(id, data) {
|
||||
const res = await fetch(`/api/tickets/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function createComment(id, comment) {
|
||||
const res = await fetch(`/api/tickets/${id}/comments`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(comment),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export function formatDateTime(date) {
|
||||
if (!date) return 'n/a';
|
||||
|
||||
// Convert SQLite DATETIME if needed
|
||||
const safeDate = date.includes('T') ? date : date.replace(' ', 'T');
|
||||
const parsed = new Date(safeDate + 'Z'); // Assume UTC
|
||||
|
||||
if (isNaN(parsed.getTime())) return 'n/a';
|
||||
|
||||
return parsed.toLocaleString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
export function formatMinutes(mins) {
|
||||
if (typeof mins !== 'number' || isNaN(mins)) return '0 Min.';
|
||||
const hours = Math.floor(mins / 60);
|
||||
const minutes = mins % 60;
|
||||
if (hours > 0 && minutes > 0) return `${hours} Std. ${minutes} Min.`;
|
||||
if (hours > 0) return `${hours} Std.`;
|
||||
return `${minutes} Min.`;
|
||||
}
|
||||
|
||||
export function getHistoryIcon(action) {
|
||||
const icons = {
|
||||
'Ticket Created': 'plus-circle',
|
||||
'Status Changed': 'sync-alt',
|
||||
'Priority Changed': 'exclamation-circle',
|
||||
'Comment Added': 'comment',
|
||||
'Ticket Deleted': 'trash-alt',
|
||||
'Category Changed': 'tags',
|
||||
'Time Logged': 'clock',
|
||||
};
|
||||
return icons[action] || 'history';
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
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);
|
||||
});
|
||||
Reference in new issue
Block a user