- Added a new section in the settings frontend for managing time multiplier presets, including UI for adding, displaying, and saving presets. - Introduced a new function to normalize and load time multiplier presets from settings. - Updated the worklog submission process to include a selected multiplier preset and its corresponding rate multiplier. - Enhanced the worklog model to support additional fields: extra_billed_hours, extended_support_flag, rate_multiplier, manual_hourly_rate, manual_rounded_hours, and rounding_override_reason. - Implemented backend validation to ensure that time entries linked to prepaid cards cannot be edited if the card is in a locked status. - Added database migration to introduce new columns and constraints for the worklog and time entry tables.
750 lines
32 KiB
HTML
750 lines
32 KiB
HTML
{% extends "base.html" %}
|
|
|
|
{% block title %}Card Details - BMC Hub{% endblock %}
|
|
|
|
{% block content %}
|
|
<div class="container-fluid py-4">
|
|
<!-- Header -->
|
|
<div class="row mb-4">
|
|
<div class="col">
|
|
<nav aria-label="breadcrumb">
|
|
<ol class="breadcrumb">
|
|
<li class="breadcrumb-item"><a href="/prepaid-cards">Prepaid Cards</a></li>
|
|
<li class="breadcrumb-item active" aria-current="page" id="cardNumber">Loading...</li>
|
|
</ol>
|
|
</nav>
|
|
<h1 class="h3 mb-0" id="pageTitle">💳 Loading...</h1>
|
|
</div>
|
|
<div class="col-auto">
|
|
<button class="btn btn-outline-secondary" onclick="window.location.href='/prepaid-cards'">
|
|
<i class="bi bi-arrow-left"></i> Tilbage
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Card Info -->
|
|
<div class="row g-4 mb-4">
|
|
<div class="col-md-8">
|
|
<div class="card border-0 shadow-sm">
|
|
<div class="card-header bg-white border-0 py-3">
|
|
<h5 class="mb-0">Kort Information</h5>
|
|
</div>
|
|
<div class="card-body">
|
|
<div class="row g-3" id="cardInfo">
|
|
<div class="col-12 text-center py-5">
|
|
<div class="spinner-border text-primary" role="status">
|
|
<span class="visually-hidden">Loading...</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="col-md-4">
|
|
<!-- Stats Card -->
|
|
<div class="card border-0 shadow-sm mb-3">
|
|
<div class="card-header bg-white border-0 py-3">
|
|
<h5 class="mb-0">Oversigt</h5>
|
|
</div>
|
|
<div class="card-body">
|
|
<!-- Usage Meter -->
|
|
<div class="mb-4">
|
|
<div class="d-flex justify-content-between mb-1">
|
|
<small class="text-muted fw-bold">Forbrug</small>
|
|
<small class="fw-bold" id="statPercent">0%</small>
|
|
</div>
|
|
<div class="progress" style="height: 10px; background-color: #e9ecef; border-radius: 6px;">
|
|
<div class="progress-bar transition-all" id="statProgressBar" role="progressbar" style="width: 0%; transition: width 0.6s ease;"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="mb-3 pb-3 border-bottom">
|
|
<small class="text-muted d-block mb-1">Købte Timer</small>
|
|
<h4 class="mb-0" id="statPurchased">-</h4>
|
|
</div>
|
|
<div class="mb-3 pb-3 border-bottom">
|
|
<small class="text-muted d-block mb-1">Brugte Timer</small>
|
|
<h4 class="mb-0 text-info" id="statUsed">-</h4>
|
|
</div>
|
|
<div class="mb-3 pb-3 border-bottom">
|
|
<small class="text-muted d-block mb-1">Tilbage</small>
|
|
<h4 class="mb-0 text-success" id="statRemaining">-</h4>
|
|
</div>
|
|
<div>
|
|
<small class="text-muted d-block mb-1">Total Beløb</small>
|
|
<h4 class="mb-0 text-primary" id="statTotal">-</h4>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Actions Card -->
|
|
<div class="card border-0 shadow-sm">
|
|
<div class="card-header bg-white border-0 py-3">
|
|
<h5 class="mb-0">Handlinger</h5>
|
|
</div>
|
|
<div class="card-body">
|
|
<div id="actionButtons">
|
|
<!-- Will be populated -->
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Timelogs -->
|
|
<div class="card border-0 shadow-sm">
|
|
<div class="card-header bg-white border-0 py-3">
|
|
<h5 class="mb-0">Timelogs</h5>
|
|
</div>
|
|
<div class="card-body">
|
|
<div class="table-responsive">
|
|
<table class="table table-hover align-middle" id="timelogsTable">
|
|
<thead class="table-light">
|
|
<tr>
|
|
<th>Dato</th>
|
|
<th>Sag / Ticket</th>
|
|
<th>Beskrivelse</th>
|
|
<th class="text-end">Multiplier</th>
|
|
<th>Tekst</th>
|
|
<th class="text-end">Faktisk tid</th>
|
|
<th class="text-end">Afrundet</th>
|
|
<th class="text-end">Handling</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="timelogsBody">
|
|
<tr>
|
|
<td colspan="8" class="text-center py-5">
|
|
<div class="spinner-border text-primary" role="status">
|
|
<span class="visually-hidden">Loading...</span>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
</tbody>
|
|
<tfoot class="table-light">
|
|
<tr>
|
|
<td colspan="5" class="text-end fw-bold">I alt:</td>
|
|
<td class="text-end fw-bold" id="totalActualHours">-</td>
|
|
<td class="text-end fw-bold" id="totalRoundedHours">-</td>
|
|
<td></td>
|
|
</tr>
|
|
</tfoot>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="modal fade" id="editTimelogModal" tabindex="-1" aria-hidden="true">
|
|
<div class="modal-dialog">
|
|
<div class="modal-content">
|
|
<div class="modal-header">
|
|
<h5 class="modal-title">Rediger tidsregistrering</h5>
|
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
|
</div>
|
|
<div class="modal-body">
|
|
<div class="mb-3">
|
|
<label class="form-label">Faktisk tid (timer)</label>
|
|
<input type="number" class="form-control" id="editActualHours" min="0.01" step="0.01">
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Fakturerbar/Afrundet tid (timer)</label>
|
|
<input type="number" class="form-control" id="editRoundedHours" min="0.00" step="0.01" readonly>
|
|
</div>
|
|
<div class="mb-3" id="editExtraWrap">
|
|
<label class="form-label">Ekstra tid (timer)</label>
|
|
<input type="number" class="form-control" id="editExtraHours" min="0.00" step="0.01" value="0">
|
|
<div class="form-text">Kun relevant for ticket-registreringer.</div>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Multiplier preset</label>
|
|
<select class="form-select" id="editMultiplierPreset" onchange="applyEditMultiplierPreset()">
|
|
<option value="">Ingen (x1.00)</option>
|
|
</select>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Tekst/Beskrivelse</label>
|
|
<textarea class="form-control" id="editDescription" rows="3" placeholder="Tekst til tidsregistreringen"></textarea>
|
|
</div>
|
|
<div class="mb-0" id="editReasonWrap">
|
|
<label class="form-label">Begrundelse</label>
|
|
<input type="text" class="form-control" id="editReason" maxlength="255" placeholder="Fx aftalt minimumsforbrug">
|
|
</div>
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Luk</button>
|
|
<button type="button" class="btn btn-primary" onclick="saveTimelogEdit()">Gem ændringer</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
const cardId = {{ card_id }};
|
|
let currentTimelogs = [];
|
|
let currentEditTimelog = null;
|
|
let editTimelogModal;
|
|
let timeMultiplierPresets = [];
|
|
let currentCardRoundingMinutes = 0;
|
|
let currentCardStatus = '';
|
|
|
|
const DEFAULT_TIME_MULTIPLIER_PRESETS = [
|
|
{ label: 'Haster', text: 'Haster', multiplier: 3 },
|
|
{ label: 'Avanceret netvaerk', text: 'Avanceret netvaerk', multiplier: 2 },
|
|
{ label: 'Haster + ava. network', text: 'Haster + ava. network', multiplier: 6 }
|
|
];
|
|
|
|
function escapeHtml(value) {
|
|
return String(value ?? '')
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/\"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
// Load card details
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
editTimelogModal = new bootstrap.Modal(document.getElementById('editTimelogModal'));
|
|
loadTimeMultiplierPresets().then(() => {
|
|
renderEditMultiplierPresetOptions();
|
|
loadCardDetails();
|
|
});
|
|
});
|
|
|
|
function normalizeMultiplierPresets(raw) {
|
|
if (!Array.isArray(raw)) return [];
|
|
const normalized = [];
|
|
for (const row of raw) {
|
|
if (!row || typeof row !== 'object') continue;
|
|
const label = String(row.label || row.name || '').trim();
|
|
const text = String(row.text || row.description || label || '').trim();
|
|
const multiplier = Number(row.multiplier ?? row.value ?? 1);
|
|
if (!label || !Number.isFinite(multiplier) || multiplier <= 0) continue;
|
|
normalized.push({
|
|
label,
|
|
text,
|
|
multiplier: Number(multiplier.toFixed(2))
|
|
});
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
async function loadTimeMultiplierPresets() {
|
|
try {
|
|
const response = await fetch('/api/v1/settings/time_multiplier_presets');
|
|
if (!response.ok) {
|
|
timeMultiplierPresets = [...DEFAULT_TIME_MULTIPLIER_PRESETS];
|
|
return;
|
|
}
|
|
const setting = await response.json();
|
|
const parsed = JSON.parse(setting.value || '[]');
|
|
const normalized = normalizeMultiplierPresets(parsed);
|
|
timeMultiplierPresets = normalized.length ? normalized : [...DEFAULT_TIME_MULTIPLIER_PRESETS];
|
|
} catch (error) {
|
|
console.warn('Kunne ikke hente multiplier presets', error);
|
|
timeMultiplierPresets = [...DEFAULT_TIME_MULTIPLIER_PRESETS];
|
|
}
|
|
}
|
|
|
|
function renderEditMultiplierPresetOptions() {
|
|
const select = document.getElementById('editMultiplierPreset');
|
|
if (!select) return;
|
|
const options = timeMultiplierPresets.map((preset, idx) => {
|
|
const value = Number(preset.multiplier).toFixed(2);
|
|
return `<option value="${idx}">${escapeHtml(preset.label)} (x${value})</option>`;
|
|
}).join('');
|
|
select.innerHTML = `<option value="">Ingen (x1.00)</option>${options}`;
|
|
}
|
|
|
|
function applyEditMultiplierPreset() {
|
|
const select = document.getElementById('editMultiplierPreset');
|
|
const descEl = document.getElementById('editDescription');
|
|
if (!select || !descEl) return;
|
|
if (select.value !== '') {
|
|
const preset = timeMultiplierPresets[Number(select.value)];
|
|
if (preset && preset.text && !(descEl.value || '').trim()) {
|
|
descEl.value = preset.text;
|
|
}
|
|
}
|
|
recalcRoundedFromInputs();
|
|
}
|
|
|
|
function findClosestPresetIndex(multiplierValue) {
|
|
const numeric = Number(multiplierValue);
|
|
if (!Number.isFinite(numeric) || numeric <= 0 || !timeMultiplierPresets.length) return '';
|
|
const idx = timeMultiplierPresets.findIndex((preset) => Math.abs(Number(preset.multiplier) - numeric) < 0.001);
|
|
return idx >= 0 ? String(idx) : '';
|
|
}
|
|
|
|
function getMultiplierText(multiplierValue) {
|
|
const numeric = Number(multiplierValue);
|
|
if (!Number.isFinite(numeric) || numeric <= 0 || !timeMultiplierPresets.length) return '';
|
|
const preset = timeMultiplierPresets.find((item) => Math.abs(Number(item.multiplier) - numeric) < 0.001);
|
|
if (!preset) return '';
|
|
return preset.text || preset.label || '';
|
|
}
|
|
|
|
function getSelectedEditMultiplier() {
|
|
const presetIdx = document.getElementById('editMultiplierPreset')?.value;
|
|
const selectedPreset = presetIdx !== '' && presetIdx != null ? timeMultiplierPresets[Number(presetIdx)] : null;
|
|
const selected = selectedPreset ? Number(selectedPreset.multiplier) : 1.0;
|
|
return Number.isFinite(selected) && selected > 0 ? selected : 1.0;
|
|
}
|
|
|
|
function roundUpHoursByMinutes(hours, roundingMinutes) {
|
|
const value = Number(hours);
|
|
if (!Number.isFinite(value) || value <= 0) return 0;
|
|
const stepMinutes = Number(roundingMinutes) || 0;
|
|
if (stepMinutes <= 0) return value;
|
|
const stepHours = stepMinutes / 60;
|
|
return Math.ceil(value / stepHours) * stepHours;
|
|
}
|
|
|
|
function recalcRoundedFromInputs() {
|
|
const actualInput = document.getElementById('editActualHours');
|
|
const roundedInput = document.getElementById('editRoundedHours');
|
|
if (!actualInput || !roundedInput) return;
|
|
|
|
const actualHours = parseFloat(actualInput.value || '0');
|
|
const multiplier = getSelectedEditMultiplier();
|
|
const roundedBase = roundUpHoursByMinutes(actualHours, currentCardRoundingMinutes);
|
|
const computed = roundedBase * multiplier;
|
|
roundedInput.value = Number.isFinite(computed) && computed > 0 ? computed.toFixed(2) : '0.00';
|
|
}
|
|
|
|
async function loadCardDetails() {
|
|
try {
|
|
const response = await fetch(`/api/v1/prepaid-cards/${cardId}`);
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Card not found');
|
|
}
|
|
|
|
const card = await response.json();
|
|
currentCardStatus = String(card.status || '').toLowerCase();
|
|
const customerName = escapeHtml(card.customer_name || '-');
|
|
const customerEmail = escapeHtml(card.customer_email || '');
|
|
const cardNumber = escapeHtml(card.card_number || '-');
|
|
const notesHtml = card.notes ? escapeHtml(card.notes) : '';
|
|
const invoiceNo = card.economic_invoice_number ? escapeHtml(card.economic_invoice_number) : '';
|
|
|
|
// Update header
|
|
document.getElementById('cardNumber').textContent = card.card_number;
|
|
document.getElementById('pageTitle').textContent = `💳 ${card.card_number}`;
|
|
|
|
// Update stats
|
|
document.getElementById('statPurchased').textContent =
|
|
parseFloat(card.purchased_hours).toFixed(1) + ' t';
|
|
document.getElementById('statUsed').textContent =
|
|
parseFloat(card.used_hours).toFixed(1) + ' t';
|
|
document.getElementById('statRemaining').textContent =
|
|
parseFloat(card.remaining_hours).toFixed(1) + ' t';
|
|
document.getElementById('statTotal').textContent =
|
|
new Intl.NumberFormat('da-DK', {
|
|
style: 'currency',
|
|
currency: 'DKK'
|
|
}).format(parseFloat(card.total_amount));
|
|
|
|
// Update Progress Bar
|
|
const purchased = parseFloat(card.purchased_hours) || 0;
|
|
const used = parseFloat(card.used_hours) || 0;
|
|
const percent = purchased > 0 ? (used / purchased) * 100 : 0;
|
|
|
|
const progressBar = document.getElementById('statProgressBar');
|
|
progressBar.style.width = Math.min(percent, 100) + '%';
|
|
document.getElementById('statPercent').textContent = Math.round(percent) + '%';
|
|
|
|
// Color logic for progress bar
|
|
progressBar.className = 'progress-bar transition-all'; // Reset class but keep transition
|
|
if (percent >= 100) {
|
|
progressBar.classList.add('bg-secondary'); // Depleted
|
|
} else if (percent > 90) {
|
|
progressBar.classList.add('bg-danger'); // Critical
|
|
} else if (percent > 75) {
|
|
progressBar.classList.add('bg-warning'); // Warning
|
|
} else {
|
|
progressBar.classList.add('bg-success'); // Good
|
|
}
|
|
|
|
// Update card info
|
|
const statusBadge = getStatusBadge(card.status);
|
|
const expiresAt = card.expires_at ?
|
|
new Date(card.expires_at).toLocaleDateString('da-DK', {
|
|
year: 'numeric',
|
|
month: 'long',
|
|
day: 'numeric'
|
|
}) : 'Ingen udløbsdato';
|
|
|
|
document.getElementById('cardInfo').innerHTML = `
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Kortnummer</label>
|
|
<p class="mb-0"><strong>${cardNumber}</strong></p>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Status</label>
|
|
<p class="mb-0">${statusBadge}</p>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Kunde</label>
|
|
<p class="mb-0">
|
|
<a href="/customers/${card.customer_id}" class="text-decoration-none">
|
|
${customerName}
|
|
</a>
|
|
</p>
|
|
<small class="text-muted">${customerEmail}</small>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Pris pr. Time</label>
|
|
<p class="mb-0"><strong>${parseFloat(card.price_per_hour).toFixed(2)} kr</strong></p>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Afrunding</label>
|
|
<div class="input-group input-group-sm">
|
|
<select class="form-select" id="roundingMinutes">
|
|
<option value="0">Ingen afrunding</option>
|
|
<option value="15">15 min</option>
|
|
<option value="30">30 min</option>
|
|
<option value="60">60 min</option>
|
|
</select>
|
|
<button class="btn btn-outline-primary" type="button" onclick="saveRounding()">Gem</button>
|
|
</div>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Købt Dato</label>
|
|
<p class="mb-0">${new Date(card.purchased_at).toLocaleDateString('da-DK')}</p>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">Udløber</label>
|
|
<p class="mb-0">${expiresAt}</p>
|
|
</div>
|
|
${card.economic_invoice_number ? `
|
|
<div class="col-md-6">
|
|
<label class="small text-muted">e-conomic Fakturanr.</label>
|
|
<p class="mb-0">${invoiceNo}</p>
|
|
</div>
|
|
` : ''}
|
|
${card.notes ? `
|
|
<div class="col-12">
|
|
<label class="small text-muted">Bemærkninger</label>
|
|
<p class="mb-0">${notesHtml}</p>
|
|
</div>
|
|
` : ''}
|
|
`;
|
|
|
|
// Update action buttons
|
|
const actions = [];
|
|
if (card.status === 'active') {
|
|
actions.push(`
|
|
<button class="btn btn-secondary w-100 mb-2" onclick="closeCard()">
|
|
<i class="bi bi-lock"></i> Luk Kort
|
|
</button>
|
|
`);
|
|
actions.push(`
|
|
<button class="btn btn-warning w-100 mb-2" onclick="cancelCard()">
|
|
<i class="bi bi-x-circle"></i> Annuller Kort
|
|
</button>
|
|
`);
|
|
} else if (card.status === 'closed') {
|
|
actions.push(`
|
|
<button class="btn btn-success w-100 mb-2" onclick="reopenCard()">
|
|
<i class="bi bi-unlock"></i> Genåbn Kort
|
|
</button>
|
|
`);
|
|
actions.push(`
|
|
<div class="alert alert-secondary py-2 mb-0 small">
|
|
Kortet er lukket. Tid og afrunding kan ikke redigeres.
|
|
</div>
|
|
`);
|
|
}
|
|
document.getElementById('actionButtons').innerHTML = actions.join('') ||
|
|
'<p class="text-muted text-center mb-0">Ingen handlinger tilgængelige</p>';
|
|
|
|
const roundingSelect = document.getElementById('roundingMinutes');
|
|
if (roundingSelect) {
|
|
roundingSelect.value = String(card.rounding_minutes || 0);
|
|
const isClosed = currentCardStatus === 'closed';
|
|
roundingSelect.disabled = isClosed;
|
|
const roundingButton = roundingSelect.parentElement?.querySelector('button');
|
|
if (roundingButton) roundingButton.disabled = isClosed;
|
|
}
|
|
currentCardRoundingMinutes = parseInt(card.rounding_minutes || 0, 10) || 0;
|
|
|
|
// Render timelogs
|
|
renderTimelogs(card.timelogs || []);
|
|
|
|
} catch (error) {
|
|
console.error('Error loading card:', error);
|
|
document.getElementById('cardInfo').innerHTML = `
|
|
<div class="col-12 text-center text-danger py-5">
|
|
<i class="bi bi-exclamation-circle fs-1 mb-3"></i>
|
|
<p>❌ Fejl ved indlæsning: ${escapeHtml(error.message)}</p>
|
|
<button class="btn btn-primary" onclick="window.location.href='/prepaid-cards'">
|
|
Tilbage til oversigt
|
|
</button>
|
|
</div>
|
|
`;
|
|
}
|
|
}
|
|
|
|
function renderTimelogs(timelogs) {
|
|
const tbody = document.getElementById('timelogsBody');
|
|
currentTimelogs = timelogs || [];
|
|
|
|
if (!timelogs || timelogs.length === 0) {
|
|
tbody.innerHTML = `
|
|
<tr><td colspan="8" class="text-center text-muted py-5">
|
|
Ingen timelogs endnu
|
|
</td></tr>
|
|
`;
|
|
document.getElementById('totalActualHours').textContent = '0.00 t';
|
|
document.getElementById('totalRoundedHours').textContent = '0.00 t';
|
|
return;
|
|
}
|
|
|
|
let totalActual = 0;
|
|
let totalRounded = 0;
|
|
|
|
tbody.innerHTML = timelogs.map((t, index) => {
|
|
const dateValue = t.worked_date || t.created_at;
|
|
const dateText = dateValue ? new Date(dateValue).toLocaleDateString('da-DK') : '-';
|
|
const sourceTitle = escapeHtml(t.source_title || '');
|
|
const description = escapeHtml(t.description || '-');
|
|
let sourceHtml = '-';
|
|
if (t.source === 'sag' && t.source_id) {
|
|
sourceHtml = `<a href="/sag/${t.source_id}/v3" class="text-decoration-none">Sag #${t.source_id}${t.source_title ? ' - ' + sourceTitle : ''}</a>`;
|
|
} else if (t.source === 'ticket' && t.source_id) {
|
|
const ticketLabel = t.ticket_number ? `#${t.ticket_number}` : `#${t.source_id}`;
|
|
sourceHtml = `<a href="/ticket/tickets/${t.source_id}" class="text-decoration-none">${escapeHtml(ticketLabel)} - ${sourceTitle || 'Ticket'}</a>`;
|
|
}
|
|
|
|
const actual = parseFloat(t.actual_hours) || 0;
|
|
const rounded = parseFloat(t.rounded_hours) || 0;
|
|
const multiplier = parseFloat(t.rate_multiplier) || 1;
|
|
const multiplierText = escapeHtml(getMultiplierText(multiplier) || '-');
|
|
totalActual += actual;
|
|
totalRounded += rounded;
|
|
const resolvedEntryId = t.entry_id || t.id || t.time_id || t.worklog_id || null;
|
|
const canEdit = !!resolvedEntryId && currentCardStatus !== 'closed';
|
|
const actionHtml = canEdit
|
|
? `<button class="btn btn-sm btn-outline-primary" onclick="openTimelogEditModal(${index})"><i class="bi bi-pencil"></i> Rediger</button>`
|
|
: (currentCardStatus === 'closed' ? '<span class="text-muted">Låst</span>' : '<span class="text-muted">-</span>');
|
|
|
|
return `
|
|
<tr>
|
|
<td>${dateText}</td>
|
|
<td>${sourceHtml}</td>
|
|
<td>${description}</td>
|
|
<td class="text-end">x${multiplier.toFixed(2)}</td>
|
|
<td>${multiplierText}</td>
|
|
<td class="text-end">${actual.toFixed(2)} t</td>
|
|
<td class="text-end">${rounded.toFixed(2)} t</td>
|
|
<td class="text-end">${actionHtml}</td>
|
|
</tr>
|
|
`;
|
|
}).join('');
|
|
|
|
// Update totals in footer
|
|
document.getElementById('totalActualHours').textContent = totalActual.toFixed(2) + ' t';
|
|
document.getElementById('totalRoundedHours').textContent = totalRounded.toFixed(2) + ' t';
|
|
}
|
|
|
|
function openTimelogEditModal(index) {
|
|
if (currentCardStatus === 'closed') {
|
|
alert('Kortet er lukket og kan ikke redigeres');
|
|
return;
|
|
}
|
|
const timelog = currentTimelogs[index];
|
|
if (!timelog) return;
|
|
const resolvedEntryId = timelog.entry_id || timelog.id || timelog.time_id || timelog.worklog_id || null;
|
|
if (!resolvedEntryId) return;
|
|
timelog._resolved_entry_id = resolvedEntryId;
|
|
currentEditTimelog = timelog;
|
|
|
|
document.getElementById('editActualHours').value = (parseFloat(timelog.actual_hours) || 0).toFixed(2);
|
|
document.getElementById('editRoundedHours').value = (parseFloat(timelog.rounded_hours) || 0).toFixed(2);
|
|
document.getElementById('editExtraHours').value = (parseFloat(timelog.extra_billed_hours) || 0).toFixed(2);
|
|
document.getElementById('editDescription').value = timelog.description || '';
|
|
document.getElementById('editReason').value = '';
|
|
document.getElementById('editMultiplierPreset').value = findClosestPresetIndex(timelog.rate_multiplier || 1.0);
|
|
|
|
const isTicket = timelog.source === 'ticket';
|
|
document.getElementById('editExtraWrap').classList.toggle('d-none', !isTicket);
|
|
document.getElementById('editReasonWrap').classList.toggle('d-none', !isTicket);
|
|
|
|
document.getElementById('editActualHours').oninput = recalcRoundedFromInputs;
|
|
recalcRoundedFromInputs();
|
|
|
|
editTimelogModal.show();
|
|
}
|
|
|
|
async function saveTimelogEdit() {
|
|
if (!currentEditTimelog) return;
|
|
const resolvedEntryId = currentEditTimelog._resolved_entry_id || currentEditTimelog.entry_id || currentEditTimelog.id || currentEditTimelog.time_id || currentEditTimelog.worklog_id;
|
|
if (!resolvedEntryId) return;
|
|
|
|
const actualHours = parseFloat(document.getElementById('editActualHours').value || '0');
|
|
const multiplier = getSelectedEditMultiplier();
|
|
const roundedBase = roundUpHoursByMinutes(actualHours, currentCardRoundingMinutes);
|
|
const roundedHours = roundedBase * multiplier;
|
|
const extraHours = parseFloat(document.getElementById('editExtraHours').value || '0');
|
|
const description = (document.getElementById('editDescription').value || '').trim();
|
|
const reason = (document.getElementById('editReason').value || '').trim();
|
|
const presetIdx = document.getElementById('editMultiplierPreset').value;
|
|
const selectedPreset = presetIdx !== '' ? timeMultiplierPresets[Number(presetIdx)] : null;
|
|
const rateMultiplier = selectedPreset ? Number(selectedPreset.multiplier) : multiplier;
|
|
const finalDescription = description || (selectedPreset ? selectedPreset.text : (currentEditTimelog.description || ''));
|
|
|
|
if (!actualHours || actualHours <= 0) {
|
|
alert('Faktisk tid skal være større end 0');
|
|
return;
|
|
}
|
|
if (extraHours < 0) {
|
|
alert('Ekstra tid kan ikke være negativ');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
if (currentEditTimelog.source === 'ticket') {
|
|
const payload = {
|
|
hours: actualHours,
|
|
manual_rounded_hours: roundedHours,
|
|
extra_billed_hours: extraHours,
|
|
rate_multiplier: Number.isFinite(rateMultiplier) && rateMultiplier > 0 ? rateMultiplier : 1.0,
|
|
description: finalDescription,
|
|
rounding_override_reason: reason || 'Redigeret fra prepaid kort detaljeside'
|
|
};
|
|
const response = await fetch(`/api/v1/worklog/${resolvedEntryId}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(payload)
|
|
});
|
|
if (!response.ok) {
|
|
const err = await response.json().catch(() => ({}));
|
|
throw new Error(err.detail || 'Kunne ikke opdatere ticket tidslinje');
|
|
}
|
|
} else {
|
|
const payload = {
|
|
faktisk_tid_min: Math.round(actualHours * 60),
|
|
fakturerbar_tid_min: Math.round(roundedHours * 60),
|
|
description: finalDescription,
|
|
rate_multiplier: Number.isFinite(rateMultiplier) && rateMultiplier > 0 ? rateMultiplier : 1.0
|
|
};
|
|
const response = await fetch(`/api/v1/timetracking/time/${resolvedEntryId}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(payload)
|
|
});
|
|
if (!response.ok) {
|
|
const err = await response.json().catch(() => ({}));
|
|
throw new Error(err.detail || 'Kunne ikke opdatere sag tidslinje');
|
|
}
|
|
}
|
|
|
|
editTimelogModal.hide();
|
|
await loadCardDetails();
|
|
alert('✅ Tidslinje opdateret');
|
|
} catch (error) {
|
|
console.error('Error updating timelog:', error);
|
|
alert('❌ Fejl: ' + (error.message || 'Ukendt fejl'));
|
|
}
|
|
}
|
|
|
|
function getStatusBadge(status) {
|
|
const badges = {
|
|
'active': '<span class="badge bg-success">Aktiv</span>',
|
|
'closed': '<span class="badge bg-dark">Lukket</span>',
|
|
'depleted': '<span class="badge bg-secondary">Opbrugt</span>',
|
|
'expired': '<span class="badge bg-danger">Udløbet</span>',
|
|
'cancelled': '<span class="badge bg-warning">Annulleret</span>'
|
|
};
|
|
return badges[status] || status;
|
|
}
|
|
|
|
async function updateCardStatus(nextStatus, successMessage) {
|
|
try {
|
|
const response = await fetch(`/api/v1/prepaid-cards/${cardId}/status`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ status: nextStatus })
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const err = await response.json().catch(() => ({}));
|
|
throw new Error(err.detail || 'Fejl ved statusændring');
|
|
}
|
|
|
|
alert(successMessage);
|
|
loadCardDetails();
|
|
} catch (error) {
|
|
console.error('Error updating status:', error);
|
|
alert('❌ Fejl: ' + (error.message || 'Ukendt fejl'));
|
|
}
|
|
}
|
|
|
|
async function closeCard() {
|
|
if (!confirm('Er du sikker på at du vil lukke dette kort?')) return;
|
|
await updateCardStatus('closed', '✅ Kort lukket');
|
|
}
|
|
|
|
async function reopenCard() {
|
|
if (!confirm('Vil du genåbne kortet?')) return;
|
|
await updateCardStatus('active', '✅ Kort genåbnet');
|
|
}
|
|
|
|
async function cancelCard() {
|
|
if (!confirm('Er du sikker på at du vil annullere dette kort?')) {
|
|
return;
|
|
}
|
|
|
|
await updateCardStatus('cancelled', '✅ Kort annulleret');
|
|
}
|
|
|
|
async function saveRounding() {
|
|
if (currentCardStatus === 'closed') {
|
|
alert('Kortet er lukket og afrunding kan ikke ændres');
|
|
return;
|
|
}
|
|
const select = document.getElementById('roundingMinutes');
|
|
if (!select) return;
|
|
const roundingMinutes = parseInt(select.value, 10) || 0;
|
|
|
|
try {
|
|
const response = await fetch(`/api/v1/prepaid-cards/${cardId}/rounding`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ rounding_minutes: roundingMinutes })
|
|
});
|
|
|
|
if (!response.ok) throw new Error('Fejl ved opdatering');
|
|
|
|
currentCardRoundingMinutes = roundingMinutes;
|
|
alert('✅ Afrunding opdateret');
|
|
loadCardDetails();
|
|
} catch (error) {
|
|
console.error('Error updating rounding:', error);
|
|
alert('❌ Fejl: ' + error.message);
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<style>
|
|
.breadcrumb {
|
|
background: transparent;
|
|
padding: 0;
|
|
}
|
|
|
|
.card-header {
|
|
font-weight: 600;
|
|
}
|
|
|
|
.table th {
|
|
font-weight: 600;
|
|
font-size: 0.85rem;
|
|
text-transform: uppercase;
|
|
letter-spacing: 0.5px;
|
|
color: var(--bs-secondary);
|
|
}
|
|
</style>
|
|
{% endblock %}
|