'use client'; /** My Day panel: today's tracked time, a quick start/stop, and a link to the * full timesheet. Private to the user (same data as the header widget). */ import { useCallback, useEffect, useState } from 'react'; import Link from 'next/link'; import { Timer, Square, Play, ArrowRight } from 'lucide-react'; import { useApp } from '@/lib/client/store'; import { api } from '@/lib/client/api'; import { getSocket } from '@/lib/client/socket'; type Entry = { durationSec: number | null; endedAt: string | null; startedAt: string }; type Running = { id: string; description: string; startedAt: string; card: { id: string; title: string } | null } | null; function fmt(sec: number): string { const m = Math.max(0, Math.round(sec / 60)); if (m < 60) return `${m}m`; const h = Math.floor(m / 60); const r = m % 60; return r === 0 ? `${h}h` : `${h}h ${r}m`; } function liveClock(fromIso: string, nowMs: number): string { const s = Math.max(0, Math.floor((nowMs - new Date(fromIso).getTime()) / 1000)); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const sec = s % 60; const pad = (n: number) => String(n).padStart(2, '0'); return h > 0 ? `${h}:${pad(m)}:${pad(sec)}` : `${m}:${pad(sec)}`; } export default function TimeTrackingCard() { const wsId = useApp((s) => s.currentWorkspaceId); const [todaySec, setTodaySec] = useState(0); const [running, setRunning] = useState(null); const [busy, setBusy] = useState(false); const [now, setNow] = useState(() => Date.now()); const load = useCallback(() => { if (!wsId) return; const start = new Date(); start.setHours(0, 0, 0, 0); Promise.all([ api<{ entries: Entry[] }>(`/api/workspaces/${wsId}/time/entries?from=${start.toISOString()}`), api<{ running: Running }>(`/api/workspaces/${wsId}/time/running`), ]).then(([e, r]) => { setTodaySec(e.entries.reduce((n, x) => n + (x.durationSec ?? 0), 0)); setRunning(r.running); }).catch(() => {}); }, [wsId]); useEffect(load, [load]); useEffect(() => { if (!running) return; const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, [running]); useEffect(() => { const socket = getSocket(); const onChanged = () => load(); socket.on('time:changed', onChanged); return () => { socket.off('time:changed', onChanged); }; }, [load]); async function start() { if (!wsId || busy) return; setBusy(true); try { await api(`/api/workspaces/${wsId}/time/start`, { method: 'POST', json: {} }); load(); } finally { setBusy(false); } } async function stop() { if (!wsId || busy) return; setBusy(true); try { await api(`/api/workspaces/${wsId}/time/stop`, { method: 'POST' }); load(); } finally { setBusy(false); } } const liveSec = running ? Math.floor((now - new Date(running.startedAt).getTime()) / 1000) : 0; const what = running?.card?.title || running?.description; return (
Time tracking
{fmt(todaySec + liveSec)} tracked today {running && · tracking {what ? `“${what}”` : 'now'}}
{running ? ( ) : ( )} Timesheet
); }