First version
This commit is contained in:
parent
19bb4146da
commit
0727798af7
7 changed files with 1581 additions and 0 deletions
733
app.js
Normal file
733
app.js
Normal file
|
|
@ -0,0 +1,733 @@
|
|||
const state = {
|
||||
settings: {},
|
||||
entries: [],
|
||||
corrections: {},
|
||||
plan: null,
|
||||
};
|
||||
|
||||
const settingKeys = [
|
||||
'planning_start_year', 'planning_start_month', 'planning_months',
|
||||
'vacation_days_per_month', 'feriefridage_per_year', 'feriefridage_expiry_month',
|
||||
'normal_day_hours', 'friday_hours', 'opening_vacation_days',
|
||||
'opening_feriefridage_days', 'opening_flex_hours'
|
||||
];
|
||||
|
||||
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
const sourceLabels = {
|
||||
auto: 'Smart',
|
||||
vacation: 'Vacation',
|
||||
feriefridag: 'Feriefridage',
|
||||
flex: 'FLEX',
|
||||
unpaid: 'Unpaid',
|
||||
};
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
init().catch((error) => toast(error.message || String(error)));
|
||||
|
||||
async function init() {
|
||||
bindEvents();
|
||||
await loadState();
|
||||
}
|
||||
|
||||
function bindEvents() {
|
||||
$('addEntryBtn').addEventListener('click', () => openEntryDialog());
|
||||
$('settingsBtn').addEventListener('click', openSettingsDialog);
|
||||
$('closeEntryDialogBtn').addEventListener('click', closeEntryDialog);
|
||||
$('closeSettingsDialogBtn').addEventListener('click', closeSettingsDialog);
|
||||
$('entryDialog').addEventListener('click', closeDialogOnBackdrop);
|
||||
$('settingsDialog').addEventListener('click', closeDialogOnBackdrop);
|
||||
$('entryForm').addEventListener('submit', saveEntry);
|
||||
$('settingsForm').addEventListener('submit', saveSettings);
|
||||
$('cancelEditBtn').addEventListener('click', resetEntryForm);
|
||||
}
|
||||
|
||||
async function loadState() {
|
||||
const res = await fetch('api.php?action=state');
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Could not load state');
|
||||
state.settings = normalizeSettings(data.settings);
|
||||
state.entries = data.entries.map(normalizeEntry);
|
||||
state.corrections = data.corrections || {};
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
renderAll();
|
||||
}
|
||||
|
||||
function normalizeSettings(settings) {
|
||||
const normalized = { ...settings };
|
||||
normalized.planning_start_month = Number(normalized.planning_start_month || 1);
|
||||
normalized.planning_months = Number(normalized.planning_months || (Number(normalized.planning_years || 3) * 12));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
fillSettingsForm();
|
||||
renderDashboard();
|
||||
renderHeaderWarnings();
|
||||
renderWarnings();
|
||||
renderEntries();
|
||||
renderPlanner();
|
||||
}
|
||||
|
||||
function fillSettingsForm() {
|
||||
for (const key of settingKeys) {
|
||||
const node = $(key);
|
||||
if (node) node.value = state.settings[key] ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSettings(event) {
|
||||
event.preventDefault();
|
||||
const settings = {};
|
||||
for (const key of settingKeys) {
|
||||
settings[key] = Number($(key).value);
|
||||
}
|
||||
const data = await post({ action: 'saveSettings', settings });
|
||||
state.settings = normalizeSettings(data.settings);
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
renderAll();
|
||||
closeSettingsDialog();
|
||||
toast('Settings saved');
|
||||
}
|
||||
|
||||
async function saveQuickFlex(event) {
|
||||
event.preventDefault();
|
||||
const value = Number($('quickFlexHours').value);
|
||||
const data = await post({ action: 'saveSettings', settings: { current_flex_hours: value } });
|
||||
state.settings = normalizeSettings(data.settings);
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
renderAll();
|
||||
toast('FLEX hours updated');
|
||||
}
|
||||
|
||||
async function saveCorrection(event) {
|
||||
const input = event.target;
|
||||
const year = Number(input.dataset.year);
|
||||
const month = Number(input.dataset.month);
|
||||
const value = Number(input.value || 0);
|
||||
const data = await post({ action: 'saveCorrection', year, month, value });
|
||||
state.corrections = data.corrections || {};
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
renderAll();
|
||||
toast('Correction saved');
|
||||
}
|
||||
|
||||
async function saveEntry(event) {
|
||||
event.preventDefault();
|
||||
const id = Number($('entryId').value || 0);
|
||||
const entry = {
|
||||
title: $('title').value.trim(),
|
||||
start_date: $('startDate').value,
|
||||
end_date: $('endDate').value,
|
||||
source: $('source').value,
|
||||
status: $('status').value,
|
||||
allow_unpaid: $('allowUnpaid').checked ? 1 : 0,
|
||||
note: $('note').value.trim(),
|
||||
};
|
||||
|
||||
const payload = id ? { action: 'updateEntry', id, entry } : { action: 'createEntry', entry };
|
||||
const data = await post(payload);
|
||||
state.entries = data.entries.map(normalizeEntry);
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
resetEntryForm();
|
||||
closeEntryDialog();
|
||||
renderAll();
|
||||
toast(id ? 'Entry updated' : 'Entry added');
|
||||
}
|
||||
|
||||
async function approveEntry(id) {
|
||||
const entry = state.entries.find((item) => item.id === id);
|
||||
if (!entry || entry.status !== 'planned') return;
|
||||
const data = await post({ action: 'updateEntry', id, entry: { ...entry, status: 'approved' } });
|
||||
state.entries = data.entries.map(normalizeEntry);
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
renderAll();
|
||||
toast('Entry approved');
|
||||
}
|
||||
|
||||
async function deleteEntry(id) {
|
||||
const entry = state.entries.find((item) => item.id === id);
|
||||
if (!confirm(`Delete "${entry?.title || 'entry'}"?`)) return;
|
||||
const data = await post({ action: 'deleteEntry', id });
|
||||
state.entries = data.entries.map(normalizeEntry);
|
||||
state.plan = calculatePlan(state.settings, state.entries, state.corrections);
|
||||
renderAll();
|
||||
toast('Entry deleted');
|
||||
}
|
||||
|
||||
async function post(payload) {
|
||||
const res = await fetch('api.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Request failed');
|
||||
return data;
|
||||
}
|
||||
|
||||
function openEntryDialog(entryId = null) {
|
||||
if (!entryId) resetEntryForm();
|
||||
$('entryDialog').showModal();
|
||||
}
|
||||
|
||||
function closeEntryDialog() {
|
||||
$('entryDialog').close();
|
||||
}
|
||||
|
||||
function openSettingsDialog() {
|
||||
fillSettingsForm();
|
||||
$('settingsDialog').showModal();
|
||||
}
|
||||
|
||||
function closeSettingsDialog() {
|
||||
$('settingsDialog').close();
|
||||
}
|
||||
|
||||
function closeDialogOnBackdrop(event) {
|
||||
if (event.target === event.currentTarget) event.currentTarget.close();
|
||||
}
|
||||
|
||||
function editEntry(id) {
|
||||
const entry = state.entries.find((item) => item.id === id);
|
||||
if (!entry) return;
|
||||
$('entryId').value = entry.id;
|
||||
$('title').value = entry.title;
|
||||
$('startDate').value = entry.start_date;
|
||||
$('endDate').value = entry.end_date;
|
||||
$('source').value = entry.source;
|
||||
$('status').value = entry.status;
|
||||
$('allowUnpaid').checked = Boolean(Number(entry.allow_unpaid));
|
||||
$('note').value = entry.note || '';
|
||||
$('entryFormTitle').textContent = 'Edit date-range entry';
|
||||
$('saveEntryBtn').textContent = 'Update entry';
|
||||
$('cancelEditBtn').classList.remove('hidden');
|
||||
openEntryDialog(id);
|
||||
}
|
||||
|
||||
function resetEntryForm() {
|
||||
$('entryForm').reset();
|
||||
$('entryId').value = '';
|
||||
$('source').value = 'auto';
|
||||
$('status').value = 'planned';
|
||||
$('entryFormTitle').textContent = 'Add date-range entry';
|
||||
$('saveEntryBtn').textContent = 'Save entry';
|
||||
$('cancelEditBtn').classList.add('hidden');
|
||||
}
|
||||
|
||||
function renderDashboard() {
|
||||
const current = state.plan.current;
|
||||
const cards = [
|
||||
['Feriefridage', days(current.feriefridage), 'Use before 31 August', current.feriefridage > 0.001 ? 'warn' : ''],
|
||||
['Vacation days', days(current.vacation), 'Available today', current.vacation < -0.001 ? 'bad' : 'good'],
|
||||
];
|
||||
|
||||
$('dashboard').innerHTML = `
|
||||
${cards.map(([label, value, hint, tone]) => `
|
||||
<article class="card ${tone}">
|
||||
<div class="label">${escapeHtml(label)}</div>
|
||||
<div class="value">${value}</div>
|
||||
<div class="hint">${escapeHtml(hint)}</div>
|
||||
</article>
|
||||
`).join('')}
|
||||
<article class="card ${current.flex < -0.001 ? 'bad' : 'good'} quick-flex-card">
|
||||
<div class="label">FLEX hours</div>
|
||||
<form id="quickFlexForm" class="quick-flex-form">
|
||||
<input id="quickFlexHours" type="number" step="0.25" value="${Number(state.settings.current_flex_hours ?? state.settings.opening_flex_hours ?? 0)}" aria-label="Current FLEX hours">
|
||||
<button type="submit" class="small">Save</button>
|
||||
</form>
|
||||
<div class="hint">Current, used from today</div>
|
||||
</article>
|
||||
<article class="card ${current.totalDays < -0.001 ? 'bad' : 'good'}">
|
||||
<div class="label">Total days</div>
|
||||
<div class="value">${days(current.totalDays)}</div>
|
||||
<div class="hint">Vacation + FF + FLEX</div>
|
||||
</article>
|
||||
`;
|
||||
$('quickFlexForm').addEventListener('submit', saveQuickFlex);
|
||||
}
|
||||
|
||||
function renderHeaderWarnings() {
|
||||
const warnings = state.plan.current.warnings;
|
||||
$('headerWarnings').innerHTML = warnings.length
|
||||
? warnings.map((warning) => `<span class="header-warning ${warning.level === 'bad' ? 'bad' : ''}">${escapeHtml(warning.text)}</span>`).join('')
|
||||
: '';
|
||||
}
|
||||
|
||||
function renderWarnings() {
|
||||
const warningsNode = $('warnings');
|
||||
if (!warningsNode) return;
|
||||
const warnings = state.plan.warnings;
|
||||
if (!warnings.length) {
|
||||
warningsNode.innerHTML = '<div class="warning good">No warnings. Your current plan looks safe.</div>';
|
||||
return;
|
||||
}
|
||||
warningsNode.innerHTML = warnings.map((warning) => `
|
||||
<div class="warning ${warning.level === 'bad' ? 'bad' : ''}">${escapeHtml(warning.text)}</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function renderEntries() {
|
||||
const tbody = $('entriesTable').querySelector('tbody');
|
||||
if (!state.entries.length) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="muted">No entries yet.</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = state.entries.map((entry) => {
|
||||
const summary = state.plan.entrySummaries[entry.id] || { workdays: 0, usedVacation: 0, usedFeriefridage: 0, usedFlex: 0, usedFlexDays: 0 };
|
||||
const source = sourceLabels[entry.source] || entry.source;
|
||||
return `
|
||||
<tr>
|
||||
<td><strong>${escapeHtml(entry.title)}</strong> <span class="muted">${escapeHtml(source)}</span><br><span class="muted entry-date">${escapeHtml(entry.start_date)} → ${escapeHtml(entry.end_date)}</span>${Number(entry.allow_unpaid) ? ' <span class="pill unpaid">unpaid</span>' : ''}</td>
|
||||
<td class="num strong-num">${days(summary.workdays)}</td>
|
||||
<td class="num">${days(summary.usedVacation)}</td>
|
||||
<td class="num">${days(summary.usedFeriefridage)}</td>
|
||||
<td class="num"><span title="${days(summary.usedFlexDays)} FLEX days">${hours(summary.usedFlex)}</span><br><span class="muted">${days(summary.usedFlexDays)}d</span></td>
|
||||
<td><span class="pill ${entry.status === 'approved' ? 'approved' : ''}">${escapeHtml(entry.status)}</span></td>
|
||||
<td>
|
||||
<div class="entry-actions">
|
||||
${entry.status === 'planned' ? `<button class="small" onclick="approveEntry(${entry.id})">Approve</button>` : ''}
|
||||
<button class="ghost small" onclick="editEntry(${entry.id})">Edit</button>
|
||||
<button class="danger small" onclick="deleteEntry(${entry.id})">Delete</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderPlanner() {
|
||||
$('planner').innerHTML = `
|
||||
<div class="table-wrap">
|
||||
<table class="month-table planner-body-table">
|
||||
<tbody>
|
||||
${state.plan.months.map(renderMonthRow).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
document.querySelectorAll('.correction-input').forEach((input) => {
|
||||
input.addEventListener('change', saveCorrection);
|
||||
});
|
||||
}
|
||||
|
||||
function renderMonthRow(month) {
|
||||
const balanceClass = month.availableDays < -0.001 ? 'bad-text' : 'good-text';
|
||||
const entries = month.entries.length
|
||||
? month.entries.map((item) => `
|
||||
<span class="month-entry">
|
||||
<strong>${escapeHtml(item.title)}</strong>
|
||||
<small class="planner-entry-meta"><strong>${days(item.workdays)} wd</strong> · ${days(item.usedVacation)} vd · ${days(item.usedFeriefridage)} ff · ${hours(item.usedFlex)} fl</small>
|
||||
<small class="planner-entry-dates">${escapeHtml(item.start_date)} → ${escapeHtml(item.end_date)}</small>
|
||||
</span>
|
||||
`).join('')
|
||||
: '<span class="muted">—</span>';
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td>${month.year} - ${monthNames[month.month - 1]}${month.expiredFeriefridage > 0 ? `<br><span class="warn-text">Expired FF: ${days(month.expiredFeriefridage)}</span>` : ''}</td>
|
||||
<td class="entries">${entries}</td>
|
||||
<td class="num ${month.vacationBalance < -0.001 ? 'bad-text' : ''}">${days(month.vacationBalance)}</td>
|
||||
<td class="num ${month.feriefridageBalance < -0.001 ? 'bad-text' : ''}">${days(month.feriefridageBalance)}</td>
|
||||
<td class="num ${month.flexBalance < -0.001 ? 'bad-text' : ''}">${hours(month.flexBalance)}</td>
|
||||
<td class="num correction-cell"><input class="correction-input" type="number" step="0.01" value="${Number(month.balanceCorrection || 0)}" data-year="${month.year}" data-month="${month.month}" aria-label="Correction for ${monthNames[month.month - 1]} ${month.year}"></td>
|
||||
<td class="num important-col ${balanceClass}">${days(month.availableDays)}</td>
|
||||
</tr>
|
||||
`;
|
||||
}
|
||||
|
||||
function calculatePlan(settings, entries, corrections = {}) {
|
||||
const startYear = Number(settings.planning_start_year || new Date().getFullYear());
|
||||
const startMonth = Number(settings.planning_start_month || 1);
|
||||
const monthCount = Number(settings.planning_months || (Number(settings.planning_years || 3) * 12));
|
||||
const startDate = dateFromParts(startYear, startMonth, 1);
|
||||
const endDate = dateFromParts(startYear, startMonth + monthCount, 0);
|
||||
const months = [];
|
||||
const warnings = [];
|
||||
const entrySummaries = {};
|
||||
const entriesById = new Map(entries.map((entry) => [entry.id, entry]));
|
||||
|
||||
let vacationBalance = Number(settings.opening_vacation_days || 0);
|
||||
let feriefridageBalance = Number(settings.opening_feriefridage_days || 0);
|
||||
let flexBalance = Number(settings.opening_flex_hours || 0);
|
||||
|
||||
const allWorkdays = [];
|
||||
for (const entry of entries) {
|
||||
const dates = workdaysBetween(entry.start_date, entry.end_date);
|
||||
entrySummaries[entry.id] = { workdays: dates.length, usedVacation: 0, usedFeriefridage: 0, usedFlex: 0, usedFlexDays: 0, usedUnpaid: 0 };
|
||||
for (const date of dates) {
|
||||
if (date < startDate || date > endDate) continue;
|
||||
allWorkdays.push({ date, entryId: entry.id });
|
||||
}
|
||||
}
|
||||
allWorkdays.sort((a, b) => a.date - b.date || a.entryId - b.entryId);
|
||||
|
||||
const workdaysByMonth = new Map();
|
||||
for (const item of allWorkdays) {
|
||||
const key = monthKey(item.date.getFullYear(), item.date.getMonth() + 1);
|
||||
if (!workdaysByMonth.has(key)) workdaysByMonth.set(key, []);
|
||||
workdaysByMonth.get(key).push(item);
|
||||
}
|
||||
|
||||
const avgDayHours = averageDayHours(settings);
|
||||
const today = dateFromParts(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate());
|
||||
const currentFlexHours = Number(settings.current_flex_hours ?? flexBalance);
|
||||
|
||||
for (let i = 0; i < monthCount; i++) {
|
||||
const cursor = dateFromParts(startYear, startMonth + i, 1);
|
||||
const year = cursor.getFullYear();
|
||||
const month = cursor.getMonth() + 1;
|
||||
const current = {
|
||||
year,
|
||||
month,
|
||||
earnedVacation: Number(settings.vacation_days_per_month || 0),
|
||||
balanceCorrection: correctionFor(corrections, year, month),
|
||||
grantedFeriefridage: month === 1 ? Number(settings.feriefridage_per_year || 0) : 0,
|
||||
expiredFeriefridage: 0,
|
||||
usedVacation: 0,
|
||||
usedFeriefridage: 0,
|
||||
usedFlex: 0,
|
||||
usedUnpaid: 0,
|
||||
vacationBalance: 0,
|
||||
feriefridageBalance: 0,
|
||||
flexBalance: 0,
|
||||
availableDays: 0,
|
||||
entries: [],
|
||||
};
|
||||
|
||||
vacationBalance += current.earnedVacation + current.balanceCorrection;
|
||||
feriefridageBalance += current.grantedFeriefridage;
|
||||
|
||||
if (month === Number(settings.feriefridage_expiry_month || 8) + 1 && feriefridageBalance > 0.001) {
|
||||
current.expiredFeriefridage = feriefridageBalance;
|
||||
warnings.push({ level: 'bad', text: `${days(feriefridageBalance)} feriefridage expired on 31 August ${year}. They must be used before that date.` });
|
||||
feriefridageBalance = 0;
|
||||
}
|
||||
|
||||
const key = monthKey(year, month);
|
||||
const monthItems = workdaysByMonth.get(key) || [];
|
||||
const isThisMonth = year === today.getFullYear() && month === today.getMonth() + 1;
|
||||
const applyWorkday = (item) => {
|
||||
const entry = entriesById.get(item.entryId);
|
||||
const allocation = allocateDay(entry, item.date, {
|
||||
vacationBalance,
|
||||
feriefridageBalance,
|
||||
flexBalance,
|
||||
}, settings);
|
||||
|
||||
vacationBalance = allocation.balances.vacationBalance;
|
||||
feriefridageBalance = allocation.balances.feriefridageBalance;
|
||||
flexBalance = allocation.balances.flexBalance;
|
||||
|
||||
current.usedVacation += allocation.usedVacation;
|
||||
current.usedFeriefridage += allocation.usedFeriefridage;
|
||||
current.usedFlex += allocation.usedFlex;
|
||||
current.usedUnpaid += allocation.usedUnpaid;
|
||||
|
||||
const summary = entrySummaries[entry.id];
|
||||
summary.usedVacation += allocation.usedVacation;
|
||||
summary.usedFeriefridage += allocation.usedFeriefridage;
|
||||
summary.usedFlex += allocation.usedFlex;
|
||||
summary.usedFlexDays += allocation.usedFlexDays;
|
||||
summary.usedUnpaid += allocation.usedUnpaid;
|
||||
|
||||
let monthEntry = current.entries.find((row) => row.id === entry.id);
|
||||
if (!monthEntry) {
|
||||
monthEntry = {
|
||||
id: entry.id,
|
||||
title: entry.title,
|
||||
source: sourceLabels[entry.source] || entry.source,
|
||||
start_date: entry.start_date,
|
||||
end_date: entry.end_date,
|
||||
workdays: 0,
|
||||
usedVacation: 0,
|
||||
usedFeriefridage: 0,
|
||||
usedFlex: 0,
|
||||
usedFlexDays: 0,
|
||||
};
|
||||
current.entries.push(monthEntry);
|
||||
}
|
||||
monthEntry.workdays += 1;
|
||||
monthEntry.usedVacation += allocation.usedVacation;
|
||||
monthEntry.usedFeriefridage += allocation.usedFeriefridage;
|
||||
monthEntry.usedFlex += allocation.usedFlex;
|
||||
monthEntry.usedFlexDays += allocation.usedFlexDays;
|
||||
};
|
||||
|
||||
if (isThisMonth) {
|
||||
monthItems.filter((item) => item.date <= today).forEach(applyWorkday);
|
||||
flexBalance = currentFlexHours;
|
||||
monthItems.filter((item) => item.date > today).forEach(applyWorkday);
|
||||
} else {
|
||||
monthItems.forEach(applyWorkday);
|
||||
}
|
||||
|
||||
if (month === Number(settings.feriefridage_expiry_month || 8) && feriefridageBalance > 0.001) {
|
||||
warnings.push({ level: 'warn', text: `${days(feriefridageBalance)} feriefridage remain at the end of August ${year}; they must be used before 31 August.` });
|
||||
}
|
||||
|
||||
current.vacationBalance = vacationBalance;
|
||||
current.feriefridageBalance = feriefridageBalance;
|
||||
current.flexBalance = flexBalance;
|
||||
current.availableDays = vacationBalance + feriefridageBalance + (flexBalance / avgDayHours);
|
||||
months.push(current);
|
||||
|
||||
if (vacationBalance < -0.001) {
|
||||
warnings.push({ level: 'bad', text: `Vacation balance is negative in ${monthNames[month - 1]} ${year}: ${days(vacationBalance)} days.` });
|
||||
}
|
||||
if (feriefridageBalance < -0.001) {
|
||||
warnings.push({ level: 'bad', text: `Feriefridage balance is negative in ${monthNames[month - 1]} ${year}: ${days(feriefridageBalance)} days.` });
|
||||
}
|
||||
if (flexBalance < -0.001) {
|
||||
warnings.push({ level: 'bad', text: `FLEX balance is negative in ${monthNames[month - 1]} ${year}: ${hours(flexBalance)}.` });
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const summary = entrySummaries[entry.id];
|
||||
if (!summary) continue;
|
||||
if (summary.usedUnpaid > 0.001) {
|
||||
warnings.push({ level: 'warn', text: `${entry.title}: ${days(summary.usedUnpaid)} unpaid days are used because unpaid fallback is enabled for that date range.` });
|
||||
}
|
||||
}
|
||||
|
||||
const totalDays = vacationBalance + feriefridageBalance + (flexBalance / avgDayHours);
|
||||
return {
|
||||
months,
|
||||
warnings: dedupeWarnings(warnings),
|
||||
current: calculateCurrentSnapshot(settings, entries, corrections),
|
||||
entrySummaries,
|
||||
final: { vacation: vacationBalance, feriefridage: feriefridageBalance, flex: flexBalance, totalDays },
|
||||
};
|
||||
}
|
||||
|
||||
function calculateCurrentSnapshot(settings, entries, corrections = {}) {
|
||||
const today = dateFromParts(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate());
|
||||
const startYear = Number(settings.planning_start_year || today.getFullYear());
|
||||
const startMonth = Number(settings.planning_start_month || 1);
|
||||
const startDate = dateFromParts(startYear, startMonth, 1);
|
||||
const avgDayHours = averageDayHours(settings);
|
||||
const warnings = [];
|
||||
|
||||
let vacationBalance = Number(settings.opening_vacation_days || 0);
|
||||
let feriefridageBalance = Number(settings.opening_feriefridage_days || 0);
|
||||
let flexBalance = Number(settings.opening_flex_hours || 0);
|
||||
const currentFlexHours = Number(settings.current_flex_hours ?? flexBalance);
|
||||
|
||||
if (today < startDate) {
|
||||
flexBalance = currentFlexHours;
|
||||
const totalDays = vacationBalance + feriefridageBalance + (flexBalance / avgDayHours);
|
||||
return { vacation: vacationBalance, feriefridage: feriefridageBalance, flex: flexBalance, totalDays, warnings };
|
||||
}
|
||||
|
||||
const workdays = [];
|
||||
for (const entry of entries) {
|
||||
for (const date of workdaysBetween(entry.start_date, entry.end_date)) {
|
||||
if (date >= startDate && date <= today) workdays.push({ date, entry });
|
||||
}
|
||||
}
|
||||
workdays.sort((a, b) => a.date - b.date || a.entry.id - b.entry.id);
|
||||
|
||||
let workdayIndex = 0;
|
||||
const monthCount = ((today.getFullYear() - startYear) * 12) + (today.getMonth() + 1 - startMonth) + 1;
|
||||
for (let i = 0; i < monthCount; i++) {
|
||||
const cursor = dateFromParts(startYear, startMonth + i, 1);
|
||||
const year = cursor.getFullYear();
|
||||
const month = cursor.getMonth() + 1;
|
||||
|
||||
vacationBalance += Number(settings.vacation_days_per_month || 0) + correctionFor(corrections, year, month);
|
||||
if (month === 1) feriefridageBalance += Number(settings.feriefridage_per_year || 0);
|
||||
|
||||
if (month === Number(settings.feriefridage_expiry_month || 8) + 1 && feriefridageBalance > 0.001) {
|
||||
feriefridageBalance = 0;
|
||||
}
|
||||
|
||||
const monthStart = dateFromParts(year, month, 1);
|
||||
const monthEnd = dateFromParts(year, month + 1, 0);
|
||||
const limit = today < monthEnd ? today : monthEnd;
|
||||
while (workdayIndex < workdays.length && workdays[workdayIndex].date >= monthStart && workdays[workdayIndex].date <= limit) {
|
||||
const item = workdays[workdayIndex++];
|
||||
const allocation = allocateDay(item.entry, item.date, { vacationBalance, feriefridageBalance, flexBalance }, settings);
|
||||
vacationBalance = allocation.balances.vacationBalance;
|
||||
feriefridageBalance = allocation.balances.feriefridageBalance;
|
||||
flexBalance = allocation.balances.flexBalance;
|
||||
}
|
||||
}
|
||||
|
||||
flexBalance = currentFlexHours;
|
||||
|
||||
if (vacationBalance < -0.001) warnings.push({ level: 'bad', text: `Vacation balance is negative today: ${days(vacationBalance)} days.` });
|
||||
if (feriefridageBalance < -0.001) warnings.push({ level: 'bad', text: `Feriefridage balance is negative today: ${days(feriefridageBalance)} days.` });
|
||||
if (flexBalance < -0.001) warnings.push({ level: 'bad', text: `FLEX balance is negative today: ${hours(flexBalance)}.` });
|
||||
if (today.getMonth() + 1 <= Number(settings.feriefridage_expiry_month || 8) && feriefridageBalance > 0.001) {
|
||||
warnings.push({ level: 'warn', text: `${days(feriefridageBalance)} feriefridage must be used before 31 August.` });
|
||||
}
|
||||
|
||||
const totalDays = vacationBalance + feriefridageBalance + (flexBalance / avgDayHours);
|
||||
return { vacation: vacationBalance, feriefridage: feriefridageBalance, flex: flexBalance, totalDays, warnings: dedupeWarnings(warnings) };
|
||||
}
|
||||
|
||||
function allocateDay(entry, date, balances, settings) {
|
||||
const source = entry.source;
|
||||
const allowUnpaid = Boolean(Number(entry.allow_unpaid));
|
||||
const dayHours = hoursForDate(date, settings);
|
||||
let { vacationBalance, feriefridageBalance, flexBalance } = balances;
|
||||
const result = { usedVacation: 0, usedFeriefridage: 0, usedFlex: 0, usedFlexDays: 0, usedUnpaid: 0 };
|
||||
|
||||
const useVacation = () => {
|
||||
if (allowUnpaid && vacationBalance < 1) {
|
||||
const use = Math.max(0, vacationBalance);
|
||||
result.usedVacation += use;
|
||||
result.usedUnpaid += 1 - use;
|
||||
vacationBalance = 0;
|
||||
} else {
|
||||
result.usedVacation += 1;
|
||||
vacationBalance -= 1;
|
||||
}
|
||||
};
|
||||
|
||||
const useFeriefridag = () => {
|
||||
if (allowUnpaid && feriefridageBalance < 1) {
|
||||
const use = Math.max(0, feriefridageBalance);
|
||||
result.usedFeriefridage += use;
|
||||
result.usedUnpaid += 1 - use;
|
||||
feriefridageBalance = 0;
|
||||
} else {
|
||||
result.usedFeriefridage += 1;
|
||||
feriefridageBalance -= 1;
|
||||
}
|
||||
};
|
||||
|
||||
const useFlex = () => {
|
||||
if (allowUnpaid && flexBalance < dayHours) {
|
||||
const useHours = Math.max(0, flexBalance);
|
||||
result.usedFlex += useHours;
|
||||
result.usedFlexDays += useHours / dayHours;
|
||||
result.usedUnpaid += 1 - (useHours / dayHours);
|
||||
flexBalance = 0;
|
||||
} else {
|
||||
result.usedFlex += dayHours;
|
||||
result.usedFlexDays += 1;
|
||||
flexBalance -= dayHours;
|
||||
}
|
||||
};
|
||||
|
||||
if (source === 'unpaid') {
|
||||
result.usedUnpaid = 1;
|
||||
} else if (source === 'vacation') {
|
||||
useVacation();
|
||||
} else if (source === 'feriefridag') {
|
||||
useFeriefridag();
|
||||
} else if (source === 'flex') {
|
||||
useFlex();
|
||||
} else {
|
||||
if (feriefridageBalance >= 1 && isBeforeFeriefridageExpiry(date, settings)) {
|
||||
useFeriefridag();
|
||||
} else if (vacationBalance >= 1) {
|
||||
useVacation();
|
||||
} else if (flexBalance >= dayHours) {
|
||||
useFlex();
|
||||
} else if (allowUnpaid) {
|
||||
const use = Math.max(0, vacationBalance);
|
||||
result.usedVacation += use;
|
||||
result.usedUnpaid += 1 - use;
|
||||
vacationBalance = 0;
|
||||
} else {
|
||||
useVacation();
|
||||
}
|
||||
}
|
||||
|
||||
return { ...result, balances: { vacationBalance, feriefridageBalance, flexBalance } };
|
||||
}
|
||||
|
||||
function isBeforeFeriefridageExpiry(date, settings) {
|
||||
return date.getMonth() + 1 <= Number(settings.feriefridage_expiry_month || 8);
|
||||
}
|
||||
|
||||
function workdaysBetween(start, end) {
|
||||
const days = [];
|
||||
let current = parseDate(start);
|
||||
const stop = parseDate(end);
|
||||
while (current <= stop) {
|
||||
const dow = current.getDay();
|
||||
if (dow >= 1 && dow <= 5) days.push(new Date(current));
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
return days;
|
||||
}
|
||||
|
||||
function hoursForDate(date, settings) {
|
||||
return date.getDay() === 5 ? Number(settings.friday_hours || 7) : Number(settings.normal_day_hours || 7.5);
|
||||
}
|
||||
|
||||
function averageDayHours(settings) {
|
||||
return ((Number(settings.normal_day_hours || 7.5) * 4) + Number(settings.friday_hours || 7)) / 5;
|
||||
}
|
||||
|
||||
function dateFromParts(year, month, day) {
|
||||
return new Date(year, month - 1, day, 12, 0, 0);
|
||||
}
|
||||
|
||||
function parseDate(value) {
|
||||
const [year, month, day] = value.split('-').map(Number);
|
||||
return dateFromParts(year, month, day);
|
||||
}
|
||||
|
||||
function monthKey(year, month) {
|
||||
return `${year}-${String(month).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function correctionFor(corrections, year, month) {
|
||||
return Number(corrections[monthKey(year, month)] || 0);
|
||||
}
|
||||
|
||||
function normalizeEntry(entry) {
|
||||
return {
|
||||
...entry,
|
||||
id: Number(entry.id),
|
||||
allow_unpaid: Number(entry.allow_unpaid),
|
||||
status: entry.status === 'confirmed' ? 'approved' : entry.status,
|
||||
};
|
||||
}
|
||||
|
||||
function days(value) {
|
||||
return formatNumber(value, 2);
|
||||
}
|
||||
|
||||
function hours(value) {
|
||||
return `${formatNumber(value, 2)}h`;
|
||||
}
|
||||
|
||||
function formatNumber(value, decimals = 2) {
|
||||
const n = Number(value || 0);
|
||||
const rounded = Math.round((n + Number.EPSILON) * Math.pow(10, decimals)) / Math.pow(10, decimals);
|
||||
return new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: decimals }).format(rounded);
|
||||
}
|
||||
|
||||
function dedupeWarnings(warnings) {
|
||||
const seen = new Set();
|
||||
return warnings.filter((warning) => {
|
||||
if (seen.has(warning.text)) return false;
|
||||
seen.add(warning.text);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>'"]/g, (char) => ({
|
||||
'&': '&', '<': '<', '>': '>', "'": ''', '"': '"'
|
||||
}[char]));
|
||||
}
|
||||
|
||||
function toast(message) {
|
||||
const node = $('toast');
|
||||
node.textContent = message;
|
||||
node.classList.remove('hidden');
|
||||
clearTimeout(toast.timer);
|
||||
toast.timer = setTimeout(() => node.classList.add('hidden'), 2200);
|
||||
}
|
||||
|
||||
window.editEntry = editEntry;
|
||||
window.approveEntry = approveEntry;
|
||||
window.deleteEntry = deleteEntry;
|
||||
Loading…
Add table
Add a link
Reference in a new issue