with open('app/modules/sag/templates/detail.html', 'r', encoding='utf-8') as f:
text = f.read()
# 1. Timeline Layout & CSS
css_start = text.find('.time-v1-global-timeline {')
if css_start == -1:
css_start = text.find('.time-v1-calendar-container {')
if css_start != -1:
css_end = text.find('', css_start)
css_new = """
.time-v1-calendar-container {
background: var(--bg-surface, #fff);
border: 1px solid var(--border-color, #e0e0e0);
border-radius: 12px;
margin-bottom: 2rem;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.03);
}
.time-v1-calendar-header {
background: var(--bg-element, #f8f9fa);
border-bottom: 1px solid var(--border-color, #e0e0e0);
padding: 12px 20px;
font-weight: 600;
font-size: 1rem;
display: flex;
align-items: center;
gap: 8px;
color: var(--text-color);
}
.time-v1-calendar-grid {
display: flex;
position: relative;
overflow-x: auto;
}
.time-v1-time-axis {
width: 60px;
flex-shrink: 0;
border-right: 1px solid var(--border-color, #f0f0f0);
position: relative;
background: var(--bg-element, #fafafa);
padding-top: 40px;
}
.time-v1-hour-marker {
position: absolute;
width: 100%;
text-align: center;
font-size: 0.75rem;
color: var(--text-secondary);
transform: translateY(-50%);
}
.time-v1-tech-col {
flex: 1;
min-width: 250px;
border-right: 1px solid var(--border-color, #f0f0f0);
position: relative;
}
.time-v1-tech-col:last-child {
border-right: none;
}
.time-v1-tech-header {
text-align: center;
padding: 8px;
height: 40px;
font-weight: 600;
font-size: 0.85rem;
border-bottom: 1px solid var(--border-color, #e0e0e0);
background: var(--bg-element, #f8f9fa);
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
position: sticky;
top: 0;
z-index: 50;
color: var(--text-color);
}
.time-v1-tech-body {
position: relative;
height: 600px; /* 10h * 60Px = 600px */
background-image: linear-gradient(to bottom, transparent 59px, var(--border-color, #f0f0f0) 60px);
background-size: 100% 60px;
}
.time-v1-entry-block {
position: absolute;
left: 4px;
right: 4px;
border-radius: 6px;
padding: 6px 8px;
font-size: 0.8rem;
overflow: hidden;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
transition: transform 0.2s, box-shadow 0.2s, z-index 0.2s;
border-left: 4px solid var(--bs-secondary);
background: var(--bg-surface, #fff);
cursor: grab;
z-index: 10;
}
.time-v1-entry-block:active { cursor: grabbing; opacity: 0.9; }
.time-v1-entry-block:hover {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0,0,0,0.15);
z-index: 20;
}
.time-v1-entry-pending { border-left-color: #f59e0b; background: rgba(245, 158, 11, 0.05) !important; }
.time-v1-entry-godkendt { border-left-color: #2fb344; background: rgba(47, 179, 68, 0.05) !important; }
.time-v1-entry-kladde { border-left-color: #6c757d; background: rgba(108, 117, 125, 0.05) !important; }
.time-v1-entry-time {
font-weight: 600;
font-size: 0.75rem;
margin-bottom: 2px;
color: var(--text-color);
}
.time-v1-entry-desc {
color: var(--text-secondary);
font-size: 0.75rem;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.time-v1-unplaced-container {
padding: 12px 20px;
border-top: 1px solid var(--border-color);
background: var(--bg-element);
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.time-v1-unplaced-item {
background: var(--bg-surface);
border: 1px solid var(--border-color);
padding: 4px 10px;
border-radius: 20px;
font-size: 0.8rem;
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--text-color);
}
"""
if css_end != -1:
text = text[:css_start] + css_new + text[css_end:]
print("CSS applied.")
js_start = text.find('function renderTimeV1Timeline(entries) {')
js_end = text.find('async function loadTimeTrackingTab() {', js_start)
js_new = """function renderTimeV1Timeline(entries) {
const timeline = document.getElementById('timeTimelineColumns');
if (!timeline) return;
if (!entries || entries.length === 0) {
timeline.innerHTML = '
Ingen tidsregistreringer endnu
';
return;
}
const START_HOUR = 7;
const TOTAL_HOURS = 10; // 07:00 to 17:00
const HOUR_HEIGHT = 60; // px
const groupedByDate = {};
entries.forEach((entry) => {
let dateKey = 'Ukendt dato';
if (entry.start_tid) {
dateKey = entry.start_tid.split('T')[0];
} else if (entry.worked_date) {
dateKey = entry.worked_date;
} else if (entry.created_at) {
dateKey = entry.created_at.split('T')[0];
}
// Keep only first 10 chars for proper grouping if it's an ISO timestamp
if (dateKey.length > 10) dateKey = dateKey.substring(0, 10);
if (!groupedByDate[dateKey]) groupedByDate[dateKey] = [];
groupedByDate[dateKey].push(entry);
});
const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a));
let html = '';
sortedDates.forEach(dateStr => {
const dayEntries = groupedByDate[dateStr];
let formattedDateLab = dateStr;
try {
const d = new Date(dateStr);
if (!isNaN(d.getTime())) {
formattedDateLab = d.toLocaleDateString('da-DK', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
formattedDateLab = formattedDateLab.charAt(0).toUpperCase() + formattedDateLab.slice(1);
}
} catch(e){}
const techs = {};
const unplaced = [];
dayEntries.forEach(entry => {
const tech = entry.bruger_navn || entry.user_name || 'Ukendt';
if (!techs[tech]) techs[tech] = [];
if (!entry.start_tid || entry.start_tid === null) {
unplaced.push(entry);
} else {
techs[tech].push(entry);
}
});
const techNames = Object.keys(techs).sort();
html += `
`;
for (let i = 0; i <= TOTAL_HOURS; i++) {
const h = START_HOUR + i;
const top = i * HOUR_HEIGHT;
html += `
${h.toString().padStart(2, '0')}:00
`;
}
html += `
`;
techNames.forEach(tech => {
html += `
`;
techs[tech].forEach(entry => {
const desc = escapeHtml(entry.beskrivelse || entry.description || 'Ingen beskrivelse');
const status = entry.entry_status || entry.status || 'kladde';
let cssClass = 'time-v1-entry-kladde';
if (status === 'afventer' || status === 'pending') cssClass = 'time-v1-entry-pending';
if (status === 'godkendt' || status === 'billed' || status === 'approved' || entry.fakturerbar_tid_min > 0) cssClass = 'time-v1-entry-godkendt';
const startObj = new Date(entry.start_tid);
let durationMin = 30; // default length
if (entry.faktisk_tid_min) {
durationMin = parseInt(entry.faktisk_tid_min);
} else if (entry.original_hours || entry.timer) {
durationMin = Math.round(parseFloat(entry.original_hours || entry.timer) * 60);
}
let startH = startObj.getHours();
let startM = startObj.getMinutes();
if (startH < START_HOUR) {
durationMin -= ((START_HOUR * 60) - (startH * 60 + startM));
startH = START_HOUR;
startM = 0;
}
let topPx = ((startH - START_HOUR) + (startM / 60)) * HOUR_HEIGHT;
let heightPx = (durationMin / 60) * HOUR_HEIGHT;
if (topPx < 0) topPx = 0;
if (topPx + heightPx > TOTAL_HOURS * HOUR_HEIGHT) {
heightPx = (TOTAL_HOURS * HOUR_HEIGHT) - topPx;
}
if (heightPx > 5 && topPx < TOTAL_HOURS * HOUR_HEIGHT) {
const endObj = new Date(startObj.getTime() + durationMin * 60000);
const timeStr = `${startObj.getHours().toString().padStart(2,'0')}:${startObj.getMinutes().toString().padStart(2,'0')} - ${endObj.getHours().toString().padStart(2,'0')}:${endObj.getMinutes().toString().padStart(2,'0')}`;
html += `
`;
}
});
html += `
`;
});
html += `
`;
if (unplaced.length > 0) {
html += `
Uden tidsrum:
`;
unplaced.forEach(u => {
const userName = escapeHtml(u.bruger_navn || u.user_name || 'Ukendt');
const hrs = u.original_hours || u.timer || 0;
html += `
${userName} • ${hrs}t
`;
});
html += `
`;
}
html += `
`;
});
timeline.innerHTML = html;
}
"""
if js_start != -1 and js_end != -1:
text = text[:js_start] + js_new + text[js_end:]
print("Timeline JS applied.")
# 2. timeManualFormV1 update
tf1_start = text.find('"""
if tf1_start != -1 and tf1_end != -1:
text = text[:tf1_start] + new_tf1 + text[tf1_end:]
print("timeManualFormV1 applied")
tf1_js_s = text.find('async function createManualTimeV1(event) {')
tf1_js_e = text.find(' document.addEventListener(\'DOMContentLoaded\'', tf1_js_s)
new_tf1_js = """function bindTimeV1Calculations() {
const startIn = document.getElementById('timeV1Start');
const endIn = document.getElementById('timeV1End');
const minIn = document.getElementById('timeV1Minutes');
if (!startIn || !endIn || !minIn) return;
const parseTime = (val) => {
if (!val) return null;
const [h,m] = val.split(':').map(Number);
return (h * 60) + m;
};
const toTimeStr = (totalMins) => {
const h = Math.floor(totalMins / 60) % 24;
const m = totalMins % 60;
return `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}`;
};
const recalculate = (trigger) => {
const s = parseTime(startIn.value);
const e = parseTime(endIn.value);
const dur = parseInt(minIn.value);
if (trigger === 'start' || trigger === 'end') {
if (s !== null && e !== null) {
let diff = e - s;
if (diff < 0) diff += 24*60;
minIn.value = diff;
} else if (s !== null && !isNaN(dur) && dur > 0 && !endIn.value) {
endIn.value = toTimeStr(s + dur);
} else if (e !== null && !isNaN(dur) && dur > 0 && !startIn.value) {
let base = e - dur;
while (base < 0) base += 24*60;
startIn.value = toTimeStr(base);
}
} else if (trigger === 'min') {
if (s !== null && !isNaN(dur) && dur > 0) {
endIn.value = toTimeStr(s + dur);
} else if (e !== null && !isNaN(dur) && dur > 0 && !startIn.value) {
let base = e - dur;
while(base < 0) base+=24*60;
startIn.value = toTimeStr(base);
}
}
};
startIn.addEventListener('change', () => recalculate('start'));
endIn.addEventListener('change', () => recalculate('end'));
minIn.addEventListener('input', () => recalculate('min'));
}
async function createManualTimeV1(event) {
event.preventDefault();
const minutes = Number(document.getElementById('timeV1Minutes')?.value || 0);
if (minutes <= 0) {
alert('Indtast minutter over 0');
return;
}
const dateVal = document.getElementById('timeV1Date')?.value || null;
const tStart = document.getElementById('timeV1Start')?.value;
const tEnd = document.getElementById('timeV1End')?.value;
let startObj = null;
let endObj = null;
if (dateVal && tStart) {
try {
const l = new Date(`${dateVal}T${tStart}:00`);
startObj = l.toISOString();
} catch(e){}
}
if (dateVal && tEnd) {
try {
const l = new Date(`${dateVal}T${tEnd}:00`);
if (startObj && new Date(startObj) > l) {
l.setDate(l.getDate() + 1);
}
endObj = l.toISOString();
} catch(e){}
}
const payload = {
sag_id: timeCaseId,
medarbejder_id: getTimeV1EmployeeId(),
faktisk_tid_min: minutes,
worked_date: dateVal,
entry_type: document.getElementById('timeV1Type')?.value || 'manuel',
entry_status: document.getElementById('timeV1Status')?.value || 'afventer',
beskrivelse: document.getElementById('timeV1Description')?.value || null,
kilde: 'manuel',
start_tid: startObj,
slut_tid: endObj
};
try {
const res = await fetch('/api/v1/timetracking/time/manual', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) throw new Error(await res.text());
const minutesInput = document.getElementById('timeV1Minutes');
const descInput = document.getElementById('timeV1Description');
const startIn = document.getElementById('timeV1Start');
const endIn = document.getElementById('timeV1End');
if (minutesInput) minutesInput.value = '';
if (descInput) descInput.value = '';
if (startIn) startIn.value = '';
if (endIn) endIn.value = '';
await loadTimeTrackingTab();
} catch (error) {
alert('Kunne ikke oprette tidsregistrering: ' + (error.message || 'ukendt fejl'));
}
}
\n"""
if tf1_js_s != -1 and tf1_js_e != -1:
text = text[:tf1_js_s] + new_tf1_js + text[tf1_js_e:]
print("createManualTimeV1 js applied.")
# Inject bindTimeV1Calculations in DOMContentLoaded (lines 6830ish)
# We find: document.addEventListener('DOMContentLoaded', () => {
# const dateInput = document.getElementById('timeV1Date');
dom_inject = """document.addEventListener('DOMContentLoaded', () => {
bindTimeV1Calculations();
const dateInput = document.getElementById('timeV1Date');"""
text = text.replace("document.addEventListener('DOMContentLoaded', () => {\n const dateInput = document.getElementById('timeV1Date');", dom_inject)
# 3. Modal timeForm Update
mhtml_start = text.find('', mhtml_start) + 7
new_mhtml = """"""
if mhtml_start != -1 and mhtml_end != -1:
text = text[:mhtml_start] + new_mhtml + text[mhtml_end:]
print("timeForm modal html applied.")
# Replace saveTime to send start_tid / slut_tid using the new fields
old_save_time_start = text.find('async function saveTime() {')
if old_save_time_start != -1:
# Safely find the end of saveTime function body
bracket_count = 0
in_function = False
old_save_time_end = -1
for i in range(old_save_time_start, len(text)):
if text[i] == '{':
bracket_count += 1
in_function = True
elif text[i] == '}':
bracket_count -= 1
if in_function and bracket_count == 0:
old_save_time_end = i + 1
break
if old_save_time_end != -1:
new_save_time_js = """ function bindTimeModalCalculations() {
const startIn = document.getElementById('time_start_input');
const endIn = document.getElementById('time_end_input');
const minIn = document.getElementById('time_total_minutes');
if (!startIn || !endIn || !minIn) return;
const parseTime = (val) => {
if (!val) return null;
const [h,m] = val.split(':').map(Number);
return (h * 60) + m;
};
const toTimeStr = (totalMins) => {
const h = Math.floor(totalMins / 60) % 24;
const m = totalMins % 60;
return `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}`;
};
const recalculate = (trigger) => {
const s = parseTime(startIn.value);
const e = parseTime(endIn.value);
const dur = parseInt(minIn.value);
if (trigger === 'start' || trigger === 'end') {
if (s !== null && e !== null) {
let diff = e - s;
if (diff < 0) diff += 24*60;
minIn.value = diff;
} else if (s !== null && !isNaN(dur) && dur > 0 && !endIn.value) {
endIn.value = toTimeStr(s + dur);
} else if (e !== null && !isNaN(dur) && dur > 0 && !startIn.value) {
let base = e - dur;
while (base < 0) base += 24*60;
startIn.value = toTimeStr(base);
}
} else if (trigger === 'min') {
if (s !== null && !isNaN(dur) && dur > 0) {
endIn.value = toTimeStr(s + dur);
} else if (e !== null && !isNaN(dur) && dur > 0 && !startIn.value) {
let base = e - dur;
while(base < 0) base+=24*60;
startIn.value = toTimeStr(base);
}
}
};
startIn.addEventListener('change', () => recalculate('start'));
endIn.addEventListener('change', () => recalculate('end'));
minIn.addEventListener('input', () => recalculate('min'));
}
document.addEventListener('DOMContentLoaded', bindTimeModalCalculations);
async function saveTime() {
const mInput = document.getElementById('time_total_minutes');
const minVal = parseInt(mInput ? mInput.value : 0);
if (!minVal || minVal <= 0) {
alert('Indtast en gyldig varighed (minutter).');
return;
}
const totalHours = minVal / 60;
const dateVal = document.getElementById('time_date').value;
// extract optional start/end limits
const tStart = document.getElementById('time_start_input')?.value;
const tEnd = document.getElementById('time_end_input')?.value;
let startObj = null;
let endObj = null;
if (dateVal && tStart) {
try {
const l = new Date(`${dateVal}T${tStart}:00`);
startObj = l.toISOString();
} catch(e){}
}
if (dateVal && tEnd) {
try {
const l = new Date(`${dateVal}T${tEnd}:00`);
if (startObj && new Date(startObj) > l) {
l.setDate(l.getDate() + 1);
}
endObj = l.toISOString();
} catch(e){}
}
const sagId = document.getElementById('time_sag_id').value;
const payload = {
sag_id: parseInt(sagId),
// Note: saveTime modal expects 'timer' as totalHours currently, let's keep compatibility:
timer: totalHours,
faktisk_tid_min: minVal,
worked_date: dateVal,
start_tid: startObj,
slut_tid: endObj,
description: document.getElementById('time_desc').value,
work_type: document.getElementById('time_work_type').value,
billing_method: document.getElementById('time_billing_method').value
};
try {
const res = await fetch(`/api/v1/cases/${sagId}/time`, {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(payload)
});
if(res.ok) {
window.location.reload();
} else {
alert("Fejl ved registrering af tid");
}
} catch(err) {
console.error(err);
alert("Forbindelsesfejl");
}
}"""
text = text[:old_save_time_start] + new_save_time_js + text[old_save_time_end:]
print("saveTime js logic replaced.")
# We also need to fix `showAddTimeModal()` reset fields:
show_add_modal = text.find('if(document.getElementById(\'time_hours_input\')) {')
show_add_modal_end = text.find('}', show_add_modal) + 1
if show_add_modal != -1:
new_reset = """if(document.getElementById('time_total_minutes')) {
document.getElementById('time_total_minutes').value = '';
document.getElementById('time_start_input').value = '';
document.getElementById('time_end_input').value = '';
}"""
text = text[:show_add_modal] + new_reset + text[show_add_modal_end:]
# And delete old 'updateTimeTotal()' function
old_update_tot_s = text.find('function updateTimeTotal() {')
if old_update_tot_s != -1:
old_update_tot_e = text.find('}', text.find('}', old_update_tot_s) + 1) + 1
# We'll just comment it out to avoid bracket mess tracking
if text[old_update_tot_e-1] == '}':
text = text[:old_update_tot_s] + "/* removed updateTimeTotal */\n" + text[old_update_tot_e:]
with open('app/modules/sag/templates/detail.html', 'w', encoding='utf-8') as f:
f.write(text)
print("Done writing to file safely.")