🗑️ Remove the Dexie data layer and its dependencies

The API client and the two stores on Dexie have been dead since the
collections took over every read and write, and nothing imports them
any more. Dexie and workbox-window go with them; the service worker is
registered by hand and needs no client library.

The static adapter wipes build/ on every build, which dropped the
tracked placeholder that keeps the directory in the repository. A
postbuild step writes it back.
This commit is contained in:
2026-12-01 18:06:39 +01:00
parent bddabbf93d
commit 1c899b2743
5 changed files with 3 additions and 602 deletions
-331
View File
@@ -1,331 +0,0 @@
// API client for Wotra backend.
// Base URL: /api (relative, works both in dev proxy and production)
//
// Offline-first: all reads come from Dexie immediately; all mutations write to
// Dexie + outbox and return without waiting for the server. The background sync
// loop (sync.ts) pushes the outbox and pulls server changes every 30 seconds.
//
// Exceptions: day/week close and reopen require server-side computation and
// remain server-only. Call triggerSync() after them to update Dexie promptly.
import { db } from '$lib/stores/db';
const API_BASE = '/api';
function getToken(): string {
return localStorage.getItem('auth_token') ?? '';
}
export function setToken(token: string) {
localStorage.setItem('auth_token', token);
}
export function hasToken(): boolean {
return !!localStorage.getItem('auth_token');
}
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`
},
body: body !== undefined ? JSON.stringify(body) : undefined
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw new ApiError(res.status, err.error ?? res.statusText);
}
if (res.status === 204) return undefined as T;
return res.json();
}
/** Enqueue an outbox item for background push to the server. */
async function enqueue(entity: string, entity_id: string, op: 'upsert' | 'delete', payload: unknown) {
await db.outbox.add({
entity,
entity_id,
op,
payload: JSON.stringify(payload),
created_at: Date.now()
});
}
export class ApiError extends Error {
constructor(
public status: number,
message: string
) {
super(message);
}
}
// ─── Types ──────────────────────────────────────────────────────────────────
export interface Entry {
id: string;
start_time: number; // unix ms UTC
end_time: number | null;
auto_stopped: boolean;
note: string;
day_key: string;
updated_at: number;
}
export interface ClosedDay {
day_key: string;
start_time: number | null;
end_time: number | null;
worked_ms: number;
kind: 'work' | 'holiday' | 'vacation' | 'sick';
closed_at: number;
updated_at: number;
}
export interface ClosedWeek {
week_key: string;
expected_ms: number;
worked_ms: number;
delta_ms: number;
closed_at: number;
updated_at: number;
}
export interface Settings {
id: string; // UUID
effective_from: string;
hours_per_week: number;
workdays_mask: number;
timezone: string;
created_at: number;
updated_at: number;
}
export interface BalanceAdjustment {
id: string;
delta_ms: number;
note: string;
effective_at: number; // unix ms
created_at: number;
updated_at: number;
}
export interface BalanceSummary {
total_delta_ms: number;
weeks_delta_ms: number;
adjustments_delta_ms: number;
closed_week_count: number;
adjustment_count: number;
}
// ─── Entries ─────────────────────────────────────────────────────────────────
export const entries = {
start: async (note = ''): Promise<Entry> => {
const entry: Entry = {
id: crypto.randomUUID(),
start_time: Date.now(),
end_time: null,
auto_stopped: false,
note,
day_key: new Date().toISOString().slice(0, 10),
updated_at: Date.now()
};
await db.entries.put(entry);
await enqueue('entries', entry.id, 'upsert', entry);
return entry;
},
createInterval: async (startTime: number, endTime: number, note = ''): Promise<Entry> => {
const entry: Entry = {
id: crypto.randomUUID(),
start_time: startTime,
end_time: endTime,
auto_stopped: false,
note,
day_key: new Date(startTime).toISOString().slice(0, 10),
updated_at: Date.now()
};
await db.entries.put(entry);
await enqueue('entries', entry.id, 'upsert', entry);
return entry;
},
stop: async (id: string): Promise<Entry> => {
const existing = await db.entries.get(id);
if (!existing) throw new ApiError(404, 'Entry not found');
const updated: Entry = { ...existing, end_time: Date.now(), updated_at: Date.now() };
await db.entries.put(updated);
await enqueue('entries', id, 'upsert', updated);
return updated;
},
list: async (from?: string, to?: string): Promise<Entry[]> => {
let q = db.entries.toCollection();
if (from && to) q = db.entries.where('day_key').between(from, to, true, true);
else if (from) q = db.entries.where('day_key').aboveOrEqual(from);
else if (to) q = db.entries.where('day_key').belowOrEqual(to);
const rows = await q.toArray();
return rows.sort((a, b) => a.start_time - b.start_time);
},
update: async (id: string, body: { start_time?: number; end_time?: number; note?: string }): Promise<Entry> => {
const existing = await db.entries.get(id);
if (!existing) throw new ApiError(404, 'Entry not found');
const updated: Entry = { ...existing, ...body, updated_at: Date.now() };
await db.entries.put(updated);
await enqueue('entries', id, 'upsert', updated);
return updated;
},
delete: async (id: string): Promise<void> => {
await db.entries.delete(id);
await enqueue('entries', id, 'delete', { id, updated_at: Date.now() });
}
};
// ─── Days ────────────────────────────────────────────────────────────────────
// close/mark/reopen remain server-only (require server-side computation).
// Call triggerSync() after them to update Dexie promptly.
export const days = {
list: async (from?: string, to?: string): Promise<ClosedDay[]> => {
let q = db.closed_days.toCollection();
if (from && to) q = db.closed_days.where('day_key').between(from, to, true, true);
else if (from) q = db.closed_days.where('day_key').aboveOrEqual(from);
else if (to) q = db.closed_days.where('day_key').belowOrEqual(to);
return q.toArray();
},
close: (dayKey: string) => request<ClosedDay>('POST', `/days/${dayKey}/close`),
mark: (dayKey: string, kind: 'holiday' | 'vacation' | 'sick') =>
request<ClosedDay>('POST', `/days/${dayKey}/mark`, { kind }),
reopen: (dayKey: string) => request<void>('DELETE', `/days/${dayKey}/close`)
};
// ─── Weeks ───────────────────────────────────────────────────────────────────
// close/reopen remain server-only (require server-side computation).
// Call triggerSync() after them to update Dexie promptly.
export const weeks = {
list: async (from?: string, to?: string): Promise<ClosedWeek[]> => {
let q = db.closed_weeks.toCollection();
if (from && to) q = db.closed_weeks.where('week_key').between(from, to, true, true);
else if (from) q = db.closed_weeks.where('week_key').aboveOrEqual(from);
else if (to) q = db.closed_weeks.where('week_key').belowOrEqual(to);
return q.toArray();
},
close: (weekKey: string) => request<ClosedWeek>('POST', `/weeks/${weekKey}/close`),
reopen: (weekKey: string) => request<void>('DELETE', `/weeks/${weekKey}/close`),
balance: async (): Promise<BalanceSummary> => {
const [ws, adjs] = await Promise.all([
db.closed_weeks.toArray(),
db.balance_adjustments.toArray()
]);
const weeks_delta_ms = ws.reduce((s, w) => s + w.delta_ms, 0);
const adjustments_delta_ms = adjs.reduce((s, a) => s + a.delta_ms, 0);
return {
total_delta_ms: weeks_delta_ms + adjustments_delta_ms,
weeks_delta_ms,
adjustments_delta_ms,
closed_week_count: ws.length,
adjustment_count: adjs.length
};
}
};
// ─── Balance adjustments ─────────────────────────────────────────────────────
export const balance = {
list: async (): Promise<BalanceAdjustment[]> => {
return db.balance_adjustments.orderBy('effective_at').reverse().toArray();
},
create: async (body: { delta_ms: number; note?: string; effective_at?: number }): Promise<BalanceAdjustment> => {
const now = Date.now();
const adj: BalanceAdjustment = {
id: crypto.randomUUID(),
delta_ms: body.delta_ms,
note: body.note ?? '',
effective_at: body.effective_at ?? now,
created_at: now,
updated_at: now
};
await db.balance_adjustments.put(adj);
await enqueue('balance_adjustments', adj.id, 'upsert', adj);
return adj;
},
update: async (id: string, body: { delta_ms: number; note?: string; effective_at?: number }): Promise<BalanceAdjustment> => {
const existing = await db.balance_adjustments.get(id);
if (!existing) throw new ApiError(404, 'Adjustment not found');
const updated: BalanceAdjustment = { ...existing, ...body, updated_at: Date.now() };
await db.balance_adjustments.put(updated);
await enqueue('balance_adjustments', id, 'upsert', updated);
return updated;
},
delete: async (id: string): Promise<void> => {
const existing = await db.balance_adjustments.get(id);
await db.balance_adjustments.delete(id);
await enqueue('balance_adjustments', id, 'delete', { id, updated_at: existing?.updated_at ?? Date.now() });
}
};
// ─── Settings ────────────────────────────────────────────────────────────────
export const settings = {
current: async (): Promise<Settings> => {
const today = new Date().toISOString().slice(0, 10);
const all = await db.settings_history.orderBy('effective_from').reverse().toArray();
const match = all.find((s) => s.effective_from <= today) ?? all[0];
if (!match) throw new ApiError(503, 'No settings available — sync pending');
return match;
},
history: async (): Promise<Settings[]> => {
return db.settings_history.orderBy('effective_from').reverse().toArray();
},
upsert: async (body: {
effective_from: string;
hours_per_week: number;
workdays_mask: number;
timezone: string;
}): Promise<Settings> => {
const now = Date.now();
const s: Settings = {
id: crypto.randomUUID(),
...body,
created_at: now,
updated_at: now
};
await db.settings_history.put(s);
await enqueue('settings_history', s.id, 'upsert', s);
return s;
},
update: async (id: string, body: {
effective_from: string;
hours_per_week: number;
workdays_mask: number;
timezone: string;
}): Promise<Settings> => {
const existing = await db.settings_history.get(id);
if (!existing) throw new ApiError(404, 'Settings row not found');
const updated: Settings = { ...existing, ...body, updated_at: Date.now() };
await db.settings_history.put(updated);
await enqueue('settings_history', id, 'upsert', updated);
return updated;
},
delete: async (id: string): Promise<void> => {
await db.settings_history.delete(id);
await enqueue('settings_history', id, 'delete', { id, updated_at: Date.now() });
}
};
// ─── Health ──────────────────────────────────────────────────────────────────
export const healthz = () =>
fetch('/healthz').then((r) => r.ok);
-54
View File
@@ -1,54 +0,0 @@
import Dexie, { type Table } from 'dexie';
import type { Entry, ClosedDay, ClosedWeek, Settings, BalanceAdjustment } from '$lib/api/client';
export interface OutboxItem {
id?: number; // auto-increment
entity: string; // 'entries' | 'closed_days' | 'closed_weeks' | 'settings_history' | 'balance_adjustments'
entity_id: string;
op: 'upsert' | 'delete';
payload: string; // JSON
created_at: number;
}
export class WotraDB extends Dexie {
entries!: Table<Entry, string>;
closed_days!: Table<ClosedDay, string>;
closed_weeks!: Table<ClosedWeek, string>;
settings_history!: Table<Settings, string>; // UUID PK as of v3
balance_adjustments!: Table<BalanceAdjustment, string>;
outbox!: Table<OutboxItem, number>;
meta!: Table<{ key: string; value: string }, string>;
constructor() {
super('wotra');
this.version(1).stores({
entries: 'id, day_key, start_time, updated_at',
closed_days: 'day_key, updated_at',
closed_weeks: 'week_key, updated_at',
settings_history: '++id, effective_from',
outbox: '++id, entity, entity_id',
meta: 'key'
});
this.version(2).stores({
balance_adjustments: 'id, effective_at, updated_at'
});
// v3: settings_history switches from integer autoincrement PK to UUID TEXT PK.
// Clear the table on upgrade; the next pull will repopulate it from the server.
this.version(3).stores({
settings_history: 'id, effective_from, updated_at'
}).upgrade(tx => {
return tx.table('settings_history').clear();
});
}
}
export const db = new WotraDB();
/** Get/set last pulled server version */
export async function getLastVersion(): Promise<number> {
const row = await db.meta.get('last_version');
return row ? Number(row.value) : 0;
}
export async function setLastVersion(v: number) {
await db.meta.put({ key: 'last_version', value: String(v) });
}
-205
View File
@@ -1,205 +0,0 @@
/**
* Sync layer: push local outbox to server, pull server changes.
*
* Offline-first:
* - All reads and writes go through Dexie immediately (see client.ts).
* - This loop pushes any queued outbox items, then pulls new server changes.
* - triggerSync() can be called imperatively (e.g. after day/week close).
* - On 410 Gone the client is stale: wipe all tables and re-pull from 0.
*/
import { db, getLastVersion, setLastVersion } from './db';
import { hasToken } from '$lib/api/client';
import { writable, derived } from 'svelte/store';
const API = '/api';
function headers() {
const token = localStorage.getItem('auth_token') ?? '';
return {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
};
}
// ─── Sync state ───────────────────────────────────────────────────────────────
export type SyncStatus = 'idle' | 'syncing' | 'error';
interface SyncState {
status: SyncStatus;
lastSynced: Date | null;
pendingCount: number;
error: string | null;
}
const _syncState = writable<SyncState>({
status: 'idle',
lastSynced: null,
pendingCount: 0,
error: null
});
export const syncState = derived(_syncState, (s) => s);
async function refreshPendingCount() {
const count = await db.outbox.count();
_syncState.update((s) => ({ ...s, pendingCount: count }));
}
// ─── Push ─────────────────────────────────────────────────────────────────────
export async function pushOutbox(): Promise<void> {
if (!hasToken()) return;
const items = await db.outbox.toArray();
if (items.length === 0) return;
let res: Response;
try {
res = await fetch(`${API}/sync/push`, {
method: 'POST',
headers: headers(),
body: JSON.stringify({
changes: items.map((i) => ({
entity: i.entity,
entity_id: i.entity_id,
op: i.op,
payload: JSON.parse(i.payload)
}))
})
});
} catch {
return; // network unavailable; retry next cycle
}
if (!res.ok) return;
const { applied } = (await res.json()) as { applied: string[]; skipped: string[] };
const appliedSet = new Set(applied);
const toDelete = items
.filter((i) => appliedSet.has(i.entity_id))
.map((i) => i.id!);
if (toDelete.length > 0) await db.outbox.bulkDelete(toDelete);
}
// ─── Pull ─────────────────────────────────────────────────────────────────────
export async function pullChanges(): Promise<void> {
if (!hasToken()) return;
const since = await getLastVersion();
let res: Response;
try {
res = await fetch(`${API}/sync/pull?since=${since}`, { headers: headers() });
} catch {
return; // network unavailable
}
if (res.status === 410) {
// Server has pruned data the client hasn't seen — full re-sync.
await coldStart();
return pullChanges();
}
if (!res.ok) return;
const { changes, server_version } = (await res.json()) as {
changes: Array<{ entity: string; entity_id: string; op: string; payload: string }>;
server_version: number;
};
for (const change of changes) {
try {
const data = typeof change.payload === 'string'
? JSON.parse(change.payload)
: change.payload;
if (change.op === 'delete') {
await applyDelete(change.entity, change.entity_id);
} else {
await applyUpsert(change.entity, data);
}
} catch {
// Skip malformed change; will not block remaining changes.
}
}
await setLastVersion(server_version);
}
// ─── Cold start ───────────────────────────────────────────────────────────────
/** Wipe all local tables and reset version so the next pull fetches everything. */
export async function coldStart(): Promise<void> {
await Promise.all([
db.entries.clear(),
db.closed_days.clear(),
db.closed_weeks.clear(),
db.settings_history.clear(),
db.balance_adjustments.clear()
]);
await setLastVersion(0);
}
// ─── Apply helpers ────────────────────────────────────────────────────────────
async function applyUpsert(entity: string, data: unknown) {
switch (entity) {
case 'entries': await db.entries.put(data as any); break;
case 'closed_days': await db.closed_days.put(data as any); break;
case 'closed_weeks': await db.closed_weeks.put(data as any); break;
case 'settings_history': await db.settings_history.put(data as any); break;
case 'balance_adjustments': await db.balance_adjustments.put(data as any); break;
}
}
async function applyDelete(entity: string, id: string) {
switch (entity) {
case 'entries': await db.entries.delete(id); break;
case 'closed_days': await db.closed_days.delete(id); break;
case 'closed_weeks': await db.closed_weeks.delete(id); break;
case 'settings_history': await db.settings_history.delete(id); break;
case 'balance_adjustments': await db.balance_adjustments.delete(id); break;
}
}
// ─── Sync loop ────────────────────────────────────────────────────────────────
let syncInterval: ReturnType<typeof setInterval> | null = null;
let syncInFlight = false;
/** Start background sync loop (every 30 seconds). */
export function startSync() {
if (syncInterval) return;
sync();
syncInterval = setInterval(sync, 30_000);
}
export function stopSync() {
if (syncInterval) {
clearInterval(syncInterval);
syncInterval = null;
}
}
/** Trigger an immediate sync cycle — fire and forget. */
export function triggerSync() {
sync();
}
/** Trigger an immediate sync and return a promise that resolves when it completes. */
export function waitForSync(): Promise<void> {
return sync();
}
async function sync(): Promise<void> {
if (syncInFlight) return;
syncInFlight = true;
_syncState.update((s) => ({ ...s, status: 'syncing', error: null }));
try {
await pushOutbox();
await pullChanges();
await refreshPendingCount();
_syncState.update((s) => ({ ...s, status: 'idle', lastSynced: new Date() }));
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
_syncState.update((s) => ({ ...s, status: 'error', error: msg }));
} finally {
syncInFlight = false;
}
}