File size: 4,796 Bytes
e4a1ec6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
'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<Running>(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 (
    <div className="panel p-4">
      <div className="flex flex-wrap items-center gap-3">
        <span className="grad flex h-9 w-9 shrink-0 items-center justify-center rounded-[10px] text-white shadow-soft"><Timer className="h-5 w-5" /></span>
        <div className="min-w-0">
          <div className="text-sm font-bold text-gray-800">Time tracking</div>
          <div className="text-xs text-gray-500">
            <span className="font-bold text-gray-700">{fmt(todaySec + liveSec)}</span> tracked today
            {running && <span className="text-emerald-600"> · tracking {what ? `“${what}”` : 'now'}</span>}
          </div>
        </div>

        <div className="ml-auto flex items-center gap-2">
          {running ? (
            <button onClick={stop} disabled={busy}
              className="flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-bold text-white hover:bg-emerald-700 disabled:opacity-50">
              <Square className="h-3.5 w-3.5" fill="currentColor" /> Stop <span className="font-mono">{liveClock(running.startedAt, now)}</span>
            </button>
          ) : (
            <button onClick={start} disabled={busy}
              className="flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-bold text-gray-600 hover:bg-gray-50 disabled:opacity-50">
              <Play className="h-3.5 w-3.5" fill="currentColor" /> Start timer
            </button>
          )}
          <Link href={`/w/${wsId}/time`}
            className="flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-bold text-primary-600 hover:bg-gray-50">
            Timesheet <ArrowRight className="h-3.5 w-3.5" />
          </Link>
        </div>
      </div>
    </div>
  );
}