✨ Add tracking domain functions on SignalDB
This commit is contained in:
@@ -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<Settings> {
|
||||
let best: Doc<Settings> | 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<Settings> {
|
||||
return settingsAt(dayKey);
|
||||
}
|
||||
|
||||
export function settingsHistory(): Doc<Settings>[] {
|
||||
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<string> {
|
||||
validateSettings(s);
|
||||
return save('settings_history', null, s);
|
||||
}
|
||||
|
||||
export async function updateSettings(id: string, patch: Partial<Settings>): Promise<void> {
|
||||
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<void> {
|
||||
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<Entry>[] {
|
||||
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<Entry>[] {
|
||||
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<Entry> | undefined {
|
||||
return all('entries').find((e) => e.end_time === null);
|
||||
}
|
||||
|
||||
export async function startEntry(note = ''): Promise<string> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<string> {
|
||||
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<Pick<Entry, 'start_time' | 'end_time' | 'note'>>): Promise<void> {
|
||||
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<void> {
|
||||
await remove('entries', id);
|
||||
}
|
||||
|
||||
export async function autoStopStale(): Promise<number> {
|
||||
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<ClosedDay> | undefined {
|
||||
return all('closed_days').find((d) => d.day_key === dayKey);
|
||||
}
|
||||
|
||||
export function closedDaysInRange(from: string, to: string): Doc<ClosedDay>[] {
|
||||
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<void> {
|
||||
await pb.send(`/api/days/${encodeURIComponent(dayKey)}/close`, { method: 'POST' });
|
||||
await syncNow();
|
||||
}
|
||||
|
||||
export async function markDay(dayKey: string, kind: DayKind): Promise<void> {
|
||||
await pb.send(`/api/days/${encodeURIComponent(dayKey)}/mark`, { method: 'POST', body: { kind } });
|
||||
await syncNow();
|
||||
}
|
||||
|
||||
export async function reopenDay(dayKey: string): Promise<void> {
|
||||
await pb.send(`/api/days/${encodeURIComponent(dayKey)}/close`, { method: 'DELETE' });
|
||||
await syncNow();
|
||||
}
|
||||
|
||||
export function closedWeek(weekKey: string): Doc<ClosedWeek> | undefined {
|
||||
return all('closed_weeks').find((w) => w.week_key === weekKey);
|
||||
}
|
||||
|
||||
export function closedWeeksInRange(from: string, to: string): Doc<ClosedWeek>[] {
|
||||
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<void> {
|
||||
await pb.send(`/api/weeks/${encodeURIComponent(weekKey)}/close`, { method: 'POST' });
|
||||
await syncNow();
|
||||
}
|
||||
|
||||
export async function reopenWeek(weekKey: string): Promise<void> {
|
||||
await pb.send(`/api/weeks/${encodeURIComponent(weekKey)}/close`, { method: 'DELETE' });
|
||||
await syncNow();
|
||||
}
|
||||
|
||||
export function adjustments(): Doc<BalanceAdjustment>[] {
|
||||
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<string> {
|
||||
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<BalanceAdjustment>): Promise<void> {
|
||||
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<void> {
|
||||
await remove('balance_adjustments', id);
|
||||
}
|
||||
|
||||
onBeforeSync(async () => {
|
||||
await autoStopStale();
|
||||
});
|
||||
Reference in New Issue
Block a user