From d9890db12f806a40a7c0e9ee2c62751bfe3372f2 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Sun, 29 Nov 2026 20:16:41 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20tracking=20domain=20functions?= =?UTF-8?q?=20on=20SignalDB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/lib/app.svelte.ts | 263 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 web/src/lib/app.svelte.ts diff --git a/web/src/lib/app.svelte.ts b/web/src/lib/app.svelte.ts new file mode 100644 index 0000000..6cefc12 --- /dev/null +++ b/web/src/lib/app.svelte.ts @@ -0,0 +1,263 @@ +import { all, get, onBeforeSync, remove, save, syncNow, update, type Doc } from '$lib/db.svelte'; +import { pb } from '$lib/pb'; +import { + DEFAULT_SETTINGS, + type BalanceAdjustment, + type BalanceSummary, + type ClosedDay, + type ClosedWeek, + type DayKind, + type Entry, + type Settings +} from '$lib/types'; +import { dayKeyForMs, endOfDayMs } from '$lib/utils'; + +const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const LAST_DAY = '9999-12-31'; +/** The server rejects longer notes, which would block every later push. */ +const NOTE_MAX = 5000; + +function checkNote(note: string): void { + if (note.length > NOTE_MAX) throw new Error(`note is too long, at most ${NOTE_MAX} characters`); +} + +function settingsAt(dayKey: string): Doc { + let best: Doc | undefined; + for (const s of all('settings_history')) { + if (s.effective_from > dayKey) continue; + const later = best !== undefined && s.effective_from === best.effective_from && s.client_updated_at > best.client_updated_at; + if (!best || s.effective_from > best.effective_from || later) best = s; + } + return best ?? { ...DEFAULT_SETTINGS, id: '', client_updated_at: 0, rev: 0, deleted: false, updated: '' }; +} + +/** Day key of now in the timezone of the settings effective today. */ +export function todayKey(): string { + const now = Date.now(); + const latest = settingsAt(LAST_DAY).timezone; + const today = dayKeyForMs(now, latest); + const tz = settingsAt(today).timezone; + return tz === latest ? today : dayKeyForMs(now, tz); +} + +export function currentSettings(dayKey: string = todayKey()): Doc { + return settingsAt(dayKey); +} + +export function settingsHistory(): Doc[] { + return all('settings_history').sort((a, b) => { + if (a.effective_from !== b.effective_from) return a.effective_from < b.effective_from ? 1 : -1; + return b.client_updated_at - a.client_updated_at; + }); +} + +function validateSettings(s: Settings): void { + if (!(s.hours_per_week > 0)) throw new Error('hours_per_week must be greater than 0'); + if (!Number.isInteger(s.workdays_mask) || s.workdays_mask < 1 || s.workdays_mask > 127) { + throw new Error('workdays_mask must be between 1 and 127'); + } + if (!DAY_PATTERN.test(s.effective_from)) throw new Error('effective_from must be a date in the form YYYY-MM-DD'); + if (!s.timezone) throw new Error('timezone must not be empty'); + try { + new Intl.DateTimeFormat(undefined, { timeZone: s.timezone }); + } catch { + throw new Error('unknown timezone'); + } +} + +export async function addSettings(s: Settings): Promise { + validateSettings(s); + return save('settings_history', null, s); +} + +export async function updateSettings(id: string, patch: Partial): Promise { + const cur = get('settings_history', id); + if (!cur) throw new Error('settings row not found'); + validateSettings({ ...cur, ...patch }); + await update('settings_history', id, patch); +} + +export async function deleteSettings(id: string): Promise { + const cur = get('settings_history', id); + if (!cur) return; + if (!cur.deleted && all('settings_history').length <= 1) throw new Error('cannot delete the only settings row'); + await remove('settings_history', id); +} + +export function entriesForDay(dayKey: string): Doc[] { + return all('entries') + .filter((e) => e.day_key === dayKey) + .sort((a, b) => a.start_time - b.start_time); +} + +export function entriesForRange(from: string, to: string): Doc[] { + return all('entries') + .filter((e) => e.day_key >= from && e.day_key <= to) + .sort((a, b) => a.start_time - b.start_time); +} + +export function runningEntry(): Doc | undefined { + return all('entries').find((e) => e.end_time === null); +} + +export async function startEntry(note = ''): Promise { + if (runningEntry()) throw new Error('an entry is already running'); + checkNote(note); + const now = Date.now(); + const day = dayKeyForMs(now, currentSettings().timezone); + if (closedDay(day)) throw new Error('day is already closed'); + return save('entries', null, { start_time: now, end_time: null, auto_stopped: false, note, day_key: day }); +} + +export async function stopEntry(id: string): Promise { + const e = get('entries', id); + if (!e || e.deleted || e.end_time !== null) throw new Error('no running entry found'); + const cap = endOfDayMs(e.day_key, currentSettings().timezone); + const now = Date.now(); + await update('entries', id, { + end_time: Math.min(Math.max(now, e.start_time + 1), cap), + auto_stopped: now > cap + }); +} + +export async function stopRunning(): Promise { + const e = runningEntry(); + if (!e) throw new Error('no running entry found'); + await stopEntry(e.id); +} + +export async function createInterval(startTime: number, endTime: number, note = ''): Promise { + if (!Number.isFinite(startTime) || !Number.isFinite(endTime)) throw new Error('start_time and end_time are required'); + if (endTime <= startTime) throw new Error('end_time must be after start_time'); + checkNote(note); + const tz = currentSettings().timezone; + const day = dayKeyForMs(startTime, tz); + if (dayKeyForMs(endTime, tz) !== day) throw new Error('entry end_time must be on the same calendar day as start_time'); + if (day > todayKey()) throw new Error('intervals cannot be created or edited in the future'); + if (closedDay(day)) throw new Error('day is already closed'); + return save('entries', null, { start_time: startTime, end_time: endTime, auto_stopped: false, note, day_key: day }); +} + +export async function updateEntry(id: string, patch: Partial>): Promise { + const e = get('entries', id); + if (!e || e.deleted) throw new Error('entry not found'); + const start = patch.start_time ?? e.start_time; + const end = patch.end_time === undefined ? e.end_time : patch.end_time; + if (!Number.isFinite(start) || (end !== null && !Number.isFinite(end))) throw new Error('start_time and end_time are required'); + if (patch.note !== undefined) checkNote(patch.note); + const tz = currentSettings().timezone; + const day = dayKeyForMs(start, tz); + if (end !== null) { + if (end <= start) throw new Error('end_time must be after start_time'); + if (dayKeyForMs(end, tz) !== day) throw new Error('entry end_time must be on the same calendar day as start_time'); + } + if (day > todayKey()) throw new Error('intervals cannot be created or edited in the future'); + if (closedDay(day) || closedDay(e.day_key)) throw new Error('day is already closed'); + await update('entries', id, { ...patch, day_key: day }); +} + +export async function deleteEntry(id: string): Promise { + await remove('entries', id); +} + +export async function autoStopStale(): Promise { + const tz = currentSettings().timezone; + const today = todayKey(); + let count = 0; + for (const e of all('entries')) { + if (e.end_time !== null || e.day_key >= today) continue; + await update('entries', e.id, { end_time: endOfDayMs(e.day_key, tz), auto_stopped: true }); + count += 1; + } + return count; +} + +export function closedDay(dayKey: string): Doc | undefined { + return all('closed_days').find((d) => d.day_key === dayKey); +} + +export function closedDaysInRange(from: string, to: string): Doc[] { + return all('closed_days') + .filter((d) => d.day_key >= from && d.day_key <= to) + .sort((a, b) => (a.day_key < b.day_key ? -1 : a.day_key > b.day_key ? 1 : 0)); +} + +export async function closeDay(dayKey: string): Promise { + await pb.send(`/api/days/${encodeURIComponent(dayKey)}/close`, { method: 'POST' }); + await syncNow(); +} + +export async function markDay(dayKey: string, kind: DayKind): Promise { + await pb.send(`/api/days/${encodeURIComponent(dayKey)}/mark`, { method: 'POST', body: { kind } }); + await syncNow(); +} + +export async function reopenDay(dayKey: string): Promise { + await pb.send(`/api/days/${encodeURIComponent(dayKey)}/close`, { method: 'DELETE' }); + await syncNow(); +} + +export function closedWeek(weekKey: string): Doc | undefined { + return all('closed_weeks').find((w) => w.week_key === weekKey); +} + +export function closedWeeksInRange(from: string, to: string): Doc[] { + return all('closed_weeks') + .filter((w) => w.week_key >= from && w.week_key <= to) + .sort((a, b) => (a.week_key < b.week_key ? -1 : a.week_key > b.week_key ? 1 : 0)); +} + +export async function closeWeek(weekKey: string): Promise { + await pb.send(`/api/weeks/${encodeURIComponent(weekKey)}/close`, { method: 'POST' }); + await syncNow(); +} + +export async function reopenWeek(weekKey: string): Promise { + await pb.send(`/api/weeks/${encodeURIComponent(weekKey)}/close`, { method: 'DELETE' }); + await syncNow(); +} + +export function adjustments(): Doc[] { + return all('balance_adjustments').sort((a, b) => b.effective_at - a.effective_at); +} + +export function balance(): BalanceSummary { + const weeks = all('closed_weeks'); + const adj = adjustments(); + const weeksDelta = weeks.reduce((sum, w) => sum + w.delta_ms, 0); + const adjustmentsDelta = adj.reduce((sum, a) => sum + a.delta_ms, 0); + return { + total_delta_ms: weeksDelta + adjustmentsDelta, + weeks_delta_ms: weeksDelta, + adjustments_delta_ms: adjustmentsDelta, + closed_week_count: weeks.length, + adjustment_count: adj.length + }; +} + +export async function addAdjustment(a: { delta_ms: number; note?: string; effective_at?: number }): Promise { + if (!Number.isFinite(a.delta_ms) || a.delta_ms === 0) throw new Error('delta_ms must be non-zero'); + checkNote(a.note ?? ''); + return save('balance_adjustments', null, { + delta_ms: a.delta_ms, + note: a.note ?? '', + effective_at: a.effective_at ?? Date.now() + }); +} + +export async function updateAdjustment(id: string, patch: Partial): Promise { + const cur = get('balance_adjustments', id); + if (!cur) throw new Error('adjustment not found'); + const delta = patch.delta_ms ?? cur.delta_ms; + if (!Number.isFinite(delta) || delta === 0) throw new Error('delta_ms must be non-zero'); + if (patch.note !== undefined) checkNote(patch.note); + await update('balance_adjustments', id, patch); +} + +export async function deleteAdjustment(id: string): Promise { + await remove('balance_adjustments', id); +} + +onBeforeSync(async () => { + await autoStopStale(); +});