Compare commits

..

No commits in common. "main" and "feat/v1-app" have entirely different histories.

49 changed files with 548 additions and 1521 deletions

View file

@ -1,8 +0,0 @@
# Keep the image build context small and free of secrets/local data.
**/node_modules
**/dist
data
.env
test-results
playwright-report
.git

View file

@ -1,19 +0,0 @@
# Optional settings for a standalone deploy (podman compose without the
# panel). Copy to .env next to compose.yaml and `chmod 600 .env`. Never
# commit .env. With the panel, set these in the app's Environment tab instead.
# Everything has a working default; see compose.yaml for what each one does.
# Standalone HTTPS: public hostname with a DNS record pointing here.
DOMAIN=oweme.example.com
#VAPID_SUBJECT=mailto:you@example.com
#MAX_PHOTO_BYTES=2097152
#MAX_EVENT_BYTES=65536
#MAX_GROUP_BYTES=209715200
#GROUP_CREATE_PER_HOUR=10
#PUSH_DISABLED=0
# Where the standalone Caddy listens. Defaults: all interfaces, ports 80/443.
#BIND_ADDR=0.0.0.0
#HTTP_PORT=80
#HTTPS_PORT=443

1
.gitignore vendored
View file

@ -2,6 +2,7 @@ node_modules/
dist/ dist/
data/ data/
.env .env
deploy/.env
test-results/ test-results/
playwright-report/ playwright-report/
*.log *.log

View file

@ -13,10 +13,7 @@ End-to-end encrypted group expense splitter (a Settle Up clone). Read
that way unless there's a strong reason. that way unless there's a strong reason.
- `apps/web/` — Svelte 5 SPA + service worker (`src/sw.ts`, built separately - `apps/web/` — Svelte 5 SPA + service worker (`src/sw.ts`, built separately
by `vite.sw.config.ts` as a classic script). by `vite.sw.config.ts` as a classic script).
- `compose.yaml` (repo root) — the deployment; the panel needs it at the root. - `deploy/` — Containerfile, compose.yaml, Caddyfile, `.env.example`, deploy docs.
Settings are `${VAR:-default}` there; push keys are generated into the volume.
Caddy is only in the `standalone` profile (the panel brings its own).
- `deploy/` — Containerfile, Caddyfile, deploy docs.
- `e2e/` — Playwright tests against the production build. - `e2e/` — Playwright tests against the production build.
## Run ## Run
@ -59,4 +56,4 @@ notifications.
Push payloads carry only the group id. Push payloads carry only the group id.
7. Strict CSP: no inline scripts, no third-party origins. 7. Strict CSP: no inline scripts, no third-party origins.
8. Containers: rootless Podman; for local testing publish to `127.0.0.1` only 8. Containers: rootless Podman; for local testing publish to `127.0.0.1` only
(`BIND_ADDR=127.0.0.1` in `.env` for the standalone profile). (`BIND_ADDR=127.0.0.1` in `deploy/.env`).

View file

@ -5,8 +5,7 @@ Settle Up clone that runs in any browser and installs as an app.
- Groups you open via a link; the key travels in the `#fragment` and never reaches the server - Groups you open via a link; the key travels in the `#fragment` and never reaches the server
- Equal, shares, exact-amount and percent splits; several payers; any member can be left out - Equal, shares, exact-amount and percent splits; several payers; any member can be left out
- Multiple currencies with daily rates — ECB, plus ExchangeRate-API for the - Multiple currencies with ECB daily rates (stored per expense, editable)
rest (stored per expense, editable)
- One receipt photo per expense (resized, location data stripped, encrypted) - One receipt photo per expense (resized, location data stripped, encrypted)
- Who-pays-whom settle-up suggestions, with "record payment" - Who-pays-whom settle-up suggestions, with "record payment"
- Full history: restore any version, or rewind the whole group (and undo that) - Full history: restore any version, or rewind the whole group (and undo that)

161
SPEC.md
View file

