Add Svelte web client and service worker
Mobile-first PWA: groups via key-in-fragment links, encrypted outbox and sync over SSE, all split modes, currencies with ECB rate prefill, photos, comments, history and rewind, stats, recurring expenses, CSV and backup, EN/CS, dark/light theme, Web Push decrypted in the service worker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
This commit is contained in:
parent
f67add3660
commit
8fbbb4933e
53 changed files with 4558 additions and 37 deletions
100
apps/web/src/components/Activity.svelte
Normal file
100
apps/web/src/components/Activity.svelte
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
<script lang="ts">
|
||||
import type { Activity, Expense } from '@oweme/core';
|
||||
import { fmtDateTime, money } from '../lib/format.ts';
|
||||
import type { MsgKey } from '../lib/i18n.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
let { session }: { session: GroupSession } = $props();
|
||||
let limit = $state(100);
|
||||
|
||||
const entries = $derived(session.activity.filter((a) => !a.ignored).reverse());
|
||||
const all = $derived(session.activity);
|
||||
|
||||
function expenseTitle(a: Activity): string {
|
||||
const e = (a.after ?? a.before) as Expense | null;
|
||||
const fromState = a.entityId ? session.state.expenses[a.entityId]?.expense : undefined;
|
||||
const x = e && 'amount' in e ? e : fromState;
|
||||
if (!x) return '…';
|
||||
const label = x.kind === 'transfer'
|
||||
? t('transfer_line', { from: session.memberName(x.payers[0]?.member), to: session.memberName(x.split.entries.find((s) => s.value > 0)?.member) })
|
||||
: x.title;
|
||||
return `${label} (${money(x.amount, x.currency)})`;
|
||||
}
|
||||
|
||||
function describe(a: Activity): string {
|
||||
const actor = a.actor && session.memberName(a.actor) !== '?' ? session.memberName(a.actor) : t('someone');
|
||||
const key = `act_${a.type.replace('.', '_')}` as MsgKey;
|
||||
const after = (a.after ?? {}) as { name?: string; template?: Expense };
|
||||
const before = (a.before ?? {}) as { name?: string; template?: Expense };
|
||||
switch (a.type) {
|
||||
case 'member.added':
|
||||
return t(key, { actor, name: after.name ?? '' });
|
||||
case 'member.updated':
|
||||
return t(key, { actor, old: before.name ?? '', name: after.name ?? '' });
|
||||
case 'member.archived':
|
||||
case 'member.restored':
|
||||
return t(key, { actor, name: session.memberName(a.entityId) });
|
||||
case 'recurring.created':
|
||||
case 'recurring.updated':
|
||||
case 'recurring.deleted':
|
||||
return t(key, { actor, title: (after.template ?? before.template)?.title ?? '' });
|
||||
case 'comment.added':
|
||||
case 'comment.deleted': {
|
||||
const ex = a.entityId ? session.state.expenses[a.entityId]?.expense : undefined;
|
||||
return t(key, { actor, title: ex ? (ex.title || t('kind_transfer')) : '…' });
|
||||
}
|
||||
case 'revert': {
|
||||
const target = all.find((x) => x.eventId === a.entityId);
|
||||
return t(key, { actor, time: target ? fmtDateTime(target.at) : '?' });
|
||||
}
|
||||
case 'group.created':
|
||||
case 'group.updated':
|
||||
return t(key, { actor });
|
||||
default:
|
||||
return t(key, { actor, title: expenseTitle(a) });
|
||||
}
|
||||
}
|
||||
|
||||
async function rewindTo(eventId: string) {
|
||||
if (!confirm(t('confirm_rewind'))) return;
|
||||
await session.emit({ type: 'revert', data: { targetId: eventId } });
|
||||
}
|
||||
|
||||
/** Undo a rewind = rewind to the event just before it. */
|
||||
function beforeOf(eventId: string): string | null {
|
||||
const i = all.findIndex((x) => x.eventId === eventId);
|
||||
return i > 0 ? all[i - 1].eventId : null;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="stack">
|
||||
{#if entries.length === 0}
|
||||
<p class="empty">{t('no_activity')}</p>
|
||||
{:else}
|
||||
<div class="list">
|
||||
{#each entries.slice(0, limit) as a, i (a.eventId)}
|
||||
<div class="item" style:align-items="flex-start">
|
||||
<span class="grow">
|
||||
<span style:display="block">{describe(a)}</span>
|
||||
<span class="small muted">{fmtDateTime(a.at)}{a.seq === null ? ' · ⏳' : ''}</span>
|
||||
</span>
|
||||
{#if a.type === 'revert'}
|
||||
{@const prev = beforeOf(a.eventId)}
|
||||
{#if prev}
|
||||
<button class="btn small" onclick={() => rewindTo(prev)}><Icon name="undo" size={16} /> {t('undo_rewind')}</button>
|
||||
{/if}
|
||||
{:else if i > 0}
|
||||
<button class="btn small ghost" onclick={() => rewindTo(a.eventId)} title={t('rewind_here')}>
|
||||
<Icon name="undo" size={16} /><span class="sr-only">{t('rewind_here')}</span>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if entries.length > limit}
|
||||
<button class="btn" onclick={() => (limit += 100)}>…</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
32
apps/web/src/components/AppSettings.svelte
Normal file
32
apps/web/src/components/AppSettings.svelte
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<script lang="ts">
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import { settings, t } from '../lib/settings.svelte.ts';
|
||||
import Icon from './Icon.svelte';
|
||||
</script>
|
||||
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={() => router.back('/')} aria-label={t('back')}><Icon name="back" /></button>
|
||||
<h1>{t('app_settings')}</h1>
|
||||
</header>
|
||||
|
||||
<main class="page stack">
|
||||
<div class="section">
|
||||
<h3>{t('language')}</h3>
|
||||
<div class="seg" role="group" aria-label={t('language')}>
|
||||
<button aria-pressed={settings.langPref === 'auto'} onclick={() => settings.setLang('auto')}>{t('lang_auto')}</button>
|
||||
<button aria-pressed={settings.langPref === 'en'} onclick={() => settings.setLang('en')}>English</button>
|
||||
<button aria-pressed={settings.langPref === 'cs'} onclick={() => settings.setLang('cs')}>Čeština</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h3>{t('theme')}</h3>
|
||||
<div class="seg" role="group" aria-label={t('theme')}>
|
||||
<button aria-pressed={settings.themePref === 'system'} onclick={() => settings.setTheme('system')}>{t('theme_system')}</button>
|
||||
<button aria-pressed={settings.themePref === 'dark'} onclick={() => settings.setTheme('dark')}>{t('theme_dark')}</button>
|
||||
<button aria-pressed={settings.themePref === 'light'} onclick={() => settings.setTheme('light')}>{t('theme_light')}</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="muted small row" style:align-items="flex-start" style:margin-top="24px">
|
||||
<Icon name="lock" size={16} /> <span>{t('e2e_note')}</span>
|
||||
</p>
|
||||
</main>
|
||||
12
apps/web/src/components/Avatar.svelte
Normal file
12
apps/web/src/components/Avatar.svelte
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<script lang="ts">
|
||||
import type { Member } from '@oweme/core';
|
||||
import { MEMBER_COLORS } from '../lib/format.ts';
|
||||
|
||||
let { member, index = 0, size = 36 }: { member: Member | undefined; index?: number; size?: number } = $props();
|
||||
const initials = $derived(
|
||||
(member?.name ?? '?').split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0]!.toUpperCase()).join('') || '?',
|
||||
);
|
||||
const color = $derived(member?.color || MEMBER_COLORS[index % MEMBER_COLORS.length]);
|
||||
</script>
|
||||
|
||||
<span class="avatar" style:background={color} style:width="{size}px" style:height="{size}px" style:font-size="{size * 0.38}px" aria-hidden="true">{initials}</span>
|
||||
92
apps/web/src/components/Balances.svelte
Normal file
92
apps/web/src/components/Balances.svelte
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { exponent, settleUp } from '@oweme/core';
|
||||
import { money } from '../lib/format.ts';
|
||||
import { displayRate } from '../lib/rates.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Avatar from './Avatar.svelte';
|
||||
import CurrencySelect from './CurrencySelect.svelte';
|
||||
|
||||
let { session, compact = false }: { session: GroupSession; compact?: boolean } = $props();
|
||||
|
||||
// Optional display in another currency at today's rate (never stored).
|
||||
let showIn = $state(untrack(() => session.base));
|
||||
let factor = $state<number | null>(1);
|
||||
$effect(() => {
|
||||
const target = showIn || session.base;
|
||||
displayRate(session.base, target).then((r) => (factor = r));
|
||||
});
|
||||
const cur = $derived(factor === null ? session.base : showIn || session.base);
|
||||
const conv = (v: number) => {
|
||||
if (!showIn || showIn === session.base || factor === null) return money(v, session.base);
|
||||
// display only: float maths is fine here
|
||||
return money(Math.round(v * factor * 10 ** (exponent(cur) - exponent(session.base))), cur);
|
||||
};
|
||||
|
||||
const members = $derived(session.state.members.map((m, i) => ({ m, i, bal: session.balances[m.id] ?? 0 })).filter((x) => !x.m.archived || x.bal !== 0));
|
||||
const maxAbs = $derived(Math.max(1, ...members.map((x) => Math.abs(x.bal))));
|
||||
const transfers = $derived(settleUp(session.balances, session.state.members.map((m) => m.id)));
|
||||
|
||||
function record(from: string, to: string, amount: number) {
|
||||
const p = new URLSearchParams({ kind: 'transfer', from, to, amount: String(amount) });
|
||||
router.go(`/g/${session.id}/e/new?${p}`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="stack">
|
||||
{#if !compact}
|
||||
<h3>{t('balances')}</h3>
|
||||
{/if}
|
||||
<div class="list">
|
||||
{#each members as { m, i, bal } (m.id)}
|
||||
<div class="item">
|
||||
<Avatar member={m} index={i} size={32} />
|
||||
<span class="grow">
|
||||
<span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span>
|
||||
<span class="bar" aria-hidden="true">
|
||||
<span class={bal >= 0 ? 'fill pos-fill' : 'fill neg-fill'} style:width="{(Math.abs(bal) / maxAbs) * 100}%"></span>
|
||||
</span>
|
||||
</span>
|
||||
<span class="end num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : 'muted'}">
|
||||
{bal === 0 ? t('settled') : (bal > 0 ? '+' : '−') + conv(Math.abs(bal))}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<h3 style:margin-top="12px">{t('settle_up')}</h3>
|
||||
{#if transfers.length === 0}
|
||||
<p class="card muted">{t('all_settled')}</p>
|
||||
{:else}
|
||||
<div class="list">
|
||||
{#each transfers as tr}
|
||||
<div class="item">
|
||||
<span class="grow">
|
||||
<span class="title" style:display="block">{session.memberName(tr.from)} → {session.memberName(tr.to)}</span>
|
||||
<span class="num" style:font-weight="700">{conv(tr.amount)}</span>
|
||||
</span>
|
||||
<button class="btn small" onclick={() => record(tr.from, tr.to, tr.amount)}>{t('mark_paid')}</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !compact}
|
||||
<label class="field" style:margin-top="12px">
|
||||
{t('show_in')}
|
||||
<CurrencySelect bind:value={showIn} />
|
||||
{#if showIn && showIn !== session.base}
|
||||
<span class="small">{factor === null ? t('rate_unavailable') : t('display_only_rate')}</span>
|
||||
{/if}
|
||||
</label>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.bar { display: block; height: 6px; margin-top: 6px; background: var(--surface-2); border-radius: 3px; overflow: hidden; }
|
||||
.fill { display: block; height: 100%; border-radius: 3px; }
|
||||
.pos-fill { background: var(--accent); }
|
||||
.neg-fill { background: var(--owe); }
|
||||
</style>
|
||||
37
apps/web/src/components/CurrencySelect.svelte
Normal file
37
apps/web/src/components/CurrencySelect.svelte
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<script lang="ts">
|
||||
import { currencyList } from '../lib/rates.ts';
|
||||
import { currencyName } from '../lib/format.ts';
|
||||
|
||||
let { value = $bindable(), disabled = false, id }: { value: string; disabled?: boolean; id?: string } = $props();
|
||||
let lists = $state<{ ecb: string[]; other: string[] }>({ ecb: [], other: [] });
|
||||
currencyList().then((l) => (lists = l));
|
||||
|
||||
const recent = (() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('oweme.recentCurrencies') ?? '[]') as string[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
// Keep the current value selectable even before the lists load, or if
|
||||
// it's a code this browser doesn't know.
|
||||
const ecb = $derived(
|
||||
[...lists.ecb, ...lists.other, ...recent].includes(value) ? lists.ecb : [value, ...lists.ecb],
|
||||
);
|
||||
</script>
|
||||
|
||||
<select bind:value {disabled} {id}>
|
||||
{#if recent.length}
|
||||
<optgroup label="★">
|
||||
{#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
</optgroup>
|
||||
{/if}
|
||||
<optgroup label="ECB">
|
||||
{#each ecb as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
</optgroup>
|
||||
{#if lists.other.length}
|
||||
<optgroup label="…">
|
||||
{#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
</optgroup>
|
||||
{/if}
|
||||
</select>
|
||||
161
apps/web/src/components/ExpenseDetail.svelte
Normal file
161
apps/web/src/components/ExpenseDetail.svelte
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
<script lang="ts">
|
||||
import { inBase, owedOriginal, type Expense } from '@oweme/core';
|
||||
import { randomId } from '../lib/crypto.ts';
|
||||
import { CATEGORY_ICONS, fmtDate, fmtDateTime, money } from '../lib/format.ts';
|
||||
import type { MsgKey } from '../lib/i18n.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Avatar from './Avatar.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import PhotoView from './PhotoView.svelte';
|
||||
import Sheet from './Sheet.svelte';
|
||||
|
||||
let { session, eid }: { session: GroupSession; eid: string } = $props();
|
||||
let comment = $state('');
|
||||
|
||||
const rec = $derived(session.state.expenses[eid]);
|
||||
const e = $derived(rec?.expense);
|
||||
const b = $derived(e ? inBase(e, session.base) : null);
|
||||
const orig = $derived(e ? owedOriginal(e) : {});
|
||||
const comments = $derived(Object.values(session.state.comments).filter((c) => c.expenseId === eid).sort((a, b) => a.at.localeCompare(b.at)));
|
||||
const versions = $derived(
|
||||
session.activity
|
||||
.filter((a) => a.entityId === eid && !a.ignored && (a.type === 'expense.created' || a.type === 'expense.updated'))
|
||||
.map((a) => ({ ...a, exp: a.after as Expense }))
|
||||
.reverse(),
|
||||
);
|
||||
const memberIdx = (id: string) => session.state.members.findIndex((m) => m.id === id);
|
||||
const member = (id: string) => session.state.members.find((m) => m.id === id);
|
||||
|
||||
const close = () => router.back(`/g/${session.id}`);
|
||||
const edit = () => router.go(`/g/${session.id}/e/${encodeURIComponent(eid)}/edit`, { replace: true });
|
||||
|
||||
async function remove() {
|
||||
if (!confirm(t('confirm_delete'))) return;
|
||||
await session.emit({ type: 'expense.deleted', data: { id: eid } });
|
||||
close();
|
||||
}
|
||||
|
||||
async function restoreVersion(v: Expense) {
|
||||
const events = [];
|
||||
if (rec?.deleted) events.push({ type: 'expense.restored' as const, data: { id: eid } });
|
||||
events.push({ type: 'expense.updated' as const, data: v });
|
||||
await session.emit(...events);
|
||||
}
|
||||
|
||||
async function addComment(ev: SubmitEvent) {
|
||||
ev.preventDefault();
|
||||
const text = comment.trim();
|
||||
if (!text) return;
|
||||
comment = '';
|
||||
await session.emit({ type: 'comment.added', data: { id: randomId(9), expenseId: eid, text } });
|
||||
}
|
||||
|
||||
/** Field names that differ between two versions, for the history list. */
|
||||
function changed(a: Expense | undefined, bb: Expense): string {
|
||||
if (!a) return '';
|
||||
const labels: [keyof Expense, MsgKey][] = [
|
||||
['title', 'title'], ['amount', 'amount'], ['currency', 'currency'], ['rate', 'rate'], ['date', 'date'],
|
||||
['category', 'category'], ['payers', 'paid_by_label'], ['split', 'split'], ['note', 'note'], ['photo', 'photo'],
|
||||
];
|
||||
const out = labels.filter(([k]) => JSON.stringify(a[k]) !== JSON.stringify(bb[k])).map(([, l]) => t(l).replace(/[?:]$/, ''));
|
||||
return out.length ? t('changed_fields', { fields: out.join(', ') }) : '';
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !e || !b}
|
||||
<Sheet title="…" onclose={close}><p class="empty">{t('loading')}</p></Sheet>
|
||||
{:else}
|
||||
<Sheet title={e.kind === 'transfer' ? t('kind_transfer') : e.title} onclose={close}>
|
||||
{#snippet actions()}
|
||||
{#if !rec.deleted}
|
||||
<button class="icon-btn" onclick={edit} aria-label={t('edit')}><Icon name="edit" /></button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
<div class="stack">
|
||||
{#if rec.deleted}
|
||||
<div class="banner warn row">
|
||||
<span class="grow" style:flex="1">{t('deleted_banner')}</span>
|
||||
<button class="btn small" onclick={() => session.emit({ type: 'expense.restored', data: { id: eid } })}>{t('restore')}</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="card stack" style:align-items="center" style:text-align="center">
|
||||
<span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category]}</span>
|
||||
<div class="num" style:font-size="2rem" style:font-weight="700">{money(e.amount, e.currency)}</div>
|
||||
{#if e.currency !== session.base}
|
||||
<div class="muted small num">{t('converted', { amount: money(b.total, session.base), rate: e.rate })}</div>
|
||||
{/if}
|
||||
<div class="muted small">
|
||||
{fmtDate(e.date, 'long')} · {t(`cat_${e.category}` as MsgKey)}
|
||||
{#if e.recurringId} · <Icon name="repeat" size={12} /> {t('recurring_badge')}{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if e.photo}<PhotoView {session} photo={e.photo} />{/if}
|
||||
{#if e.note}<p class="card" style:white-space="pre-wrap">{e.note}</p>{/if}
|
||||
|
||||
<h3>{t('split_details')}</h3>
|
||||
<div class="list">
|
||||
{#each session.state.members.filter((m) => b.paid[m.id] || b.owed[m.id]) as m (m.id)}
|
||||
<div class="item">
|
||||
<Avatar member={m} index={memberIdx(m.id)} size={32} />
|
||||
<span class="grow">
|
||||
<span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span>
|
||||
{#if b.paid[m.id]}<span class="sub pos" style:display="block">{t('paid', { amount: money(e.payers.find((p) => p.member === m.id)!.amount, e.currency) })}</span>{/if}
|
||||
</span>
|
||||
{#if b.owed[m.id]}
|
||||
<span class="end num small">
|
||||
{t('owes_share', { amount: money(orig[m.id] ?? 0, e.currency) })}
|
||||
{#if e.currency !== session.base}<span class="muted" style:display="block">{money(b.owed[m.id], session.base)}</span>{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<h3>{t('comments')}</h3>
|
||||
{#if comments.length}
|
||||
<div class="list">
|
||||
{#each comments as c (c.id)}
|
||||
<div class="item" style:align-items="flex-start">
|
||||
<Avatar member={member(c.author ?? '')} index={memberIdx(c.author ?? '')} size={28} />
|
||||
<span class="grow">
|
||||
<span class="small muted">{session.memberName(c.author)} · {fmtDateTime(c.at)}</span>
|
||||
<span style:display="block" style:white-space="pre-wrap">{c.text}</span>
|
||||
</span>
|
||||
<button class="icon-btn" onclick={() => session.emit({ type: 'comment.deleted', data: { id: c.id } })} aria-label={t('delete')}><Icon name="trash" size={16} /></button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<form class="row" onsubmit={addComment}>
|
||||
<input bind:value={comment} placeholder={t('add_comment')} maxlength="2000" aria-label={t('add_comment')} />
|
||||
<button class="btn" type="submit" disabled={!comment.trim()}>{t('send')}</button>
|
||||
</form>
|
||||
|
||||
<h3>{t('history')}</h3>
|
||||
<div class="list">
|
||||
{#each versions as v, i (v.eventId)}
|
||||
<div class="item">
|
||||
<span class="grow">
|
||||
<span class="small muted" style:display="block">{session.memberName(v.actor) === '?' ? t('someone') : session.memberName(v.actor)} · {fmtDateTime(v.at)}</span>
|
||||
<span style:display="block">{v.exp.title || t('kind_transfer')} · <span class="num">{money(v.exp.amount, v.exp.currency)}</span></span>
|
||||
<span class="small muted">{changed(versions[i + 1]?.exp, v.exp)}</span>
|
||||
</span>
|
||||
{#if !rec.deleted && JSON.stringify(v.exp) === JSON.stringify(e)}
|
||||
<span class="small muted">{t('current_version')}</span>
|
||||
{:else}
|
||||
<button class="btn small" onclick={() => restoreVersion(v.exp)}>{t('restore')}</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if !rec.deleted}
|
||||
<button class="btn danger" onclick={remove}><Icon name="trash" size={18} /> {t('delete')}</button>
|
||||
{/if}
|
||||
</div>
|
||||
</Sheet>
|
||||
{/if}
|
||||
422
apps/web/src/components/ExpenseEditor.svelte
Normal file
422
apps/web/src/components/ExpenseEditor.svelte
Normal file
|
|
@ -0,0 +1,422 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import {
|
||||
CATEGORIES, exponent, isValidRate, owedOriginal, parseAmount, validateExpense,
|
||||
type Category, type Expense, type Freq, type Photo, type SplitMode,
|
||||
} from '@oweme/core';
|
||||
import { serverConfig } from '../lib/api.ts';
|
||||
import { randomId } from '../lib/crypto.ts';
|
||||
import { amountInput, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
|
||||
import { processPhoto, type ProcessedPhoto } from '../lib/photo.ts';
|
||||
import { suggestRate } from '../lib/rates.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { settings, t } from '../lib/settings.svelte.ts';
|
||||
import type { MsgKey } from '../lib/i18n.ts';
|
||||
import Avatar from './Avatar.svelte';
|
||||
import CurrencySelect from './CurrencySelect.svelte';
|
||||
import PhotoView from './PhotoView.svelte';
|
||||
import Sheet from './Sheet.svelte';
|
||||
|
||||
// Read once: the editor is keyed by route, so a new expense remounts it.
|
||||
const props: { session: GroupSession; eid: string | null; params: URLSearchParams } = $props();
|
||||
const { session, eid, params } = untrack(() => props);
|
||||
|
||||
const existing: Expense | null = eid ? (session.state.expenses[eid]?.expense ?? null) : null;
|
||||
const base = session.base;
|
||||
const me = session.me;
|
||||
const allMembers = session.state.members;
|
||||
// Archived members only show up if this expense already involves them.
|
||||
const involved = new Set([...(existing?.payers.map((p) => p.member) ?? []), ...(existing?.split.entries.map((s) => s.member) ?? [])]);
|
||||
const members = allMembers.filter((m) => !m.archived || involved.has(m.id));
|
||||
const memberIndex = (id: string) => allMembers.findIndex((m) => m.id === id);
|
||||
const defaultPayer = me ?? members[0]?.id ?? '';
|
||||
|
||||
// ---- form state ----------------------------------------------------
|
||||
const pAmount = Number(params.get('amount'));
|
||||
let kind = $state<'expense' | 'transfer'>(existing?.kind ?? (params.get('kind') === 'transfer' ? 'transfer' : 'expense'));
|
||||
let currency = $state(existing?.currency ?? base);
|
||||
let amountText = $state(existing ? amountInput(existing.amount, existing.currency) : pAmount > 0 ? amountInput(pAmount, base) : '');
|
||||
let title = $state(existing?.title ?? '');
|
||||
let category = $state<Category>(existing?.category === 'transfer' ? 'other' : (existing?.category ?? 'food'));
|
||||
let date = $state(existing?.date ?? today());
|
||||
let note = $state(existing?.note ?? '');
|
||||
let rateText = $state(existing && existing.currency !== base ? existing.rate : '1');
|
||||
let rateSource = $state(existing?.rateSource ?? 'same');
|
||||
let rateMissing = $state(false);
|
||||
|
||||
let multiPayer = $state((existing?.payers.length ?? 1) > 1);
|
||||
let payer = $state(existing?.payers[0]?.member ?? params.get('from') ?? defaultPayer);
|
||||
let payerAmounts = $state<Record<string, string>>(
|
||||
Object.fromEntries(members.map((m) => {
|
||||
const p = existing?.payers.find((x) => x.member === m.id);
|
||||
return [m.id, p ? amountInput(p.amount, existing!.currency) : ''];
|
||||
})),
|
||||
);
|
||||
let transferTo = $state(
|
||||
existing?.kind === 'transfer' ? (existing.split.entries.find((s) => s.value > 0)?.member ?? '') : (params.get('to') ?? members.find((m) => m.id !== payer)?.id ?? ''),
|
||||
);
|
||||
|
||||
let mode = $state<SplitMode>(existing?.kind === 'expense' ? existing.split.mode : 'equal');
|
||||
const initValue = (id: string): string => {
|
||||
const e = existing?.kind === 'expense' ? existing.split.entries.find((s) => s.member === id) : undefined;
|
||||
if (!e) return mode === 'equal' ? '1' : mode === 'shares' ? '1' : '';
|
||||
if (mode === 'exact') return e.value ? amountInput(e.value, existing!.currency) : '';
|
||||
if (mode === 'percent') return e.value ? String(e.value / 100).replace('.', settings.lang === 'cs' ? ',' : '.') : '';
|
||||
return String(e.value);
|
||||
};
|
||||
let values = $state<Record<string, string>>(Object.fromEntries(members.map((m) => [m.id, initValue(m.id)])));
|
||||
let included = $state<Record<string, boolean>>(
|
||||
Object.fromEntries(members.map((m) => {
|
||||
const e = existing?.kind === 'expense' ? existing.split.entries.find((s) => s.member === m.id) : undefined;
|
||||
return [m.id, existing?.kind === 'expense' ? !!e && e.value > 0 : !m.archived];
|
||||
})),
|
||||
);
|
||||
|
||||
let photo = $state<Photo | null>(existing?.photo ?? null);
|
||||
let newPhoto = $state<ProcessedPhoto | null>(null);
|
||||
let newPhotoUrl = $state<string | null>(null);
|
||||
let photoBusy = $state(false);
|
||||
let repeat = $state<'none' | Freq>('none');
|
||||
let error = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
// ---- derived -------------------------------------------------------
|
||||
const amount = $derived(parseAmount(amountText, currency));
|
||||
const exp = $derived(exponent(currency));
|
||||
|
||||
/** Parse a member's split value into the integer the event stores. */
|
||||
function splitValue(id: string): number | null {
|
||||
const raw = (values[id] ?? '').trim();
|
||||
if (mode === 'equal') return included[id] ? 1 : 0;
|
||||
if (!included[id] || raw === '' || raw === '0') return 0;
|
||||
if (mode === 'shares') return /^\d{1,6}$/.test(raw) ? Number(raw) : null;
|
||||
if (mode === 'exact') return parseAmount(raw, currency);
|
||||
const m = /^(\d{1,3})(?:[.,](\d{1,2}))?$/.exec(raw); // percent → basis points
|
||||
return m ? Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0')) : null;
|
||||
}
|
||||
|
||||
const splitEntries = $derived(members.map((m) => ({ member: m.id, value: splitValue(m.id) })));
|
||||
const splitSum = $derived(splitEntries.reduce((a, e) => a + (e.value ?? 0), 0));
|
||||
const remaining = $derived(mode === 'exact' ? (amount ?? 0) - splitSum : mode === 'percent' ? 10000 - splitSum : 0);
|
||||
|
||||
const payers = $derived.by(() => {
|
||||
if (!multiPayer || kind === 'transfer') return amount ? [{ member: payer, amount }] : [];
|
||||
return members
|
||||
.map((m) => ({ member: m.id, amount: parseAmount(payerAmounts[m.id] ?? '', currency) ?? 0 }))
|
||||
.filter((p) => p.amount > 0);
|
||||
});
|
||||
const payersRemaining = $derived((amount ?? 0) - payers.reduce((a, p) => a + p.amount, 0));
|
||||
|
||||
function build(): Expense | null {
|
||||
if (!amount) return null;
|
||||
const isTransfer = kind === 'transfer';
|
||||
return {
|
||||
id: existing?.id ?? randomId(12),
|
||||
kind,
|
||||
title: isTransfer ? '' : title.trim(),
|
||||
category: isTransfer ? 'transfer' : category,
|
||||
date,
|
||||
currency,
|
||||
amount,
|
||||
rate: currency === base ? '1' : rateText.trim().replace(',', '.'),
|
||||
rateSource: currency === base ? 'same' : rateSource,
|
||||
payers,
|
||||
split: isTransfer
|
||||
? { mode: 'equal', entries: [{ member: transferTo, value: 1 }] }
|
||||
: { mode, entries: splitEntries.filter((e) => e.value !== null && (mode === 'equal' || e.value > 0 || included[e.member])).map((e) => ({ member: e.member, value: e.value ?? 0 })) },
|
||||
note: note.trim(),
|
||||
photo,
|
||||
...(existing?.recurringId ? { recurringId: existing.recurringId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Live per-member preview of the split, in the expense currency. */
|
||||
const preview = $derived.by(() => {
|
||||
const e = build();
|
||||
if (!e || kind === 'transfer' || validateExpense({ ...e, photo: null }, allMembers) !== null) return {} as Record<string, number>;
|
||||
return owedOriginal(e);
|
||||
});
|
||||
|
||||
// Prefill the exchange rate from ECB rates. A rate typed by hand is kept
|
||||
// when the date changes, but not when the currency does. An existing
|
||||
// expense keeps its stored rate until one of them changes.
|
||||
let lastCurrency = untrack(() => currency);
|
||||
let firstRun = true;
|
||||
$effect(() => {
|
||||
const c = currency;
|
||||
const d = date;
|
||||
const currencyChanged = c !== lastCurrency;
|
||||
lastCurrency = c;
|
||||
const keepStored = firstRun && !!existing;
|
||||
firstRun = false;
|
||||
if (c === base) {
|
||||
rateText = '1';
|
||||
rateSource = 'same';
|
||||
rateMissing = false;
|
||||
return;
|
||||
}
|
||||
if (keepStored || (!currencyChanged && untrack(() => rateSource) === 'manual')) return;
|
||||
suggestRate(c, base, d).then((r) => {
|
||||
if (c !== currency || d !== date) return;
|
||||
rateMissing = !r;
|
||||
if (r) {
|
||||
rateText = r.rate;
|
||||
rateSource = r.source;
|
||||
} else if (currencyChanged) {
|
||||
rateText = '';
|
||||
rateSource = 'manual';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function setMode(m: SplitMode) {
|
||||
mode = m;
|
||||
for (const mem of members) values[mem.id] = m === 'shares' ? '1' : '';
|
||||
}
|
||||
|
||||
async function pickPhoto(e: Event) {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
photoBusy = true;
|
||||
error = '';
|
||||
try {
|
||||
const cfg = await serverConfig().catch(() => ({ maxPhotoBytes: 2 * 1024 * 1024 }));
|
||||
newPhoto = await processPhoto(file, cfg.maxPhotoBytes);
|
||||
if (newPhotoUrl) URL.revokeObjectURL(newPhotoUrl);
|
||||
newPhotoUrl = URL.createObjectURL(newPhoto.full);
|
||||
photo = null;
|
||||
} catch (err) {
|
||||
error = (err as Error).message === 'too large' ? t('photo_too_large') : t('error_generic', { msg: (err as Error).message });
|
||||
} finally {
|
||||
photoBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removePhoto() {
|
||||
photo = null;
|
||||
newPhoto = null;
|
||||
if (newPhotoUrl) URL.revokeObjectURL(newPhotoUrl);
|
||||
newPhotoUrl = null;
|
||||
}
|
||||
|
||||
const ERRORS: Record<string, MsgKey> = {
|
||||
amount: 'invalid_amount', 'payers sum': 'invalid_payers', 'payer amount': 'invalid_payers', payers: 'invalid_payers',
|
||||
'exact sum': 'invalid_split', 'percent sum': 'invalid_split', equal: 'invalid_split', shares: 'invalid_split',
|
||||
'split value': 'invalid_split', split: 'invalid_split', transfer: 'invalid_split', rate: 'rate_unavailable',
|
||||
};
|
||||
|
||||
async function save(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
error = '';
|
||||
if (!members.length) return (error = t('need_members'));
|
||||
if (kind === 'expense' && !title.trim()) return (error = t('need_title'));
|
||||
if (currency !== base && !isValidRate(rateText.trim().replace(',', '.'))) return (error = t('rate_unavailable'));
|
||||
const exp = build();
|
||||
if (!exp) return (error = t('invalid_amount'));
|
||||
const reason = validateExpense({ ...exp, photo: null }, allMembers);
|
||||
if (reason) return (error = t(ERRORS[reason] ?? 'invalid_split'));
|
||||
|
||||
saving = true;
|
||||
try {
|
||||
if (newPhoto) {
|
||||
const blobId = await session.addBlob(await newPhoto.full.arrayBuffer());
|
||||
const thumbBlobId = await session.addBlob(await newPhoto.thumb.arrayBuffer());
|
||||
exp.photo = { blobId, thumbBlobId, w: newPhoto.w, h: newPhoto.h };
|
||||
}
|
||||
if (existing) {
|
||||
await session.emit({ type: 'expense.updated', data: exp });
|
||||
} else if (repeat !== 'none' && kind === 'expense') {
|
||||
const { id: _id, date: start, photo: _p, recurringId: _r, ...template } = exp;
|
||||
await session.emit({ type: 'recurring.created', data: { id: randomId(9), template, rule: { freq: repeat, interval: 1, start, end: null } } });
|
||||
await session.createDueOccurrences();
|
||||
} else {
|
||||
await session.emit({ type: 'expense.created', data: exp });
|
||||
}
|
||||
try {
|
||||
const recent = JSON.parse(localStorage.getItem('oweme.recentCurrencies') ?? '[]') as string[];
|
||||
localStorage.setItem('oweme.recentCurrencies', JSON.stringify([currency, ...recent.filter((c) => c !== currency)].slice(0, 4)));
|
||||
} catch { /* per-device nicety only */ }
|
||||
close();
|
||||
} catch (err) {
|
||||
error = t('error_generic', { msg: (err as Error).message });
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function close() {
|
||||
router.back(`/g/${session.id}`);
|
||||
}
|
||||
|
||||
const heading = $derived(existing ? t('edit_expense') : kind === 'transfer' ? t('new_transfer') : t('new_expense'));
|
||||
</script>
|
||||
|
||||
<Sheet title={heading} onclose={close}>
|
||||
<form class="stack" onsubmit={save} novalidate>
|
||||
{#if !existing}
|
||||
<div class="seg" role="group">
|
||||
<button type="button" aria-pressed={kind === 'expense'} onclick={() => (kind = 'expense')}>{t('kind_expense')}</button>
|
||||
<button type="button" aria-pressed={kind === 'transfer'} onclick={() => (kind = 'transfer')}>{t('kind_transfer')}</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="card stack" style:gap="4px">
|
||||
<label class="sr-only" for="amount">{t('amount')}</label>
|
||||
<input id="amount" class="amount-input num" bind:value={amountText} inputmode="decimal" placeholder={exp === 0 ? '0' : `0${settings.lang === 'cs' ? ',' : '.'}${'0'.repeat(exp)}`} autocomplete="off" />
|
||||
<div class="row" style:justify-content="center">
|
||||
<label class="sr-only" for="currency">{t('currency')}</label>
|
||||
<div style:max-width="260px" style:width="100%"><CurrencySelect id="currency" bind:value={currency} /></div>
|
||||
</div>
|
||||
{#if currency !== base}
|
||||
<div class="row small" style:justify-content="center" style:margin-top="6px">
|
||||
<label for="rate" class="muted">1 {currency} =</label>
|
||||
<input id="rate" class="num" style:width="120px" style:min-height="36px" inputmode="decimal" bind:value={rateText}
|
||||
oninput={() => (rateSource = 'manual')} />
|
||||
<span class="muted">{base}</span>
|
||||
</div>
|
||||
<p class="small muted" style:text-align="center">
|
||||
{#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')}
|
||||
{:else if rateSource.startsWith('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })}
|
||||
{:else}{t('rate_source_manual')}{/if}
|
||||
{#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if kind === 'expense'}
|
||||
<label class="field">{t('title')}<input bind:value={title} placeholder={t('title_ph')} maxlength="200" /></label>
|
||||
<div class="field">
|
||||
<span class="small muted">{t('category')}</span>
|
||||
<div class="chips">
|
||||
{#each CATEGORIES as c}
|
||||
<button type="button" class="chip" aria-pressed={category === c} onclick={() => (category = c)}>
|
||||
<span aria-hidden="true">{CATEGORY_ICONS[c]}</span> {t(`cat_${c}` as MsgKey)}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="field">{t('date')}<input type="date" bind:value={date} required /></label>
|
||||
|
||||
<!-- who paid -->
|
||||
{#if kind === 'transfer'}
|
||||
<div class="row">
|
||||
<label class="field" style:flex="1">{t('from_label')}
|
||||
<select bind:value={payer}>{#each members as m}<option value={m.id}>{m.name}</option>{/each}</select>
|
||||
</label>
|
||||
<label class="field" style:flex="1">{t('to_label')}
|
||||
<select bind:value={transferTo}>{#each members.filter((m) => m.id !== payer) as m}<option value={m.id}>{m.name}</option>{/each}</select>
|
||||
</label>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="field">
|
||||
<span class="row small muted">
|
||||
<span class="grow" style:flex="1">{t('paid_by_label')}</span>
|
||||
<label class="row" style:gap="6px"><input type="checkbox" bind:checked={multiPayer} /> {t('multiple_payers')}</label>
|
||||
</span>
|
||||
{#if multiPayer}
|
||||
<div class="list">
|
||||
{#each members as m (m.id)}
|
||||
<div class="item">
|
||||
<Avatar member={m} index={memberIndex(m.id)} size={30} />
|
||||
<span class="grow">{m.name}</span>
|
||||
<input class="num" style:width="120px" inputmode="decimal" bind:value={payerAmounts[m.id]} aria-label="{t('paid_by_label')}: {m.name}" />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if payersRemaining !== 0 && amount}
|
||||
<span class="small {payersRemaining < 0 ? 'neg' : 'muted'}">
|
||||
{payersRemaining > 0 ? t('remaining', { amount: money(payersRemaining, currency) }) : t('over_by', { amount: money(-payersRemaining, currency) })}
|
||||
</span>
|
||||
{/if}
|
||||
{:else}
|
||||
<select bind:value={payer} aria-label={t('paid_by_label')}>
|
||||
{#each members as m}<option value={m.id}>{m.name}{m.id === me ? ` (${t('you')})` : ''}</option>{/each}
|
||||
</select>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- split -->
|
||||
<div class="field">
|
||||
<span class="small muted">{t('split')}</span>
|
||||
<div class="seg" role="group" aria-label={t('split')}>
|
||||
{#each [['equal', 'split_equal'], ['shares', 'split_shares'], ['exact', 'split_exact'], ['percent', 'split_percent']] as const as [m, label]}
|
||||
<button type="button" aria-pressed={mode === m} onclick={() => setMode(m)}>{t(label)}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="row small" style:justify-content="flex-end">
|
||||
<button type="button" class="btn ghost small" onclick={() => members.forEach((m) => (included[m.id] = true))}>{t('select_all')}</button>
|
||||
<button type="button" class="btn ghost small" onclick={() => members.forEach((m) => (included[m.id] = false))}>{t('select_none')}</button>
|
||||
</div>
|
||||
<div class="list">
|
||||
{#each members as m (m.id)}
|
||||
<div class="item">
|
||||
<input type="checkbox" bind:checked={included[m.id]} aria-label={m.name} />
|
||||
<Avatar member={m} index={memberIndex(m.id)} size={30} />
|
||||
<span class="grow">
|
||||
<span style:display="block">{m.name}</span>
|
||||
{#if preview[m.id]}<span class="small muted num">{money(preview[m.id], currency)}</span>{/if}
|
||||
</span>
|
||||
{#if mode !== 'equal'}
|
||||
<span class="row" style:gap="4px">
|
||||
<input class="num" style:width={mode === 'exact' ? '110px' : '72px'} inputmode={mode === 'shares' ? 'numeric' : 'decimal'}
|
||||
bind:value={values[m.id]} disabled={!included[m.id]} aria-label="{t('split')}: {m.name}" />
|
||||
{#if mode === 'percent'}<span class="muted">%</span>{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if (mode === 'exact' || mode === 'percent') && remaining !== 0}
|
||||
<span class="small {remaining < 0 ? 'neg' : 'muted'}">
|
||||
{#if mode === 'exact'}
|
||||
{remaining > 0 ? t('remaining', { amount: money(remaining, currency) }) : t('over_by', { amount: money(-remaining, currency) })}
|
||||
{:else}
|
||||
{remaining > 0 ? t('remaining', { amount: `${remaining / 100} %` }) : t('over_by', { amount: `${-remaining / 100} %` })}
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- photo -->
|
||||
{#if repeat === 'none'}
|
||||
<div class="field">
|
||||
<span class="small muted">{t('photo')}</span>
|
||||
{#if newPhotoUrl}
|
||||
<img class="photo-thumb" src={newPhotoUrl} alt={t('photo')} />
|
||||
{:else if photo}
|
||||
<PhotoView {session} {photo} />
|
||||
{/if}
|
||||
<div class="row">
|
||||
<label class="btn small">
|
||||
{photo || newPhoto ? t('replace_photo') : t('add_photo')}
|
||||
<input class="sr-only" type="file" accept="image/*" onchange={pickPhoto} disabled={photoBusy} />
|
||||
</label>
|
||||
{#if photo || newPhoto}<button type="button" class="btn small ghost" onclick={removePhoto}>{t('remove_photo')}</button>{/if}
|
||||
{#if photoBusy}<span class="small muted">{t('processing_photo')}</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="field">{t('note')}<textarea bind:value={note} maxlength="2000"></textarea></label>
|
||||
|
||||
{#if !existing && kind === 'expense'}
|
||||
<label class="field">{t('repeat')}
|
||||
<select bind:value={repeat}>
|
||||
<option value="none">{t('repeat_none')}</option>
|
||||
<option value="weekly">{t('repeat_weekly')}</option>
|
||||
<option value="monthly">{t('repeat_monthly')}</option>
|
||||
<option value="yearly">{t('repeat_yearly')}</option>
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
{#if error}<p class="neg" role="alert">{error}</p>{/if}
|
||||
<div class="row">
|
||||
<button type="button" class="btn" style:flex="1" onclick={close}>{t('cancel')}</button>
|
||||
<button type="submit" class="btn primary" style:flex="2" disabled={saving || photoBusy}>{t('save')}</button>
|
||||
</div>
|
||||
</form>
|
||||
</Sheet>
|
||||
103
apps/web/src/components/ExpenseList.svelte
Normal file
103
apps/web/src/components/ExpenseList.svelte
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
<script lang="ts">
|
||||
import { inBase } from '@oweme/core';
|
||||
import { addDays, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
let { session }: { session: GroupSession } = $props();
|
||||
let query = $state('');
|
||||
|
||||
const rows = $derived.by(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
const recs = Object.values(session.state.expenses)
|
||||
.filter((r) => !r.deleted)
|
||||
.filter((r) => !q || r.expense.title.toLowerCase().includes(q) || r.expense.note.toLowerCase().includes(q))
|
||||
.sort((a, b) => b.expense.date.localeCompare(a.expense.date) || b.createdAt.localeCompare(a.createdAt));
|
||||
const groups: { date: string; items: typeof recs }[] = [];
|
||||
for (const r of recs) {
|
||||
const last = groups[groups.length - 1];
|
||||
if (last?.date === r.expense.date) last.items.push(r);
|
||||
else groups.push({ date: r.expense.date, items: [r] });
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
|
||||
const total = $derived(
|
||||
Object.values(session.state.expenses)
|
||||
.filter((r) => !r.deleted && r.expense.kind === 'expense')
|
||||
.reduce((a, r) => a + inBase(r.expense, session.base).total, 0),
|
||||
);
|
||||
|
||||
function dayLabel(d: string) {
|
||||
if (d === today()) return t('today');
|
||||
if (d === addDays(today(), -1)) return t('yesterday');
|
||||
return fmtDate(d, 'long');
|
||||
}
|
||||
|
||||
function mine(e: (typeof rows)[number]['items'][number]['expense']) {
|
||||
const me = session.me;
|
||||
if (!me) return null;
|
||||
const b = inBase(e, session.base);
|
||||
const net = (b.paid[me] ?? 0) - (b.owed[me] ?? 0);
|
||||
if (net > 0) return { cls: 'pos', text: t('you_lent', { amount: money(net, session.base) }) };
|
||||
if (net < 0) return { cls: 'neg', text: t('you_borrowed', { amount: money(-net, session.base) }) };
|
||||
return { cls: 'muted', text: b.owed[me] ? t('your_share', { amount: money(b.owed[me], session.base) }) : t('not_involved') };
|
||||
}
|
||||
|
||||
function open(e: MouseEvent, id: string) {
|
||||
e.preventDefault();
|
||||
router.go(`/g/${session.id}/e/${encodeURIComponent(id)}`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="stack">
|
||||
<div class="card row">
|
||||
<div class="grow">
|
||||
<div class="muted small">{t('total_spent')}</div>
|
||||
<div class="num" style:font-size="1.6rem" style:font-weight="700">{money(total, session.base)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if Object.keys(session.state.expenses).length > 6}
|
||||
<input type="search" bind:value={query} placeholder={t('search')} aria-label={t('search')} />
|
||||
{/if}
|
||||
|
||||
{#if rows.length === 0}
|
||||
<p class="empty">{session.status === 'loading' ? t('loading') : t('no_expenses')}</p>
|
||||
{/if}
|
||||
|
||||
{#each rows as day (day.date)}
|
||||
<section class="stack" style:gap="6px">
|
||||
<h3>{dayLabel(day.date)}</h3>
|
||||
<div class="list">
|
||||
{#each day.items as r (r.expense.id)}
|
||||
{@const e = r.expense}
|
||||
{@const m = mine(e)}
|
||||
<a class="item" href="/g/{session.id}/e/{encodeURIComponent(e.id)}" onclick={(ev) => open(ev, e.id)}>
|
||||
<span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category] ?? '🧾'}</span>
|
||||
<span class="grow">
|
||||
<span class="title row" style:gap="6px">
|
||||
{#if e.kind === 'transfer'}
|
||||
{t('transfer_line', { from: session.memberName(e.payers[0]?.member), to: session.memberName(e.split.entries.find((x) => x.value > 0)?.member) })}
|
||||
{:else}
|
||||
{e.title}
|
||||
{/if}
|
||||
{#if e.recurringId}<Icon name="repeat" size={14} />{/if}
|
||||
{#if e.photo}<Icon name="camera" size={14} />{/if}
|
||||
</span>
|
||||
<span class="sub" style:display="block">
|
||||
{e.payers.length === 1 ? t('paid_by', { name: session.memberName(e.payers[0].member) }) : t('paid_by_many', { n: e.payers.length })}
|
||||
</span>
|
||||
</span>
|
||||
<span class="end">
|
||||
<span class="num" style:display="block" style:font-weight="600">{money(e.amount, e.currency)}</span>
|
||||
{#if m}<span class="small num {m.cls}" style:display="block">{m.text}</span>{/if}
|
||||
</span>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/each}
|
||||
</div>
|
||||
132
apps/web/src/components/GroupPage.svelte
Normal file
132
apps/web/src/components/GroupPage.svelte
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<script lang="ts">
|
||||
import { onDestroy, untrack } from 'svelte';
|
||||
import { forgetGroup } from '../lib/idb.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import { closeSession, openSession, type GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Activity from './Activity.svelte';
|
||||
import Balances from './Balances.svelte';
|
||||
import ExpenseDetail from './ExpenseDetail.svelte';
|
||||
import ExpenseEditor from './ExpenseEditor.svelte';
|
||||
import ExpenseList from './ExpenseList.svelte';
|
||||
import GroupSettings from './GroupSettings.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import IdentityPicker from './IdentityPicker.svelte';
|
||||
import Stats from './Stats.svelte';
|
||||
|
||||
// Keyed by group id in App.svelte, so reading it once is enough.
|
||||
const props: { id: string } = $props();
|
||||
const id = untrack(() => props.id);
|
||||
let session = $state<GroupSession | null | undefined>(undefined);
|
||||
let skippedIdentity = $state(false);
|
||||
|
||||
openSession(id).then((s) => (session = s));
|
||||
onDestroy(() => closeSession(id));
|
||||
|
||||
const route = $derived(router.route);
|
||||
const tab = $derived(route.name === 'group' ? route.tab : 'expenses');
|
||||
const base = `/g/${id}`;
|
||||
const tabs = [
|
||||
{ key: 'expenses', path: base, icon: 'list', label: 'expenses' },
|
||||
{ key: 'balances', path: `${base}/balances`, icon: 'scale', label: 'balances' },
|
||||
{ key: 'stats', path: `${base}/stats`, icon: 'chart', label: 'stats' },
|
||||
{ key: 'activity', path: `${base}/activity`, icon: 'clock', label: 'activity' },
|
||||
] as const;
|
||||
|
||||
function nav(e: MouseEvent, path: string, replace = false) {
|
||||
e.preventDefault();
|
||||
router.go(path, { replace });
|
||||
}
|
||||
|
||||
const needsIdentity = $derived(
|
||||
!!session && session.status !== 'loading' && session.state.members.length > 0 && !session.me && !skippedIdentity,
|
||||
);
|
||||
|
||||
async function remove() {
|
||||
await forgetGroup(id);
|
||||
router.go('/', { replace: true });
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if session === undefined}
|
||||
<main class="page"><p class="empty">{t('loading')}</p></main>
|
||||
{:else if session === null}
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button>
|
||||
<h1>{t('app_name')}</h1>
|
||||
</header>
|
||||
<main class="page"><p class="card">{t('group_not_on_device')}</p></main>
|
||||
{:else if route.name === 'group-settings'}
|
||||
<GroupSettings {session} />
|
||||
{:else}
|
||||
{@const s = session}
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button>
|
||||
<h1><span aria-hidden="true">{s.state.group?.icon}</span> {s.state.group?.name ?? s.local.name}</h1>
|
||||
<a class="icon-btn" href="{base}/settings" onclick={(e) => nav(e, `${base}/settings`)} aria-label={t('group_settings')}><Icon name="settings" /></a>
|
||||
</header>
|
||||
|
||||
<main class="page wide stack">
|
||||
{#if s.status === 'gone'}
|
||||
<div class="banner danger stack">
|
||||
<p>{t('not_found_group')}</p>
|
||||
<button class="btn small danger" onclick={remove}>{t('remove_from_device')}</button>
|
||||
</div>
|
||||
{:else if s.status === 'offline'}
|
||||
<p class="banner">{t('offline')}</p>
|
||||
{/if}
|
||||
{#if s.pending.length && s.status !== 'online'}
|
||||
<p class="muted small">{t('pending', { n: s.pending.length })}</p>
|
||||
{/if}
|
||||
{#if s.rollback}<p class="banner warn">{t('rollback_warning')}</p>{/if}
|
||||
|
||||
<nav class="tabbar" aria-label={s.state.group?.name}>
|
||||
{#each tabs as tb}
|
||||
<a href={tb.path} aria-current={tab === tb.key ? 'page' : undefined} onclick={(e) => nav(e, tb.path, true)}>
|
||||
<Icon name={tb.icon} size={20} />
|
||||
{t(tb.label)}
|
||||
</a>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<div class="layout" class:with-side={tab === 'expenses'}>
|
||||
<div class="main-col">
|
||||
{#if tab === 'expenses'}
|
||||
<ExpenseList session={s} />
|
||||
{:else if tab === 'balances'}
|
||||
<Balances session={s} />
|
||||
{:else if tab === 'stats'}
|
||||
<Stats session={s} />
|
||||
{:else}
|
||||
<Activity session={s} />
|
||||
{/if}
|
||||
</div>
|
||||
{#if tab === 'expenses'}
|
||||
<aside class="side-col"><Balances session={s} compact /></aside>
|
||||
{/if}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{#if s.status !== 'gone' && (tab === 'expenses' || tab === 'balances')}
|
||||
<a class="fab" href="{base}/e/new" onclick={(e) => nav(e, `${base}/e/new`)} aria-label={t('add_expense')}><Icon name="plus" size={28} /></a>
|
||||
{/if}
|
||||
|
||||
{#if route.name === 'expense'}
|
||||
<ExpenseDetail session={s} eid={route.eid} />
|
||||
{:else if route.name === 'expense-edit'}
|
||||
{#key route.eid}
|
||||
<ExpenseEditor session={s} eid={route.eid} params={route.params} />
|
||||
{/key}
|
||||
{:else if needsIdentity}
|
||||
<IdentityPicker session={s} onskip={() => (skippedIdentity = true)} />
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.layout { display: grid; gap: 24px; }
|
||||
.side-col { display: none; }
|
||||
@media (min-width: 960px) {
|
||||
.layout.with-side { grid-template-columns: minmax(0, 1fr) 340px; }
|
||||
.side-col { display: block; position: sticky; top: 80px; align-self: start; }
|
||||
}
|
||||
</style>
|
||||
257
apps/web/src/components/GroupSettings.svelte
Normal file
257
apps/web/src/components/GroupSettings.svelte
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { balancesCsv, expensesCsv, nextOccurrence } from '@oweme/core';
|
||||
import { renderSVG } from 'uqr';
|
||||
import { api } from '../lib/api.ts';
|
||||
import { makeBackup } from '../lib/backup.ts';
|
||||
import { randomId } from '../lib/crypto.ts';
|
||||
import { download, fmtDate, MEMBER_COLORS, money, slug, today } from '../lib/format.ts';
|
||||
import { forgetGroup } from '../lib/idb.ts';
|
||||
import { disablePush, enablePush, pushSupport, type PushSupport } from '../lib/push.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import { closeSession, type GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import { ui } from '../lib/ui.svelte.ts';
|
||||
import Avatar from './Avatar.svelte';
|
||||
import CurrencySelect from './CurrencySelect.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
const props: { session: GroupSession } = $props();
|
||||
const s = untrack(() => props.session);
|
||||
const justCreated = new URLSearchParams(location.search).has('share');
|
||||
|
||||
const link = `${location.origin}/g/${s.id}#${s.local.secret}`;
|
||||
let showQr = $state(justCreated);
|
||||
const qr = renderSVG(link, { border: 2, whiteColor: '#ffffff', blackColor: '#0B2E22' });
|
||||
|
||||
let name = $state(s.state.group?.name ?? '');
|
||||
let icon = $state(s.state.group?.icon ?? '');
|
||||
let baseCurrency = $state(s.base);
|
||||
let newMember = $state('');
|
||||
let deleteConfirm = $state('');
|
||||
let push = $state<PushSupport | null>(null);
|
||||
let pushBusy = $state(false);
|
||||
pushSupport().then((p) => (push = p));
|
||||
|
||||
const locked = $derived(Object.keys(s.state.expenses).length > 0);
|
||||
const dirty = $derived(name.trim() !== s.state.group?.name || icon !== s.state.group?.icon || baseCurrency !== s.base);
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(link);
|
||||
ui.show(t('copied'));
|
||||
}
|
||||
|
||||
async function nativeShare() {
|
||||
try {
|
||||
await navigator.share({ title: s.state.group?.name, url: link });
|
||||
} catch { /* cancelled */ }
|
||||
}
|
||||
|
||||
async function saveGroup(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) return;
|
||||
const data: { name?: string; icon?: string; baseCurrency?: string } = {};
|
||||
if (name.trim() !== s.state.group?.name) data.name = name.trim();
|
||||
if (icon !== s.state.group?.icon) data.icon = icon;
|
||||
if (!locked && baseCurrency !== s.base) data.baseCurrency = baseCurrency;
|
||||
await s.emit({ type: 'group.updated', data });
|
||||
ui.show(t('saved'));
|
||||
}
|
||||
|
||||
async function addMember(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
const n = newMember.trim();
|
||||
if (!n) return;
|
||||
newMember = '';
|
||||
await s.emit({ type: 'member.added', data: { id: randomId(9), name: n, color: MEMBER_COLORS[s.state.members.length % MEMBER_COLORS.length] } });
|
||||
}
|
||||
|
||||
async function rename(id: string, old: string) {
|
||||
const n = prompt(t('rename'), old)?.trim();
|
||||
if (n && n !== old) await s.emit({ type: 'member.updated', data: { id, name: n.slice(0, 60) } });
|
||||
}
|
||||
|
||||
async function togglePush() {
|
||||
pushBusy = true;
|
||||
try {
|
||||
if (s.local.push) await disablePush(s);
|
||||
else if (!(await enablePush(s))) push = await pushSupport();
|
||||
} catch (e) {
|
||||
ui.show(t('error_generic', { msg: (e as Error).message }), 4000);
|
||||
} finally {
|
||||
pushBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
const fileBase = () => `oweme-${slug(s.state.group?.name ?? 'group')}-${today()}`;
|
||||
|
||||
async function backup() {
|
||||
download(`${fileBase()}.json`, await makeBackup(s), 'application/json');
|
||||
}
|
||||
|
||||
async function removeFromDevice() {
|
||||
if (s.local.push) await disablePush(s).catch(() => {});
|
||||
closeSession(s.id);
|
||||
await forgetGroup(s.id);
|
||||
router.go('/', { replace: true });
|
||||
}
|
||||
|
||||
async function deleteGroup() {
|
||||
if (deleteConfirm.trim() !== s.state.group?.name) return;
|
||||
await api.deleteGroup(s.id, s.keys.authToken);
|
||||
closeSession(s.id);
|
||||
await forgetGroup(s.id);
|
||||
router.go('/', { replace: true });
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={() => (justCreated ? router.go(`/g/${s.id}`, { replace: true }) : router.back(`/g/${s.id}`))} aria-label={t('back')}><Icon name="back" /></button>
|
||||
<h1>{t('group_settings')}</h1>
|
||||
</header>
|
||||
|
||||
<main class="page stack">
|
||||
<!-- share -->
|
||||
<section class="section">
|
||||
<h3>{t('share_group')}</h3>
|
||||
<div class="card stack">
|
||||
{#if justCreated}<p class="banner warn">{t('save_link_warning')}</p>{/if}
|
||||
<p class="small muted">{t('share_intro')}</p>
|
||||
<div class="row wrap">
|
||||
<button class="btn primary" onclick={copy}><Icon name="copy" size={18} /> {t('copy_link')}</button>
|
||||
{#if 'share' in navigator}<button class="btn" onclick={nativeShare}><Icon name="share" size={18} /> {t('share')}</button>{/if}
|
||||
<button class="btn ghost" onclick={() => (showQr = !showQr)}>QR</button>
|
||||
</div>
|
||||
{#if showQr}
|
||||
<div class="qr">{@html qr}</div>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- group -->
|
||||
<section class="section">
|
||||
<h3>{t('group_settings')}</h3>
|
||||
<form class="card stack" onsubmit={saveGroup}>
|
||||
<div class="row">
|
||||
<label class="field" style:width="80px">{t('icon')}<input bind:value={icon} maxlength="8" /></label>
|
||||
<label class="field" style:flex="1">{t('group_name')}<input bind:value={name} maxlength="100" required /></label>
|
||||
</div>
|
||||
<label class="field">
|
||||
{t('base_currency')}
|
||||
<CurrencySelect bind:value={baseCurrency} disabled={locked} />
|
||||
<span class="small">{locked ? t('base_currency_locked') : t('base_currency_hint')}</span>
|
||||
</label>
|
||||
<button class="btn primary" type="submit" disabled={!dirty || !name.trim()}>{t('save')}</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<!-- identity -->
|
||||
<section class="section">
|
||||
<h3>{t('identity')}</h3>
|
||||
<select value={s.me ?? ''} onchange={(e) => s.setMe((e.target as HTMLSelectElement).value || null)} aria-label={t('identity')}>
|
||||
<option value="">{t('not_set')}</option>
|
||||
{#each s.state.members.filter((m) => !m.archived) as m}<option value={m.id}>{m.name}</option>{/each}
|
||||
</select>
|
||||
</section>
|
||||
|
||||
<!-- members -->
|
||||
<section class="section">
|
||||
<h3>{t('members')}</h3>
|
||||
<div class="list">
|
||||
{#each s.state.members as m, i (m.id)}
|
||||
{@const bal = s.balances[m.id] ?? 0}
|
||||
<div class="item">
|
||||
<Avatar member={m} index={i} size={32} />
|
||||
<span class="grow">
|
||||
<span class="title" style:display="block">{m.name}{m.archived ? ` · ${t('archived')}` : ''}</span>
|
||||
<span class="sub num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : ''}">{bal === 0 ? t('settled') : money(bal, s.base, { sign: true })}</span>
|
||||
</span>
|
||||
<button class="btn small ghost" onclick={() => rename(m.id, m.name)}>{t('rename')}</button>
|
||||
{#if m.archived}
|
||||
<button class="btn small ghost" onclick={() => s.emit({ type: 'member.restored', data: { id: m.id } })}>{t('unarchive')}</button>
|
||||
{:else}
|
||||
<button class="btn small ghost" disabled={bal !== 0} title={bal !== 0 ? t('archive_needs_zero') : ''}
|
||||
onclick={() => s.emit({ type: 'member.archived', data: { id: m.id } })}>{t('archive')}</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<form class="row" onsubmit={addMember}>
|
||||
<input bind:value={newMember} placeholder={t('member_name')} maxlength="60" aria-label={t('member_name')} />
|
||||
<button class="btn" type="submit" disabled={!newMember.trim()}><Icon name="plus" size={18} /> {t('add_member')}</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<!-- notifications -->
|
||||
<section class="section">
|
||||
<h3>{t('notifications')}</h3>
|
||||
<div class="card stack">
|
||||
{#if push === 'ok' || s.local.push}
|
||||
<label class="row">
|
||||
<input type="checkbox" checked={s.local.push} disabled={pushBusy} onchange={togglePush} />
|
||||
<span>{t('notifications_hint')}</span>
|
||||
</label>
|
||||
{:else if push === 'needs-install'}
|
||||
<p class="small">{t('notifications_ios')}</p>
|
||||
{:else if push === 'denied'}
|
||||
<p class="small">{t('notifications_denied')}</p>
|
||||
{:else if push}
|
||||
<p class="small muted">{t('notifications_unavailable')}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- recurring -->
|
||||
<section class="section">
|
||||
<h3>{t('recurring')}</h3>
|
||||
{#if Object.keys(s.state.recurring).length === 0}
|
||||
<p class="card small muted">{t('no_recurring')}</p>
|
||||
{:else}
|
||||
<div class="list">
|
||||
{#each Object.values(s.state.recurring) as r (r.id)}
|
||||
{@const next = nextOccurrence(r.rule, today())}
|
||||
<div class="item">
|
||||
<Icon name="repeat" size={18} />
|
||||
<span class="grow">
|
||||
<span class="title" style:display="block">{r.template.title} · <span class="num">{money(r.template.amount, r.template.currency)}</span></span>
|
||||
<span class="sub">{t(`repeat_${r.rule.freq}`)}{next ? ` · ${t('next_on', { date: fmtDate(next) })}` : ''}</span>
|
||||
</span>
|
||||
<button class="btn small ghost" onclick={() => s.emit({ type: 'recurring.deleted', data: { id: r.id } })}>{t('stop')}</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<!-- export -->
|
||||
<section class="section">
|
||||
<h3>{t('export')}</h3>
|
||||
<div class="row wrap">
|
||||
<button class="btn" onclick={() => download(`${fileBase()}-expenses.csv`, '' + expensesCsv(s.state), 'text/csv')}>{t('export_expenses')}</button>
|
||||
<button class="btn" onclick={() => download(`${fileBase()}-balances.csv`, '' + balancesCsv(s.state), 'text/csv')}>{t('export_balances')}</button>
|
||||
<button class="btn" onclick={backup}>{t('backup')}</button>
|
||||
</div>
|
||||
<p class="small muted">{t('backup_hint')}</p>
|
||||
</section>
|
||||
|
||||
<!-- danger -->
|
||||
<section class="section">
|
||||
<h3>{t('danger_zone')}</h3>
|
||||
<div class="card stack">
|
||||
<p class="small muted">{t('remove_from_device_hint')}</p>
|
||||
<button class="btn" onclick={removeFromDevice}>{t('remove_from_device')}</button>
|
||||
</div>
|
||||
<div class="card stack">
|
||||
<p class="small muted">{t('delete_group_hint')}</p>
|
||||
<input bind:value={deleteConfirm} placeholder={s.state.group?.name} aria-label={t('group_name')} />
|
||||
<button class="btn danger" disabled={deleteConfirm.trim() !== s.state.group?.name} onclick={deleteGroup}>
|
||||
<Icon name="trash" size={18} /> {t('delete_group')}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.qr { width: min(260px, 100%); margin: 0 auto; background: #fff; border-radius: 12px; padding: 8px; }
|
||||
.qr :global(svg) { width: 100%; height: auto; display: block; }
|
||||
</style>
|
||||
95
apps/web/src/components/Home.svelte
Normal file
95
apps/web/src/components/Home.svelte
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<script lang="ts">
|
||||
import { getAll, type LocalGroup } from '../lib/idb.ts';
|
||||
import { isGroupId, isGroupSecret } from '../lib/crypto.ts';
|
||||
import { money } from '../lib/format.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import { addGroup } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
let groups = $state<LocalGroup[] | null>(null);
|
||||
let link = $state('');
|
||||
let linkError = $state(false);
|
||||
let showLink = $state(false);
|
||||
|
||||
getAll<LocalGroup>('groups').then((g) => (groups = g.sort((a, b) => b.lastOpened - a.lastOpened)));
|
||||
|
||||
async function openLink(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
const m = /\/g\/([A-Za-z0-9_-]{22})#([A-Za-z0-9_-]{43})\s*$/.exec(link.trim());
|
||||
if (!m || !isGroupId(m[1]) || !isGroupSecret(m[2])) {
|
||||
linkError = true;
|
||||
return;
|
||||
}
|
||||
await addGroup(m[1], m[2]);
|
||||
router.go(`/g/${m[1]}`);
|
||||
}
|
||||
|
||||
function nav(e: MouseEvent, path: string) {
|
||||
e.preventDefault();
|
||||
router.go(path);
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="topbar">
|
||||
<h1><span aria-hidden="true">💸</span> {t('app_name')}</h1>
|
||||
<a class="icon-btn" href="/settings" onclick={(e) => nav(e, '/settings')} aria-label={t('settings')}><Icon name="settings" /></a>
|
||||
</header>
|
||||
|
||||
<main class="page stack">
|
||||
<p class="muted">{t('tagline')}</p>
|
||||
|
||||
<div class="section">
|
||||
<h3>{t('your_groups')}</h3>
|
||||
{#if groups === null}
|
||||
<p class="muted">{t('loading')}</p>
|
||||
{:else if groups.length === 0}
|
||||
<p class="card muted">{t('no_groups')}</p>
|
||||
{:else}
|
||||
<div class="list">
|
||||
{#each groups as g (g.id)}
|
||||
<a class="item" href="/g/{g.id}" onclick={(e) => nav(e, `/g/${g.id}`)}>
|
||||
<span class="cat-icon" aria-hidden="true">{g.icon || '👥'}</span>
|
||||
<span class="grow">
|
||||
<span class="title" style:display="block">{g.name || '…'}</span>
|
||||
<span class="sub" style:display="block">
|
||||
{#if g.gone}
|
||||
{t('group_gone')}
|
||||
{:else if g.myBalance === null}
|
||||
{t('pick_identity_hint')}
|
||||
{:else if g.myBalance > 0}
|
||||
<span class="pos">{t('you_are_owed', { amount: money(g.myBalance, g.baseCurrency) })}</span>
|
||||
{:else if g.myBalance < 0}
|
||||
<span class="neg">{t('you_owe', { amount: money(-g.myBalance, g.baseCurrency) })}</span>
|
||||
{:else}
|
||||
{t('settled')}
|
||||
{/if}
|
||||
</span>
|
||||
</span>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<a class="btn primary block" href="/new" onclick={(e) => nav(e, '/new')}><Icon name="plus" /> {t('new_group')}</a>
|
||||
{#if showLink}
|
||||
<form class="stack card" onsubmit={openLink}>
|
||||
<label class="field">
|
||||
{t('paste_link')}
|
||||
<input bind:value={link} oninput={() => (linkError = false)} placeholder="https://…/g/…#…" autocomplete="off" spellcheck="false" />
|
||||
</label>
|
||||
{#if linkError}<p class="neg small" role="alert">{t('invalid_link')}</p>{/if}
|
||||
<button class="btn" type="submit">{t('open')}</button>
|
||||
</form>
|
||||
{:else}
|
||||
<button class="btn block" onclick={() => (showLink = true)}><Icon name="link" /> {t('open_link')}</button>
|
||||
{/if}
|
||||
<a class="btn ghost block" href="/restore" onclick={(e) => nav(e, '/restore')}><Icon name="upload" /> {t('restore_backup')}</a>
|
||||
</div>
|
||||
|
||||
<p class="muted small row" style:align-items="flex-start" style:margin-top="24px">
|
||||
<Icon name="lock" size={16} /> <span>{t('e2e_note')}</span>
|
||||
</p>
|
||||
</main>
|
||||
29
apps/web/src/components/Icon.svelte
Normal file
29
apps/web/src/components/Icon.svelte
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<script lang="ts">
|
||||
// Inline SVG icons (no icon font: keeps the CSP strict and works offline).
|
||||
const paths = {
|
||||
plus: 'M12 5v14M5 12h14',
|
||||
back: 'M15 18l-6-6 6-6',
|
||||
close: 'M18 6L6 18M6 6l12 12',
|
||||
settings: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z',
|
||||
share: 'M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8M16 6l-4-4-4 4M12 2v13',
|
||||
camera: 'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2zM12 17a4 4 0 1 0 0-8 4 4 0 0 0 0 8z',
|
||||
list: 'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01',
|
||||
scale: 'M12 3v18M5 7h14M5 7l-3 7a4 4 0 0 0 6 0L5 7zM19 7l-3 7a4 4 0 0 0 6 0l-3-7z',
|
||||
chart: 'M3 3v18h18M8 17V11M13 17V7M18 17v-4',
|
||||
clock: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM12 6v6l4 2',
|
||||
trash: 'M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6',
|
||||
edit: 'M12 20h9M16.5 3.5a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4z',
|
||||
copy: 'M9 9h11v11H9zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1',
|
||||
lock: 'M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4',
|
||||
repeat: 'M17 1l4 4-4 4M3 11V9a4 4 0 0 1 4-4h14M7 23l-3-4 3-4M21 13v2a4 4 0 0 1-4 4H3',
|
||||
undo: 'M3 7v6h6M21 17a9 9 0 0 0-15-6.7L3 13',
|
||||
link: 'M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7',
|
||||
upload: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12',
|
||||
} as const;
|
||||
|
||||
let { name, size = 22 }: { name: keyof typeof paths; size?: number } = $props();
|
||||
</script>
|
||||
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d={paths[name]} />
|
||||
</svg>
|
||||
50
apps/web/src/components/IdentityPicker.svelte
Normal file
50
apps/web/src/components/IdentityPicker.svelte
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<script lang="ts">
|
||||
import { randomId } from '../lib/crypto.ts';
|
||||
import { MEMBER_COLORS } from '../lib/format.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import Avatar from './Avatar.svelte';
|
||||
import Sheet from './Sheet.svelte';
|
||||
|
||||
let { session, onskip }: { session: GroupSession; onskip: () => void } = $props();
|
||||
let newName = $state('');
|
||||
let adding = $state(false);
|
||||
|
||||
const members = $derived(session.state.members.filter((m) => !m.archived));
|
||||
|
||||
async function pick(id: string) {
|
||||
await session.setMe(id);
|
||||
}
|
||||
|
||||
async function addMe(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
const name = newName.trim();
|
||||
if (!name) return;
|
||||
const id = randomId(9);
|
||||
await session.emit({ type: 'member.added', data: { id, name, color: MEMBER_COLORS[session.state.members.length % MEMBER_COLORS.length] } });
|
||||
await session.setMe(id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<Sheet title={t('who_are_you')} onclose={onskip}>
|
||||
<div class="stack">
|
||||
<p class="muted">{t('who_are_you_hint')}</p>
|
||||
<div class="list">
|
||||
{#each members as m, i (m.id)}
|
||||
<button class="item" onclick={() => pick(m.id)}>
|
||||
<Avatar member={m} index={i} />
|
||||
<span class="grow title">{m.name}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if adding}
|
||||
<form class="row" onsubmit={addMe}>
|
||||
<input bind:value={newName} placeholder={t('your_name')} maxlength="60" aria-label={t('your_name')} />
|
||||
<button class="btn primary" type="submit" disabled={!newName.trim()}>{t('save')}</button>
|
||||
</form>
|
||||
{:else}
|
||||
<button class="btn" onclick={() => (adding = true)}>{t('im_new')}</button>
|
||||
{/if}
|
||||
<button class="btn ghost" onclick={onskip}>{t('just_looking')}</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
105
apps/web/src/components/NewGroup.svelte
Normal file
105
apps/web/src/components/NewGroup.svelte
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<script lang="ts">
|
||||
import type { EventBody } from '@oweme/core';
|
||||
import { api } from '../lib/api.ts';
|
||||
import { deriveKeys, randomId, sha256hex } from '../lib/crypto.ts';
|
||||
import { MEMBER_COLORS } from '../lib/format.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import { addGroup, openSession } from '../lib/session.svelte.ts';
|
||||
import { settings, t } from '../lib/settings.svelte.ts';
|
||||
import CurrencySelect from './CurrencySelect.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
const ICONS = ['👥', '🏔️', '🏖️', '🏠', '🍻', '🚗', '🎉', '⛺', '🎿', '✈️', '🍕', '💼'];
|
||||
|
||||
let name = $state('');
|
||||
let icon = $state(ICONS[0]);
|
||||
let currency = $state(settings.lang === 'cs' ? 'CZK' : 'EUR');
|
||||
let me = $state('');
|
||||
let others = $state<string[]>(['']);
|
||||
let busy = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
async function create(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
if (!name.trim() || !me.trim()) return;
|
||||
busy = true;
|
||||
error = '';
|
||||
try {
|
||||
const id = randomId(16);
|
||||
const secret = randomId(32);
|
||||
const keys = await deriveKeys(secret);
|
||||
await api.createGroup(id, await sha256hex(keys.authToken));
|
||||
const meId = randomId(9);
|
||||
await addGroup(id, secret, { name: name.trim(), icon, baseCurrency: currency, me: meId });
|
||||
const s = await openSession(id);
|
||||
if (!s) throw new Error('could not open group');
|
||||
const names = [me, ...others].map((n) => n.trim()).filter(Boolean);
|
||||
const events: EventBody[] = [
|
||||
{ type: 'group.created', data: { name: name.trim(), baseCurrency: currency, icon } },
|
||||
...names.map((n, i) => ({
|
||||
type: 'member.added' as const,
|
||||
data: { id: i === 0 ? meId : randomId(9), name: n.slice(0, 60), color: MEMBER_COLORS[i % MEMBER_COLORS.length] },
|
||||
})),
|
||||
];
|
||||
await s.emit(...events);
|
||||
router.go(`/g/${id}/settings?share=1`, { replace: true });
|
||||
} catch (err) {
|
||||
error = t('error_generic', { msg: (err as Error).message });
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={() => router.back('/')} aria-label={t('back')}><Icon name="back" /></button>
|
||||
<h1>{t('new_group')}</h1>
|
||||
</header>
|
||||
|
||||
<main class="page">
|
||||
<form class="stack" onsubmit={create}>
|
||||
<label class="field">
|
||||
{t('group_name')}
|
||||
<input bind:value={name} placeholder={t('group_name_ph')} maxlength="100" required />
|
||||
</label>
|
||||
|
||||
<div class="field">
|
||||
<span class="small muted">{t('icon')}</span>
|
||||
<div class="chips">
|
||||
{#each ICONS as i}
|
||||
<button type="button" class="chip" aria-pressed={icon === i} onclick={() => (icon = i)}>{i}</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="field">
|
||||
{t('base_currency')}
|
||||
<CurrencySelect bind:value={currency} />
|
||||
<span class="small">{t('base_currency_hint')}</span>
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
{t('your_name')}
|
||||
<input bind:value={me} maxlength="60" required autocomplete="given-name" />
|
||||
</label>
|
||||
|
||||
<div class="field">
|
||||
<span class="small muted">{t('other_members')}</span>
|
||||
{#each others as _, i}
|
||||
<div class="row">
|
||||
<input bind:value={others[i]} placeholder={t('member_name')} maxlength="60" aria-label={t('member_name')} />
|
||||
{#if others.length > 1}
|
||||
<button type="button" class="icon-btn" onclick={() => others.splice(i, 1)} aria-label={t('delete')}><Icon name="close" /></button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
<button type="button" class="btn small ghost" style:align-self="flex-start" onclick={() => others.push('')}>
|
||||
<Icon name="plus" size={18} /> {t('add_member')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="neg" role="alert">{error}</p>{/if}
|
||||
<button class="btn primary block" type="submit" disabled={busy || !name.trim() || !me.trim()}>
|
||||
{busy ? t('creating') : t('create_group')}
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
50
apps/web/src/components/PhotoView.svelte
Normal file
50
apps/web/src/components/PhotoView.svelte
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<script lang="ts">
|
||||
import type { Photo } from '@oweme/core';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
|
||||
let { session, photo }: { session: GroupSession; photo: Photo } = $props();
|
||||
let thumb = $state<string | null>(null);
|
||||
let full = $state<string | null>(null);
|
||||
let failed = $state(false);
|
||||
let open = $state(false);
|
||||
let dialog = $state<HTMLDialogElement>();
|
||||
|
||||
$effect(() => {
|
||||
const p = photo;
|
||||
thumb = null;
|
||||
session.blobUrl(p.thumbBlobId).then((u) => (thumb = u)).catch(() => (failed = true));
|
||||
});
|
||||
|
||||
async function show() {
|
||||
open = true;
|
||||
full ??= await session.blobUrl(photo.blobId).catch(() => null);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (open) dialog?.showModal();
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if failed}
|
||||
<p class="small muted">📷 …</p>
|
||||
{:else}
|
||||
<button type="button" class="thumb-btn" onclick={show} aria-label={t('photo')}>
|
||||
{#if thumb}<img class="photo-thumb" src={thumb} alt={t('photo')} style:aspect-ratio="{photo.w} / {photo.h}" />
|
||||
{:else}<span class="photo-thumb placeholder" style:aspect-ratio="{photo.w} / {photo.h}"></span>{/if}
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if open}
|
||||
<dialog class="viewer" bind:this={dialog} onclose={() => (open = false)} onclick={() => dialog?.close()}>
|
||||
<img src={full ?? thumb ?? ''} alt={t('photo')} />
|
||||
</dialog>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.thumb-btn { padding: 0; border: 0; background: none; width: 100%; display: block; cursor: zoom-in; }
|
||||
.placeholder { display: block; max-height: 240px; }
|
||||
.viewer { padding: 0; border: 0; background: transparent; max-width: 100vw; max-height: 100dvh; }
|
||||
.viewer::backdrop { background: rgb(0 0 0 / 0.9); }
|
||||
.viewer img { max-width: 100vw; max-height: 100dvh; object-fit: contain; display: block; }
|
||||
</style>
|
||||
40
apps/web/src/components/Restore.svelte
Normal file
40
apps/web/src/components/Restore.svelte
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
<script lang="ts">
|
||||
import { restoreBackup } from '../lib/backup.ts';
|
||||
import { router } from '../lib/router.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
import { ui } from '../lib/ui.svelte.ts';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
let busy = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
async function pick(e: Event) {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
busy = true;
|
||||
error = '';
|
||||
try {
|
||||
const { id, existed } = await restoreBackup(await file.text());
|
||||
if (existed) ui.show(t('restore_exists'), 4000);
|
||||
router.go(`/g/${id}`, { replace: true });
|
||||
} catch (err) {
|
||||
error = (err as Error).message === 'bad file' ? t('restore_bad_file') : t('error_generic', { msg: (err as Error).message });
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={() => router.back('/')} aria-label={t('back')}><Icon name="back" /></button>
|
||||
<h1>{t('restore_title')}</h1>
|
||||
</header>
|
||||
|
||||
<main class="page stack">
|
||||
<label class="field">
|
||||
{t('restore_pick')}
|
||||
<input type="file" accept="application/json,.json" onchange={pick} disabled={busy} />
|
||||
</label>
|
||||
{#if busy}<p class="muted">{t('restoring')}</p>{/if}
|
||||
{#if error}<p class="neg" role="alert">{error}</p>{/if}
|
||||
</main>
|
||||
32
apps/web/src/components/Sheet.svelte
Normal file
32
apps/web/src/components/Sheet.svelte
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<script lang="ts">
|
||||
// Modal sheet: full screen on phones, a centered dialog on desktop.
|
||||
// Uses <dialog> for focus trapping and Escape handling.
|
||||
import type { Snippet } from 'svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
|
||||
let { title, onclose, children, actions }: { title: string; onclose: () => void; children: Snippet; actions?: Snippet } = $props();
|
||||
let dialog: HTMLDialogElement;
|
||||
|
||||
$effect(() => {
|
||||
dialog.showModal();
|
||||
return () => dialog.close();
|
||||
});
|
||||
</script>
|
||||
|
||||
<dialog
|
||||
class="sheet"
|
||||
bind:this={dialog}
|
||||
aria-label={title}
|
||||
oncancel={(e) => { e.preventDefault(); onclose(); }}
|
||||
onclick={(e) => { if (e.target === dialog) onclose(); }}
|
||||
>
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" onclick={onclose} aria-label={t('close')}><Icon name="close" /></button>
|
||||
<h1>{title}</h1>
|
||||
{@render actions?.()}
|
||||
</header>
|
||||
<div class="sheet-body">
|
||||
{@render children()}
|
||||
</div>
|
||||
</dialog>
|
||||
143
apps/web/src/components/Stats.svelte
Normal file
143
apps/web/src/components/Stats.svelte
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
<script lang="ts">
|
||||
import { computeStats } from '@oweme/core';
|
||||
import { addDays, CATEGORY_ICONS, fmtMonth, money, today } from '../lib/format.ts';
|
||||
import type { MsgKey } from '../lib/i18n.ts';
|
||||
import type { GroupSession } from '../lib/session.svelte.ts';
|
||||
import { t } from '../lib/settings.svelte.ts';
|
||||
|
||||
let { session }: { session: GroupSession } = $props();
|
||||
type Range = 'all' | 'month' | '30' | 'year';
|
||||
let range = $state<Range>('all');
|
||||
let hoverMonth = $state<string | null>(null);
|
||||
|
||||
const bounds = $derived.by((): [string | null, string | null] => {
|
||||
const d = today();
|
||||
if (range === 'month') return [`${d.slice(0, 7)}-01`, d];
|
||||
if (range === '30') return [addDays(d, -29), d];
|
||||
if (range === 'year') return [`${d.slice(0, 4)}-01-01`, d];
|
||||
return [null, null];
|
||||
});
|
||||
const st = $derived(computeStats(session.state, bounds[0], bounds[1]));
|
||||
const base = $derived(session.base);
|
||||
const maxCat = $derived(Math.max(1, ...st.byCategory.map((c) => c.amount)));
|
||||
const maxMonth = $derived(Math.max(1, ...st.byMonth.map((m) => m.amount)));
|
||||
const peakMonth = $derived(st.byMonth.reduce((a, m) => (m.amount > (a?.amount ?? -1) ? m : a), null as null | { month: string; amount: number }));
|
||||
const shownMonth = $derived(st.byMonth.find((m) => m.month === hoverMonth) ?? peakMonth);
|
||||
const members = $derived(st.perMember.filter((p) => p.paid || p.consumed));
|
||||
const maxMember = $derived(Math.max(1, ...members.flatMap((p) => [p.paid, p.consumed])));
|
||||
const mine = $derived(st.perMember.find((p) => p.member === session.me));
|
||||
// Label every month on short ranges, fewer on long ones, so labels never collide.
|
||||
const labelEvery = $derived(Math.ceil(st.byMonth.length / 8));
|
||||
</script>
|
||||
|
||||
<div class="stack">
|
||||
<div class="seg" role="group" aria-label={t('stats')}>
|
||||
{#each [['all', 'range_all'], ['year', 'range_year'], ['month', 'range_month'], ['30', 'range_30']] as const as [r, label]}
|
||||
<button aria-pressed={range === r} onclick={() => (range = r)}>{t(label)}</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="tiles">
|
||||
<div class="card">
|
||||
<div class="muted small">{t('total_spent')}</div>
|
||||
<div class="hero num">{money(st.total, base)}</div>
|
||||
</div>
|
||||
{#if mine}
|
||||
<div class="card">
|
||||
<div class="muted small">{t('my_spending')}</div>
|
||||
<div class="hero num">{money(mine.consumed, base)}</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if st.total === 0}
|
||||
<p class="empty">{t('no_data')}</p>
|
||||
{:else}
|
||||
<section class="card stack">
|
||||
<h2>{t('by_category')}</h2>
|
||||
<ul class="bars">
|
||||
{#each st.byCategory as c (c.category)}
|
||||
<li title="{t(`cat_${c.category}` as MsgKey)}: {money(c.amount, base)}">
|
||||
<span class="label"><span aria-hidden="true">{CATEGORY_ICONS[c.category]}</span> {t(`cat_${c.category}` as MsgKey)}</span>
|
||||
<span class="track"><span class="hbar s1" style:width="{(c.amount / maxCat) * 100}%"></span></span>
|
||||
<span class="value num">{money(c.amount, base)}</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{#if st.byMonth.length > 1}
|
||||
<section class="card stack">
|
||||
<div class="row">
|
||||
<h2 class="grow" style:flex="1">{t('by_month')}</h2>
|
||||
{#if shownMonth}<span class="small num" aria-live="polite">{fmtMonth(shownMonth.month)}: <strong>{money(shownMonth.amount, base)}</strong></span>{/if}
|
||||
</div>
|
||||
<div class="months">
|
||||
{#each st.byMonth as m, i (m.month)}
|
||||
<button
|
||||
type="button" class="month"
|
||||
aria-label="{fmtMonth(m.month)}: {money(m.amount, base)}"
|
||||
onmouseenter={() => (hoverMonth = m.month)} onmouseleave={() => (hoverMonth = null)}
|
||||
onfocus={() => (hoverMonth = m.month)} onblur={() => (hoverMonth = null)}
|
||||
>
|
||||
<span class="col"><span class="vbar s1" class:active={shownMonth?.month === m.month} style:height="{(m.amount / maxMonth) * 100}%"></span></span>
|
||||
<span class="mlabel small muted">{i % labelEvery === 0 ? fmtMonth(m.month) : ''}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
{#if members.length}
|
||||
<section class="card stack">
|
||||
<h2>{t('per_member')}</h2>
|
||||
<div class="legend small muted row">
|
||||
<span class="row" style:gap="6px"><span class="swatch s1"></span>{t('legend_paid')}</span>
|
||||
<span class="row" style:gap="6px"><span class="swatch s2"></span>{t('legend_share')}</span>
|
||||
</div>
|
||||
<ul class="bars grouped">
|
||||
{#each members as p (p.member)}
|
||||
<li>
|
||||
<span class="label">{session.memberName(p.member)}</span>
|
||||
<span class="pair">
|
||||
<span class="line" title="{t('legend_paid')}: {money(p.paid, base)}">
|
||||
<span class="track"><span class="hbar s1" style:width="{(p.paid / maxMember) * 100}%"></span></span>
|
||||
<span class="value num">{money(p.paid, base)}</span>
|
||||
</span>
|
||||
<span class="line" title="{t('legend_share')}: {money(p.consumed, base)}">
|
||||
<span class="track"><span class="hbar s2" style:width="{(p.consumed / maxMember) * 100}%"></span></span>
|
||||
<span class="value num">{money(p.consumed, base)}</span>
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }
|
||||
.hero { font-size: 1.6rem; font-weight: 700; }
|
||||
.s1 { background: var(--chart-1); }
|
||||
.s2 { background: var(--chart-2); }
|
||||
.bars { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.bars li { display: grid; grid-template-columns: minmax(90px, 34%) 1fr auto; align-items: center; gap: 10px; }
|
||||
.label { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.track { display: block; height: 12px; }
|
||||
.hbar { display: block; height: 100%; min-width: 2px; border-radius: 0 4px 4px 0; }
|
||||
.value { font-size: 0.85rem; color: var(--text); text-align: right; }
|
||||
.grouped li { grid-template-columns: minmax(70px, 28%) 1fr; }
|
||||
.pair { display: flex; flex-direction: column; gap: 2px; }
|
||||
.line { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: center; }
|
||||
.legend { gap: 16px; }
|
||||
.swatch { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
|
||||
.months { display: flex; align-items: stretch; gap: 2px; height: 160px; }
|
||||
.month { flex: 1; display: flex; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: default; flex-direction: column; min-width: 0; outline-offset: 2px; }
|
||||
.month:focus-visible { outline: 2px solid var(--accent); border-radius: 4px; }
|
||||
.col { flex: 1; display: flex; align-items: flex-end; border-bottom: 1px solid var(--border); }
|
||||
.vbar { display: block; width: 100%; max-width: 28px; margin: 0 auto; min-height: 2px; border-radius: 4px 4px 0 0; opacity: 0.85; }
|
||||
.vbar.active { opacity: 1; }
|
||||
.mlabel { text-align: center; white-space: nowrap; overflow: visible; height: 1.4em; font-size: 0.7rem; }
|
||||
</style>
|
||||
Loading…
Add table
Add a link
Reference in a new issue