Spaces:
Sleeping
Sleeping
Commit ·
4ae345a
1
Parent(s): 650ab40
feat(ui): add expense form with live split editor and photo upload
Browse filesFiles changed (6)
12345678910111213141516171819202122232425/** * Downscales an image file in the browser to at most `maxEdge` px on its longest side * and re-encodes it as JPEG. Returns null when no processing is needed or possible. */export async function downscaleImage(file: File, maxEdge = 1600, quality = 0.85): Promise<Blob | null> { if (typeof createImageBitmap === 'undefined' || typeof document === 'undefined') return null; try { const bitmap = await createImageBitmap(file); const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height)); if (scale === 1 && file.type === 'image/jpeg') { bitmap.close(); return null; } const canvas = document.createElement('canvas'); canvas.width = Math.max(1, Math.round(bitmap.width * scale)); canvas.height = Math.max(1, Math.round(bitmap.height * scale)); const ctx = canvas.getContext('2d'); if (!ctx) return null; ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height); bitmap.close(); return await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', quality)); } catch { return null; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115<script lang="ts"> import { enhance } from '$app/forms'; import { downscaleImage } from '$lib/client/downscale'; import type { ExpensePhoto, PublicUser } from '$lib/domain/types'; import type { ExpenseFormValues, FieldErrors } from '$lib/forms/types'; import FormError from './FormError.svelte'; import SplitEditor from './SplitEditor.svelte';
let { members, currency, values, errors = {}, existingPhoto, version, submitLabel }: { members: PublicUser[]; currency: string; values: ExpenseFormValues; errors?: FieldErrors; existingPhoto?: ExpensePhoto; version?: number; submitLabel: string; } = $props();
let amount = $state(values.amount); let submitting = $state(false);</script>
<form method="POST" enctype="multipart/form-data" class="space-y-4" use:enhance={async ({ formData }) => { submitting = true; const photo = formData.get('photo'); if (photo instanceof File && photo.size > 0 && photo.type.startsWith('image/')) { const small = await downscaleImage(photo); if (small) formData.set('photo', small, 'photo.jpg'); } return async ({ update }) => { submitting = false; await update(); }; }}> {#if version !== undefined} <input type="hidden" name="version" value={version} /> {/if}
<div> <label for="description">Description</label> <input id="description" name="description" required maxlength="120" value={values.description} placeholder="Dinner, groceries, tickets…" /> <FormError message={errors.description} /> </div>
<div class="grid grid-cols-2 gap-3"> <div> <label for="amount">Amount ({currency})</label> <input id="amount" name="amount" inputmode="decimal" placeholder="0.00" required bind:value={amount} /> <FormError message={errors.amount} /> </div> <div> <label for="date">Date</label> <input id="date" name="date" type="date" required value={values.date} /> <FormError message={errors.date} /> </div> </div>
<div> <label for="paidBy">Paid by</label> <select id="paidBy" name="paidBy" value={values.paidBy}> {#each members as m (m.id)} <option value={m.id}>{m.displayName}</option> {/each} </select> <FormError message={errors.paidBy} /> </div>
<SplitEditor {members} {currency} {values} {amount} error={errors.participants ?? errors.shares} />
<div> <label for="notes">Notes (optional)</label> <textarea id="notes" name="notes" rows="2" maxlength="2000" value={values.notes}></textarea> </div>
<div> <label for="photo">Receipt photo (optional)</label> {#if existingPhoto} <img src="/{existingPhoto.key}" alt="Current receipt" class="mb-2 max-h-40 rounded-lg" /> <label class="mb-2 flex items-center gap-2 font-normal" ><input type="checkbox" name="removePhoto" class="h-5 w-5" /> Remove current photo</label > {/if} <input id="photo" name="photo" type="file" accept="image/*" /> <FormError message={errors.photo} /> </div>
<FormError message={errors.form} /> <button type="submit" disabled={submitting} class="w-full rounded-lg bg-green-700 py-3 font-semibold text-white disabled:opacity-60" > {submitting ? 'Saving…' : submitLabel} </button></form>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131<script lang="ts"> import { formatCents, parseAmountToCents, parsePercentToBp } from '$lib/domain/money'; import { allocate } from '$lib/domain/split'; import type { PublicUser, SplitMode } from '$lib/domain/types'; import type { ExpenseFormValues } from '$lib/forms/types'; import FormError from './FormError.svelte';
let { members, currency, values, amount, error }: { members: PublicUser[]; currency: string; values: ExpenseFormValues; amount: string; error?: string; } = $props();
const modes: { value: SplitMode; label: string }[] = [ { value: 'equal', label: 'Equally' }, { value: 'percent', label: 'By %' }, { value: 'exact', label: 'Exact' } ];
let mode = $state<SplitMode>(values.mode); let participants = $state<string[]>([...values.participants]); let pct = $state<Record<string, string>>({ ...values.pct }); let exact = $state<Record<string, string>>({ ...values.exact });
const amountCents = $derived(parseAmountToCents(amount) ?? 0); const selected = $derived(members.filter((m) => participants.includes(m.id))); const equalShares = $derived<Record<string, number>>( amountCents > 0 && selected.length > 0 ? allocate( amountCents, selected.map((m) => ({ id: m.id, weight: 1 })) ) : {} ); const pctTotalBp = $derived( selected.reduce((acc, m) => acc + (parsePercentToBp(pct[m.id] ?? '') ?? 0), 0) ); const exactTotal = $derived( selected.reduce((acc, m) => acc + (parseAmountToCents(exact[m.id] ?? '') ?? 0), 0) );</script>
<fieldset class="space-y-3"> <legend class="text-sm font-medium text-gray-700">Split</legend>
<div class="grid grid-cols-3 gap-1 rounded-lg bg-gray-100 p-1"> {#each modes as m (m.value)} <label class="cursor-pointer rounded-md py-2 text-center text-sm {mode === m.value ? 'bg-white font-semibold shadow' : 'text-gray-600'}" > <input type="radio" name="mode" value={m.value} bind:group={mode} class="sr-only" /> {m.label} </label> {/each} </div>
<ul class="divide-y divide-gray-200 rounded-lg border border-gray-200 bg-white"> {#each members as m (m.id)} {@const on = participants.includes(m.id)} <li class="flex items-center gap-3 px-3 py-2"> <input type="checkbox" name="participants" value={m.id} bind:group={participants} id="p_{m.id}" class="h-5 w-5 shrink-0" /> <label for="p_{m.id}" class="flex-1 font-normal {on ? '' : 'text-gray-400'}" >{m.displayName}</label > {#if mode === 'equal'} <span class="text-sm text-gray-500 tabular-nums" >{on && amountCents > 0 ? formatCents(equalShares[m.id] ?? 0, currency) : ''}</span > {:else if mode === 'percent'} <div class="flex w-28 items-center gap-1"> <input name="pct_{m.id}" inputmode="decimal" placeholder="0" bind:value={pct[m.id]} disabled={!on} class="text-right" aria-label="Percent for {m.displayName}" /> <span class="text-sm text-gray-500">%</span> </div> {:else} <input name="exact_{m.id}" inputmode="decimal" placeholder="0.00" bind:value={exact[m.id]} disabled={!on} class="w-28 text-right" aria-label="Amount for {m.displayName}" /> {/if} </li> {/each} </ul>
{#if mode === 'percent'} <p class="text-sm tabular-nums {pctTotalBp === 10000 ? 'text-green-700' : 'text-amber-700'}"> Total {(pctTotalBp / 100).toFixed(2)}% · {((10000 - pctTotalBp) / 100).toFixed(2)}% remaining </p> {:else if mode === 'exact'} <p class="text-sm tabular-nums {exactTotal === amountCents && amountCents > 0 ? 'text-green-700' : 'text-amber-700'}" > Assigned {formatCents(exactTotal, currency)} · {formatCents( amountCents - exactTotal, currency )} remaining </p> {/if} <FormError message={error} /></fieldset>12374 unmodified lines787980export const MAX_PHOTO_BYTES = 5 * 1024 * 1024;export type ImageType = 'image/jpeg' | 'image/png' | 'image/webp';74 unmodified linesfunction check(width: number, height: number): { width: number; height: number } | null {return width > 0 && height > 0 && width <= MAX_IMAGE_DIMENSION && height <= MAX_IMAGE_DIMENSION ? { width, height } : null;}123456774 unmodified lines828384858687888990919293949596979899100101102103104import { ulid } from '../domain/ulid';import type { ExpensePhoto } from '../domain/types';import type { BucketStore } from './storage/store';export const MAX_PHOTO_BYTES = 5 * 1024 * 1024;export type ImageType = 'image/jpeg' | 'image/png' | 'image/webp';74 unmodified linesfunction check(width: number, height: number): { width: number; height: number } | null {return width > 0 && height > 0 && width <= MAX_IMAGE_DIMENSION && height <= MAX_IMAGE_DIMENSION ? { width, height } : null;}/** Returns the uploaded file for `name`, or null when the field is absent/empty. */export function uploadedFile(form: FormData, name: string): File | null {const f = form.get(name);return f instanceof File && f.size > 0 ? f : null;}export type StoredPhoto = { ok: true; photo: ExpensePhoto } | { ok: false; error: string };/** Validates and stores an uploaded image under photos/<expenseId>/<ulid>.<ext>. */export async function storeUploadedPhoto(store: BucketStore, expenseId: string, file: File): Promise<StoredPhoto> {if (file.size > MAX_PHOTO_BYTES) return { ok: false, error: 'Photo must be 5 MB or smaller' };const bytes = new Uint8Array(await file.arrayBuffer());const type = sniffImageType(bytes);if (!type) return { ok: false, error: 'Photo must be a JPEG, PNG or WebP image' };const key = photoKey(expenseId, ulid(), type);await store.put(key, bytes, type);const dims = imageDimensions(bytes, type);return { ok: true, photo: { key, contentType: type, ...(dims ?? {}) } };}
12345678910111213141516171819202122232425262728293031323334353637383940import { toPublicUser } from '$lib/domain/types';import { ulid } from '$lib/domain/ulid';import { buildExpenseBody, emptyExpenseForm, readExpenseForm } from '$lib/server/forms/expense-form';import { today } from '$lib/server/forms/form-utils';import { storeUploadedPhoto, uploadedFile } from '$lib/server/photos';import { fail, redirect } from '@sveltejs/kit';import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = ({ locals }) => { const members = locals.app.users.activeMembers().map(toPublicUser); return { members, values: emptyExpenseForm( locals.user!.id, members.map((m) => m.id), today() ) };};
export const actions: Actions = { default: async ({ request, locals }) => { const { users, ledger, store, config } = locals.app; const active = users.activeMembers().map((u) => u.id); const form = await request.formData(); const values = readExpenseForm(form, active); const built = buildExpenseBody(values, { activeMemberIds: active, currency: config.currency }); if (!built.ok) return fail(400, { values, errors: built.errors });
const expenseId = `e_${ulid()}`; const file = uploadedFile(form, 'photo'); if (file) { const saved = await storeUploadedPhoto(store, expenseId, file); if (!saved.ok) return fail(400, { values, errors: { photo: saved.error } }); built.body.photo = saved.photo; } await ledger.createExpense(locals.user!.id, built.body, expenseId); redirect(303, `/expenses/${expenseId}`); }};123456789101112131415161718192021222324<script lang="ts"> import ExpenseForm from '$lib/components/ExpenseForm.svelte'; import type { PageProps } from './$types';
let { data, form }: PageProps = $props();</script>
<main class="p-4"> <header class="mb-4 flex items-center gap-3"> <a href="/" class="text-gray-500" aria-label="Back">←</a> <h1 class="text-2xl font-bold">Add expense</h1> </header> {#if data.members.length === 0} <p class="text-gray-600">No members yet. Ask the admin to add users first.</p> {:else} <ExpenseForm members={data.members} currency={data.currency} values={form?.values ?? data.values} errors={form?.errors ?? {}} submitLabel="Save expense" /> {/if}</main>src/lib/client/downscale.tsAdded+25
src/lib/components/ExpenseForm.svelteAdded+115
src/lib/components/SplitEditor.svelteAdded+131
src/lib/server/photos.ts+24
src/routes/expenses/new/+page.server.tsAdded+40
src/routes/expenses/new/+page.svelteAdded+24