fix(zeiterfassung): mark today, honest interim reports, approver feedback

Submitter side:
- Month grid now marks TODAY (Europe/Zurich) with a filled day-badge +
  ring + aria-current; it was invisible before (focus sat on the 1st).
- Absence requests now confirm on submit ("Antrag eingereicht — wartet auf
  Genehmigung") instead of silently clearing the form.

Monatsrapport:
- A running month reports AS OF today, not month-end — pre-filled future
  days no longer show as "worked" and Soll/Ist/Saldo match the live
  dashboard. Interim sheets are labelled "Zwischenstand per <date>" and note
  how many planned days are still excluded.
- Drop the internal "Aus offiziellem Standardschedule" marker from the
  Bemerkung column so only real remarks show on the document.

Approver side:
- Single approve/reject/reopen/edit now show a positive acknowledgement in
  the review drawer (was silent) and the drawer stays open on the just-acted
  card — no more hunting for what you approved.
- Add a Monatsrapport link in the drawer (footer + after approval) — the
  concrete next step for sending the sheet to the social worker.

Companion data fix applied on prod: Georgy's Pensum reconciled to the
Arbeitsplan (21h) and the unsourced −37h opening zeroed, so the saldo no
longer manufactures a deficit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mao NakamotoandClaude Fable 5 committed 2026-07-20 17:54:34 +02:00
1 parent 29d73cae36
commit 38d4ce4dec
5 files changed
+129 -36

No files matched your search

@@ -16,6 +16,7 @@ import { canAccessSection } from '@/lib/permissions'
import { getMonthlyReport, REPORT_MONTH_REGEX } from '@/lib/services/report'
import { getTimecardMonthLabel } from '@/lib/team/timecard-period-label'
import { getDisplayDate } from '@/lib/team/timecard-utils'
import { SCHEDULE_FILL_DESCRIPTION } from '@/lib/team/schedule'
import { formatTimecardDuration, getTimecardEntryCategoryLabel, getTimecardStatusLabel, isAbsenceCategory } from '@/config/timecards'
import { ORG, LOCATIONS } from '@/config/org'
import { PrintButton } from './PrintButton'
@@ -45,7 +46,12 @@ export default async function MonthlyReportPage({
if (!report) notFound()
const monthLabel = getTimecardMonthLabel(`${month}-01`)
const entries = report.card?.entries ?? []
// Only days up to the as-of date are "worked" — a running month must not
// present pre-filled future days as done (they'd also inflate the totals).
const allEntries = report.card?.entries ?? []
const entries = allEntries.filter(e => e.work_date <= report.asOfDate)
const futureCount = allEntries.length - entries.length
const asOfLabel = getDisplayDate(report.asOfDate)
const workedMinutes = entries.filter(e => !isAbsenceCategory(e.category)).reduce((s, e) => s + e.duration_minutes, 0)
const absenceMinutes = entries.filter(e => isAbsenceCategory(e.category)).reduce((s, e) => s + e.duration_minutes, 0)
const absenceDaysByCategory = new Map<string, number>()
@@ -72,6 +78,11 @@ export default async function MonthlyReportPage({
<p className="mt-2 text-lg font-semibold text-text-primary">
Monatsrapport Arbeitszeit — {monthLabel}
</p>
{report.isInterim && (
<p className="mt-1 text-sm font-medium text-warning-700 dark:text-warning-400">
Zwischenstand per {asOfLabel} — der Monat läuft noch; Zahlen bis zu diesem Tag.
</p>
)}
</header>
{/* Person + status */}
@@ -88,15 +99,15 @@ export default async function MonthlyReportPage({
{/* Summary */}
<section className="grid grid-cols-2 gap-2 rounded-lg border border-neutral-300 p-4 text-sm sm:grid-cols-4 print:border-black">
<div>
<p className="text-xs uppercase tracking-wide text-text-tertiary">Soll (Monat)</p>
<p className="text-xs uppercase tracking-wide text-text-tertiary">Soll {report.isInterim ? `(bis ${asOfLabel})` : '(Monat)'}</p>
<p className="font-mono font-semibold">{report.saldo ? formatTimecardDuration(report.saldo.time.monthSollMinutes) : '—'}</p>
</div>
<div>
<p className="text-xs uppercase tracking-wide text-text-tertiary">Ist (Monat)</p>
<p className="text-xs uppercase tracking-wide text-text-tertiary">Ist {report.isInterim ? `(bis ${asOfLabel})` : '(Monat)'}</p>
<p className="font-mono font-semibold">{report.saldo ? formatTimecardDuration(report.saldo.time.monthIstMinutes) : formatTimecardDuration(workedMinutes + absenceMinutes)}</p>
</div>
<div>
<p className="text-xs uppercase tracking-wide text-text-tertiary">Zeitsaldo (Ende Monat)</p>
<p className="text-xs uppercase tracking-wide text-text-tertiary">Zeitsaldo {report.isInterim ? `(per ${asOfLabel})` : '(Ende Monat)'}</p>
<p className="font-mono font-semibold">
{report.saldo
? `${report.saldo.time.saldoMinutes < 0 ? '−' : '+'}${formatTimecardDuration(Math.abs(report.saldo.time.saldoMinutes))}`
@@ -145,11 +156,18 @@ export default async function MonthlyReportPage({
{e.start_time && e.end_time ? `${e.start_time}–${e.end_time}${e.break_minutes ? ` (${e.break_minutes}′ Pause)` : ''}` : '—'}
</td>
<td className="py-1 pr-2 text-right font-mono tabular-nums">{formatTimecardDuration(e.duration_minutes)}</td>
<td className="py-1 text-text-secondary">{e.description ?? ''}</td>
{/* The plan-fill source marker is internal noise on a document —
show only genuine, hand-written remarks. */}
<td className="py-1 text-text-secondary">{e.description === SCHEDULE_FILL_DESCRIPTION ? '' : (e.description ?? '')}</td>
</tr>
))}
</tbody>
</table>
{futureCount > 0 && (
<p className="mt-2 text-xs text-text-tertiary">
{futureCount} geplante {futureCount === 1 ? 'Tag' : 'Tage'} nach dem {asOfLabel} noch nicht berücksichtigt (Monat läuft noch).
</p>
)}
{report.holidays.length > 0 && (
<p className="mt-2 text-xs text-text-tertiary">
Feiertage im {monthLabel}: {report.holidays.map(h => `${getDisplayDate(h.date)} (${h.name})`).join(', ')} — reduzieren die Sollzeit automatisch.
@@ -1,9 +1,10 @@
'use client'
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTranslations } from 'next-intl'
import { X, Check, Ban, Pencil, Save, RotateCcw, Send } from 'lucide-react'
import Link from 'next/link'
import { X, Check, Ban, Pencil, Save, RotateCcw, Send, FileText } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select } from '@/components/ui/select'
@@ -69,20 +70,23 @@ export function TimecardReviewDrawer({
const [note, setNote] = useState('')
const [busy, setBusy] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
// Positive acknowledgement after an action — the drawer stays open showing
// this + the next step (the report), so the approver never has to hunt for
// the card they just acted on.
const [flash, setFlash] = useState<string | null>(null)
// eslint-disable-next-line react-hooks/set-state-in-effect -- portal mount guard (SSR-safe)
useEffect(() => { setMounted(true) }, [])
useEffect(() => {
let active = true
apiFetch<ReviewCard>(`/api/admin/timecards/${cardId}`).then(r => {
if (!active) return
if (r.success && r.data) { setCard(r.data); setEntries(r.data.entries ?? []) }
else setError(r.error || t('draftLoadError'))
})
return () => { active = false }
const load = useCallback(async () => {
const r = await apiFetch<ReviewCard>(`/api/admin/timecards/${cardId}`)
if (r.success && r.data) { setCard(r.data); setEntries(r.data.entries ?? []) }
else setError(r.error || t('draftLoadError'))
}, [cardId, t])
// eslint-disable-next-line react-hooks/set-state-in-effect -- async fetch → setState resolves off-render
useEffect(() => { void load() }, [load])
const total = entries.reduce((s, e) => s + (Number(e.duration_minutes) || 0), 0)
const isApproved = card?.status === 'approved'
const isDraft = card?.status === 'draft' || card?.status === 'rejected'
@@ -95,7 +99,7 @@ export function TimecardReviewDrawer({
const save = async () => {
if (!card) return
setBusy('save'); setError(null)
setBusy('save'); setError(null); setFlash(null)
const r = await apiFetch(`/api/admin/timecards/${cardId}`, {
method: 'PUT',
body: {
@@ -108,41 +112,51 @@ export function TimecardReviewDrawer({
setBusy(null)
if (!r.success) { setError(r.error || t('saveFailed')); return }
setEditing(false)
await load()
setFlash(t('reviewDoneSaved'))
onChanged()
}
const review = async (status: 'approved' | 'rejected') => {
setBusy(status); setError(null)
setBusy(status); setError(null); setFlash(null)
const r = await apiFetch(`/api/admin/timecards/${cardId}`, {
method: 'PATCH',
body: { status, review_notes: note.trim() || null },
})
setBusy(null)
if (!r.success) { setError(r.error || t('actionFailed')); return }
setNote('')
await load()
setFlash(status === 'approved' ? t('reviewDoneApproved') : t('reviewDoneRejected'))
onChanged()
onClose()
}
// Proxy path: submit a draft on the owner's behalf (audited, owner notified).
const submitOnBehalf = async () => {
setBusy('submit'); setError(null)
setBusy('submit'); setError(null); setFlash(null)
const r = await apiFetch(`/api/admin/timecards/${cardId}/submit`, { method: 'POST' })
setBusy(null)
if (!r.success) { setError(r.error || t('actionFailed')); return }
await load()
setFlash(t('reviewDoneSubmitted'))
onChanged()
onClose()
}
// Un-approve: back to draft so the owner (or approver) can rework it.
const reopen = async () => {
setBusy('reopen'); setError(null)
setBusy('reopen'); setError(null); setFlash(null)
const r = await apiFetch(`/api/admin/timecards/${cardId}/reopen`, { method: 'POST' })
setBusy(null)
if (!r.success) { setError(r.error || t('actionFailed')); return }
await load()
setFlash(t('reviewDoneReopened'))
onChanged()
onClose()
}
// Monatsrapport for this card's owner + month (the sheet the approver sends
// to the social worker) — the concrete next step after approving.
const reportHref = card ? `/admin/team/report/${card.user_id}/${card.period_start.slice(0, 7)}` : null
if (!mounted) return null
return createPortal(
@@ -179,6 +193,16 @@ export function TimecardReviewDrawer({
<div className="flex-1 overflow-y-auto px-5 py-4">
{error && <p className="mb-3 text-sm text-error-600 dark:text-error-400">{error}</p>}
{flash && (
<div className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md border border-success-600/30 bg-success-600/10 px-3 py-2 text-sm text-success-700 dark:text-success-400">
<span className="inline-flex items-center gap-1.5 font-medium"><Check className="h-4 w-4" /> {flash}</span>
{isApproved && reportHref && (
<Link href={reportHref} target="_blank" className="inline-flex items-center gap-1 font-medium text-action hover:underline">
<FileText className="h-3.5 w-3.5" /> {t('openReport')}
</Link>
)}
</div>
)}
{!card ? (
<p className="text-sm text-text-tertiary">{t('loading')}</p>
) : entries.length === 0 ? (
@@ -299,6 +323,15 @@ export function TimecardReviewDrawer({
</>
)}
</div>
{!editing && reportHref && (
<Link
href={reportHref}
target="_blank"
className="inline-flex items-center gap-1.5 text-xs font-medium text-action hover:underline"
>
<FileText className="h-3.5 w-3.5" /> {t('openReport')}
</Link>
)}
</div>
</div>
</div>,
+8 -1
View File
@@ -41,6 +41,7 @@ export function TimeOffPanel() {
const [note, setNote] = useState('')
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState<string | null>(null)
const load = useCallback(async () => {
const res = await apiFetch<TimeOffRequest[]>('/api/time-off')
@@ -53,7 +54,7 @@ export function TimeOffPanel() {
}, [open, load])
const submit = async () => {
setError(null)
setError(null); setSuccess(null)
if (!startsOn || !endsOn) {
setError(t('missingDates'))
return
@@ -71,6 +72,7 @@ export function TimeOffPanel() {
setStartsOn('')
setEndsOn('')
setNote('')
setSuccess(t('requestSubmitted'))
void load()
}
@@ -98,6 +100,11 @@ export function TimeOffPanel() {
{error}
</p>
)}
{success && (
<p className="rounded-lg border border-success-600/30 bg-success-600/10 px-3 py-2 text-sm text-success-700 dark:text-success-400">
{success}
</p>
)}
{/* Request form */}
<div className="grid gap-3 sm:grid-cols-2">
+28 -11
View File
@@ -106,6 +106,10 @@ export function TimecardMonthGrid({
return d === 0 ? 6 : d - 1
})()
// "Today" in Europe/Zurich (server saldo uses the same tz) — so the grid
// marks the real current day, not a UTC-shifted one near midnight.
const todayIso = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Zurich' }).format(new Date())
return (
<div
{...input.containerProps}
@@ -161,6 +165,7 @@ export function TimecardMonthGrid({
const entry = getEntryForDate(entries, date)
const isFocused = focusedDate === date
const isSelected = selected.has(date)
const isToday = date === todayIso
const d = new Date(`${date}T00:00:00.000Z`)
const dayNum = d.getUTCDate()
const isWeekend = d.getUTCDay() === 0 || d.getUTCDay() === 6
@@ -187,16 +192,19 @@ export function TimecardMonthGrid({
if (!selected.has(date)) onDaySelect(date, 'single')
onDayContextMenu(date, { x: e.clientX, y: e.clientY })
}}
title={entryCategoryLabel}
title={isToday ? t('today') : entryCategoryLabel}
aria-pressed={isSelected}
aria-current={isToday ? 'date' : undefined}
className={cn(
'group relative flex h-auto min-h-[3.25rem] w-full min-w-0 flex-col items-start gap-0.5 rounded-md border px-1.5 py-1 text-left transition-colors sm:min-h-[4rem] sm:px-2 sm:py-1.5',
isSelected
? 'border-action bg-action-muted'
: isFocused
? 'border-action ring-2 ring-action/15'
: 'border-subtle hover:border-strong',
!entry && !isSelected && !isFocused && 'bg-canvas',
: isToday
? 'border-action/60 ring-1 ring-action/30'
: 'border-subtle hover:border-strong',
!entry && !isSelected && !isFocused && !isToday && 'bg-canvas',
)}
>
{isSelected && (
@@ -204,14 +212,23 @@ export function TimecardMonthGrid({
<Check className="h-2.5 w-2.5" aria-hidden="true" />
</span>
)}
<span
className={cn(
'font-mono text-xs tabular-nums',
isWeekend ? 'text-text-tertiary' : 'text-text-secondary',
)}
>
{String(dayNum).padStart(2, '0')}
</span>
{isToday ? (
<span className="inline-flex items-center gap-1">
<span className="inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-action px-1 font-mono text-[0.6rem] font-semibold tabular-nums leading-none text-action-text">
{String(dayNum).padStart(2, '0')}
</span>
<span className="hidden text-[0.55rem] font-medium uppercase tracking-wide text-action sm:inline">{t('today')}</span>
</span>
) : (
<span
className={cn(
'font-mono text-xs tabular-nums',
isWeekend ? 'text-text-tertiary' : 'text-text-secondary',
)}
>
{String(dayNum).padStart(2, '0')}
</span>
)}
{absence ? (
<span className="w-full truncate text-[0.65rem] font-medium leading-tight text-action sm:text-xs">
{entryCategoryLabel}
+20 -2
View File
@@ -20,6 +20,12 @@ export interface MonthlyReport {
reviewerName: string | null
saldo: PersonSaldo | null
holidays: { date: string; name: string }[]
/** The date the figures are computed through (month-end, or today if the
* month is still running). Entries after this are not yet "worked". */
asOfDate: string
/** True while the month is still in progress — the sheet is a Zwischenstand,
* not a final record, and must not present future days as done. */
isInterim: boolean
}
function lastDayOfMonth(month: string): string {
@@ -28,6 +34,10 @@ function lastDayOfMonth(month: string): string {
return d.toISOString().slice(0, 10)
}
function todayIsoZurich(): string {
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Zurich' }).format(new Date())
}
export async function getMonthlyReport(userId: string, month: string): Promise<MonthlyReport | null> {
const [user] = await db
.select({ name: users.name, email: users.email })
@@ -66,8 +76,14 @@ export async function getMonthlyReport(userId: string, month: string): Promise<M
reviewerName = reviewer?.name || reviewer?.email || null
}
// Saldo as of the month's end (past months report their closing state).
const saldo = await getPersonSaldo(userId, lastDayOfMonth(month)).catch(() => null)
// A finished month reports its closing state (month-end). A month still in
// progress reports as of today — otherwise pre-filled future days would show
// as "worked" and the Soll/Ist/Saldo would diverge from the live dashboard.
const monthEnd = lastDayOfMonth(month)
const today = todayIsoZurich()
const asOfDate = today < monthEnd ? today : monthEnd
const isInterim = asOfDate < monthEnd
const saldo = await getPersonSaldo(userId, asOfDate).catch(() => null)
const year = Number(month.slice(0, 4))
const holidays = getPublicHolidays(year).filter(h => h.date.startsWith(month))
@@ -84,6 +100,8 @@ export async function getMonthlyReport(userId: string, month: string): Promise<M
reviewerName,
saldo,
holidays,
asOfDate,
isInterim,
}
}