@ -156,7 +156,7 @@ entity fully defines it. Conflicts resolve **last-writer-wins by server
"currency": "EUR", "currency": "EUR",
"amount": 12050, // 120.50 EUR "amount": 12050, // 120.50 EUR
"rate": "25.214", // decimal string: 1 EUR = 25.214 base; "1" if same currency "rate": "25.214", // decimal string: 1 EUR = 25.214 base; "1" if same currency
"rateSource": "ecb:2026-10-08", // or "xr:<date>", "manual" (see 8.2) "rateSource": "ecb:2026-10-08", // or "manual"
"payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount "payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount
"split": { "split": {
"mode": "equal", // equal | shares | exact | percent "mode": "equal", // equal | shares | exact | percent
@ -180,11 +180,8 @@ Split `value` meaning per mode:
| `exact` | amount in minor units | sum == amount | | `exact` | amount in minor units | sum == amount |
| `percent` | basis points (100 % = 10000) | sum == 10000 | | `percent` | basis points (100 % = 10000) | sum == 10000 |
Multiple payers are supported (`payers` list) — e.g. several people chipping Multiple payers are supported (`payers` list); the default UI shows a single
in for a car. The editor shows a single payer by default; choosing "Several payer with an "add payer" option.
people" in *Paid by* lists every member with an amount box. Empty boxes show
the unassigned remainder as a placeholder, a live line reads "Remaining" /
"Over by" / "Adds up to the total", and the expense list shows "N payers".
--- ---
@ -265,8 +262,8 @@ the minimum in practice, and is easy to reason about.
- Create group: name, base currency (default by locale: CZK for Czech, EUR - Create group: name, base currency (default by locale: CZK for Czech, EUR
otherwise), icon/emoji, initial members. otherwise), icon/emoji, initial members.
- Share: copy link, native share sheet, QR code. - Share: copy link, native share sheet, QR code.
- Settings: rename, members, "who am I", default category, remove from - Settings: rename, members, "who am I", remove from device, export, delete
device, export, delete group (see 8.3). group (see 8.3).
- **Base currency is locked once the group has any expense or transfer.** It - **Base currency is locked once the group has any expense or transfer.** It
can be changed freely while the group is empty; afterwards the setting is can be changed freely while the group is empty; afterwards the setting is
read-only with a short explanation. Clients enforce this during replay too: read-only with a short explanation. Clients enforce this during replay too:
@ -281,18 +278,6 @@ the minimum in practice, and is easy to reason about.
the daily rate for the expense date and is editable. the daily rate for the expense date and is editable.
- Split editor: equal / shares / exact / percent tabs; tap to exclude people; - Split editor: equal / shares / exact / percent tabs; tap to exclude people;
live "remaining to assign" indicator for exact and percent modes. live "remaining to assign" indicator for exact and percent modes.
- The add sheet fits one phone screen (390×844, three members): currency as a
pill beside the amount; categories as 12 equal icon tiles (6 × 2 on phones,
one row of 12 when wider) with the chosen name beside the label; date and
payer side by side ("Several people" is the last payer option); photo, note
and repeat stay folded behind small buttons; Save is pinned to the bottom.
- Touch gestures on the group page (shortcuts; every action also has a
button): pull up past the end of the Expenses or Balances tab to add an
expense (a "Pull up to add expense" pill rises from behind the tab bar and
reads "Release to add" once far enough; at the bottom so the browser's
pull-to-refresh still works), and swipe left/right to move between the
Expenses, Balances, Stats and Activity tabs. Swipes starting within 24px
of the screen edge are left to the OS back gesture.
- **One photo per expense** (receipt), see 9. - **One photo per expense** (receipt), see 9.
- Category, date, note. - Category, date, note.
- Comments thread on each expense. - Comments thread on each expense.
@ -303,12 +288,6 @@ Fixed v1 set with icons: food & drink, groceries, transport, accommodation,
entertainment, shopping, utilities, rent, travel, gifts, health, other. entertainment, shopping, utilities, rent, travel, gifts, health, other.
Transfers have their own implicit category. Transfers have their own implicit category.
Each group has a **default category** (`group.updated` → `defaultCategory`,
one of the set above; absent means "other") that new expenses start with.
Replay ignores a `group.updated` whose `defaultCategory` isn't in the set,
without applying any other field of that event. Each category has an icon
colour (`CATEGORY_COLORS` in `apps/web/src/lib/format.ts`).
### 7.4 Recurring expenses ### 7.4 Recurring expenses
- A template (expense object + rule: weekly / monthly / yearly, interval, - A template (expense object + rule: weekly / monthly / yearly, interval,
@ -391,27 +370,9 @@ which group ids exist.
ECB's own XML feed) every 6 hours and caches them in SQLite. The first run ECB's own XML feed) every 6 hours and caches them in SQLite. The first run
loads the full history (back to 1999) for back-dated expenses; later runs loads the full history (back to 1999) for back-dated expenses; later runs
fetch the last 90 days. fetch the last 90 days.
- For currencies the ECB doesn't publish (e.g. ALL), the server also fetches
a **supplementary EUR-based feed** on the same schedule: ExchangeRate-API's
free endpoint (`RATES_EXTRA_URL`, default
`https://open.er-api.com/v6/latest/EUR`; empty turns it off). It has no
history, so its daily snapshots accumulate from when the server starts
fetching them; one older than a week before the requested date is not
used. It is stored apart from the ECB rates, and **the ECB rate always wins**
for a currency both publish. `GET /api/rates` merges the two and returns
`sources: { CODE: "xr:<date>" }` for every supplementary rate.
- An expense's `rateSource` is `ecb:<date>`, or `xr:<date>` when either side
of the conversion came from the supplementary feed. The editor labels `xr:`
rates with a link to exchangerate-api.com (the free tier's attribution
requirement).
- Clients fetch from our server only, so third parties don't learn users' IPs - Clients fetch from our server only, so third parties don't learn users' IPs
or currency usage. Clients cache rates offline. or currency usage. Clients cache rates offline.
- The currency picker offers only **ISO 4217 currencies in circulation** - Currencies outside the ECB set can be used with a manually entered rate.
(`ACTIVE_CURRENCIES` in `packages/core/src/currencies.ts`, hand-maintained;
browsers' `Intl.supportedValuesOf('currency')` includes long-gone codes).
Those with a daily rate come first; the rest can be used with a manually
entered rate. A group or recent currency that has since been withdrawn
stays selectable.
- Behind an interface so a paid intraday provider can be swapped in later. - Behind an interface so a paid intraday provider can be swapped in later.
### 8.3 Storage and limits ### 8.3 Storage and limits
@ -456,22 +417,11 @@ which group ids exist.
1. **Home**: groups saved on this device, each showing my balance. "New 1. **Home**: groups saved on this device, each showing my balance. "New
group", "Open link/scan QR". group", "Open link/scan QR".
2. **Group**: on Expenses and Balances, a header with my balance as the 2. **Group**: tabs: Expenses · Balances (settle up) · Stats · Activity.
headline number ("You're owed / You owe / settled up"; the group total if Floating "+" button for a new expense.
"who am I" isn't set), the group's total spent, and round quick actions:
Add · Payment · Settle up · Share. Tabs: Expenses · Balances (settle up) ·
Stats · Activity. A floating "+" appears only once the quick actions have
scrolled off screen. Touch gestures: pull up at the end of the page to
add, swipe sideways to change tab (see 7.2).
3. **Expense editor** (sheet on mobile, dialog on desktop). 3. **Expense editor** (sheet on mobile, dialog on desktop).
4. **Expense detail**: photo, split breakdown, comments, history. 4. **Expense detail**: photo, split breakdown, comments, history.
5. **Group settings**, kept short: Share (copy link, native share, QR), 5. **Group settings**.
Group (icon, name, main currency and default category side by side; Save
appears only when something changed), Members ("You are" picker on top;
rename/archive as icon buttons; add member as the last row),
Notifications (one switch; hidden where push isn't available), Repeating
expenses (only when there are any), Export, Danger zone (delete asks for
the group name only after it is tapped).
6. **App settings**: language, theme, notifications. 6. **App settings**: language, theme, notifications.
### 10.3 Language ### 10.3 Language
@ -486,26 +436,19 @@ which group ids exist.
### 10.4 Theme ### 10.4 Theme
Three themes, chosen per device in app settings: **System** (default: Dark and light, following the system setting by default with a manual
follows the OS between soft dark and light), **Dark** (soft near-black), override. Starting palette (to be validated for WCAG AA contrast):
**Black** (true black, for OLED screens) and **Light**. Neutral backgrounds;
green is the accent only. Tokens live in `apps/web/src/app.css`:
| Token | Dark | Black | Light | | Token | Dark | Light |
|---|---|---|---| |---|---|---|
| background | `#0A0B0D` | `#000000` | `#F2F3F5` | | background | `#0B2E22` | `#F2F7F4` |
| surface | `#16181C` | `#121316` | `#FFFFFF` | | surface | `#123D2E` | `#FFFFFF` |
| surface-raised | `#1F2227` | `#1B1D21` | `#E9EBEE` | | surface-raised | `#1A4D3A` | `#E4EFE9` |
| text | `#F5F6F7` | same as Dark | `#0D0F12` | | text | `#E8F3EC` | `#0B2E22` |
| text-muted | `#8B9099` | same as Dark | `#5F6670` | | text-muted | `#9FBFAE` | `#4A6B5B` |
| accent / you are owed | `#3DDC97` | same as Dark | `#0B7549` | | accent / you are owed | `#3DDC97` | `#16865A` |
| you owe | `#FF9466` | same as Dark | `#B53C0A` | | you owe | `#F2A65A` | `#B5541C` |
| highlight (sparingly) | `#D4AF37` | same as Dark | `#9A7B12` | | highlight (sparingly) | `#D4AF37` | `#9A7B12` |
Text, muted, accent, owe and danger colours have at least 4.5:1 contrast on
every background and surface in each theme. Cards and lists are separated by
shade with hairline dividers; controls are pill-shaped; the phone tab bar
floats as a pill above the content.
Positive/negative amounts also differ by sign and icon, never by colour alone. Positive/negative amounts also differ by sign and icon, never by colour alone.
@ -553,40 +496,52 @@ Repo layout (monorepo):
apps/web Svelte client + service worker apps/web Svelte client + service worker
apps/server Node API (no dependencies) apps/server Node API (no dependencies)
packages/core shared: types, event schema, money math, replay, settle-up, recurring, stats, CSV packages/core shared: types, event schema, money math, replay, settle-up, recurring, stats, CSV
compose.yaml podman compose deployment (with .env.example) deploy/ Containerfile, compose.yaml, Caddyfile, .env.example, README
deploy/ Containerfile, Caddyfile, README
e2e/ Playwright tests e2e/ Playwright tests
``` ```
--- ---
## 13. Deployment (podman compose, with or without the panel) ## 13. Deployment (VPS, podman compose)
`compose.yaml` (repo root) runs the `app` service: the Node server, which `deploy/compose.yaml` runs two services:
also serves the built static client, on port 8080 (`PORT`) with its data in the
`oweme-data` volume. It works with **zero configuration**: VAPID keys are
generated on first start and stored in the volume (`vapid.json`, mode 600),
and the push contact defaults to `https://<site domain>`.
Every setting is an optional environment variable, written in `compose.yaml` - `app`: the Node server, which also serves the built static client. Listens
as `${VAR:-default}` so it is visible and documented in one place: on the internal network only.
`MAX_PHOTO_BYTES`, `MAX_EVENT_BYTES`, `MAX_GROUP_BYTES`, - `caddy`: TLS termination + reverse proxy, the only service publishing
`GROUP_CREATE_PER_HOUR`, `PORT`, `VAPID_SUBJECT`, `VAPID_PUBLIC_KEY` / ports (80/443).
`VAPID_PRIVATE_KEY` (pin keys), `PUSH_DISABLED`.
- **With the panel** (the main target): the panel clones the repo, finds Volumes: `oweme-data` (SQLite + blobs), `caddy-data` (certificates).
`compose.yaml` at the root, routes the app's domain to `app:$PORT` through
its own Caddy (HTTPS) and passes the Environment tab's variables to
compose for `${VAR}` interpolation. "Pass to every container" must stay
off until the panel's injection override stops clashing with variables the
compose file sets (podman-compose: `can't merge value of [KEY]`).
- **Standalone**: `podman compose --profile standalone up -d` adds a Caddy
container with automatic HTTPS for `DOMAIN`, published on
`${BIND_ADDR}:${HTTP_PORT}/${HTTPS_PORT}` (defaults all interfaces, 80/443).
Settings come from `.env` next to `compose.yaml`.
Step-by-step instructions, the full settings table, ports for rootless Podman Deploy steps (documented in `deploy/README.md`):
and backups are in `deploy/README.md`.
1. Point a DNS A/AAAA record at the VPS.
2. `cp deploy/.env.example deploy/.env && chmod 600 deploy/.env`, then set
`DOMAIN` (e.g. `oweme.example.com`); Caddy uses it for the site address
and certificate. (The app itself needs no domain: share links use the
page's own origin and the CSP is `'self'`.) Generate VAPID keys with
`gen-vapid.ts` inside the built image, which writes them into `.env`
without printing them.
3. Rootless Podman cannot bind ports < 1024 by default: either set
`net.ipv4.ip_unprivileged_port_start=80` via sysctl, or publish 8080/8443 and
redirect with the firewall — both documented.
4. `cd deploy && podman compose up -d`. Updates: `git pull && podman compose up -d --build`.
5. Backups: copy the data volume. All contents are already encrypted, so
backups can be stored anywhere.
Environment variables (`deploy/.env`, read by `compose.yaml`):
| Variable | Required | Default | Purpose |
|---|---|---|---|
| `DOMAIN` | yes | — | Public hostname; Caddy site + TLS, share links |
| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | for push | — | Web Push (generated by script); empty = notifications off |
| `VAPID_SUBJECT` | for push | — | `mailto:` contact for push services |
| `MAX_PHOTO_BYTES` | no | `2097152` | Per-photo upload cap |
| `MAX_EVENT_BYTES` | no | `65536` | Per-event cap |
| `MAX_GROUP_BYTES` | no | `209715200` | Per-group storage cap |
| `GROUP_CREATE_PER_HOUR` | no | `10` | Group creations per IP per hour |
| `BIND_ADDR` | no | `0.0.0.0` | Address Caddy's ports are published on |
| `HTTP_PORT` / `HTTPS_PORT` | no | `80` / `443` | Host ports for Caddy |
Development (on the dev box): servers bind `127.0.0.1` only; preview over an Development (on the dev box): servers bind `127.0.0.1` only; preview over an
SSH tunnel. Ports and commands go in `AGENTS.md`. SSH tunnel. Ports and commands go in `AGENTS.md`.

View file

@ -6,7 +6,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
import { extname, join, normalize, sep } from 'node:path'; import { extname, join, normalize, sep } from 'node:path';
import type { Config } from './config.ts'; import type { Config } from './config.ts';
import type { Store } from './db.ts'; import type { Store } from './db.ts';
import { isAllowedEndpoint, loadVapidKeys, sendPush, type Vapid } from './push.ts'; import { isAllowedEndpoint, sendPush, type Vapid } from './push.ts';
const ID_RE = /^[A-Za-z0-9_-]{22}$/; // 16 random bytes, base64url const ID_RE = /^[A-Za-z0-9_-]{22}$/; // 16 random bytes, base64url
const EVENT_ID_RE = /^[A-Za-z0-9_-]{8,100}$/; const EVENT_ID_RE = /^[A-Za-z0-9_-]{8,100}$/;
@ -114,9 +114,10 @@ export function createApp(cfg: Config, store: Store) {
const streams = new Map<string, Set<ServerResponse>>(); const streams = new Map<string, Set<ServerResponse>>();
const createLimiter = new RateLimiter(cfg.groupCreatePerHour, 3600_000); const createLimiter = new RateLimiter(cfg.groupCreatePerHour, 3600_000);
const pushLimiter = new RateLimiter(60, 3600_000); const pushLimiter = new RateLimiter(60, 3600_000);
const keys = cfg.pushEnabled ? loadVapidKeys(cfg.dataDir, cfg.vapidPublicKey, cfg.vapidPrivateKey) : null; const vapid: Vapid | null =
if (keys) console.log(`push: VAPID keys from ${keys.source}`); cfg.vapidPublicKey && cfg.vapidPrivateKey && cfg.vapidSubject
const vapid: Vapid | null = keys ? { publicKey: keys.publicKey, privateKey: keys.privateKey, subject: cfg.vapidSubject } : null; ? { publicKey: cfg.vapidPublicKey, privateKey: cfg.vapidPrivateKey, subject: cfg.vapidSubject }
: null;
const blobDir = (g: string) => join(cfg.dataDir, 'blobs', g); const blobDir = (g: string) => join(cfg.dataDir, 'blobs', g);
function clientIp(req: IncomingMessage): string { function clientIp(req: IncomingMessage): string {
@ -140,18 +141,9 @@ export function createApp(cfg: Config, store: Store) {
return g; return g;
} }
// Push services want a contact URL in the VAPID token. Without
// VAPID_SUBJECT, use the public site address the requests arrive on.
function rememberOrigin(req: IncomingMessage) {
if (!vapid || cfg.vapidSubject) return;
const fwd = cfg.trustProxy ? req.headers['x-forwarded-host'] : undefined;
const host = String(fwd ?? req.headers.host ?? '').split(',')[0].trim().toLowerCase();
if (/^[a-z0-9.-]+\.[a-z]{2,}(:\d+)?$/.test(host) && !host.startsWith('localhost')) vapid.subject = `https://${host}`;
}
function notify(groupId: string, seq: number, deviceId: string): void { function notify(groupId: string, seq: number, deviceId: string): void {
for (const res of streams.get(groupId) ?? []) res.write(`data: ${seq}\n\n`); for (const res of streams.get(groupId) ?? []) res.write(`data: ${seq}\n\n`);
if (!vapid?.subject) return; if (!vapid) return;
for (const sub of store.pushSubs(groupId)) { for (const sub of store.pushSubs(groupId)) {
if (sub.deviceId === deviceId) continue; if (sub.deviceId === deviceId) continue;
void sendPush(sub, { g: groupId }, vapid).then((r) => { void sendPush(sub, { g: groupId }, vapid).then((r) => {
@ -292,7 +284,7 @@ export function createApp(cfg: Config, store: Store) {
function rates(res: ServerResponse, url: URL) { function rates(res: ServerResponse, url: URL) {
const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10); const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(Date.parse(date))) throw new HttpError(400, 'bad date'); if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new HttpError(400, 'bad date');
const r = store.ratesOn(date); const r = store.ratesOn(date);
if (!r) throw new HttpError(404, 'no rates'); if (!r) throw new HttpError(404, 'no rates');
// Past dates never change; today's may still be published later. // Past dates never change; today's may still be published later.
@ -344,7 +336,6 @@ export function createApp(cfg: Config, store: Store) {
return send(res, 200, { vapidPublicKey: vapid?.publicKey ?? null, maxPhotoBytes: cfg.maxPhotoBytes, maxGroupBytes: cfg.maxGroupBytes }); return send(res, 200, { vapidPublicKey: vapid?.publicKey ?? null, maxPhotoBytes: cfg.maxPhotoBytes, maxGroupBytes: cfg.maxGroupBytes });
if (p === '/api/rates' && m === 'GET') return rates(res, url); if (p === '/api/rates' && m === 'GET') return rates(res, url);
if (p === '/api/groups' && m === 'POST') return createGroup(req, res); if (p === '/api/groups' && m === 'POST') return createGroup(req, res);
rememberOrigin(req);
const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p); const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p);
if (g) { if (g) {

View file

@ -1,4 +1,4 @@
// All configuration comes from environment variables (see .env.example). // All configuration comes from environment variables (see deploy/.env.example).
import { resolve } from 'node:path'; import { resolve } from 'node:path';
function int(env: NodeJS.ProcessEnv, name: string, def: number): number { function int(env: NodeJS.ProcessEnv, name: string, def: number): number {
@ -23,11 +23,8 @@ export interface Config {
vapidPublicKey: string; vapidPublicKey: string;
vapidPrivateKey: string; vapidPrivateKey: string;
vapidSubject: string; vapidSubject: string;
pushEnabled: boolean;
ratesEnabled: boolean; ratesEnabled: boolean;
ratesBaseUrl: string; ratesBaseUrl: string;
/** supplementary EUR-based rates for currencies the ECB doesn't publish; empty = off */
ratesExtraUrl: string;
} }
export function loadConfig(env = process.env): Config { export function loadConfig(env = process.env): Config {
@ -44,10 +41,7 @@ export function loadConfig(env = process.env): Config {
vapidPublicKey: env.VAPID_PUBLIC_KEY || '', vapidPublicKey: env.VAPID_PUBLIC_KEY || '',
vapidPrivateKey: env.VAPID_PRIVATE_KEY || '', vapidPrivateKey: env.VAPID_PRIVATE_KEY || '',
vapidSubject: env.VAPID_SUBJECT || '', vapidSubject: env.VAPID_SUBJECT || '',
pushEnabled: env.PUSH_DISABLED !== '1',
ratesEnabled: env.RATES_DISABLED !== '1', ratesEnabled: env.RATES_DISABLED !== '1',
ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref',
// `??`, not `||`: an explicitly empty value turns the extra source off.
ratesExtraUrl: env.RATES_EXTRA_URL ?? 'https://open.er-api.com/v6/latest/EUR',
}; };
} }

View file

@ -19,12 +19,6 @@ export interface PushSub {
deviceId: string; deviceId: string;
} }
export interface RatesDay {
date: string;
rates: Record<string, string>;
sources: Record<string, string>;
}
export class Store { export class Store {
readonly db: DatabaseSync; readonly db: DatabaseSync;
@ -71,13 +65,6 @@ export class Store {
date TEXT PRIMARY KEY, date TEXT PRIMARY KEY,
json TEXT NOT NULL json TEXT NOT NULL
); );
-- Supplementary rates (see rates.ts), kept apart so ECB refreshes never
-- overwrite them and ECB always wins for currencies both publish.
CREATE TABLE IF NOT EXISTS rates_extra (
date TEXT PRIMARY KEY,
source TEXT NOT NULL,
json TEXT NOT NULL
);
`); `);
} }
@ -173,37 +160,12 @@ export class Store {
this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates)); this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates));
} }
saveExtraRates(date: string, source: string, rates: Record<string, string>): void { /** Rates for the latest published date on or before `date`. */
this.db ratesOn(date: string): { date: string; rates: Record<string, string> } | undefined {
.prepare('INSERT OR REPLACE INTO rates_extra (date, source, json) VALUES (?, ?, ?)')
.run(date, source, JSON.stringify(rates));
}
/**
* ECB rates for the latest published date on or before `date`, plus
* supplementary rates for currencies the ECB doesn't publish. `sources`
* names the origin of each supplementary rate ("<source>:<date>").
* Supplementary rates older than a week before `date` are not used.
*/
ratesOn(date: string): RatesDay | undefined {
const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as
| { date: string; json: string } | { date: string; json: string }
| undefined; | undefined;
if (!r) return undefined; return r && { date: r.date, rates: JSON.parse(r.json) };
const rates: Record<string, string> = JSON.parse(r.json);
const sources: Record<string, string> = {};
const weekBefore = new Date(Date.parse(date) - 7 * 86400_000).toISOString().slice(0, 10);
const x = this.db
.prepare('SELECT date, source, json FROM rates_extra WHERE date <= ? AND date >= ? ORDER BY date DESC LIMIT 1')
.get(date, weekBefore) as { date: string; source: string; json: string } | undefined;
if (x) {
for (const [code, rate] of Object.entries(JSON.parse(x.json) as Record<string, string>)) {
if (code in rates) continue;
rates[code] = rate;
sources[code] = `${x.source}:${x.date}`;
}
}
return { date: r.date, rates, sources };
} }
latestRatesDate(): string | undefined { latestRatesDate(): string | undefined {

View file

@ -0,0 +1,28 @@
// Generate VAPID keys and write them into an env file without printing the
// private key: `node apps/server/src/gen-vapid.ts deploy/.env`.
// Existing VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY lines are kept unless
// --force is given (rotating keys invalidates every push subscription).
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { generateVapidKeys } from './push.ts';
const file = process.argv[2];
const force = process.argv.includes('--force');
if (!file) {
console.error('usage: node gen-vapid.ts <env-file> [--force]');
process.exit(2);
}
const lines = existsSync(file) ? readFileSync(file, 'utf8').split('\n') : [];
const has = (k: string) => lines.some((l) => l.startsWith(`${k}=`) && l.length > k.length + 1);
if (has('VAPID_PUBLIC_KEY') && has('VAPID_PRIVATE_KEY') && !force) {
console.error(`${file} already has VAPID keys; leaving them alone (use --force to rotate).`);
process.exit(0);
}
const { publicKey, privateKey } = generateVapidKeys();
const kept = lines.filter((l) => !l.startsWith('VAPID_PUBLIC_KEY=') && !l.startsWith('VAPID_PRIVATE_KEY='));
while (kept.length && kept[kept.length - 1] === '') kept.pop();
kept.push(`VAPID_PUBLIC_KEY=${publicKey}`, `VAPID_PRIVATE_KEY=${privateKey}`, '');
writeFileSync(file, kept.join('\n'), { mode: 0o600 });
chmodSync(file, 0o600);
console.error(`Wrote VAPID keys to ${file} (private key ${privateKey.length} chars, not shown).`);

View file

@ -11,12 +11,12 @@ const server = createServer(createApp(cfg, store));
server.requestTimeout = 0; server.requestTimeout = 0;
server.headersTimeout = 30_000; server.headersTimeout = 30_000;
const rates = new RatesService(store, cfg.ratesBaseUrl, cfg.ratesExtraUrl); const rates = new RatesService(store, cfg.ratesBaseUrl);
if (cfg.ratesEnabled) rates.start(); if (cfg.ratesEnabled) rates.start();
server.listen(cfg.port, cfg.host, () => { server.listen(cfg.port, cfg.host, () => {
console.log(`oweme server on http://${cfg.host}:${cfg.port}` + (cfg.staticDir ? ` serving ${cfg.staticDir}` : ' (API only)')); console.log(`oweme server on http://${cfg.host}:${cfg.port}` + (cfg.staticDir ? ` serving ${cfg.staticDir}` : ' (API only)'));
if (!cfg.pushEnabled) console.log('push notifications disabled (PUSH_DISABLED=1)'); if (!cfg.vapidPublicKey) console.log('push notifications disabled: VAPID_* not set');
}); });
for (const sig of ['SIGINT', 'SIGTERM'] as const) { for (const sig of ['SIGINT', 'SIGTERM'] as const) {

View file

@ -3,8 +3,6 @@
// the service worker fetches and decrypts the actual events itself, so the // the service worker fetches and decrypts the actual events itself, so the
// push service never sees content (SPEC.md §7.7). // push service never sees content (SPEC.md §7.7).
import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign } from 'node:crypto'; import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { PushSub } from './db.ts'; import type { PushSub } from './db.ts';
const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url'); const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url');
@ -37,23 +35,6 @@ export function generateVapidKeys(): { publicKey: string; privateKey: string } {
return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) }; return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) };
} }
/**
* VAPID keys from the environment if both are set, otherwise generated once
* and kept in the data directory, so push works without any configuration.
* Deleting vapid.json rotates them (and invalidates every subscription).
*/
export function loadVapidKeys(dataDir: string, envPublic: string, envPrivate: string): { publicKey: string; privateKey: string; source: string } {
if (envPublic && envPrivate) return { publicKey: envPublic, privateKey: envPrivate, source: 'environment' };
const file = join(dataDir, 'vapid.json');
if (existsSync(file)) {
const k = JSON.parse(readFileSync(file, 'utf8'));
if (typeof k.publicKey === 'string' && typeof k.privateKey === 'string') return { ...k, source: file };
}
const k = generateVapidKeys();
writeFileSync(file, JSON.stringify(k), { mode: 0o600, flag: 'wx' });
return { ...k, source: `${file} (new)` };
}
export interface Vapid { export interface Vapid {
publicKey: string; publicKey: string;
privateKey: string; privateKey: string;

View file

@ -1,35 +1,7 @@
// Exchange rates, fetched by the server so that clients never contact a // ECB daily reference rates (EUR-based). Fetched by the server so that
// third party (SPEC.md §8.2): // clients never contact a third party (SPEC.md §8.2).
// - ECB daily reference rates (EUR-based, ~30 currencies, history to 1999);
// - a supplementary EUR-based feed for everything else (e.g. ALL), in the
// format of ExchangeRate-API's free endpoint. It has no history, so its
// daily snapshots accumulate from the day the server starts fetching.
import type { Store } from './db.ts'; import type { Store } from './db.ts';
/** Short name stored with supplementary rates; the client labels it. */
export const EXTRA_SOURCE = 'xr';
const DECIMAL_RE = /^\d{1,12}(?:\.\d{1,12})?$/;
/**
* Parse an ExchangeRate-API style response
* (`{ result, base_code, time_last_update_unix, rates: { CODE: number } }`)
* into its UTC date and decimal-string rates.
*/
export function parseExtraRates(json: unknown): { date: string; rates: Record<string, string> } {
const d = json as { result?: unknown; base_code?: unknown; time_last_update_unix?: unknown; rates?: unknown };
if (d?.result !== 'success' || d.base_code !== 'EUR') throw new Error('not a successful EUR-based response');
if (typeof d.time_last_update_unix !== 'number' || typeof d.rates !== 'object' || !d.rates) throw new Error('malformed response');
const rates: Record<string, string> = {};
for (const [code, value] of Object.entries(d.rates as Record<string, unknown>)) {
if (!/^[A-Z]{3}$/.test(code) || typeof value !== 'number' || !(value > 0)) continue;
const str = String(value); // e.g. 1e-7 would not be a valid rate string; skip it
if (DECIMAL_RE.test(str)) rates[code] = str;
}
if (Object.keys(rates).length === 0) throw new Error('no rates parsed');
return { date: new Date(d.time_last_update_unix * 1000).toISOString().slice(0, 10), rates };
}
/** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */ /** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */
export function parseEcbXml(xml: string): Map<string, Record<string, string>> { export function parseEcbXml(xml: string): Map<string, Record<string, string>> {
const out = new Map<string, Record<string, string>>(); const out = new Map<string, Record<string, string>>();
@ -47,12 +19,10 @@ export class RatesService {
private timer: NodeJS.Timeout | undefined; private timer: NodeJS.Timeout | undefined;
private readonly store: Store; private readonly store: Store;
private readonly baseUrl: string; private readonly baseUrl: string;
private readonly extraUrl: string;
constructor(store: Store, baseUrl: string, extraUrl = '') { constructor(store: Store, baseUrl: string) {
this.store = store; this.store = store;
this.baseUrl = baseUrl; this.baseUrl = baseUrl;
this.extraUrl = extraUrl;
} }
async refresh(): Promise<void> { async refresh(): Promise<void> {
@ -68,20 +38,9 @@ export class RatesService {
console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`);
} }
async refreshExtra(): Promise<void> {
const res = await fetch(this.extraUrl, { signal: AbortSignal.timeout(60_000) });
if (!res.ok) throw new Error(`extra rates: HTTP ${res.status}`);
const { date, rates } = parseExtraRates(await res.json());
this.store.saveExtraRates(date, EXTRA_SOURCE, rates);
console.log(`rates: stored ${Object.keys(rates).length} extra rates for ${date}`);
}
/** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */ /** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */
start(): void { start(): void {
const run = () => { const run = () => this.refresh().catch((e) => console.error(`rates: ${e.message}`));
this.refresh().catch((e) => console.error(`rates: ${e.message}`));
if (this.extraUrl) this.refreshExtra().catch((e) => console.error(`rates: ${e.message}`));
};
void run(); void run();
this.timer = setInterval(run, 6 * 3600_000); this.timer = setInterval(run, 6 * 3600_000);
this.timer.unref(); this.timer.unref();

View file

@ -8,8 +8,8 @@ import { after, before, describe, it } from 'node:test';
import { createApp } from '../src/app.ts'; import { createApp } from '../src/app.ts';
import { loadConfig } from '../src/config.ts'; import { loadConfig } from '../src/config.ts';
import { Store } from '../src/db.ts'; import { Store } from '../src/db.ts';
import { encryptPayload, isAllowedEndpoint, loadVapidKeys } from '../src/push.ts'; import { encryptPayload, isAllowedEndpoint } from '../src/push.ts';
import { parseEcbXml, parseExtraRates } from '../src/rates.ts'; import { parseEcbXml } from '../src/rates.ts';
const b64u = (b: Buffer) => b.toString('base64url'); const b64u = (b: Buffer) => b.toString('base64url');
const newGroup = () => { const newGroup = () => {
@ -35,7 +35,6 @@ before(async () => {
}); });
store = new Store(cfg.dataDir); store = new Store(cfg.dataDir);
store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' }); store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' });
store.saveExtraRates('2026-10-09', 'xr', { EUR: '1', CZK: '24.9', ALL: '98.38' });
server = createServer(createApp(cfg, store)); server = createServer(createApp(cfg, store));
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r)); await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
const addr = server.address() as { port: number }; const addr = server.address() as { port: number };
@ -143,27 +142,6 @@ describe('rates and static', () => {
assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404); assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404);
}); });
it('fills in currencies the ECB lacks from the extra source, ECB first', async () => {
const r = await api('GET', '/api/rates?date=2026-10-11');
assert.equal(r.data.rates.ALL, '98.38');
assert.equal(r.data.rates.CZK, '24.4');
assert.deepEqual(r.data.sources, { ALL: 'xr:2026-10-09' });
// A snapshot more than a week old is not used; ECB rates still are.
const late = await api('GET', '/api/rates?date=2026-10-20');
assert.equal(late.data.rates.ALL, undefined);
assert.equal(late.data.rates.CZK, '24.4');
assert.equal((await api('GET', '/api/rates?date=2026-02-30x')).status, 400);
assert.equal((await api('GET', '/api/rates?date=2026-13-45')).status, 400);
});
it('parses the extra rates feed', () => {
const t = Date.UTC(2026, 10, 6, 0, 2) / 1000;
const p = parseExtraRates({ result: 'success', base_code: 'EUR', time_last_update_unix: t, rates: { EUR: 1, ALL: 98.38, BAD: -1, XYZ: 1e-9, lower: 2 } });
assert.deepEqual(p, { date: '2026-11-06', rates: { EUR: '1', ALL: '98.38' } });
assert.throws(() => parseExtraRates({ result: 'error' }));
assert.throws(() => parseExtraRates({ result: 'success', base_code: 'USD', time_last_update_unix: t, rates: { EUR: 1 } }));
});
it('parses ECB XML', () => { it('parses ECB XML', () => {
const xml = '<Cube><Cube time="2026-10-09"><Cube currency="USD" rate="1.1206"/><Cube currency="CZK" rate="24.369"/></Cube></Cube>'; const xml = '<Cube><Cube time="2026-10-09"><Cube currency="USD" rate="1.1206"/><Cube currency="CZK" rate="24.369"/></Cube></Cube>';
assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' }); assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' });
@ -183,23 +161,6 @@ describe('rates and static', () => {
}); });
}); });
describe('vapid keys', () => {
it('generates keys once and keeps them in the data dir', () => {
const d = mkdtempSync(join(tmpdir(), 'oweme-vapid-'));
const a = loadVapidKeys(d, '', '');
const b = loadVapidKeys(d, '', '');
assert.equal(a.publicKey, b.publicKey);
assert.match(a.publicKey, /^[A-Za-z0-9_-]{87}$/);
assert.equal(loadVapidKeys(d, 'pub', 'priv').publicKey, 'pub'); // env wins
rmSync(d, { recursive: true, force: true });
});
it('exposes the public key without any configuration', async () => {
const r = await api('GET', '/api/config');
assert.match(r.data.vapidPublicKey, /^[A-Za-z0-9_-]{87}$/);
});
});
describe('web push encryption', () => { describe('web push encryption', () => {
it('produces an RFC 8291 payload the browser side can decrypt', () => { it('produces an RFC 8291 payload the browser side can decrypt', () => {
// Play the browser: generate a subscription key pair and auth secret. // Play the browser: generate a subscription key pair and auth secret.

View file

@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0a0b0d" /> <meta name="theme-color" content="#0B2E22" />
<meta name="referrer" content="no-referrer" /> <meta name="referrer" content="no-referrer" />
<meta name="description" content="Split group expenses, end-to-end encrypted." /> <meta name="description" content="Split group expenses, end-to-end encrypted." />
<title>OweMe</title> <title>OweMe</title>

View file

@ -5,8 +5,8 @@
"start_url": "/", "start_url": "/",
"scope": "/", "scope": "/",
"display": "standalone", "display": "standalone",
"background_color": "#0a0b0d", "background_color": "#0B2E22",
"theme_color": "#0a0b0d", "theme_color": "#0B2E22",
"icons": [ "icons": [
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" }, { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" },
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },

View file

@ -1,76 +1,63 @@
/* OweMe theme (SPEC.md §10.4): soft dark (default), black and light. /* OweMe theme: dark & light "money green" (SPEC.md §10.4). */
"System" follows the OS between soft dark and light; black is opt-in.
Contrast of text, muted, accent, owe and danger against bg, surface and
surface-2 is ≥ 4.5:1 in every theme. */
:root { :root {
--bg: #0a0b0d; --bg: #0b2e22;
--surface: #16181c; --surface: #123d2e;
--surface-2: #1f2227; --surface-2: #1a4d3a;
--border: #3a3e45; /* controls: inputs, buttons */ --border: #255c46;
--line: #ffffff0f; /* quiet dividers: cards, lists */ --text: #e8f3ec;
--text: #f5f6f7; --muted: #9fbfae;
--muted: #8b9099;
--accent: #3ddc97; --accent: #3ddc97;
--accent-ink: #04140d; --accent-ink: #062016;
--owe: #ff9466; --owe: #f2a65a;
--danger: #f87171; --danger: #f87171;
--gold: #d4af37; --gold: #d4af37;
/* chart series, validated for CVD separation on --surface */ /* chart series, validated for CVD separation on --surface */
--chart-1: #22a66e; --chart-1: #22a66e;
--chart-2: #4a8fd0; --chart-2: #4a8fd0;
--shadow: 0 10px 30px rgb(0 0 0 / 0.45); --shadow: 0 8px 30px rgb(0 0 0 / 0.35);
--radius: 20px; --radius: 14px;
--gutter: 16px; --gutter: 16px;
color-scheme: dark; color-scheme: dark;
} }
:root[data-theme='black'] {
--bg: #000000;
--surface: #121316;
--surface-2: #1b1d21;
--border: #363a40;
}
@media (prefers-color-scheme: light) { @media (prefers-color-scheme: light) {
:root:not([data-theme]) { :root:not([data-theme='dark']) {
--bg: #f2f3f5; --bg: #f2f7f4;
--surface: #ffffff; --surface: #ffffff;
--surface-2: #e9ebee; --surface-2: #e4efe9;
--border: #c9cdd3; --border: #cfe0d6;
--line: #0000000f; --text: #0b2e22;
--text: #0d0f12; --muted: #4a6b5b;
--muted: #5f6670; --accent: #16865a;
--accent: #0b7549;
--accent-ink: #ffffff; --accent-ink: #ffffff;
--owe: #b53c0a; --owe: #b5541c;
--danger: #c0392b; --danger: #c0392b;
--gold: #9a7b12; --gold: #9a7b12;
--chart-1: #16865a; --chart-1: #16865a;
--chart-2: #2f6fb0; --chart-2: #2f6fb0;
--shadow: 0 8px 24px rgb(13 15 18 / 0.08); --shadow: 0 8px 30px rgb(11 46 34 / 0.12);
color-scheme: light; color-scheme: light;
} }
} }
:root[data-theme='light'] { :root[data-theme='light'] {
--bg: #f2f3f5; --bg: #f2f7f4;
--surface: #ffffff; --surface: #ffffff;
--surface-2: #e9ebee; --surface-2: #e4efe9;
--border: #c9cdd3; --border: #cfe0d6;
--line: #0000000f; --text: #0b2e22;
--text: #0d0f12; --muted: #4a6b5b;
--muted: #5f6670; --accent: #16865a;
--accent: #0b7549;
--accent-ink: #ffffff; --accent-ink: #ffffff;
--owe: #b53c0a; --owe: #b5541c;
--danger: #c0392b; --danger: #c0392b;
--gold: #9a7b12; --gold: #9a7b12;
--chart-1: #16865a; --chart-1: #16865a;
--chart-2: #2f6fb0; --chart-2: #2f6fb0;
--shadow: 0 8px 24px rgb(13 15 18 / 0.08); --shadow: 0 8px 30px rgb(11 46 34 / 0.12);
color-scheme: light; color-scheme: light;
} }
* { box-sizing: border-box; } * { box-sizing: border-box; }
svg { flex-shrink: 0; } /* icons beside wrapping text must not be squashed */
html { -webkit-text-size-adjust: 100%; } html { -webkit-text-size-adjust: 100%; }
body { body {
margin: 0; margin: 0;
@ -83,8 +70,7 @@ body {
h1, h2, h3 { line-height: 1.2; margin: 0; } h1, h2, h3 { line-height: 1.2; margin: 0; }
h1 { font-size: 1.35rem; } h1 { font-size: 1.35rem; }
h2 { font-size: 1.05rem; } h2 { font-size: 1.05rem; }
h3 { font-size: 1.05rem; font-weight: 700; letter-spacing: -0.01em; } h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); font-weight: 600; }
h3.day { font-size: 0.85rem; font-weight: 600; letter-spacing: 0; color: var(--muted); padding-left: 4px; }
a { color: var(--accent); } a { color: var(--accent); }
p { margin: 0; } p { margin: 0; }
.muted { color: var(--muted); } .muted { color: var(--muted); }
@ -115,12 +101,12 @@ p { margin: 0; }
.card { .card {
background: var(--surface); background: var(--surface);
border: 1px solid var(--line); border: 1px solid var(--border);
border-radius: var(--radius); border-radius: var(--radius);
padding: 14px 16px; padding: 14px 16px;
} }
.list { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; } .list { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
.list > * + * { border-top: 1px solid var(--line); } .list > * + * { border-top: 1px solid var(--border); }
.item { .item {
display: flex; align-items: center; gap: 12px; padding: 12px 14px; width: 100%; display: flex; align-items: center; gap: 12px; padding: 12px 14px; width: 100%;
background: none; border: 0; color: inherit; font: inherit; text-align: left; text-decoration: none; background: none; border: 0; color: inherit; font: inherit; text-align: left; text-decoration: none;
@ -138,7 +124,7 @@ button, .btn {
} }
.btn { .btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px; display: inline-flex; align-items: center; justify-content: center; gap: 8px;
min-height: 44px; padding: 0 18px; border-radius: 999px; min-height: 44px; padding: 0 16px; border-radius: 12px;
border: 1px solid var(--border); background: var(--surface); color: var(--text); border: 1px solid var(--border); background: var(--surface); color: var(--text);
font-weight: 600; text-decoration: none; white-space: nowrap; font-weight: 600; text-decoration: none; white-space: nowrap;
} }
@ -147,21 +133,19 @@ button, .btn {
.btn.primary:hover { filter: brightness(1.08); } .btn.primary:hover { filter: brightness(1.08); }
.btn.danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 40%, var(--border)); } .btn.danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 40%, var(--border)); }
.btn.ghost { background: transparent; border-color: transparent; } .btn.ghost { background: transparent; border-color: transparent; }
.btn.tint { background: color-mix(in srgb, var(--accent) 15%, var(--surface)); border-color: transparent; color: var(--accent); } .btn.small { min-height: 34px; padding: 0 12px; font-size: 0.9rem; border-radius: 10px; }
.btn.tint:hover { background: color-mix(in srgb, var(--accent) 24%, var(--surface)); }
.btn.small { min-height: 34px; padding: 0 14px; font-size: 0.9rem; }
.btn.block { width: 100%; } .btn.block { width: 100%; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; } .btn:disabled { opacity: 0.5; cursor: not-allowed; }
.icon-btn { .icon-btn {
display: inline-grid; place-items: center; width: 44px; height: 44px; flex-shrink: 0; display: inline-grid; place-items: center; width: 44px; height: 44px; flex-shrink: 0;
border-radius: 50%; border: 0; background: transparent; color: var(--text); border-radius: 12px; border: 0; background: transparent; color: var(--text);
} }
.icon-btn:hover { background: var(--surface-2); } .icon-btn:hover { background: var(--surface-2); }
label.field { display: flex; flex-direction: column; gap: 6px; font-size: 0.9rem; color: var(--muted); } label.field { display: flex; flex-direction: column; gap: 6px; font-size: 0.9rem; color: var(--muted); }
input, select, textarea { input, select, textarea {
font: inherit; color: var(--text); background: var(--surface); width: 100%; font: inherit; color: var(--text); background: var(--surface); width: 100%;
border: 1px solid var(--border); border-radius: 12px; padding: 10px 12px; min-height: 44px; border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; min-height: 44px;
} }
textarea { min-height: 80px; resize: vertical; } textarea { min-height: 80px; resize: vertical; }
input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-visible, .icon-btn:focus-visible, .item:focus-visible, .chip:focus-visible { input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-visible, .icon-btn:focus-visible, .item:focus-visible, .chip:focus-visible {
@ -170,20 +154,16 @@ input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-vi
input[type='checkbox'] { width: 22px; height: 22px; min-height: 0; accent-color: var(--accent); flex-shrink: 0; } input[type='checkbox'] { width: 22px; height: 22px; min-height: 0; accent-color: var(--accent); flex-shrink: 0; }
input[type='date'] { min-width: 0; } input[type='date'] { min-width: 0; }
.seg { .seg { display: flex; background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 3px; gap: 3px; }
display: flex; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; padding: 3px; gap: 3px;
overflow-x: auto; scrollbar-width: none; /* very narrow screens scroll rather than wrap */
}
.seg::-webkit-scrollbar { display: none; }
.seg button { .seg button {
flex: 1 0 auto; white-space: nowrap; min-height: 38px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px; flex: 1; min-height: 38px; border: 0; border-radius: 9px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px;
} }
.seg button[aria-pressed='true'] { background: var(--surface-2); color: var(--text); } .seg button[aria-pressed='true'] { background: var(--surface-2); color: var(--text); }
.chips { display: flex; flex-wrap: wrap; gap: 8px; } .chips { display: flex; flex-wrap: wrap; gap: 8px; }
.chip { .chip {
display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px; display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px;
border-radius: 999px; border: 1px solid var(--line); background: var(--surface); color: var(--text); font-size: 0.9rem; border-radius: 999px; border: 1px solid var(--border); background: var(--surface); color: var(--text); font-size: 0.9rem;
} }
.chip[aria-pressed='true'] { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, var(--surface)); } .chip[aria-pressed='true'] { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, var(--surface)); }
@ -194,53 +174,45 @@ input[type='date'] { min-width: 0; }
} }
.cat-icon { .cat-icon {
display: inline-grid; place-items: center; flex-shrink: 0; display: inline-grid; place-items: center; flex-shrink: 0;
width: 40px; height: 40px; border-radius: 50%; background: var(--surface-2); font-size: 1.2rem; width: 40px; height: 40px; border-radius: 12px; background: var(--surface-2); font-size: 1.2rem;
} }
.banner { padding: 10px 14px; border-radius: 14px; font-size: 0.9rem; background: var(--surface-2); border: 1px solid var(--line); } .banner { padding: 10px 14px; border-radius: 12px; font-size: 0.9rem; background: var(--surface-2); border: 1px solid var(--border); }
.banner.warn { border-color: color-mix(in srgb, var(--owe) 60%, var(--border)); } .banner.warn { border-color: color-mix(in srgb, var(--owe) 60%, var(--border)); }
.banner.danger { border-color: color-mix(in srgb, var(--danger) 60%, var(--border)); } .banner.danger { border-color: color-mix(in srgb, var(--danger) 60%, var(--border)); }
.fab { .fab {
position: fixed; right: max(var(--gutter), calc(50% - 360px + var(--gutter))); bottom: calc(96px + env(safe-area-inset-bottom)); z-index: 30; position: fixed; right: max(var(--gutter), calc(50% - 360px + var(--gutter))); bottom: calc(80px + env(safe-area-inset-bottom)); z-index: 30;
width: 60px; height: 60px; border-radius: 50%; border: 0; width: 60px; height: 60px; border-radius: 20px; border: 0;
background: var(--accent); color: var(--accent-ink); box-shadow: var(--shadow); background: var(--accent); color: var(--accent-ink); box-shadow: var(--shadow);
display: grid; place-items: center; display: grid; place-items: center;
} }
/* floating pill tab bar */
.tabbar { .tabbar {
position: fixed; z-index: 25; position: fixed; left: 0; right: 0; bottom: 0; z-index: 25;
left: var(--gutter); right: var(--gutter); bottom: calc(12px + env(safe-area-inset-bottom)); display: flex; justify-content: center;
max-width: 560px; margin: 0 auto; background: color-mix(in srgb, var(--surface) 94%, transparent);
display: flex; justify-content: center; padding: 5px; border-radius: 999px; backdrop-filter: blur(10px);
background: color-mix(in srgb, var(--surface-2) 90%, transparent); -webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(16px); border-top: 1px solid var(--border);
-webkit-backdrop-filter: blur(16px); padding-bottom: env(safe-area-inset-bottom);
border: 1px solid var(--line);
box-shadow: var(--shadow);
} }
.tabbar a { .tabbar a {
flex: 1; display: flex; flex-direction: column; align-items: center; gap: 2px; border-radius: 999px; flex: 1; max-width: 180px; display: flex; flex-direction: column; align-items: center; gap: 2px;
padding: 7px 4px; color: var(--muted); text-decoration: none; font-size: 0.72rem; font-weight: 600; padding: 8px 4px; color: var(--muted); text-decoration: none; font-size: 0.75rem; font-weight: 600;
} }
.tabbar a[aria-current='page'] { color: var(--text); background: var(--surface); } .tabbar a[aria-current='page'] { color: var(--accent); }
/* dialogs: full-screen sheet on phones, centered on desktop */ /* dialogs: full-screen sheet on phones, centered on desktop */
dialog.sheet { dialog.sheet {
padding: 0; border: 0; color: var(--text); background: var(--bg); padding: 0; border: 0; color: var(--text); background: var(--bg);
width: 100%; max-width: 100%; height: 100%; max-height: 100%; margin: 0; width: 100%; max-width: 100%; height: 100%; max-height: 100%; margin: 0;
} }
dialog.sheet:focus { outline: none; }
/* Sheets scroll under an opaque header (and, in the editor, a pinned Save bar):
keep focused fields clear of both. */
dialog.sheet { scroll-padding: 72px 0 96px; }
dialog.sheet .topbar { background: var(--bg); }
dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); } dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); }
@media (min-width: 760px) { @media (min-width: 760px) {
dialog.sheet { dialog.sheet {
width: min(640px, calc(100% - 48px)); height: auto; max-height: calc(100dvh - 64px); width: min(640px, calc(100% - 48px)); height: auto; max-height: calc(100dvh - 64px);
margin: auto; border-radius: 24px; border: 1px solid var(--line); box-shadow: var(--shadow); margin: auto; border-radius: 20px; border: 1px solid var(--border); box-shadow: var(--shadow);
} }
} }
.sheet-body { padding: 0 var(--gutter) calc(24px + env(safe-area-inset-bottom)); } .sheet-body { padding: 0 var(--gutter) calc(24px + env(safe-area-inset-bottom)); }
@ -261,16 +233,9 @@ dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); }
/* desktop: group page with a side column */ /* desktop: group page with a side column */
@media (min-width: 960px) { @media (min-width: 960px) {
.tabbar { position: static; justify-content: flex-start; gap: 4px; background: none; border: 0; box-shadow: none; backdrop-filter: none; padding: 0; margin: 0; max-width: none; } .tabbar { position: static; justify-content: flex-start; gap: 4px; background: none; border: 0; backdrop-filter: none; padding: 0; }
.tabbar a { flex: 0 0 auto; flex-direction: row; gap: 8px; font-size: 0.95rem; padding: 10px 14px; border-radius: 10px; } .tabbar a { flex: 0 0 auto; flex-direction: row; gap: 8px; font-size: 0.95rem; padding: 10px 14px; border-radius: 10px; }
.tabbar a[aria-current='page'] { background: var(--surface); } .tabbar a[aria-current='page'] { background: var(--surface); }
.fab { bottom: 32px; right: max(32px, calc(50% - 560px + 32px)); } .fab { bottom: 32px; right: max(32px, calc(50% - 560px + 32px)); }
.page { padding-bottom: 48px; } .page { padding-bottom: 48px; }
} }
/* round category icon tinted with its category colour (set --cat inline) */
.cat-icon { background: color-mix(in srgb, var(--cat, var(--muted)) 24%, var(--surface-2)); }
/* money with the whole number emphasised (see moneyParts) */
.money .cur, .money .frac { color: var(--muted); font-size: 0.82em; font-weight: inherit; }
.pos .money .cur, .pos .money .frac, .neg .money .cur, .neg .money .frac { color: inherit; opacity: 0.8; }

View file

@ -23,7 +23,6 @@
<div class="seg" role="group" aria-label={t('theme')}> <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 === '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 === 'dark'} onclick={() => settings.setTheme('dark')}>{t('theme_dark')}</button>
<button aria-pressed={settings.themePref === 'black'} onclick={() => settings.setTheme('black')}>{t('theme_black')}</button>
<button aria-pressed={settings.themePref === 'light'} onclick={() => settings.setTheme('light')}>{t('theme_light')}</button> <button aria-pressed={settings.themePref === 'light'} onclick={() => settings.setTheme('light')}>{t('theme_light')}</button>
</div> </div>
</div> </div>

View file

@ -42,14 +42,14 @@
<div class="list"> <div class="list">
{#each members as { m, i, bal } (m.id)} {#each members as { m, i, bal } (m.id)}
<div class="item"> <div class="item">
<Avatar member={m} index={i} size={40} /> <Avatar member={m} index={i} size={32} />
<span class="grow"> <span class="grow">
<span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span> <span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span>
<span class="bar" aria-hidden="true"> <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 class={bal >= 0 ? 'fill pos-fill' : 'fill neg-fill'} style:width="{(Math.abs(bal) / maxAbs) * 100}%"></span>
</span> </span>
</span> </span>
<span class="end num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : 'muted'}" style:font-weight="650"> <span class="end num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : 'muted'}">
{bal === 0 ? t('settled') : (bal > 0 ? '+' : '−') + conv(Math.abs(bal))} {bal === 0 ? t('settled') : (bal > 0 ? '+' : '−') + conv(Math.abs(bal))}
</span> </span>
</div> </div>
@ -62,18 +62,12 @@
{:else} {:else}
<div class="list"> <div class="list">
{#each transfers as tr} {#each transfers as tr}
{@const from = session.state.members.findIndex((m) => m.id === tr.from)}
{@const to = session.state.members.findIndex((m) => m.id === tr.to)}
<div class="item"> <div class="item">
<span class="pair" aria-hidden="true">
<Avatar member={session.state.members[from]} index={from} size={34} />
<Avatar member={session.state.members[to]} index={to} size={34} />
</span>
<span class="grow"> <span class="grow">
<span class="title" style:display="block">{session.memberName(tr.from)} → {session.memberName(tr.to)}</span> <span class="title" style:display="block">{session.memberName(tr.from)} → {session.memberName(tr.to)}</span>
<span class="num sub" style:display="block">{conv(tr.amount)}</span> <span class="num" style:font-weight="700">{conv(tr.amount)}</span>
</span> </span>
<button class="btn small tint" onclick={() => record(tr.from, tr.to, tr.amount)}>{t('mark_paid')}</button> <button class="btn small" onclick={() => record(tr.from, tr.to, tr.amount)}>{t('mark_paid')}</button>
</div> </div>
{/each} {/each}
</div> </div>
@ -91,10 +85,7 @@
</div> </div>
<style> <style>
.pair { display: flex; flex-shrink: 0; } .bar { display: block; height: 6px; margin-top: 6px; background: var(--surface-2); border-radius: 3px; overflow: hidden; }
.pair :global(.avatar) { box-shadow: 0 0 0 3px var(--surface); }
.pair :global(.avatar + .avatar) { margin-left: -10px; }
.bar { display: block; height: 5px; margin-top: 7px; background: var(--surface-2); border-radius: 3px; overflow: hidden; }
.fill { display: block; height: 100%; border-radius: 3px; } .fill { display: block; height: 100%; border-radius: 3px; }
.pos-fill { background: var(--accent); } .pos-fill { background: var(--accent); }
.neg-fill { background: var(--owe); } .neg-fill { background: var(--owe); }

View file

@ -1,10 +1,9 @@
<script lang="ts"> <script lang="ts">
import { currencyList } from '../lib/rates.ts'; import { currencyList } from '../lib/rates.ts';
import { currencyName } from '../lib/format.ts'; import { currencyName } from '../lib/format.ts';
import { t } from '../lib/settings.svelte.ts';
let { value = $bindable(), disabled = false, id }: { value: string; disabled?: boolean; id?: string } = $props(); let { value = $bindable(), disabled = false, id }: { value: string; disabled?: boolean; id?: string } = $props();
let lists = $state<{ rated: string[]; other: string[] }>({ rated: [], other: [] }); let lists = $state<{ ecb: string[]; other: string[] }>({ ecb: [], other: [] });
currencyList().then((l) => (lists = l)); currencyList().then((l) => (lists = l));
const recent = (() => { const recent = (() => {
@ -15,9 +14,9 @@
} }
})(); })();
// Keep the current value selectable even before the lists load, or if // Keep the current value selectable even before the lists load, or if
// it's a code that is no longer in circulation (e.g. an old group in BGN). // it's a code this browser doesn't know.
const rated = $derived( const ecb = $derived(
[...lists.rated, ...lists.other, ...recent].includes(value) ? lists.rated : [value, ...lists.rated], [...lists.ecb, ...lists.other, ...recent].includes(value) ? lists.ecb : [value, ...lists.ecb],
); );
</script> </script>
@ -27,11 +26,11 @@
{#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each} {#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup> </optgroup>
{/if} {/if}
<optgroup label={t('currencies_rated')}> <optgroup label="ECB">
{#each rated as c}<option value={c}>{c} · {currencyName(c)}</option>{/each} {#each ecb as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup> </optgroup>
{#if lists.other.length} {#if lists.other.length}
<optgroup label={t('currencies_manual')}> <optgroup label="…">
{#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each} {#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup> </optgroup>
{/if} {/if}

View file

@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { inBase, owedOriginal, type Expense } from '@oweme/core'; import { inBase, owedOriginal, type Expense } from '@oweme/core';
import { randomId } from '../lib/crypto.ts'; import { randomId } from '../lib/crypto.ts';
import { CATEGORY_COLORS, CATEGORY_ICONS, fmtDate, fmtDateTime, money } from '../lib/format.ts'; import { CATEGORY_ICONS, fmtDate, fmtDateTime, money } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts'; import type { MsgKey } from '../lib/i18n.ts';
import { router } from '../lib/router.svelte.ts'; import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts'; import type { GroupSession } from '../lib/session.svelte.ts';
@ -82,7 +82,7 @@
{/if} {/if}
<div class="card stack" style:align-items="center" style:text-align="center"> <div class="card stack" style:align-items="center" style:text-align="center">
<span class="cat-icon" style:--cat={CATEGORY_COLORS[e.category]} aria-hidden="true">{CATEGORY_ICONS[e.category]}</span> <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> <div class="num" style:font-size="2rem" style:font-weight="700">{money(e.amount, e.currency)}</div>
{#if e.currency !== session.base} {#if e.currency !== session.base}
<div class="muted small num">{t('converted', { amount: money(b.total, session.base), rate: e.rate })}</div> <div class="muted small num">{t('converted', { amount: money(b.total, session.base), rate: e.rate })}</div>

View file

@ -1,12 +1,12 @@
<script lang="ts"> <script lang="ts">
import { tick, untrack } from 'svelte'; import { untrack } from 'svelte';
import { import {
CATEGORIES, exponent, isValidRate, owedOriginal, parseAmount, validateExpense, CATEGORIES, exponent, isValidRate, owedOriginal, parseAmount, validateExpense,
type Category, type Expense, type Freq, type Photo, type SplitMode, type Category, type Expense, type Freq, type Photo, type SplitMode,
} from '@oweme/core'; } from '@oweme/core';
import { serverConfig } from '../lib/api.ts'; import { serverConfig } from '../lib/api.ts';
import { randomId } from '../lib/crypto.ts'; import { randomId } from '../lib/crypto.ts';
import { amountInput, CATEGORY_COLORS, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts'; import { amountInput, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
import { processPhoto, type ProcessedPhoto } from '../lib/photo.ts'; import { processPhoto, type ProcessedPhoto } from '../lib/photo.ts';
import { suggestRate } from '../lib/rates.ts'; import { suggestRate } from '../lib/rates.ts';
import { router } from '../lib/router.svelte.ts'; import { router } from '../lib/router.svelte.ts';
@ -15,7 +15,6 @@
import type { MsgKey } from '../lib/i18n.ts'; import type { MsgKey } from '../lib/i18n.ts';
import Avatar from './Avatar.svelte'; import Avatar from './Avatar.svelte';
import CurrencySelect from './CurrencySelect.svelte'; import CurrencySelect from './CurrencySelect.svelte';
import Icon from './Icon.svelte';
import PhotoView from './PhotoView.svelte'; import PhotoView from './PhotoView.svelte';
import Sheet from './Sheet.svelte'; import Sheet from './Sheet.svelte';
@ -39,7 +38,7 @@
let currency = $state(existing?.currency ?? base); let currency = $state(existing?.currency ?? base);
let amountText = $state(existing ? amountInput(existing.amount, existing.currency) : pAmount > 0 ? amountInput(pAmount, base) : ''); let amountText = $state(existing ? amountInput(existing.amount, existing.currency) : pAmount > 0 ? amountInput(pAmount, base) : '');
let title = $state(existing?.title ?? ''); let title = $state(existing?.title ?? '');
let category = $state<Category>(existing?.category === 'transfer' ? 'other' : (existing?.category ?? session.state.group?.defaultCategory ?? 'other')); let category = $state<Category>(existing?.category === 'transfer' ? 'other' : (existing?.category ?? 'food'));
let date = $state(existing?.date ?? today()); let date = $state(existing?.date ?? today());
let note = $state(existing?.note ?? ''); let note = $state(existing?.note ?? '');
let rateText = $state(existing && existing.currency !== base ? existing.rate : '1'); let rateText = $state(existing && existing.currency !== base ? existing.rate : '1');
@ -79,12 +78,6 @@
let newPhotoUrl = $state<string | null>(null); let newPhotoUrl = $state<string | null>(null);
let photoBusy = $state(false); let photoBusy = $state(false);
let repeat = $state<'none' | Freq>('none'); let repeat = $state<'none' | Freq>('none');
// Note and repeat are folded into small buttons until used.
let showNote = $state(!!existing?.note);
let showRepeat = $state(false);
let noteEl = $state<HTMLTextAreaElement>();
/** "Paid by" value that switches to the several-payers list. */
const SEVERAL = '*several';
let error = $state(''); let error = $state('');
let saving = $state(false); let saving = $state(false);
@ -145,7 +138,7 @@
return owedOriginal(e); return owedOriginal(e);
}); });
// Prefill the exchange rate from the server's daily rates. A rate typed by hand is kept // 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 // when the date changes, but not when the currency does. An existing
// expense keeps its stored rate until one of them changes. // expense keeps its stored rate until one of them changes.
let lastCurrency = untrack(() => currency); let lastCurrency = untrack(() => currency);
@ -200,12 +193,6 @@
} }
} }
async function openNote() {
showNote = true;
await tick();
noteEl?.focus();
}
function removePhoto() { function removePhoto() {
photo = null; photo = null;
newPhoto = null; newPhoto = null;
@ -265,133 +252,115 @@
</script> </script>
<Sheet title={heading} onclose={close}> <Sheet title={heading} onclose={close}>
<form class="editor" onsubmit={save} novalidate> <form class="stack" onsubmit={save} novalidate>
{#if !existing} {#if !existing}
<div class="seg kind" role="group"> <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 === 'expense'} onclick={() => (kind = 'expense')}>{t('kind_expense')}</button>
<button type="button" aria-pressed={kind === 'transfer'} onclick={() => (kind = 'transfer')}>{t('kind_transfer')}</button> <button type="button" aria-pressed={kind === 'transfer'} onclick={() => (kind = 'transfer')}>{t('kind_transfer')}</button>
</div> </div>
{/if} {/if}
<!-- amount, with the currency as a pill; the real <select> sits invisibly on top of it --> <div class="card stack" style:gap="4px">
<div class="card amount-card">
<div class="amount-row">
<span class="cur-pill">
<span aria-hidden="true">{currency}</span><Icon name="down" size={16} />
<label class="sr-only" for="currency">{t('currency')}</label>
<CurrencySelect id="currency" bind:value={currency} />
</span>
<label class="sr-only" for="amount">{t('amount')}</label> <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" /> <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> </div>
{#if currency !== base} {#if currency !== base}
<div class="rate"> <div class="row small" style:justify-content="center" style:margin-top="6px">
<span class="row small">
<label for="rate" class="muted">1 {currency} =</label> <label for="rate" class="muted">1 {currency} =</label>
<input id="rate" class="num" inputmode="decimal" bind:value={rateText} oninput={() => (rateSource = 'manual')} /> <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> <span class="muted">{base}</span>
</span> </div>
<!-- xr: rates come from ExchangeRate-API's free tier, which requires the attribution link. --> <p class="small muted" style:text-align="center">
<span class="small muted">
{#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')} {#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')}
{:else if rateSource.startsWith('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })} {:else if rateSource.startsWith('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })}
{:else if rateSource.startsWith('xr:')}<a href="https://www.exchangerate-api.com" target="_blank" rel="noopener noreferrer">{t('rate_source_xr', { date: fmtDate(rateSource.slice(3)) })}</a>
{:else}{t('rate_source_manual')}{/if} {: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} {#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if}
</span> </p>
</div>
{/if} {/if}
</div> </div>
{#if kind === 'expense'} {#if kind === 'expense'}
<label class="sr-only" for="title">{t('title')}</label> <label class="field">{t('title')}<input bind:value={title} placeholder={t('title_ph')} maxlength="200" /></label>
<input id="title" bind:value={title} placeholder={t('title')} maxlength="200" />
<!-- 12 equal tiles: 6 × 2 on phones, one row of 12 on wider screens -->
<div class="field"> <div class="field">
<span class="lbl">{t('category')} · <span class="cat-name">{t(`cat_${category}` as MsgKey)}</span></span> <span class="small muted">{t('category')}</span>
<div class="cats" role="group" aria-label={t('category')}> <div class="chips">
{#each CATEGORIES as c} {#each CATEGORIES as c}
<button type="button" class="cat" style:--cat={CATEGORY_COLORS[c]} aria-pressed={category === c} <button type="button" class="chip" aria-pressed={category === c} onclick={() => (category = c)}>
aria-label={t(`cat_${c}` as MsgKey)} title={t(`cat_${c}` as MsgKey)} onclick={() => (category = c)}> <span aria-hidden="true">{CATEGORY_ICONS[c]}</span> {t(`cat_${c}` as MsgKey)}
<span aria-hidden="true">{CATEGORY_ICONS[c]}</span>
</button> </button>
{/each} {/each}
</div> </div>
</div> </div>
{/if} {/if}
<label class="field">{t('date')}<input type="date" bind:value={date} required /></label>
<!-- who paid -->
{#if kind === 'transfer'} {#if kind === 'transfer'}
<div class="pair"> <div class="row">
<label class="field">{t('from_label')} <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> <select bind:value={payer}>{#each members as m}<option value={m.id}>{m.name}</option>{/each}</select>
</label> </label>
<label class="field">{t('to_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> <select bind:value={transferTo}>{#each members.filter((m) => m.id !== payer) as m}<option value={m.id}>{m.name}</option>{/each}</select>
</label> </label>
</div> </div>
<label class="field">{t('date')}<input type="date" bind:value={date} required /></label>
{:else} {:else}
<div class="pair">
<label class="field">{t('date')}<input type="date" bind:value={date} required /></label>
<label class="field">{t('paid_by_label')}
<select aria-label={t('paid_by_label')} bind:value={() => (multiPayer ? SEVERAL : payer), (v) => { multiPayer = v === SEVERAL; if (v !== SEVERAL) payer = v; }}>
{#each members as m}<option value={m.id}>{m.name}{m.id === me ? ` (${t('you')})` : ''}</option>{/each}
{#if members.length > 1}<option value={SEVERAL}>{t('multiple_payers')}</option>{/if}
</select>
</label>
</div>
{#if multiPayer}
<div class="field"> <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"> <div class="list">
{#each members as m (m.id)} {#each members as m (m.id)}
<div class="item member"> <div class="item">
<Avatar member={m} index={memberIndex(m.id)} size={28} /> <Avatar member={m} index={memberIndex(m.id)} size={30} />
<span class="grow name">{m.name}</span> <span class="grow">{m.name}</span>
<!-- empty boxes hint at what's still unassigned --> <input class="num" style:width="120px" inputmode="decimal" bind:value={payerAmounts[m.id]} aria-label="{t('paid_by_label')}: {m.name}" />
<input class="num value" inputmode="decimal" bind:value={payerAmounts[m.id]} aria-label="{t('paid_by_label')}: {m.name}"
placeholder={payersRemaining > 0 ? amountInput(payersRemaining, currency) : ''} />
</div> </div>
{/each} {/each}
</div> </div>
{#if amount && payersRemaining !== 0} {#if payersRemaining !== 0 && amount}
<span class="small {payersRemaining < 0 ? 'neg' : 'muted'}"> <span class="small {payersRemaining < 0 ? 'neg' : 'muted'}">
{payersRemaining > 0 ? t('remaining', { amount: money(payersRemaining, currency) }) : t('over_by', { amount: money(-payersRemaining, currency) })} {payersRemaining > 0 ? t('remaining', { amount: money(payersRemaining, currency) }) : t('over_by', { amount: money(-payersRemaining, currency) })}
</span> </span>
{:else if amount && payers.length > 1} {/if}
<span class="small pos row adds-up"><Icon name="check" size={14} />{t('adds_up')}</span> {: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} {/if}
</div> </div>
{/if}
<!-- split --> <!-- split -->
<div class="field"> <div class="field">
<div class="lbl-row"> <span class="small muted">{t('split')}</span>
<span class="lbl">{t('split')}</span> <div class="seg" role="group" aria-label={t('split')}>
<button type="button" class="link" onclick={() => members.forEach((m) => (included[m.id] = true))}>{t('select_all')}</button>
<button type="button" class="link" onclick={() => members.forEach((m) => (included[m.id] = false))}>{t('select_none')}</button>
</div>
<div class="seg modes" role="group" aria-label={t('split')}>
{#each [['equal', 'split_equal'], ['shares', 'split_shares'], ['exact', 'split_exact'], ['percent', 'split_percent']] as const as [m, label]} {#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> <button type="button" aria-pressed={mode === m} onclick={() => setMode(m)}>{t(label)}</button>
{/each} {/each}
</div> </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"> <div class="list">
{#each members as m (m.id)} {#each members as m (m.id)}
<div class="item member" class:off={!included[m.id]}> <div class="item">
<input id="inc-{m.id}" type="checkbox" bind:checked={included[m.id]} aria-label={m.name} /> <input type="checkbox" bind:checked={included[m.id]} aria-label={m.name} />
<label for="inc-{m.id}" class="grow who"> <Avatar member={m} index={memberIndex(m.id)} size={30} />
<Avatar member={m} index={memberIndex(m.id)} size={28} /> <span class="grow">
<span class="name">{m.name}</span> <span style:display="block">{m.name}</span>
</label> {#if preview[m.id]}<span class="small muted num">{money(preview[m.id], currency)}</span>{/if}
<!-- what each person owes; in "Amounts" mode the input already says it --> </span>
{#if mode !== 'exact' && preview[m.id]}
<span class="num share" class:small={mode !== 'equal'} class:muted={mode !== 'equal'}>{money(preview[m.id], currency)}</span>
{/if}
{#if mode !== 'equal'} {#if mode !== 'equal'}
<span class="row value-wrap"> <span class="row" style:gap="4px">
<input class="num value" class:narrow={mode !== 'exact'} inputmode={mode === 'shares' ? 'numeric' : 'decimal'} <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}" /> bind:value={values[m.id]} disabled={!included[m.id]} aria-label="{t('split')}: {m.name}" />
{#if mode === 'percent'}<span class="muted">%</span>{/if} {#if mode === 'percent'}<span class="muted">%</span>{/if}
</span> </span>
@ -411,38 +380,29 @@
</div> </div>
{/if} {/if}
<!-- extras: photo, note and repeat stay folded away until wanted --> <!-- photo -->
<div class="extras">
{#if repeat === 'none'} {#if repeat === 'none'}
<label class="btn small"> <div class="field">
<Icon name="camera" size={16} />{photo || newPhoto ? t('replace_photo') : t('photo')} <span class="small muted">{t('photo')}</span>
<input class="sr-only" type="file" accept="image/*" onchange={pickPhoto} disabled={photoBusy} />
</label>
{/if}
{#if !showNote}
<button type="button" class="btn small" onclick={openNote}><Icon name="edit" size={16} />{t('note')}</button>
{/if}
{#if !existing && kind === 'expense' && !showRepeat}
<button type="button" class="btn small" onclick={() => (showRepeat = true)}><Icon name="repeat" size={16} />{t('repeat')}</button>
{/if}
</div>
{#if repeat === 'none' && (photo || newPhoto || photoBusy)}
<div class="photo">
{#if newPhotoUrl} {#if newPhotoUrl}
<img class="photo-thumb" src={newPhotoUrl} alt={t('photo')} /> <img class="photo-thumb" src={newPhotoUrl} alt={t('photo')} />
{:else if photo} {:else if photo}
<PhotoView {session} {photo} /> <PhotoView {session} {photo} />
{/if} {/if}
<div class="row"> <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 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} {#if photoBusy}<span class="small muted">{t('processing_photo')}</span>{/if}
</div> </div>
</div> </div>
{/if} {/if}
{#if showNote}
<label class="field">{t('note')}<textarea bind:this={noteEl} bind:value={note} maxlength="2000" rows="2"></textarea></label> <label class="field">{t('note')}<textarea bind:value={note} maxlength="2000"></textarea></label>
{/if}
{#if showRepeat && !existing && kind === 'expense'} {#if !existing && kind === 'expense'}
<label class="field">{t('repeat')} <label class="field">{t('repeat')}
<select bind:value={repeat}> <select bind:value={repeat}>
<option value="none">{t('repeat_none')}</option> <option value="none">{t('repeat_none')}</option>
@ -453,77 +413,10 @@
</label> </label>
{/if} {/if}
<div class="save-bar">
{#if error}<p class="neg" role="alert">{error}</p>{/if} {#if error}<p class="neg" role="alert">{error}</p>{/if}
<button type="submit" class="btn primary" disabled={saving || photoBusy}>{t('save')}</button> <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> </div>
</form> </form>
</Sheet> </Sheet>
<style>
.editor { display: flex; flex-direction: column; gap: 12px; }
/* On phones the sheet is full screen: keep Save at the bottom edge. */
@media (max-width: 759px) {
.editor { min-height: calc(100dvh - 88px - env(safe-area-inset-top) - env(safe-area-inset-bottom)); }
}
.seg.kind button, .seg.modes button { min-height: 32px; }
.seg.modes button { font-size: 0.86rem; padding: 0 6px; }
.lbl { font-size: 0.85rem; color: var(--muted); }
.cat-name { color: var(--text); font-weight: 600; }
.field { display: flex; flex-direction: column; gap: 6px; }
.amount-card { display: flex; flex-direction: column; gap: 8px; padding: 8px 12px; }
.amount-row { display: flex; align-items: center; gap: 12px; }
.amount-row .amount-input { flex: 1; min-width: 0; text-align: right; font-size: 2.2rem; min-height: 50px; padding: 0; }
.cur-pill {
position: relative; flex-shrink: 0; display: inline-flex; align-items: center; gap: 4px;
height: 40px; padding: 0 10px 0 14px; border-radius: 999px; background: var(--surface-2); font-weight: 700;
}
.cur-pill:focus-within { outline: 2px solid var(--accent); outline-offset: 1px; }
.cur-pill :global(select) { position: absolute; inset: 0; opacity: 0; min-height: 0; height: 100%; cursor: pointer; }
.rate { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; }
.rate input { width: 110px; min-height: 34px; padding: 4px 10px; }
.cats { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 8px; }
@media (min-width: 600px) { .cats { grid-template-columns: repeat(12, minmax(0, 1fr)); } }
.cat {
aspect-ratio: 1; max-height: 56px; display: grid; place-items: center; padding: 0;
border: 2px solid transparent; border-radius: 16px; font-size: 1.35rem; cursor: pointer;
background: color-mix(in srgb, var(--cat) 14%, var(--surface));
transition: background-color 0.12s, border-color 0.12s, transform 0.12s;
}
.cat span { filter: saturate(0.85); }
.cat[aria-pressed='true'] { border-color: var(--cat); background: color-mix(in srgb, var(--cat) 34%, var(--surface)); transform: scale(1.04); }
.cat[aria-pressed='true'] span { filter: none; }
.cat:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; }
.lbl-row { display: flex; align-items: center; gap: 4px; }
.lbl-row .lbl { flex: 1; }
.link { border: 0; background: none; color: var(--accent); font: inherit; font-size: 0.85rem; font-weight: 600; padding: 0 8px; cursor: pointer; }
.member { gap: 10px; padding: 6px 12px; min-height: 46px; }
.member.off .who, .member.off .share { opacity: 0.45; }
.who { display: flex; align-items: center; gap: 10px; min-width: 0; cursor: pointer; }
.name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.share { flex-shrink: 0; }
.value-wrap { gap: 4px; flex-shrink: 0; }
.value { width: 104px; min-height: 36px; padding: 4px 10px; text-align: right; }
.value.narrow { width: 64px; }
.value::placeholder { color: var(--muted); opacity: 0.6; }
.adds-up { gap: 4px; }
.extras { display: flex; flex-wrap: wrap; gap: 8px; }
.extras .btn { flex: 1 1 auto; gap: 6px; padding: 0 12px; }
.photo { display: flex; flex-direction: column; gap: 8px; }
.photo .photo-thumb { max-height: 160px; }
.save-bar {
position: sticky; bottom: 0; margin-top: auto; display: flex; flex-direction: column; gap: 8px;
padding: 10px 0 calc(2px + env(safe-area-inset-bottom));
background: linear-gradient(to bottom, transparent, var(--bg) 14px);
}
.save-bar .btn { width: 100%; }
.save-bar p { margin: 0; }
</style>

View file

@ -1,11 +1,10 @@
<script lang="ts"> <script lang="ts">
import { inBase } from '@oweme/core'; import { inBase } from '@oweme/core';
import { addDays, CATEGORY_COLORS, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts'; import { addDays, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
import { router } from '../lib/router.svelte.ts'; import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts'; import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts'; import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte'; import Icon from './Icon.svelte';
import Money from './Money.svelte';
let { session }: { session: GroupSession } = $props(); let { session }: { session: GroupSession } = $props();
let query = $state(''); let query = $state('');
@ -25,6 +24,12 @@
return groups; 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) { function dayLabel(d: string) {
if (d === today()) return t('today'); if (d === today()) return t('today');
if (d === addDays(today(), -1)) return t('yesterday'); if (d === addDays(today(), -1)) return t('yesterday');
@ -48,6 +53,13 @@
</script> </script>
<div class="stack"> <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} {#if Object.keys(session.state.expenses).length > 6}
<input type="search" bind:value={query} placeholder={t('search')} aria-label={t('search')} /> <input type="search" bind:value={query} placeholder={t('search')} aria-label={t('search')} />
{/if} {/if}
@ -58,36 +70,30 @@
{#each rows as day (day.date)} {#each rows as day (day.date)}
<section class="stack" style:gap="6px"> <section class="stack" style:gap="6px">
<h3 class="day">{dayLabel(day.date)}</h3> <h3>{dayLabel(day.date)}</h3>
<div class="list"> <div class="list">
{#each day.items as r (r.expense.id)} {#each day.items as r (r.expense.id)}
{@const e = r.expense} {@const e = r.expense}
{@const m = mine(e)} {@const m = mine(e)}
<a class="item" href="/g/{session.id}/e/{encodeURIComponent(e.id)}" onclick={(ev) => open(ev, e.id)}> <a class="item" href="/g/{session.id}/e/{encodeURIComponent(e.id)}" onclick={(ev) => open(ev, e.id)}>
<span class="cat-icon" style:--cat={CATEGORY_COLORS[e.category]} aria-hidden="true">{CATEGORY_ICONS[e.category] ?? '🧾'}</span> <span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category] ?? '🧾'}</span>
<!-- Two lines, each splitting its width: title | amount, then payer | your part. <span class="grow">
Keeps the title readable on narrow phones. --> <span class="title row" style:gap="6px">
<span class="grow lines">
<span class="line">
<span class="title grow">
<span class="ellipsis">
{#if e.kind === 'transfer'} {#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) })} {t('transfer_line', { from: session.memberName(e.payers[0]?.member), to: session.memberName(e.split.entries.find((x) => x.value > 0)?.member) })}
{:else} {:else}
{e.title} {e.title}
{/if} {/if}
</span>
{#if e.recurringId}<Icon name="repeat" size={14} />{/if} {#if e.recurringId}<Icon name="repeat" size={14} />{/if}
{#if e.photo}<Icon name="camera" size={14} />{/if} {#if e.photo}<Icon name="camera" size={14} />{/if}
</span> </span>
<span class="amt"><Money minor={e.amount} currency={e.currency} /></span> <span class="sub" style:display="block">
</span>
<span class="line">
<span class="sub grow">
{e.payers.length === 1 ? t('paid_by', { name: session.memberName(e.payers[0].member) }) : t('paid_by_many', { n: e.payers.length })} {e.payers.length === 1 ? t('paid_by', { name: session.memberName(e.payers[0].member) }) : t('paid_by_many', { n: e.payers.length })}
</span> </span>
{#if m}<span class="small num mine {m.cls}">{m.text}</span>{/if}
</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> </span>
</a> </a>
{/each} {/each}
@ -95,13 +101,3 @@
</section> </section>
{/each} {/each}
</div> </div>
<style>
.lines { display: flex; flex-direction: column; gap: 2px; }
.line { display: flex; align-items: baseline; gap: 10px; min-width: 0; }
.title { display: flex; align-items: center; gap: 6px; min-width: 0; }
.title :global(svg) { color: var(--muted); }
.ellipsis { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.amt { flex-shrink: 0; font-weight: 650; }
.mine { flex-shrink: 0; white-space: nowrap; } /* your part matters more than who paid */
</style>

View file

@ -1,215 +0,0 @@
<script lang="ts">
// Touch gestures on the group page (shortcuts; every action also has a button):
// - Pull up past the end of the page: a pill rises from behind the tab bar;
// letting go once it reads "Release to add" opens the add-expense sheet.
// Bottom rather than top, so the browser's pull-to-refresh keeps working.
// - Swipe sideways: previous / next tab. Touches near the screen edges are
// left to the OS back/forward gestures.
import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
const {
enabled,
addEnabled,
tabs,
current,
onadd,
ontab,
}: {
/** Gestures at all (off while a sheet or the identity picker is open). */
enabled: boolean;
/** Pull-up-to-add on this tab. */
addEnabled: boolean;
tabs: readonly string[];
current: string;
onadd: () => void;
ontab: (key: string, dir: 1 | -1) => void;
} = $props();
/** How far the pill must rise (after resistance) before a release adds. */
const THRESHOLD = 72;
const MAX = 110;
/** Finger movement before we decide which gesture this is. */
const SLOP = 10;
/** Touches starting this close to the left/right edge belong to the OS. */
const EDGE = 24;
let pull = $state(0);
let bottom = $state(0);
let releasing = $state(false);
const armed = $derived(pull >= THRESHOLD);
const atBottom = () => window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2;
/** True if the touch starts inside something that scrolls sideways itself. */
function inHorizontalScroller(el: Element | null): boolean {
for (; el && el !== document.body; el = el.parentElement) {
const ox = getComputedStyle(el).overflowX;
if ((ox === 'auto' || ox === 'scroll') && el.scrollWidth > el.clientWidth) return true;
}
return false;
}
$effect(() => {
if (!enabled) return;
// Read props through closures so the listeners always see current values
// without being re-attached on every tab change.
const add = () => addEnabled;
const tabList = () => tabs;
const cur = () => current;
type Track = { x: number; y: number; t: number; mode: 'undecided' | 'add' | 'swipe'; canAdd: boolean; canSwipe: boolean };
let tr: Track | null = null;
let wasArmed = false;
const page = () => document.querySelector<HTMLElement>('.layout');
function neighbour(dir: 1 | -1): string | undefined {
const list = tabList();
return list[list.indexOf(cur()) + dir];
}
function resetPull() {
releasing = true;
pull = 0;
wasArmed = false;
}
function resetSwipe(el: HTMLElement | null) {
if (!el) return;
el.style.transition = 'transform 0.2s ease';
el.style.transform = '';
el.addEventListener('transitionend', () => (el.style.transition = ''), { once: true });
}
const onStart = (e: TouchEvent) => {
tr = null;
if (e.touches.length !== 1) return;
const target = e.target as Element | null;
if (target?.closest('input, textarea, select, dialog')) return;
const tch = e.touches[0];
const nearEdge = tch.clientX < EDGE || tch.clientX > window.innerWidth - EDGE;
tr = {
x: tch.clientX, y: tch.clientY, t: e.timeStamp, mode: 'undecided',
canAdd: add() && atBottom(),
canSwipe: !nearEdge && !inHorizontalScroller(target),
};
if (tr.canAdd) {
const bar = document.querySelector('.tabbar')?.getBoundingClientRect();
// The tab bar floats at the bottom on phones; the pill hides behind it.
bottom = bar && getComputedStyle(document.querySelector('.tabbar')!).position === 'fixed'
? window.innerHeight - bar.top + 8 : 16;
}
};
const onMove = (e: TouchEvent) => {
if (!tr) return;
const tch = e.touches[0];
const dx = tch.clientX - tr.x;
const dy = tch.clientY - tr.y;
if (tr.mode === 'undecided') {
if (Math.abs(dx) < SLOP && Math.abs(dy) < SLOP) return;
if (tr.canSwipe && Math.abs(dx) > Math.abs(dy) * 1.2) tr.mode = 'swipe';
else if (tr.canAdd && dy < 0 && Math.abs(dy) > Math.abs(dx) && atBottom()) {
tr.mode = 'add';
releasing = false;
} else {
tr = null; // ordinary scrolling
return;
}
}
if (e.cancelable) e.preventDefault();
if (tr.mode === 'add') {
pull = Math.min(MAX, Math.max(0, -dy - SLOP) * 0.55);
const nowArmed = pull >= THRESHOLD;
if (nowArmed && !wasArmed) navigator.vibrate?.(10);
wasArmed = nowArmed;
} else {
const el = page();
if (!el) return;
// Rubber-band at the first and last tab.
const free = neighbour(dx < 0 ? 1 : -1) !== undefined;
const shift = free ? dx * 0.6 : dx * 0.15;
el.style.transition = '';
el.style.transform = `translateX(${shift}px)`;
}
};
const onEnd = (e: TouchEvent) => {
if (!tr) return;
const t0 = tr;
tr = null;
if (t0.mode === 'add') {
const go = pull >= THRESHOLD;
resetPull();
if (go) onadd();
} else if (t0.mode === 'swipe') {
const tch = e.changedTouches[0];
const dx = tch.clientX - t0.x;
const speed = Math.abs(dx) / Math.max(1, e.timeStamp - t0.t);
const dir: 1 | -1 = dx < 0 ? 1 : -1;
const next = neighbour(dir);
const el = page();
if (next && (Math.abs(dx) > window.innerWidth * 0.25 || (Math.abs(dx) > 40 && speed > 0.4))) {
if (el) { el.style.transition = ''; el.style.transform = ''; }
ontab(next, dir);
} else {
resetSwipe(el);
}
}
};
const onCancel = () => {
if (tr?.mode === 'add') resetPull();
if (tr?.mode === 'swipe') resetSwipe(page());
tr = null;
};
window.addEventListener('touchstart', onStart, { passive: true });
window.addEventListener('touchmove', onMove, { passive: false });
window.addEventListener('touchend', onEnd);
window.addEventListener('touchcancel', onCancel);
return () => {
window.removeEventListener('touchstart', onStart);
window.removeEventListener('touchmove', onMove);
window.removeEventListener('touchend', onEnd);
window.removeEventListener('touchcancel', onCancel);
const el = page();
if (el) el.style.transform = '';
pull = 0;
};
});
</script>
<div
class="pull"
class:armed
class:releasing
aria-hidden="true"
style:bottom="{bottom}px"
style:transform="translate(-50%, {48 - pull}px)"
style:opacity={Math.min(1, pull / 32)}
>
<span class="c"><Icon name={armed ? 'plus' : 'up'} size={18} /></span>
{armed ? t('release_to_add') : t('pull_to_add')}
</div>
<style>
.pull {
position: fixed; left: 50%; z-index: 19; pointer-events: none;
display: flex; align-items: center; gap: 8px;
padding: 6px 14px 6px 6px; border-radius: 999px;
background: var(--surface); border: 1px solid var(--line); box-shadow: var(--shadow);
color: var(--muted); font-size: 0.88rem; font-weight: 600; white-space: nowrap;
opacity: 0;
}
.c {
display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%;
background: var(--surface-2); color: var(--text);
}
.armed { color: var(--text); }
.armed .c { background: var(--accent); color: var(--accent-ink); }
.releasing { transition: transform 0.2s ease, opacity 0.2s ease; }
@media (prefers-reduced-motion: reduce) {
.releasing { transition: none; }
}
</style>

View file

@ -1,74 +0,0 @@
<script lang="ts">
// Top of the group page: your balance as the headline number, the group's
// total, and round quick actions. Reports whether the actions are on
// screen so the page can show the floating Add button only when they aren't.
import { inBase } from '@oweme/core';
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';
import Money from './Money.svelte';
let { session, onactionsvisible }: { session: GroupSession; onactionsvisible: (visible: boolean) => void } = $props();
const base = $derived(`/g/${session.id}`);
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),
);
const mine = $derived(session.me ? (session.balances[session.me] ?? 0) : null);
function go(e: MouseEvent, path: string, replace = false) {
e.preventDefault();
router.go(path, { replace });
}
let actions: HTMLElement;
$effect(() => {
const io = new IntersectionObserver(([entry]) => onactionsvisible(entry.isIntersecting));
io.observe(actions);
return () => io.disconnect();
});
</script>
<section class="hero" aria-label={t('summary')}>
{#if mine === null}
<div class="lbl">{t('total_spent')}</div>
<div class="big"><Money minor={total} currency={session.base} /></div>
{:else}
<div class="lbl">{mine > 0 ? t('hero_owed') : mine < 0 ? t('hero_owe') : t('hero_settled')}</div>
<div class="big {mine > 0 ? 'pos' : mine < 0 ? 'neg' : ''}"><Money minor={Math.abs(mine)} currency={session.base} /></div>
<div class="meta"><span class="dot" aria-hidden="true"></span>{t('total_spent')} <Money minor={total} currency={session.base} /></div>
{/if}
</section>
<nav class="actions" bind:this={actions} aria-label={t('quick_actions')}>
<a class="act primary" href="{base}/e/new" onclick={(e) => go(e, `${base}/e/new`)} aria-label={t('add_expense')}><span class="c"><Icon name="plus" /></span>{t('add')}</a>
<a class="act" href="{base}/e/new?kind=transfer" onclick={(e) => go(e, `${base}/e/new?kind=transfer`)} aria-label={t('add_payment')}><span class="c"><Icon name="swap" /></span>{t('payment_short')}</a>
<a class="act" href="{base}/balances" onclick={(e) => go(e, `${base}/balances`, true)}><span class="c"><Icon name="scale" /></span>{t('settle_up')}</a>
<a class="act" href="{base}/settings" onclick={(e) => go(e, `${base}/settings`)}><span class="c"><Icon name="share" /></span>{t('share_short')}</a>
</nav>
<style>
.hero { text-align: center; padding: 8px 0 0; }
.lbl { color: var(--muted); font-size: 0.92rem; font-weight: 500; }
.big { font-size: 2.75rem; font-weight: 750; letter-spacing: -0.03em; line-height: 1.15; margin: 2px 0; overflow-wrap: anywhere; }
.big :global(.cur), .big :global(.frac) { font-size: 0.55em; letter-spacing: -0.01em; }
.meta {
display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; padding: 6px 12px; border-radius: 999px;
background: var(--surface); color: var(--muted); font-size: 0.84rem; font-weight: 500;
}
.meta :global(.money), .meta :global(.money .cur), .meta :global(.money .frac) { color: var(--text); font-size: 1em; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
.actions { display: flex; justify-content: center; gap: 8px; padding: 14px 0 4px; }
.act {
flex: 0 1 84px; display: flex; flex-direction: column; align-items: center; gap: 7px; text-align: center;
font-size: 0.8rem; font-weight: 600; color: var(--text); text-decoration: none; line-height: 1.2;
}
.act .c { width: 52px; height: 52px; border-radius: 50%; background: var(--surface-2); display: grid; place-items: center; }
.act.primary .c { background: var(--accent); color: var(--accent-ink); }
.act:hover .c { filter: brightness(1.12); }
.act:focus-visible { outline: none; }
.act:focus-visible .c { outline: 2px solid var(--accent); outline-offset: 2px; }
</style>

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, tick, untrack } from 'svelte'; import { onDestroy, untrack } from 'svelte';
import { forgetGroup } from '../lib/idb.ts'; import { forgetGroup } from '../lib/idb.ts';
import { router } from '../lib/router.svelte.ts'; import { router } from '../lib/router.svelte.ts';
import { closeSession, openSession, type GroupSession } from '../lib/session.svelte.ts'; import { closeSession, openSession, type GroupSession } from '../lib/session.svelte.ts';
@ -9,11 +9,9 @@
import ExpenseDetail from './ExpenseDetail.svelte'; import ExpenseDetail from './ExpenseDetail.svelte';
import ExpenseEditor from './ExpenseEditor.svelte'; import ExpenseEditor from './ExpenseEditor.svelte';
import ExpenseList from './ExpenseList.svelte'; import ExpenseList from './ExpenseList.svelte';
import GroupHeader from './GroupHeader.svelte';
import GroupSettings from './GroupSettings.svelte'; import GroupSettings from './GroupSettings.svelte';
import Icon from './Icon.svelte'; import Icon from './Icon.svelte';
import IdentityPicker from './IdentityPicker.svelte'; import IdentityPicker from './IdentityPicker.svelte';
import GroupGestures from './GroupGestures.svelte';
import Stats from './Stats.svelte'; import Stats from './Stats.svelte';
// Keyed by group id in App.svelte, so reading it once is enough. // Keyed by group id in App.svelte, so reading it once is enough.
@ -21,16 +19,12 @@
const id = untrack(() => props.id); const id = untrack(() => props.id);
let session = $state<GroupSession | null | undefined>(undefined); let session = $state<GroupSession | null | undefined>(undefined);
let skippedIdentity = $state(false); let skippedIdentity = $state(false);
// The floating Add button only appears once the header's actions scroll away.
// Starts true so the button doesn't flash before the observer reports.
let actionsVisible = $state(true);
openSession(id).then((s) => (session = s)); openSession(id).then((s) => (session = s));
onDestroy(() => closeSession(id)); onDestroy(() => closeSession(id));
const route = $derived(router.route); const route = $derived(router.route);
const tab = $derived(route.name === 'group' ? route.tab : 'expenses'); const tab = $derived(route.name === 'group' ? route.tab : 'expenses');
const withHeader = $derived(tab === 'expenses' || tab === 'balances');
const base = `/g/${id}`; const base = `/g/${id}`;
const tabs = [ const tabs = [
{ key: 'expenses', path: base, icon: 'list', label: 'expenses' }, { key: 'expenses', path: base, icon: 'list', label: 'expenses' },
@ -48,18 +42,6 @@
!!session && session.status !== 'loading' && session.state.members.length > 0 && !session.me && !skippedIdentity, !!session && session.status !== 'loading' && session.state.members.length > 0 && !session.me && !skippedIdentity,
); );
/** Tab change from a swipe: the new tab slides in from the side it came from. */
async function switchTab(key: string, dir: 1 | -1) {
const path = tabs.find((x) => x.key === key)!.path;
router.go(path, { replace: true });
await tick();
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
document.querySelector('.layout')?.animate(
[{ transform: `translateX(${dir * 48}px)`, opacity: 0.4 }, { transform: 'none', opacity: 1 }],
{ duration: 180, easing: 'ease-out' },
);
}
async function remove() { async function remove() {
await forgetGroup(id); await forgetGroup(id);
router.go('/', { replace: true }); router.go('/', { replace: true });
@ -80,8 +62,7 @@
{@const s = session} {@const s = session}
<header class="topbar"> <header class="topbar">
<button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button> <button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button>
{#if s.state.group?.icon}<span class="group-icon" aria-hidden="true">{s.state.group.icon}</span>{/if} <h1><span aria-hidden="true">{s.state.group?.icon}</span> {s.state.group?.name ?? s.local.name}</h1>
<h1>{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> <a class="icon-btn" href="{base}/settings" onclick={(e) => nav(e, `${base}/settings`)} aria-label={t('group_settings')}><Icon name="settings" /></a>
</header> </header>
@ -99,10 +80,6 @@
{/if} {/if}
{#if s.rollback}<p class="banner warn">{t('rollback_warning')}</p>{/if} {#if s.rollback}<p class="banner warn">{t('rollback_warning')}</p>{/if}
{#if withHeader && s.status !== 'gone'}
<GroupHeader session={s} onactionsvisible={(v) => (actionsVisible = v)} />
{/if}
<nav class="tabbar" aria-label={s.state.group?.name}> <nav class="tabbar" aria-label={s.state.group?.name}>
{#each tabs as tb} {#each tabs as tb}
<a href={tb.path} aria-current={tab === tb.key ? 'page' : undefined} onclick={(e) => nav(e, tb.path, true)}> <a href={tb.path} aria-current={tab === tb.key ? 'page' : undefined} onclick={(e) => nav(e, tb.path, true)}>
@ -130,19 +107,10 @@
</div> </div>
</main> </main>
{#if s.status !== 'gone' && withHeader && !actionsVisible} {#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> <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}
<GroupGestures
enabled={route.name === 'group' && s.status !== 'gone' && !needsIdentity}
addEnabled={withHeader}
tabs={tabs.map((x) => x.key)}
current={tab}
onadd={() => router.go(`${base}/e/new`)}
ontab={switchTab}
/>
{#if route.name === 'expense'} {#if route.name === 'expense'}
<ExpenseDetail session={s} eid={route.eid} /> <ExpenseDetail session={s} eid={route.eid} />
{:else if route.name === 'expense-edit'} {:else if route.name === 'expense-edit'}
@ -155,15 +123,7 @@
{/if} {/if}
<style> <style>
/* A tab being swiped sideways must not widen the page. */ .layout { display: grid; gap: 24px; }
main { overflow-x: clip; }
.group-icon {
display: grid; place-items: center; flex-shrink: 0; width: 36px; height: 36px; border-radius: 50%;
background: var(--surface-2); font-size: 1.1rem;
}
/* minmax(0, …): without it a long title or name (nowrap + ellipsis) widens
the column past the screen and phones zoom out. */
.layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; }
.side-col { display: none; } .side-col { display: none; }
@media (min-width: 960px) { @media (min-width: 960px) {
.layout.with-side { grid-template-columns: minmax(0, 1fr) 340px; } .layout.with-side { grid-template-columns: minmax(0, 1fr) 340px; }

View file

@ -1,12 +1,11 @@
<script lang="ts"> <script lang="ts">
import { untrack } from 'svelte'; import { untrack } from 'svelte';
import { balancesCsv, CATEGORIES, expensesCsv, nextOccurrence } from '@oweme/core'; import { balancesCsv, expensesCsv, nextOccurrence } from '@oweme/core';
import { renderSVG } from 'uqr'; import { renderSVG } from 'uqr';
import { api } from '../lib/api.ts'; import { api } from '../lib/api.ts';
import { makeBackup } from '../lib/backup.ts'; import { makeBackup } from '../lib/backup.ts';
import { randomId } from '../lib/crypto.ts'; import { randomId } from '../lib/crypto.ts';
import { CATEGORY_ICONS, download, fmtDate, MEMBER_COLORS, money, slug, today } from '../lib/format.ts'; import { download, fmtDate, MEMBER_COLORS, money, slug, today } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts';
import { forgetGroup } from '../lib/idb.ts'; import { forgetGroup } from '../lib/idb.ts';
import { disablePush, enablePush, pushSupport, type PushSupport } from '../lib/push.ts'; import { disablePush, enablePush, pushSupport, type PushSupport } from '../lib/push.ts';
import { router } from '../lib/router.svelte.ts'; import { router } from '../lib/router.svelte.ts';
@ -28,19 +27,14 @@
let name = $state(s.state.group?.name ?? ''); let name = $state(s.state.group?.name ?? '');
let icon = $state(s.state.group?.icon ?? ''); let icon = $state(s.state.group?.icon ?? '');
let baseCurrency = $state(s.base); let baseCurrency = $state(s.base);
let defaultCategory = $state<string>(s.state.group?.defaultCategory ?? 'other');
let newMember = $state(''); let newMember = $state('');
let deleteConfirm = $state(''); let deleteConfirm = $state('');
let deleteOpen = $state(false);
let push = $state<PushSupport | null>(null); let push = $state<PushSupport | null>(null);
let pushBusy = $state(false); let pushBusy = $state(false);
pushSupport().then((p) => (push = p)); pushSupport().then((p) => (push = p));
const locked = $derived(Object.keys(s.state.expenses).length > 0); const locked = $derived(Object.keys(s.state.expenses).length > 0);
const dirty = $derived( const dirty = $derived(name.trim() !== s.state.group?.name || icon !== s.state.group?.icon || baseCurrency !== s.base);
name.trim() !== s.state.group?.name || icon !== s.state.group?.icon || baseCurrency !== s.base ||
defaultCategory !== (s.state.group?.defaultCategory ?? 'other'),
);
async function copy() { async function copy() {
await navigator.clipboard.writeText(link); await navigator.clipboard.writeText(link);
@ -56,11 +50,10 @@
async function saveGroup(e: SubmitEvent) { async function saveGroup(e: SubmitEvent) {
e.preventDefault(); e.preventDefault();
if (!name.trim()) return; if (!name.trim()) return;
const data: { name?: string; icon?: string; baseCurrency?: string; defaultCategory?: (typeof CATEGORIES)[number] } = {}; const data: { name?: string; icon?: string; baseCurrency?: string } = {};
if (name.trim() !== s.state.group?.name) data.name = name.trim(); if (name.trim() !== s.state.group?.name) data.name = name.trim();
if (icon !== s.state.group?.icon) data.icon = icon; if (icon !== s.state.group?.icon) data.icon = icon;
if (!locked && baseCurrency !== s.base) data.baseCurrency = baseCurrency; if (!locked && baseCurrency !== s.base) data.baseCurrency = baseCurrency;
if (defaultCategory !== (s.state.group?.defaultCategory ?? 'other')) data.defaultCategory = defaultCategory as (typeof CATEGORIES)[number];
await s.emit({ type: 'group.updated', data }); await s.emit({ type: 'group.updated', data });
ui.show(t('saved')); ui.show(t('saved'));
} }
@ -124,12 +117,10 @@
<div class="card stack"> <div class="card stack">
{#if justCreated}<p class="banner warn">{t('save_link_warning')}</p>{/if} {#if justCreated}<p class="banner warn">{t('save_link_warning')}</p>{/if}
<p class="small muted">{t('share_intro')}</p> <p class="small muted">{t('share_intro')}</p>
<div class="row"> <div class="row wrap">
<button class="btn primary grow" onclick={copy}><Icon name="copy" size={18} /> {t('copy_link')}</button> <button class="btn primary" onclick={copy}><Icon name="copy" size={18} /> {t('copy_link')}</button>
{#if 'share' in navigator} {#if 'share' in navigator}<button class="btn" onclick={nativeShare}><Icon name="share" size={18} /> {t('share')}</button>{/if}
<button class="btn square" onclick={nativeShare} aria-label={t('share')} title={t('share')}><Icon name="share" size={18} /></button> <button class="btn ghost" onclick={() => (showQr = !showQr)}>QR</button>
{/if}
<button class="btn square" aria-pressed={showQr} aria-label={t('qr_code')} title={t('qr_code')} onclick={() => (showQr = !showQr)}>QR</button>
</div> </div>
{#if showQr} {#if showQr}
<div class="qr">{@html qr}</div> <div class="qr">{@html qr}</div>
@ -139,82 +130,83 @@
<!-- group --> <!-- group -->
<section class="section"> <section class="section">
<h3>{t('group')}</h3> <h3>{t('group_settings')}</h3>
<form class="card stack" onsubmit={saveGroup}> <form class="card stack" onsubmit={saveGroup}>
<div class="row"> <div class="row">
<label class="field" style:width="72px">{t('icon')}<input bind:value={icon} maxlength="8" /></label> <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> <label class="field" style:flex="1">{t('group_name')}<input bind:value={name} maxlength="100" required /></label>
</div> </div>
<div class="pair">
<label class="field"> <label class="field">
{t('base_currency')} {t('base_currency')}
<CurrencySelect bind:value={baseCurrency} disabled={locked} /> <CurrencySelect bind:value={baseCurrency} disabled={locked} />
<span class="small">{locked ? t('base_currency_locked') : t('base_currency_hint')}</span>
</label> </label>
<label class="field"> <button class="btn primary" type="submit" disabled={!dirty || !name.trim()}>{t('save')}</button>
{t('default_category')}
<select bind:value={defaultCategory}>
{#each CATEGORIES as c}<option value={c}>{CATEGORY_ICONS[c]} {t(`cat_${c}` as MsgKey)}</option>{/each}
</select>
</label>
</div>
{#if locked}<p class="small muted">{t('base_currency_locked')}</p>{/if}
{#if dirty}<button class="btn primary" type="submit" disabled={!name.trim()}>{t('save')}</button>{/if}
</form> </form>
</section> </section>
<!-- members, with "you are" on top --> <!-- identity -->
<section class="section"> <section class="section">
<h3>{t('members')}</h3> <h3>{t('identity')}</h3>
<div class="list"> <select value={s.me ?? ''} onchange={(e) => s.setMe((e.target as HTMLSelectElement).value || null)} aria-label={t('identity')}>
<div class="item">
<span class="grow">{t('identity')}</span>
<select class="me" value={s.me ?? ''} onchange={(e) => s.setMe((e.target as HTMLSelectElement).value || null)} aria-label={t('identity')}>
<option value="">{t('not_set')}</option> <option value="">{t('not_set')}</option>
{#each s.state.members.filter((m) => !m.archived) as m}<option value={m.id}>{m.name}</option>{/each} {#each s.state.members.filter((m) => !m.archived) as m}<option value={m.id}>{m.name}</option>{/each}
</select> </select>
</div> </section>
<!-- members -->
<section class="section">
<h3>{t('members')}</h3>
<div class="list">
{#each s.state.members as m, i (m.id)} {#each s.state.members as m, i (m.id)}
{@const bal = s.balances[m.id] ?? 0} {@const bal = s.balances[m.id] ?? 0}
<div class="item" class:archived={m.archived}> <div class="item">
<Avatar member={m} index={i} size={32} /> <Avatar member={m} index={i} size={32} />
<span class="grow"> <span class="grow">
<span class="title" style:display="block">{m.name}{m.id === s.me ? ` (${t('you')})` : ''}{m.archived ? ` · ${t('archived')}` : ''}</span> <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 class="sub num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : ''}">{bal === 0 ? t('settled') : money(bal, s.base, { sign: true })}</span>
</span> </span>
<button class="icon-btn" onclick={() => rename(m.id, m.name)} aria-label="{t('rename')}: {m.name}" title={t('rename')}><Icon name="edit" size={18} /></button> <button class="btn small ghost" onclick={() => rename(m.id, m.name)}>{t('rename')}</button>
{#if m.archived} {#if m.archived}
<button class="icon-btn" onclick={() => s.emit({ type: 'member.restored', data: { id: m.id } })} aria-label="{t('unarchive')}: {m.name}" title={t('unarchive')}><Icon name="undo" size={18} /></button> <button class="btn small ghost" onclick={() => s.emit({ type: 'member.restored', data: { id: m.id } })}>{t('unarchive')}</button>
{:else} {:else}
<button class="icon-btn" disabled={bal !== 0} aria-label="{t('archive')}: {m.name}" title={bal !== 0 ? t('archive_needs_zero') : t('archive')} <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 } })}><Icon name="archive" size={18} /></button> onclick={() => s.emit({ type: 'member.archived', data: { id: m.id } })}>{t('archive')}</button>
{/if} {/if}
</div> </div>
{/each} {/each}
<form class="item" onsubmit={addMember}> </div>
<input class="bare" bind:value={newMember} placeholder={t('member_name')} maxlength="60" aria-label={t('member_name')} /> <form class="row" onsubmit={addMember}>
<button class="btn small" type="submit" disabled={!newMember.trim()}><Icon name="plus" size={16} /> {t('add_member')}</button> <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> </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> </div>
</section> </section>
{#if push === 'ok' || s.local.push} <!-- recurring -->
<section class="section">
<h3>{t('notifications')}</h3>
<label class="list item">
<span class="grow">{t('notifications_hint')}</span>
<input class="switch" type="checkbox" checked={s.local.push} disabled={pushBusy} onchange={togglePush} />
</label>
</section>
{:else if push === 'needs-install' || push === 'denied'}
<section class="section">
<h3>{t('notifications')}</h3>
<p class="small muted">{push === 'denied' ? t('notifications_denied') : t('notifications_ios')}</p>
</section>
{/if}
{#if Object.keys(s.state.recurring).length}
<section class="section"> <section class="section">
<h3>{t('recurring')}</h3> <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"> <div class="list">
{#each Object.values(s.state.recurring) as r (r.id)} {#each Object.values(s.state.recurring) as r (r.id)}
{@const next = nextOccurrence(r.rule, today())} {@const next = nextOccurrence(r.rule, today())}
@ -228,16 +220,16 @@
</div> </div>
{/each} {/each}
</div> </div>
</section>
{/if} {/if}
</section>
<!-- export --> <!-- export -->
<section class="section"> <section class="section">
<h3>{t('export')}</h3> <h3>{t('export')}</h3>
<div class="row wrap exports"> <div class="row wrap">
<button class="btn small" onclick={() => download(`${fileBase()}-expenses.csv`, '' + expensesCsv(s.state), 'text/csv')}>{t('export_expenses')}</button> <button class="btn" onclick={() => download(`${fileBase()}-expenses.csv`, '' + expensesCsv(s.state), 'text/csv')}>{t('export_expenses')}</button>
<button class="btn small" onclick={() => download(`${fileBase()}-balances.csv`, '' + balancesCsv(s.state), 'text/csv')}>{t('export_balances')}</button> <button class="btn" onclick={() => download(`${fileBase()}-balances.csv`, '' + balancesCsv(s.state), 'text/csv')}>{t('export_balances')}</button>
<button class="btn small" onclick={backup}>{t('backup')}</button> <button class="btn" onclick={backup}>{t('backup')}</button>
</div> </div>
<p class="small muted">{t('backup_hint')}</p> <p class="small muted">{t('backup_hint')}</p>
</section> </section>
@ -245,63 +237,21 @@
<!-- danger --> <!-- danger -->
<section class="section"> <section class="section">
<h3>{t('danger_zone')}</h3> <h3>{t('danger_zone')}</h3>
<div class="list"> <div class="card stack">
<button class="item" onclick={removeFromDevice}> <p class="small muted">{t('remove_from_device_hint')}</p>
<Icon name="close" size={18} /> <button class="btn" onclick={removeFromDevice}>{t('remove_from_device')}</button>
<span class="grow"> </div>
<span class="title" style:display="block">{t('remove_from_device')}</span> <div class="card stack">
<span class="sub">{t('remove_from_device_hint')}</span> <p class="small muted">{t('delete_group_hint')}</p>
</span> <input bind:value={deleteConfirm} placeholder={s.state.group?.name} aria-label={t('group_name')} />
</button>
<button class="item danger" aria-expanded={deleteOpen} onclick={() => (deleteOpen = !deleteOpen)}>
<Icon name="trash" size={18} />
<span class="grow">
<span class="title" style:display="block">{t('delete_group')}</span>
<span class="sub">{t('delete_group_hint')}</span>
</span>
</button>
{#if deleteOpen}
<div class="confirm stack">
<label class="field">
{t('type_name_to_confirm')}
<input bind:value={deleteConfirm} placeholder={s.state.group?.name} />
</label>
<button class="btn danger" disabled={deleteConfirm.trim() !== s.state.group?.name} onclick={deleteGroup}> <button class="btn danger" disabled={deleteConfirm.trim() !== s.state.group?.name} onclick={deleteGroup}>
<Icon name="trash" size={18} /> {t('delete_group')} <Icon name="trash" size={18} /> {t('delete_group')}
</button> </button>
</div> </div>
{/if}
</div>
</section> </section>
</main> </main>
<style> <style>
.qr { width: min(240px, 100%); margin: 0 auto; background: #fff; border-radius: 12px; padding: 8px; } .qr { width: min(260px, 100%); margin: 0 auto; background: #fff; border-radius: 12px; padding: 8px; }
.qr :global(svg) { width: 100%; height: auto; display: block; } .qr :global(svg) { width: 100%; height: auto; display: block; }
.grow { flex: 1; }
.btn.square { width: 48px; padding: 0; flex-shrink: 0; font-weight: 700; }
.btn.square[aria-pressed='true'] { background: var(--surface-2); }
.pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; }
.item select.me { width: auto; max-width: 55%; min-height: 36px; padding: 4px 10px; }
.item .icon-btn { width: 36px; height: 36px; color: var(--muted); }
.item .icon-btn:disabled { opacity: 0.35; }
.item.archived .title { color: var(--muted); }
.item input.bare { border: 0; background: none; padding: 0; min-height: 36px; min-width: 0; flex: 1; }
.item.danger, .item.danger .sub { color: var(--danger); }
.item .sub { white-space: normal; }
.exports .btn { flex: 1 1 auto; }
.confirm { padding: 12px 14px 14px; }
.switch {
appearance: none; -webkit-appearance: none; flex-shrink: 0; cursor: pointer;
width: 46px; height: 28px; min-height: 0; padding: 0; border-radius: 999px; position: relative;
background: var(--surface-2); border: 1px solid var(--line); transition: background 0.15s;
}
.switch::after {
content: ''; position: absolute; top: 2px; left: 2px; width: 22px; height: 22px; border-radius: 50%;
background: var(--text); transition: transform 0.15s;
}
.switch:checked { background: var(--accent); border-color: transparent; }
.switch:checked::after { transform: translateX(18px); background: var(--accent-ink); }
.switch:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { .switch, .switch::after { transition: none; } }
</style> </style>

View file

@ -2,7 +2,6 @@
// Inline SVG icons (no icon font: keeps the CSP strict and works offline). // Inline SVG icons (no icon font: keeps the CSP strict and works offline).
const paths = { const paths = {
plus: 'M12 5v14M5 12h14', plus: 'M12 5v14M5 12h14',
swap: 'M7 7h11l-3-3M17 17H6l3 3',
back: 'M15 18l-6-6 6-6', back: 'M15 18l-6-6 6-6',
close: 'M18 6L6 18M6 6l12 12', 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', 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',
@ -20,10 +19,6 @@
undo: 'M3 7v6h6M21 17a9 9 0 0 0-15-6.7L3 13', 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', 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', upload: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12',
down: 'M6 9l6 6 6-6',
up: 'M6 15l6-6 6 6',
check: 'M20 6L9 17l-5-5',
archive: 'M3 4h18v5H3zM5 9v11h14V9M10 13h4',
} as const; } as const;
let { name, size = 22 }: { name: keyof typeof paths; size?: number } = $props(); let { name, size = 22 }: { name: keyof typeof paths; size?: number } = $props();

View file

@ -1,10 +0,0 @@
<script lang="ts">
// An amount with the whole number emphasised and the currency and
// decimals de-emphasised. Reads the same as money() to screen readers.
import { money, moneyParts } from '../lib/format.ts';
let { minor, currency, sign = false }: { minor: number; currency: string; sign?: boolean } = $props();
const p = $derived(moneyParts(minor, currency, { sign }));
</script>
<span class="money num"><span class="sr-only">{money(minor, currency, { sign })}</span><span aria-hidden="true"><span class="cur">{p.before}</span>{p.whole}<span class="frac">{p.frac}</span><span class="cur">{p.after}</span></span></span>

View file

@ -10,17 +10,12 @@
$effect(() => { $effect(() => {
dialog.showModal(); dialog.showModal();
// showModal() focuses the first control (the close button), which shows a
// focus ring even after a tap. Focus the dialog itself instead, unless a
// field asked for focus with autofocus. Tab still reaches every control.
if (!dialog.querySelector('[autofocus]')) dialog.focus();
return () => dialog.close(); return () => dialog.close();
}); });
</script> </script>
<dialog <dialog
class="sheet" class="sheet"
tabindex="-1"
bind:this={dialog} bind:this={dialog}
aria-label={title} aria-label={title}
oncancel={(e) => { e.preventDefault(); onclose(); }} oncancel={(e) => { e.preventDefault(); onclose(); }}

View file

@ -31,7 +31,7 @@
</script> </script>
<div class="stack"> <div class="stack">
<div class="seg compact" role="group" aria-label={t('stats')}> <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]} {#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> <button aria-pressed={range === r} onclick={() => (range = r)}>{t(label)}</button>
{/each} {/each}
@ -118,20 +118,19 @@
</div> </div>
<style> <style>
.seg.compact :global(button) { font-size: 0.84rem; padding: 0 6px; }
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; } .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }
.hero { font-size: 1.6rem; font-weight: 700; } .hero { font-size: 1.6rem; font-weight: 700; }
.s1 { background: var(--chart-1); } .s1 { background: var(--chart-1); }
.s2 { background: var(--chart-2); } .s2 { background: var(--chart-2); }
.bars { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; } .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%) minmax(0, 1fr) auto; align-items: center; 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; } .label { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.track { display: block; height: 12px; } .track { display: block; height: 12px; }
.hbar { display: block; height: 100%; min-width: 2px; border-radius: 0 4px 4px 0; } .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; } .value { font-size: 0.85rem; color: var(--text); text-align: right; }
.grouped li { grid-template-columns: minmax(70px, 28%) 1fr; } .grouped li { grid-template-columns: minmax(70px, 28%) 1fr; }
.pair { display: flex; flex-direction: column; gap: 2px; } .pair { display: flex; flex-direction: column; gap: 2px; }
.line { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; } .line { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: center; }
.legend { gap: 16px; } .legend { gap: 16px; }
.swatch { width: 12px; height: 12px; border-radius: 3px; display: inline-block; } .swatch { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
.months { display: flex; align-items: stretch; gap: 2px; height: 160px; } .months { display: flex; align-items: stretch; gap: 2px; height: 160px; }

View file

@ -62,7 +62,7 @@ export const api = {
pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) => pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) =>
req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }), req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }),
pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }), pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }),
rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string>; sources?: Record<string, string> }>('GET', `/api/rates?date=${date}`), rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string> }>('GET', `/api/rates?date=${date}`),
}; };
/** /**

View file

@ -3,7 +3,8 @@ import { settings } from './settings.svelte.ts';
const cache = new Map<string, Intl.NumberFormat>(); const cache = new Map<string, Intl.NumberFormat>();
function formatter(currency: string, opts: { sign?: boolean }): Intl.NumberFormat { /** Format minor units as money in the current locale ("1 234,50 Kč"). */
export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string {
const key = `${settings.locale}|${currency}|${opts.sign ? 1 : 0}`; const key = `${settings.locale}|${currency}|${opts.sign ? 1 : 0}`;
let f = cache.get(key); let f = cache.get(key);
if (!f) { if (!f) {
@ -18,30 +19,7 @@ function formatter(currency: string, opts: { sign?: boolean }): Intl.NumberForma
} }
cache.set(key, f); cache.set(key, f);
} }
return f; return f.format(minor / 10 ** exponent(currency));
}
/** Format minor units as money in the current locale ("1 234,50 Kč"). */
export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string {
return formatter(currency, opts).format(minor / 10 ** exponent(currency));
}
/**
* The same text as money(), split so the whole number can be emphasised:
* `before` (sign, currency), `whole` ("1 234"), `frac` (",50"), `after` (" Kč").
*/
export function moneyParts(minor: number, currency: string, opts: { sign?: boolean } = {}) {
const out = { before: '', whole: '', frac: '', after: '' };
let seenNumber = false;
for (const p of formatter(currency, opts).formatToParts(minor / 10 ** exponent(currency))) {
if (p.type === 'integer' || p.type === 'group') {
out.whole += p.value;
seenNumber = true;
} else if (p.type === 'decimal' || p.type === 'fraction') out.frac += p.value;
else if (seenNumber) out.after += p.value;
else out.before += p.value;
}
return out;
} }
/** Editable amount text for an input, in the user's decimal style. */ /** Editable amount text for an input, in the user's decimal style. */
@ -85,13 +63,6 @@ export function currencyName(code: string): string {
} }
} }
/** A hue per category, used to tint its round icon background. */
export const CATEGORY_COLORS: Record<string, string> = {
food: '#ff8f6b', groceries: '#3ddc97', transport: '#ffc85a', accommodation: '#7aa7ff', entertainment: '#e879a6',
shopping: '#c084fc', utilities: '#facc15', rent: '#4fd1c5', travel: '#60a5fa', gifts: '#f472b6', health: '#f87171',
other: '#9ca3af', transfer: '#3ddc97',
};
export const CATEGORY_ICONS: Record<string, string> = { export const CATEGORY_ICONS: Record<string, string> = {
food: '🍽️', groceries: '🛒', transport: '🚕', accommodation: '🏨', entertainment: '🎟️', food: '🍽️', groceries: '🛒', transport: '🚕', accommodation: '🏨', entertainment: '🎟️',
shopping: '🛍️', utilities: '💡', rent: '🏠', travel: '✈️', gifts: '🎁', health: '💊', shopping: '🛍️', utilities: '💡', rent: '🏠', travel: '✈️', gifts: '🎁', health: '💊',

View file

@ -26,7 +26,6 @@ const cs: Messages = {
theme: 'Vzhled', theme: 'Vzhled',
theme_system: 'Podle systému', theme_system: 'Podle systému',
theme_dark: 'Tmavý', theme_dark: 'Tmavý',
theme_black: 'Černý',
theme_light: 'Světlý', theme_light: 'Světlý',
create_group: 'Vytvořit skupinu', create_group: 'Vytvořit skupinu',
@ -43,7 +42,7 @@ const cs: Messages = {
creating: 'Vytvářím…', creating: 'Vytvářím…',
share_group: 'Sdílet skupinu', share_group: 'Sdílet skupinu',
share_intro: 'Kdo má odkaz, může skupinu vidět i upravovat.', share_intro: 'Kdokoli s tímto odkazem může skupinu vidět i upravovat. Posílejte ho jen členům.',
save_link_warning: 'Uložte si tento odkaz na bezpečné místo. Pokud se ztratí všechny kopie, skupinu nepůjde obnovit.', save_link_warning: 'Uložte si tento odkaz na bezpečné místo. Pokud se ztratí všechny kopie, skupinu nepůjde obnovit.',
copy_link: 'Kopírovat odkaz', copy_link: 'Kopírovat odkaz',
copied: 'Zkopírováno', copied: 'Zkopírováno',
@ -62,21 +61,10 @@ const cs: Messages = {
stats: 'Statistiky', stats: 'Statistiky',
activity: 'Aktivita', activity: 'Aktivita',
add_expense: 'Přidat výdaj', add_expense: 'Přidat výdaj',
pull_to_add: 'Táhněte nahoru pro nový výdaj',
release_to_add: 'Pusťte a přidejte',
no_expenses: 'Zatím žádné výdaje. Klepněte na + a přidejte první.', no_expenses: 'Zatím žádné výdaje. Klepněte na + a přidejte první.',
total_spent: 'Celkem utraceno', total_spent: 'Celkem utraceno',
summary: 'Přehled',
hero_owed: 'Dluží vám',
hero_owe: 'Dlužíte',
hero_settled: 'Máte vyrovnáno',
quick_actions: 'Rychlé akce',
add: 'Přidat',
share_short: 'Sdílet',
payment_short: 'Platba',
add_payment: 'Zaznamenat platbu',
paid_by: 'Platil(a) {name}', paid_by: 'Platil(a) {name}',
paid_by_many: { one: '{n} plátce', few: '{n} plátci', other: '{n} plátců' }, paid_by_many: 'Platilo {n} lidí',
your_share: 'váš podíl {amount}', your_share: 'váš podíl {amount}',
you_lent: 'půjčili jste {amount}', you_lent: 'půjčili jste {amount}',
you_borrowed: 'dlužíte {amount}', you_borrowed: 'dlužíte {amount}',
@ -108,18 +96,14 @@ const cs: Messages = {
title: 'Za co?', title: 'Za co?',
title_ph: 'Večeře', title_ph: 'Večeře',
category: 'Kategorie', category: 'Kategorie',
default_category: 'Výchozí kategorie',
date: 'Datum', date: 'Datum',
currency: 'Měna', currency: 'Měna',
rate: 'Směnný kurz', rate: 'Směnný kurz',
rate_source_ecb: 'Kurz ECB ze dne {date}', rate_source_ecb: 'Kurz ECB ze dne {date}',
rate_source_manual: 'Zadáno ručně', rate_source_manual: 'Zadáno ručně',
rate_source_xr: 'Kurz od Exchange Rate API ze dne {date}',
currencies_rated: 'Denní kurz',
currencies_manual: 'Kurz zadáte ručně',
rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.', rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.',
paid_by_label: 'Platil(a)', paid_by_label: 'Platil(a)',
multiple_payers: 'Více lidí', multiple_payers: 'Platilo více lidí',
from_label: 'Od', from_label: 'Od',
to_label: 'Komu', to_label: 'Komu',
split: 'Rozdělení', split: 'Rozdělení',
@ -129,11 +113,11 @@ const cs: Messages = {
split_percent: 'Procenta', split_percent: 'Procenta',
remaining: 'Zbývá: {amount}', remaining: 'Zbývá: {amount}',
over_by: 'Přebývá: {amount}', over_by: 'Přebývá: {amount}',
adds_up: 'Součet sedí',
select_all: 'Všichni', select_all: 'Všichni',
select_none: 'Nikdo', select_none: 'Nikdo',
note: 'Poznámka', note: 'Poznámka',
photo: 'Fotka', photo: 'Fotka',
add_photo: 'Přidat fotku',
replace_photo: 'Vyměnit', replace_photo: 'Vyměnit',
remove_photo: 'Odebrat', remove_photo: 'Odebrat',
processing_photo: 'Zpracovávám fotku…', processing_photo: 'Zpracovávám fotku…',
@ -191,10 +175,10 @@ const cs: Messages = {
changed_fields: 'Změněno: {fields}', changed_fields: 'Změněno: {fields}',
no_activity: 'Zatím žádná aktivita.', no_activity: 'Zatím žádná aktivita.',
range_all: 'Vše', range_all: 'Celé období',
range_month: 'Tento měsíc', range_month: 'Tento měsíc',
range_30: '30 dní', range_30: 'Posledních 30 dní',
range_year: 'Letos', range_year: 'Tento rok',
by_category: 'Podle kategorie', by_category: 'Podle kategorie',
by_month: 'Podle měsíce', by_month: 'Podle měsíce',
per_member: 'Zaplaceno vs. podíl', per_member: 'Zaplaceno vs. podíl',
@ -214,7 +198,7 @@ const cs: Messages = {
not_set: 'Nenastaveno', not_set: 'Nenastaveno',
change: 'Změnit', change: 'Změnit',
notifications: 'Oznámení', notifications: 'Oznámení',
notifications_hint: 'Upozornit mě, když skupinu změní ostatní', notifications_hint: 'Dostanete oznámení, když skupinu změní někdo jiný.',
notifications_ios: 'Na iPhonu a iPadu nejdřív přidejte OweMe na plochu (Sdílet → Přidat na plochu).', notifications_ios: 'Na iPhonu a iPadu nejdřív přidejte OweMe na plochu (Sdílet → Přidat na plochu).',
notifications_denied: 'Oznámení jsou pro tento web zablokovaná v nastavení prohlížeče.', notifications_denied: 'Oznámení jsou pro tento web zablokovaná v nastavení prohlížeče.',
notifications_unavailable: 'Oznámení nejsou na tomto serveru nebo v tomto prohlížeči k dispozici.', notifications_unavailable: 'Oznámení nejsou na tomto serveru nebo v tomto prohlížeči k dispozici.',
@ -226,14 +210,11 @@ const cs: Messages = {
export_expenses: 'Výdaje (CSV)', export_expenses: 'Výdaje (CSV)',
export_balances: 'Zůstatky (CSV)', export_balances: 'Zůstatky (CSV)',
backup: 'Soubor se zálohou', backup: 'Soubor se zálohou',
backup_hint: 'Záloha obsahuje klíč skupiny. Uložte ji bezpečně.', backup_hint: 'Obsahuje klíč skupiny: kdokoli se souborem skupinu otevře. Uložte ho bezpečně.',
danger_zone: 'Nebezpečná zóna', danger_zone: 'Nebezpečná zóna',
remove_from_device_hint: 'Zůstane na serveru i v ostatních zařízeních.', remove_from_device_hint: 'Skupina zůstane na serveru i v ostatních zařízeních.',
delete_group: 'Smazat skupinu pro všechny', delete_group: 'Smazat skupinu pro všechny',
delete_group_hint: 'Všem smaže všechny výdaje a fotky.', delete_group_hint: 'Smaže ze serveru všechny výdaje a fotky. Pro potvrzení napište název skupiny.',
type_name_to_confirm: 'Pro potvrzení napište název skupiny',
qr_code: 'QR kód',
group: 'Skupina',
confirm: 'Potvrdit', confirm: 'Potvrdit',
saved: 'Uloženo', saved: 'Uloženo',

View file

@ -28,7 +28,6 @@ const en = {
theme: 'Theme', theme: 'Theme',
theme_system: 'System', theme_system: 'System',
theme_dark: 'Dark', theme_dark: 'Dark',
theme_black: 'Black',
theme_light: 'Light', theme_light: 'Light',
// new group // new group
@ -47,7 +46,7 @@ const en = {
// share // share
share_group: 'Share group', share_group: 'Share group',
share_intro: 'Anyone with the link can view and edit this group.', share_intro: 'Anyone with this link can see and edit the group. Send it only to group members.',
save_link_warning: 'Save this link somewhere safe. If every copy is lost, the group can’t be recovered.', save_link_warning: 'Save this link somewhere safe. If every copy is lost, the group can’t be recovered.',
copy_link: 'Copy link', copy_link: 'Copy link',
copied: 'Copied', copied: 'Copied',
@ -68,21 +67,10 @@ const en = {
stats: 'Stats', stats: 'Stats',
activity: 'Activity', activity: 'Activity',
add_expense: 'Add expense', add_expense: 'Add expense',
pull_to_add: 'Pull up to add expense',
release_to_add: 'Release to add',
no_expenses: 'No expenses yet. Tap + to add the first one.', no_expenses: 'No expenses yet. Tap + to add the first one.',
total_spent: 'Total spent', total_spent: 'Total spent',
summary: 'Summary',
hero_owed: 'You’re owed',
hero_owe: 'You owe',
hero_settled: 'You’re settled up',
quick_actions: 'Quick actions',
add: 'Add',
share_short: 'Share',
payment_short: 'Payment',
add_payment: 'Record a payment',
paid_by: 'Paid by {name}', paid_by: 'Paid by {name}',
paid_by_many: { one: '{n} payer', few: '{n} payers', other: '{n} payers' }, paid_by_many: 'Paid by {n} people',
your_share: 'your share {amount}', your_share: 'your share {amount}',
you_lent: 'you lent {amount}', you_lent: 'you lent {amount}',
you_borrowed: 'you borrowed {amount}', you_borrowed: 'you borrowed {amount}',
@ -116,18 +104,14 @@ const en = {
title: 'What was it for?', title: 'What was it for?',
title_ph: 'Dinner', title_ph: 'Dinner',
category: 'Category', category: 'Category',
default_category: 'Default category',
date: 'Date', date: 'Date',
currency: 'Currency', currency: 'Currency',
rate: 'Exchange rate', rate: 'Exchange rate',
rate_source_ecb: 'ECB rate from {date}', rate_source_ecb: 'ECB rate from {date}',
rate_source_manual: 'Entered manually', rate_source_manual: 'Entered manually',
rate_source_xr: 'Rates By Exchange Rate API, {date}',
currencies_rated: 'Daily rate',
currencies_manual: 'Enter rate manually',
rate_unavailable: 'No rate available for this currency, please enter it.', rate_unavailable: 'No rate available for this currency, please enter it.',
paid_by_label: 'Paid by', paid_by_label: 'Paid by',
multiple_payers: 'Several people', multiple_payers: 'Several people paid',
from_label: 'From', from_label: 'From',
to_label: 'To', to_label: 'To',
split: 'Split', split: 'Split',
@ -137,11 +121,11 @@ const en = {
split_percent: 'Percent', split_percent: 'Percent',
remaining: 'Remaining: {amount}', remaining: 'Remaining: {amount}',
over_by: 'Over by: {amount}', over_by: 'Over by: {amount}',
adds_up: 'Adds up to the total',
select_all: 'All', select_all: 'All',
select_none: 'None', select_none: 'None',
note: 'Note', note: 'Note',
photo: 'Photo', photo: 'Photo',
add_photo: 'Add photo',
replace_photo: 'Replace', replace_photo: 'Replace',
remove_photo: 'Remove', remove_photo: 'Remove',
processing_photo: 'Processing photo…', processing_photo: 'Processing photo…',
@ -202,9 +186,9 @@ const en = {
no_activity: 'No activity yet.', no_activity: 'No activity yet.',
// stats // stats
range_all: 'All', range_all: 'All time',
range_month: 'This month', range_month: 'This month',
range_30: '30 days', range_30: 'Last 30 days',
range_year: 'This year', range_year: 'This year',
by_category: 'By category', by_category: 'By category',
by_month: 'By month', by_month: 'By month',
@ -226,7 +210,7 @@ const en = {
not_set: 'Not set', not_set: 'Not set',
change: 'Change', change: 'Change',
notifications: 'Notifications', notifications: 'Notifications',
notifications_hint: 'Notify me when others change the group', notifications_hint: 'Get a notification when someone else changes this group.',
notifications_ios: 'On iPhone and iPad, add OweMe to your home screen first (Share → Add to Home Screen).', notifications_ios: 'On iPhone and iPad, add OweMe to your home screen first (Share → Add to Home Screen).',
notifications_denied: 'Notifications are blocked for this site in your browser settings.', notifications_denied: 'Notifications are blocked for this site in your browser settings.',
notifications_unavailable: 'Notifications aren’t available on this server or in this browser.', notifications_unavailable: 'Notifications aren’t available on this server or in this browser.',
@ -238,14 +222,11 @@ const en = {
export_expenses: 'Expenses (CSV)', export_expenses: 'Expenses (CSV)',
export_balances: 'Balances (CSV)', export_balances: 'Balances (CSV)',
backup: 'Backup file', backup: 'Backup file',
backup_hint: 'The backup file contains the group key. Store it safely.', backup_hint: 'Contains the group key: anyone with the file can open the group. Store it safely.',
danger_zone: 'Danger zone', danger_zone: 'Danger zone',
remove_from_device_hint: 'Stays on the server and other devices.', remove_from_device_hint: 'The group stays on the server and on other devices.',
delete_group: 'Delete group for everyone', delete_group: 'Delete group for everyone',
delete_group_hint: 'Removes all expenses and photos for everyone.', delete_group_hint: 'Deletes all expenses and photos from the server. Type the group name to confirm.',
type_name_to_confirm: 'Type the group name to confirm',
qr_code: 'QR code',
group: 'Group',
confirm: 'Confirm', confirm: 'Confirm',
saved: 'Saved', saved: 'Saved',

View file

@ -1,7 +1,6 @@
// Exchange rates from our own server (EUR-based: ECB daily, plus a // Exchange rates from our own server (ECB daily, EUR-based). Cached in
// supplementary source for currencies the ECB doesn't publish). Cached in
// IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2). // IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2).
import { ACTIVE_CURRENCIES, isActiveCurrency, rateToString } from '@oweme/core'; import { rateToString } from '@oweme/core';
import { api } from './api.ts'; import { api } from './api.ts';
import { kvGet, kvSet } from './idb.ts'; import { kvGet, kvSet } from './idb.ts';
import { today } from './format.ts'; import { today } from './format.ts';
@ -9,8 +8,6 @@ import { today } from './format.ts';
export interface RatesDay { export interface RatesDay {
date: string; date: string;
rates: Record<string, string>; rates: Record<string, string>;
/** "<source>:<date>" for rates not from the ECB (absent in older caches) */
sources?: Record<string, string>;
} }
const memory = new Map<string, Promise<RatesDay | null>>(); const memory = new Map<string, Promise<RatesDay | null>>();
@ -26,7 +23,7 @@ export function ratesOn(date: string): Promise<RatesDay | null> {
if (cached && date < today()) return cached; if (cached && date < today()) return cached;
try { try {
const r = await api.rates(date); const r = await api.rates(date);
const day: RatesDay = { date: r.date, rates: r.rates, sources: r.sources ?? {} }; const day = { date: r.date, rates: r.rates };
await kvSet(key, day); await kvSet(key, day);
await kvSet('rates:latest', day); await kvSet('rates:latest', day);
return day; return day;
@ -47,9 +44,7 @@ export async function suggestRate(from: string, to: string, date: string): Promi
const f = Number(day?.rates[from]); const f = Number(day?.rates[from]);
const tt = Number(day?.rates[to]); const tt = Number(day?.rates[to]);
if (!day || !(f > 0) || !(tt > 0)) return null; if (!day || !(f > 0) || !(tt > 0)) return null;
// A cross rate is only as good as its weaker leg, so name that leg's source. return { rate: rateToString(tt / f), source: `ecb:${day.date}` };
const source = day.sources?.[from] ?? day.sources?.[to] ?? `ecb:${day.date}`;
return { rate: rateToString(tt / f), source };
} }
/** Float conversion for display only (never stored). */ /** Float conversion for display only (never stored). */
@ -61,9 +56,13 @@ export async function displayRate(from: string, to: string): Promise<number | nu
return f > 0 && tt > 0 ? tt / f : null; return f > 0 && tt > 0 ? tt / f : null;
} }
/** Active currencies with a known rate first, then the rest (manual rate). */ /** Currencies with ECB rates first, then every other ISO currency. */
export async function currencyList(): Promise<{ rated: string[]; other: string[] }> { export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> {
const day = await ratesOn(today()); const day = await ratesOn(today());
const rated = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).filter(isActiveCurrency).sort(); const ecb = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).sort();
return { rated, other: ACTIVE_CURRENCIES.filter((c) => !rated.includes(c)) }; let all: string[] = [];
try {
all = Intl.supportedValuesOf('currency');
} catch { /* old browser */ }
return { ecb, other: all.filter((c) => !ecb.includes(c)) };
} }

View file

@ -4,10 +4,7 @@ import { detectLang, localeOf, translate, type Lang, type MsgKey } from './i18n.
import { kvSet } from './idb.ts'; import { kvSet } from './idb.ts';
type LangPref = 'auto' | Lang; type LangPref = 'auto' | Lang;
type ThemePref = 'system' | 'dark' | 'black' | 'light'; type ThemePref = 'system' | 'dark' | 'light';
/** Browser/OS chrome colour per theme; matches --bg in app.css. */
const THEME_COLOR = { dark: '#0a0b0d', black: '#000000', light: '#f2f3f5' } as const;
function load<T extends string>(key: string, allowed: readonly T[], def: T): T { function load<T extends string>(key: string, allowed: readonly T[], def: T): T {
try { try {
@ -25,7 +22,7 @@ function save(key: string, v: string) {
class Settings { class Settings {
langPref = $state<LangPref>(load('oweme.lang', ['auto', 'en', 'cs'], 'auto')); langPref = $state<LangPref>(load('oweme.lang', ['auto', 'en', 'cs'], 'auto'));
themePref = $state<ThemePref>(load('oweme.theme', ['system', 'dark', 'black', 'light'], 'system')); themePref = $state<ThemePref>(load('oweme.theme', ['system', 'dark', 'light'], 'system'));
lang = $derived<Lang>(this.langPref === 'auto' ? detectLang() : this.langPref); lang = $derived<Lang>(this.langPref === 'auto' ? detectLang() : this.langPref);
locale = $derived(localeOf(this.lang)); locale = $derived(localeOf(this.lang));
@ -48,10 +45,8 @@ class Settings {
const root = document.documentElement; const root = document.documentElement;
if (this.themePref === 'system') delete root.dataset.theme; if (this.themePref === 'system') delete root.dataset.theme;
else root.dataset.theme = this.themePref; else root.dataset.theme = this.themePref;
// "System" follows the OS between soft dark and light. const dark = this.themePref === 'dark' || (this.themePref === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
const effective = this.themePref !== 'system' ? this.themePref document.querySelector('meta[name=theme-color]')?.setAttribute('content', dark ? '#0B2E22' : '#F2F7F4');
: matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
document.querySelector('meta[name=theme-color]')?.setAttribute('content', THEME_COLOR[effective]);
} }
} }

View file

@ -1,80 +0,0 @@
# OweMe. Works as-is with zero configuration; every setting below can be
# overridden with an environment variable (in the panel's Environment tab,
# or in a .env file next to this file).
#
# With the panel: point the app's domain at service `app`, port $PORT
# (8080 unless you set PORT).
# The panel's Caddy provides HTTPS.
# Standalone (no panel): set DOMAIN and run
# podman compose --profile standalone up -d --build
# which adds a Caddy container with automatic HTTPS. See deploy/README.md.
name: oweme
services:
app:
build:
context: .
dockerfile: deploy/Containerfile
image: localhost/oweme:latest
restart: unless-stopped
environment:
# Max size of one uploaded (encrypted) photo, in bytes. Default 2 MB.
MAX_PHOTO_BYTES: ${MAX_PHOTO_BYTES:-2097152}
# Max size of one encrypted event, in bytes. Default 64 KB.
MAX_EVENT_BYTES: ${MAX_EVENT_BYTES:-65536}
# Storage cap per group (events + photos), in bytes. Default 200 MB.
MAX_GROUP_BYTES: ${MAX_GROUP_BYTES:-209715200}
# New groups per client IP per hour.
GROUP_CREATE_PER_HOUR: ${GROUP_CREATE_PER_HOUR:-10}
# Contact sent to push services, e.g. mailto:you@example.com.
# Empty = https://<the site's domain>.
VAPID_SUBJECT: ${VAPID_SUBJECT:-}
# Push keys. Empty = generated on first start and kept in the data
# volume (recommended). Set both only to pin specific keys.
VAPID_PUBLIC_KEY: ${VAPID_PUBLIC_KEY:-}
VAPID_PRIVATE_KEY: ${VAPID_PRIVATE_KEY:-}
# 1 = turn push notifications off.
PUSH_DISABLED: ${PUSH_DISABLED:-0}
# Port the app listens on inside the container. If you change it,
# point the panel's domain at the new port too.
PORT: ${PORT:-8080}
# Fixed for the container; no need to change these.
HOST: 0.0.0.0
DATA_DIR: /data
STATIC_DIR: /app/web
TRUST_PROXY: "1"
volumes:
- oweme-data:/data
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:${PORT:-8080}/api/health"]
interval: 30s
timeout: 5s
# No ports: the panel publishes $PORT for its routes; standalone, only
# Caddy reaches the app.
caddy:
profiles: [standalone]
image: docker.io/library/caddy:2.10.2-alpine
restart: unless-stopped
depends_on:
- app
environment:
# Public hostname for standalone HTTPS (needs a DNS record).
DOMAIN: ${DOMAIN:-localhost}
# Where Caddy finds the app (same as the app's PORT).
APP_PORT: ${PORT:-8080}
ports:
# Rootless Podman can't bind ports below 1024 by default; see
# deploy/README.md "Ports".
- "${BIND_ADDR:-0.0.0.0}:${HTTP_PORT:-80}:80"
- "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443"
- "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443/udp"
volumes:
- ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro,Z
- caddy-data:/data
- caddy-config:/config
volumes:
oweme-data:
caddy-data:
caddy-config:

23
deploy/.env.example Normal file
View file

@ -0,0 +1,23 @@
# Copy to deploy/.env and `chmod 600 deploy/.env`. Never commit .env.
# Required: public hostname, with a DNS A/AAAA record pointing at this server.
DOMAIN=oweme.example.com
# Web Push. Generate the keys with:
# podman run --rm --user root -v ./:/out:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env
# (or, with Node 24 installed: node apps/server/src/gen-vapid.ts deploy/.env)
# Leave empty to disable notifications.
VAPID_SUBJECT=mailto:you@example.com
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
# Limits (bytes). Defaults shown.
MAX_PHOTO_BYTES=2097152
MAX_EVENT_BYTES=65536
MAX_GROUP_BYTES=209715200
GROUP_CREATE_PER_HOUR=10
# Where Caddy listens. Defaults: all interfaces, ports 80/443.
#BIND_ADDR=0.0.0.0
#HTTP_PORT=80
#HTTPS_PORT=443

View file

@ -3,7 +3,7 @@
# Security headers (CSP etc.) are set by the app itself. # Security headers (CSP etc.) are set by the app itself.
{$DOMAIN} { {$DOMAIN} {
encode zstd gzip encode zstd gzip
reverse_proxy app:{$APP_PORT:8080} { reverse_proxy app:8080 {
# Server-Sent Events: don't buffer # Server-Sent Events: don't buffer
flush_interval -1 flush_interval -1
} }

View file

@ -25,6 +25,5 @@ COPY --from=build /src/apps/web/dist ./web
RUN mkdir -p /data && chown node:node /data RUN mkdir -p /data && chown node:node /data
USER node USER node
VOLUME /data VOLUME /data
# Default port; compose sets PORT (see compose.yaml).
EXPOSE 8080 EXPOSE 8080
CMD ["node", "--disable-warning=ExperimentalWarning", "server/main.ts"] CMD ["node", "--disable-warning=ExperimentalWarning", "server/main.ts"]

View file

@ -1,49 +1,60 @@
# Deploying OweMe # Deploying OweMe on a VPS
`compose.yaml` (repo root) runs the **app** container: the Node server plus Two containers via `podman compose`: **app** (the Node server plus the built
the built web client, listening on port 8080 (or `PORT`), with its data in the web client) and **caddy** (HTTPS and reverse proxy). Only Caddy publishes ports.
`oweme-data` volume. It needs **no configuration**: push keys are generated
on first start and kept in the volume. Every setting is an optional
environment variable, listed with its default in `compose.yaml`.
HTTPS comes either from the panel's Caddy or, standalone, from a Caddy ## Requirements
container enabled with the `standalone` profile.
## With the panel - Podman ≥ 4 with `podman compose` (podman-compose or docker-compose as the provider)
- A domain with an A/AAAA record pointing at the VPS
- Ports 80 and 443 (TCP, plus UDP 443 for HTTP/3) open in the firewall
1. **New app → Git repository**: this repo, branch `main`. The panel finds ## First deploy
`compose.yaml` in the repository root.
2. **Domain**: point it at service **`app`**, port **`8080`** (or the
`PORT` you set in the Environment tab). The panel
publishes the port on 127.0.0.1 and its Caddy serves HTTPS.
3. **Environment** (optional): any variable from `compose.yaml`, for example
`MAX_PHOTO_BYTES=5242880` or `VAPID_SUBJECT=mailto:you@example.com`.
Untick **Pass to every container**. `compose.yaml` already passes each
setting to the app, and the panel's per-container copy currently makes
podman-compose fail with `can't merge value of [KEY] …` for variables the
compose file also sets.
4. **Deploy.** Check `https://<domain>/api/health` → `{"ok":true}`.
Changing a variable takes effect on the next deploy. Volume backups in the
panel include the `oweme-data` volume (database, encrypted photos, push keys).
## Standalone (no panel)
Requirements: Podman ≥ 4 with podman-compose ≥ 1.1 (for profiles), a domain
with an A/AAAA record pointing at the server, and ports 80 and 443 (TCP, plus
UDP 443 for HTTP/3) open.
```sh ```sh
git clone <repo> oweme && cd oweme git clone <repo> oweme && cd oweme/deploy
cp .env.example .env && chmod 600 .env
$EDITOR .env # set DOMAIN cp .env.example .env
podman compose --profile standalone up -d --build chmod 600 .env
podman compose logs -f # Caddy gets the certificate on the first request $EDITOR .env # set DOMAIN and VAPID_SUBJECT (mailto:)
podman compose build # builds localhost/oweme:latest
# Web Push keys: written into .env, private key never printed.
podman run --rm --user root -v ./:/out:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env
podman compose up -d
podman compose logs -f # Caddy obtains the certificate on first request
``` ```
Updating: `git pull && podman compose --profile standalone up -d --build`. Open `https://$DOMAIN`. `curl https://$DOMAIN/api/health` should say `{"ok":true}`.
### Ports (rootless Podman) ## Updating
```sh
cd oweme && git pull
cd deploy && podman compose up -d --build
```
Data lives in the `oweme-data` volume and survives rebuilds.
## Configuration (`deploy/.env`)
| Variable | Required | Default | Purpose |
|---|---|---|---|
| `DOMAIN` | yes | — | Public hostname; Caddy's site address and certificate |
| `VAPID_SUBJECT` | for push | — | `mailto:` contact sent to push services |
| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | for push | — | Generated by `gen-vapid.ts`; empty = notifications off |
| `MAX_PHOTO_BYTES` | no | `2097152` | Max size of one uploaded (encrypted) photo |
| `MAX_EVENT_BYTES` | no | `65536` | Max size of one encrypted event |
| `MAX_GROUP_BYTES` | no | `209715200` | Storage cap per group (events + photos) |
| `GROUP_CREATE_PER_HOUR` | no | `10` | Group creations per client IP per hour |
| `BIND_ADDR` | no | `0.0.0.0` | Address Caddy's ports are published on |
| `HTTP_PORT` / `HTTPS_PORT` | no | `80` / `443` | Host ports for Caddy |
Rotating the VAPID keys (`gen-vapid.ts … --force`) silently invalidates every
push subscription; users have to toggle notifications off and on again.
## Ports (rootless Podman)
Rootless Podman can't bind ports below 1024 by default. Pick one: Rootless Podman can't bind ports below 1024 by default. Pick one:
@ -52,53 +63,30 @@ Rootless Podman can't bind ports below 1024 by default. Pick one:
echo 'net.ipv4.ip_unprivileged_port_start=80' | sudo tee /etc/sysctl.d/90-unprivileged-ports.conf echo 'net.ipv4.ip_unprivileged_port_start=80' | sudo tee /etc/sysctl.d/90-unprivileged-ports.conf
sudo sysctl --system sudo sysctl --system
``` ```
2. Or publish high ports (`HTTP_PORT=8080`, `HTTPS_PORT=8443` in `.env`) and 2. Or publish high ports (`HTTP_PORT=8080`, `HTTPS_PORT=8443`) and redirect
redirect 80→8080 / 443→8443 in your firewall. 80→8080 / 443→8443 in your firewall (e.g. nftables/UFW `nat` rules).
With rootless Podman, published ports go through `rootlessport` and are With rootless Podman, published ports go through `rootlessport` and are
subject to the host firewall. Rootful container networking can add its own subject to the host firewall. Rootful container networking can add its own
firewall rules around UFW, so don't rely on UFW alone if you run rootful. firewall rules around UFW, so don't rely on UFW alone if you run rootful.
## Settings
All optional. Set them in the panel's Environment tab, or in `.env` for a
standalone deploy.
| Variable | Default | Purpose |
|---|---|---|
| `MAX_PHOTO_BYTES` | `2097152` | Max size of one uploaded (encrypted) photo |
| `MAX_EVENT_BYTES` | `65536` | Max size of one encrypted event |
| `MAX_GROUP_BYTES` | `209715200` | Storage cap per group (events + photos) |
| `GROUP_CREATE_PER_HOUR` | `10` | Group creations per client IP per hour |
| `VAPID_SUBJECT` | `https://<site domain>` | Contact sent to push services |
| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | generated | Pin push keys (set both); otherwise kept in the volume as `vapid.json` |
| `PUSH_DISABLED` | `0` | `1` turns push notifications off |
| `PORT` | `8080` | Port the app listens on inside the container (the panel's domain must target it) |
| `DOMAIN` | `localhost` | Standalone only: Caddy's site address and certificate |
| `BIND_ADDR` | `0.0.0.0` | Standalone only: address Caddy's ports are published on |
| `HTTP_PORT` / `HTTPS_PORT` | `80` / `443` | Standalone only: host ports for Caddy |
Deleting `vapid.json` from the volume (or changing pinned keys) invalidates
every push subscription; people then turn notifications off and on again.
## Backups ## Backups
The `oweme-data` volume holds everything (SQLite database, encrypted photos, Back up the `oweme-data` volume (SQLite database + encrypted photos):
push keys). Its contents are end-to-end encrypted, so backups can be stored
anywhere. Standalone:
```sh ```sh
podman volume export oweme_oweme-data > oweme-data-$(date +%F).tar podman volume export oweme_oweme-data > oweme-data-$(date +%F).tar
``` ```
People can also download per-group backup files in the app. Everything in it is already end-to-end encrypted, so the backup can be stored
anywhere. Users can also download per-group backup files in the app.
## Testing a deployment ## Testing a deployment
From a machine with the repo and Node 24: From a machine with the repo and Node 24:
```sh ```sh
npm ci && E2E_BASE_URL=https://<domain> npx playwright test e2e/app.spec.ts npm ci && E2E_BASE_URL=https://$DOMAIN npx playwright test e2e/app.spec.ts
``` ```
This creates a throwaway group on that server. This creates a throwaway group on that server.

49
deploy/compose.yaml Normal file
View file

@ -0,0 +1,49 @@
# podman compose up -d --build (run from this directory; reads ./.env)
# See deploy/README.md for the full deploy steps.
name: oweme
services:
app:
build:
context: ..
dockerfile: deploy/Containerfile
image: localhost/oweme:latest
restart: unless-stopped
env_file: .env
environment:
# fixed inside the container; everything else comes from .env
HOST: 0.0.0.0
PORT: "8080"
DATA_DIR: /data
STATIC_DIR: /app/web
TRUST_PROXY: "1"
volumes:
- oweme-data:/data
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/api/health"]
interval: 30s
timeout: 5s
# no published ports: only Caddy can reach the app
caddy:
image: docker.io/library/caddy:2.10.2-alpine
restart: unless-stopped
depends_on:
- app
environment:
DOMAIN: ${DOMAIN:?set DOMAIN in deploy/.env}
ports:
# BIND_ADDR defaults to all interfaces (a public VPS). Rootless Podman
# can't bind ports below 1024 by default; see README "Ports".
- "${BIND_ADDR:-0.0.0.0}:${HTTP_PORT:-80}:80"
- "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443"
- "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro,Z
- caddy-data:/data
- caddy-config:/config
volumes:
oweme-data:
caddy-data:
caddy-config:

View file

@ -99,7 +99,7 @@ test('two devices share a group end to end', async ({ browser }) => {
const fmt = (minor: number) => (minor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 }); const fmt = (minor: number) => (minor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 });
const shown = `${annaBal > 0 ? '+' : '−'}CZK ${fmt(Math.abs(annaBal))}`; const shown = `${annaBal > 0 ? '+' : '−'}CZK ${fmt(Math.abs(annaBal))}`;
await expect(anna.getByText(shown).first()).toBeVisible(); await expect(anna.getByText(shown).first()).toBeVisible();
await expect(anna.getByRole('heading', { name: 'Settle up' })).toBeVisible(); await expect(anna.getByText('Settle up')).toBeVisible();
const recordButtons = anna.getByRole('button', { name: 'Record payment' }); const recordButtons = anna.getByRole('button', { name: 'Record payment' });
const transfers = await recordButtons.count(); const transfers = await recordButtons.count();
expect(transfers).toBeGreaterThan(0); expect(transfers).toBeGreaterThan(0);
@ -143,40 +143,3 @@ test('two devices share a group end to end', async ({ browser }) => {
await expect(anna.getByRole('heading', { name: 'By category' })).toBeVisible(); await expect(anna.getByRole('heading', { name: 'By category' })).toBeVisible();
await expect(anna.getByRole('heading', { name: 'Paid vs. share' })).toBeVisible(); await expect(anna.getByRole('heading', { name: 'Paid vs. share' })).toBeVisible();
}); });
test('several people pay for one expense', async ({ browser }) => {
const p = await device(browser, 'en-US');
await p.goto('/');
await p.getByRole('link', { name: 'New group' }).click();
await p.getByLabel('Group name').fill('Shared car');
await p.getByLabel('Main currency').selectOption('CZK');
await p.getByLabel('Your name').fill('Anna');
await p.getByPlaceholder('Name').fill('Petr');
await p.getByRole('button', { name: 'Add member' }).click();
await p.getByPlaceholder('Name').nth(1).fill('Jana');
await p.getByRole('button', { name: 'Create group' }).click();
await p.getByRole('button', { name: 'Back', exact: true }).click();
await p.getByRole('link', { name: 'Add expense' }).click();
await p.getByLabel('Amount').fill('300000');
await p.getByLabel('What was it for?').fill('Car');
await p.getByLabel('Paid by', { exact: true }).selectOption({ label: 'Several people' });
await p.getByLabel('Paid by: Anna').fill('100000');
await p.getByLabel('Paid by: Petr').fill('150000');
await expect(p.getByText('Remaining: CZK 50,000.00')).toBeVisible();
// The empty box suggests what's left.
await expect(p.getByLabel('Paid by: Jana')).toHaveAttribute('placeholder', '50000.00');
await p.getByLabel('Paid by: Jana').fill('80000');
await expect(p.getByText('Over by: CZK 30,000.00')).toBeVisible();
await p.getByRole('button', { name: 'Save', exact: true }).click();
await expect(p.getByRole('alert')).toHaveText('The payers don’t add up to the amount.');
await p.getByLabel('Paid by: Jana').fill('50000');
await expect(p.getByText('Adds up to the total')).toBeVisible();
await p.getByRole('button', { name: 'Save', exact: true }).click();
await expect(p.getByRole('link', { name: /Car/ })).toContainText('3 payers');
await p.getByRole('link', { name: 'Balances' }).click();
await expect(p.getByText('+CZK 50,000.00')).toBeVisible();
await expect(p.getByText('−CZK 50,000.00')).toBeVisible();
await expect(p.getByText('Jana → Petr')).toBeVisible();
});

View file

@ -1,32 +0,0 @@
// Currencies offered in the picker. Hardcoded rather than read from
// Intl.supportedValuesOf('currency'), which in browsers also returns
// historical codes (ATS, DEM, YUM, …) that nobody can spend any more.
/**
* ISO 4217 currencies in circulation today. Excludes fund codes (CLF, USN, …),
* precious metals and other non-cash units (XAU, XDR, XSU), and codes that
* have been replaced: ANG → XCG (2025), BGN → EUR (2026), CUC (2021),
* HRK → EUR (2023), SLL → SLE (2024), ZWL → ZWG (2024).
* Update this list when ISO 4217 changes.
*/
export const ACTIVE_CURRENCIES: readonly string[] = [
'AED', 'AFN', 'ALL', 'AMD', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT',
'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD',
'CDF', 'CHF', 'CLP', 'CNY', 'COP', 'CRC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP',
'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD',
'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR',
'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD',
'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK',
'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO',
'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR',
'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLE',
'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP',
'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VES', 'VND', 'VUV',
'WST', 'XAF', 'XCD', 'XCG', 'XOF', 'XPF', 'YER', 'ZAR', 'ZMW', 'ZWG',
];
const ACTIVE = new Set(ACTIVE_CURRENCIES);
export function isActiveCurrency(code: string): boolean {
return ACTIVE.has(code);
}

View file

@ -6,4 +6,3 @@ export * from './settle.ts';
export * from './recurring.ts'; export * from './recurring.ts';
export * from './stats.ts'; export * from './stats.ts';
export * from './csv.ts'; export * from './csv.ts';
export * from './currencies.ts';

View file

@ -4,9 +4,7 @@
// after its target event; nothing is ever erased from the log. See SPEC.md §6. // after its target event; nothing is ever erased from the log. See SPEC.md §6.
import { validateExpense } from './expense.ts'; import { validateExpense } from './expense.ts';
import { isCurrencyCode } from './money.ts'; import { isCurrencyCode } from './money.ts';
import { CATEGORIES, type Activity, type GroupEvent, type GroupState, type Recurring } from './types.ts'; import type { Activity, GroupEvent, GroupState, Recurring } from './types.ts';
const isCategory = (c: unknown): c is (typeof CATEGORIES)[number] => (CATEGORIES as readonly unknown[]).includes(c);
export function emptyState(): GroupState { export function emptyState(): GroupState {
return { group: null, members: [], expenses: {}, comments: {}, recurring: {} }; return { group: null, members: [], expenses: {}, comments: {}, recurring: {} };
@ -42,22 +40,18 @@ function apply(s: GroupState, ev: GroupEvent, snapshots: Map<string, GroupState>
const d = ev.data; const d = ev.data;
if (s.group || !str(d?.name, 100) || !isCurrencyCode(d.baseCurrency)) return ignore(); if (s.group || !str(d?.name, 100) || !isCurrencyCode(d.baseCurrency)) return ignore();
s.group = { name: d.name, baseCurrency: d.baseCurrency, icon: typeof d.icon === 'string' ? d.icon.slice(0, 16) : '' }; s.group = { name: d.name, baseCurrency: d.baseCurrency, icon: typeof d.icon === 'string' ? d.icon.slice(0, 16) : '' };
if (isCategory(d.defaultCategory)) s.group.defaultCategory = d.defaultCategory;
act.after = { ...s.group }; act.after = { ...s.group };
break; break;
} }
case 'group.updated': { case 'group.updated': {
if (!s.group) return ignore(); if (!s.group) return ignore();
const d = ev.data ?? {}; const d = ev.data ?? {};
// Validate before changing anything, so an invalid event has no effect.
if (d.defaultCategory !== undefined && !isCategory(d.defaultCategory)) return ignore();
act.before = { ...s.group }; act.before = { ...s.group };
if (d.name !== undefined) { if (d.name !== undefined) {
if (!str(d.name, 100)) return ignore(); if (!str(d.name, 100)) return ignore();
s.group.name = d.name; s.group.name = d.name;
} }
if (typeof d.icon === 'string') s.group.icon = d.icon.slice(0, 16); if (typeof d.icon === 'string') s.group.icon = d.icon.slice(0, 16);
if (d.defaultCategory !== undefined) s.group.defaultCategory = d.defaultCategory;
if (d.baseCurrency !== undefined && d.baseCurrency !== s.group.baseCurrency) { if (d.baseCurrency !== undefined && d.baseCurrency !== s.group.baseCurrency) {
// Locked once the group has any expense (SPEC §7.1). // Locked once the group has any expense (SPEC §7.1).
if (hasExpenses || !isCurrencyCode(d.baseCurrency)) return ignore(); if (hasExpenses || !isCurrencyCode(d.baseCurrency)) return ignore();

View file

@ -81,8 +81,6 @@ export interface GroupInfo {
name: string; name: string;
baseCurrency: string; baseCurrency: string;
icon: string; icon: string;
/** category new expenses start with; absent = 'other' */
defaultCategory?: (typeof CATEGORIES)[number];
} }
export type EventBody = export type EventBody =

View file

@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { ACTIVE_CURRENCIES, isActiveCurrency } from '../src/index.ts';
import { import {
allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence, allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence,
occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats, occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats,
@ -110,31 +109,6 @@ describe('replay', () => {
expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0); expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0);
}); });
it('credits each of several payers (three people buy a car together)', () => {
const car = expense({
amount: 30000000,
payers: [{ member: 'a', amount: 10000000 }, { member: 'b', amount: 15000000 }, { member: 'c', amount: 5000000 }],
});
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: car })]);
const bal = balances(state);
expect(bal).toEqual({ a: 0, b: 5000000, c: -5000000 });
expect(settleUp(bal, ['a', 'b', 'c'])).toEqual([{ from: 'c', to: 'b', amount: 5000000 }]);
});
it('credits several payers in a foreign currency, summing exactly to the base total', () => {
// €100.01 at 25.1 = 2510.251 Kč → 2510.25; payer and share vectors must each sum to it.
const e = expense({
currency: 'EUR', amount: 10001, rate: '25.1',
payers: [{ member: 'a', amount: 5001 }, { member: 'b', amount: 5000 }],
});
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: e })]);
const bal = balances(state);
expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0);
expect(bal.a).toBeGreaterThan(0);
expect(bal.b).toBeGreaterThan(0);
expect(bal.c).toBeLessThan(0);
});
it('ignores invalid expenses (bad sums, unknown members)', () => { it('ignores invalid expenses (bad sums, unknown members)', () => {
const bad1 = expense({ id: 'x2', payers: [{ member: 'a', amount: 1 }] }); const bad1 = expense({ id: 'x2', payers: [{ member: 'a', amount: 1 }] });
const bad2 = expense({ id: 'x3', split: { mode: 'equal', entries: [{ member: 'zzz', value: 1 }] } }); const bad2 = expense({ id: 'x3', split: { mode: 'equal', entries: [{ member: 'zzz', value: 1 }] } });
@ -174,15 +148,6 @@ describe('replay', () => {
expect(replay(locked).state.group!.baseCurrency).toBe('CZK'); expect(replay(locked).state.group!.baseCurrency).toBe('CZK');
}); });
it('sets a default category and ignores invalid ones', () => {
const set = [...baseGroup(), ev({ type: 'group.updated', data: { defaultCategory: 'travel' } })];
expect(replay(set).state.group!.defaultCategory).toBe('travel');
const bad = [...set, ev({ type: 'group.updated', data: { defaultCategory: 'transfer' as never, name: 'Renamed' } })];
const g = replay(bad).state.group!;
expect(g.defaultCategory).toBe('travel');
expect(g.name).not.toBe('Renamed'); // the whole invalid event is ignored
});
it('revert restores an earlier state, and can itself be reverted', () => { it('revert restores an earlier state, and can itself be reverted', () => {
const evs = [...baseGroup(), ev({ type: 'expense.created', data: expense() }, 'a', 'keep')]; const evs = [...baseGroup(), ev({ type: 'expense.created', data: expense() }, 'a', 'keep')];
evs.push(ev({ type: 'expense.updated', data: expense({ amount: 99900, payers: [{ member: 'a', amount: 99900 }] }) }, 'b', 'vandal')); evs.push(ev({ type: 'expense.updated', data: expense({ amount: 99900, payers: [{ member: 'a', amount: 99900 }] }) }, 'b', 'vandal'));
@ -265,13 +230,3 @@ describe('stats and csv', () => {
expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`); expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`);
}); });
}); });
describe('ACTIVE_CURRENCIES', () => {
it('is sorted, unique ISO codes without replaced currencies', () => {
expect([...ACTIVE_CURRENCIES].sort()).toEqual(ACTIVE_CURRENCIES);
expect(new Set(ACTIVE_CURRENCIES).size).toBe(ACTIVE_CURRENCIES.length);
expect(ACTIVE_CURRENCIES.every((c) => /^[A-Z]{3}$/.test(c))).toBe(true);
for (const gone of ['ANG', 'BGN', 'CUC', 'HRK', 'SLL', 'ZWL', 'DEM', 'XDR']) expect(isActiveCurrency(gone)).toBe(false);
for (const c of ['ALL', 'CZK', 'EUR', 'XCG', 'ZWG']) expect(isActiveCurrency(c)).toBe(true);
});
});