🐛 add env to useDb and apply prettier
tinyedge/deploy Deployed by TinyEdge

This commit is contained in:
2026-08-07 13:28:26 +02:00
parent 67727f96ab
commit cbe1b42f6e
54 changed files with 5492 additions and 2406 deletions
+4
View File
@@ -0,0 +1,4 @@
{
"semi": true,
"singleQuote": true
}
+3 -1
View File
@@ -1,5 +1,7 @@
<template> <template>
<div class="min-h-screen bg-orange-50/40 text-stone-900 dark:bg-stone-950 dark:text-stone-100"> <div
class="min-h-screen bg-orange-50/40 text-stone-900 dark:bg-stone-950 dark:text-stone-100"
>
<NuxtRouteAnnouncer /> <NuxtRouteAnnouncer />
<main class="mx-auto max-w-md px-4 py-8"> <main class="mx-auto max-w-md px-4 py-8">
<NuxtPage /> <NuxtPage />
+71 -37
View File
@@ -1,48 +1,60 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ExpenseView, ParticipantView } from '../types' import type { ExpenseView, ParticipantView } from '../types';
const props = defineProps<{ const props = defineProps<{
participants: ParticipantView[] participants: ParticipantView[];
currency: string currency: string;
editing?: ExpenseView | null editing?: ExpenseView | null;
defaultPayerId?: number defaultPayerId?: number;
}>() }>();
const emit = defineEmits<{ const emit = defineEmits<{
submit: [payload: { description: string, amountCents: number, payerId: number, participantIds: number[] }] submit: [
cancel: [] payload: {
}>() description: string;
amountCents: number;
payerId: number;
participantIds: number[];
},
];
cancel: [];
}>();
const description = ref(props.editing?.description ?? '') const description = ref(props.editing?.description ?? '');
const amount = ref(props.editing ? fromCents(props.editing.amountCents).toString() : '') const amount = ref(
const payerId = ref<number>(props.editing?.payerId ?? props.defaultPayerId ?? props.participants[0]!.id) props.editing ? fromCents(props.editing.amountCents).toString() : '',
const selectedIds = ref<number[]>(props.editing?.participantIds ?? props.participants.map(p => p.id)) );
const error = ref('') const payerId = ref<number>(
props.editing?.payerId ?? props.defaultPayerId ?? props.participants[0]!.id,
);
const selectedIds = ref<number[]>(
props.editing?.participantIds ?? props.participants.map((p) => p.id),
);
const error = ref('');
function toggleParticipant(id: number) { function toggleParticipant(id: number) {
if (selectedIds.value.includes(id)) { if (selectedIds.value.includes(id)) {
selectedIds.value = selectedIds.value.filter(existing => existing !== id) selectedIds.value = selectedIds.value.filter((existing) => existing !== id);
} } else {
else { selectedIds.value = [...selectedIds.value, id];
selectedIds.value = [...selectedIds.value, id]
} }
} }
function onSubmit() { function onSubmit() {
error.value = '' error.value = '';
const amountCents = toCents(Number(amount.value)) const amountCents = toCents(Number(amount.value));
if (!description.value.trim()) { if (!description.value.trim()) {
error.value = 'Description is required.' error.value = 'Description is required.';
return return;
} }
if (!Number.isFinite(amountCents) || amountCents <= 0) { if (!Number.isFinite(amountCents) || amountCents <= 0) {
error.value = 'Enter a valid amount.' error.value = 'Enter a valid amount.';
return return;
} }
if (selectedIds.value.length === 0) { if (selectedIds.value.length === 0) {
error.value = 'Select at least one participant to split with.' error.value = 'Select at least one participant to split with.';
return return;
} }
emit('submit', { emit('submit', {
@@ -50,14 +62,21 @@ function onSubmit() {
amountCents, amountCents,
payerId: payerId.value, payerId: payerId.value,
participantIds: selectedIds.value, participantIds: selectedIds.value,
}) });
} }
</script> </script>
<template> <template>
<form class="space-y-4 rounded-2xl border border-stone-200 bg-white p-4 shadow-sm dark:border-stone-800 dark:bg-stone-900" @submit.prevent="onSubmit"> <form
class="space-y-4 rounded-2xl border border-stone-200 bg-white p-4 shadow-sm dark:border-stone-800 dark:bg-stone-900"
@submit.prevent="onSubmit"
>
<div> <div>
<label for="description" class="block text-sm font-medium text-stone-700 dark:text-stone-300">Description</label> <label
for="description"
class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>Description</label
>
<input <input
id="description" id="description"
v-model="description" v-model="description"
@@ -65,11 +84,14 @@ function onSubmit() {
required required
class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900" class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900"
placeholder="Dinner, taxi, groceries…" placeholder="Dinner, taxi, groceries…"
> />
</div> </div>
<div> <div>
<label for="amount" class="block text-sm font-medium text-stone-700 dark:text-stone-300"> <label
for="amount"
class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>
Amount ({{ currency }}) Amount ({{ currency }})
</label> </label>
<input <input
@@ -81,33 +103,45 @@ function onSubmit() {
required required
class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900" class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900"
placeholder="0.00" placeholder="0.00"
> />
</div> </div>
<div> <div>
<label for="payer" class="block text-sm font-medium text-stone-700 dark:text-stone-300">Paid by</label> <label
for="payer"
class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>Paid by</label
>
<select <select
id="payer" id="payer"
v-model="payerId" v-model="payerId"
class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:focus:ring-orange-900" class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:focus:ring-orange-900"
> >
<option v-for="participant in participants" :key="participant.id" :value="participant.id"> <option
v-for="participant in participants"
:key="participant.id"
:value="participant.id"
>
{{ participant.name }} {{ participant.name }}
</option> </option>
</select> </select>
</div> </div>
<div> <div>
<span class="block text-sm font-medium text-stone-700 dark:text-stone-300">Split equally among</span> <span class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>Split equally among</span
>
<div class="mt-2 flex flex-wrap gap-2"> <div class="mt-2 flex flex-wrap gap-2">
<button <button
v-for="participant in participants" v-for="participant in participants"
:key="participant.id" :key="participant.id"
type="button" type="button"
class="rounded-full border px-3 py-1.5 text-sm font-medium transition-colors" class="rounded-full border px-3 py-1.5 text-sm font-medium transition-colors"
:class="selectedIds.includes(participant.id) :class="
selectedIds.includes(participant.id)
? 'border-orange-400 bg-orange-100 text-orange-800 dark:border-orange-700 dark:bg-orange-900/40 dark:text-orange-200' ? 'border-orange-400 bg-orange-100 text-orange-800 dark:border-orange-700 dark:bg-orange-900/40 dark:text-orange-200'
: 'border-stone-300 bg-white text-stone-600 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-400'" : 'border-stone-300 bg-white text-stone-600 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-400'
"
@click="toggleParticipant(participant.id)" @click="toggleParticipant(participant.id)"
> >
{{ participant.name }} {{ participant.name }}
+116 -63
View File
@@ -1,92 +1,97 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ParticipantView, SettlementView } from '../types' import type { ParticipantView, SettlementView } from '../types';
import { isValidPaymentLink } from '~~/shared/utils/paymentLink' import { isValidPaymentLink } from '~~/shared/utils/paymentLink';
const props = defineProps<{ const props = defineProps<{
slug: string slug: string;
participants: ParticipantView[] participants: ParticipantView[];
netBalances: Record<number, number> netBalances: Record<number, number>;
settlements: SettlementView[] settlements: SettlementView[];
currency: string currency: string;
}>() }>();
const emit = defineEmits<{ settled: [], updated: [] }>() const emit = defineEmits<{ settled: []; updated: [] }>();
const { lastLink, rememberLink } = usePaymentLinkCache() const { lastLink, rememberLink } = usePaymentLinkCache();
const settlingKey = ref<string | null>(null) const settlingKey = ref<string | null>(null);
const editingId = ref<number | null>(null) const editingId = ref<number | null>(null);
const editValue = ref('') const editValue = ref('');
const editError = ref('') const editError = ref('');
const savingLink = ref(false) const savingLink = ref(false);
function nameOf(id: number) { function nameOf(id: number) {
return props.participants.find(p => p.id === id)?.name ?? 'Unknown' return props.participants.find((p) => p.id === id)?.name ?? 'Unknown';
} }
function paymentLinkOf(id: number) { function paymentLinkOf(id: number) {
return props.participants.find(p => p.id === id)?.paymentLink || null return props.participants.find((p) => p.id === id)?.paymentLink || null;
} }
function initialOf(participantName: string) { function initialOf(participantName: string) {
return participantName.trim().charAt(0).toUpperCase() || '?' return participantName.trim().charAt(0).toUpperCase() || '?';
} }
function keyOf(settlement: SettlementView) { function keyOf(settlement: SettlementView) {
return `${settlement.fromId}-${settlement.toId}-${settlement.amountCents}` return `${settlement.fromId}-${settlement.toId}-${settlement.amountCents}`;
} }
function startEdit(participant: ParticipantView) { function startEdit(participant: ParticipantView) {
editingId.value = participant.id editingId.value = participant.id;
editValue.value = participant.paymentLink ?? lastLink.value ?? '' editValue.value = participant.paymentLink ?? lastLink.value ?? '';
editError.value = '' editError.value = '';
} }
function cancelEdit() { function cancelEdit() {
editingId.value = null editingId.value = null;
editError.value = '' editError.value = '';
} }
async function saveEdit(participant: ParticipantView) { async function saveEdit(participant: ParticipantView) {
const trimmed = editValue.value.trim() const trimmed = editValue.value.trim();
if (trimmed && !isValidPaymentLink(trimmed)) { if (trimmed && !isValidPaymentLink(trimmed)) {
editError.value = 'Enter a valid link starting with http:// or https://.' editError.value = 'Enter a valid link starting with http:// or https://.';
return return;
} }
savingLink.value = true savingLink.value = true;
try { try {
await $fetch(`/api/pots/${props.slug}/participants/${participant.id}`, { await $fetch(`/api/pots/${props.slug}/participants/${participant.id}`, {
method: 'PATCH', method: 'PATCH',
body: { paymentLink: trimmed }, body: { paymentLink: trimmed },
}) });
if (trimmed) rememberLink(trimmed) if (trimmed) rememberLink(trimmed);
editingId.value = null editingId.value = null;
emit('updated') emit('updated');
} } finally {
finally { savingLink.value = false;
savingLink.value = false
} }
} }
async function markSettled(settlement: SettlementView) { async function markSettled(settlement: SettlementView) {
const key = keyOf(settlement) const key = keyOf(settlement);
settlingKey.value = key settlingKey.value = key;
try { try {
await $fetch(`/api/pots/${props.slug}/payments`, { await $fetch(`/api/pots/${props.slug}/payments`, {
method: 'POST', method: 'POST',
body: { fromId: settlement.fromId, toId: settlement.toId, amountCents: settlement.amountCents }, body: {
}) fromId: settlement.fromId,
emit('settled') toId: settlement.toId,
} amountCents: settlement.amountCents,
finally { },
settlingKey.value = null });
emit('settled');
} finally {
settlingKey.value = null;
} }
} }
</script> </script>
<template> <template>
<div class="space-y-4"> <div class="space-y-4">
<p v-if="participants.length === 0" class="rounded-2xl border border-dashed border-stone-300 p-4 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400"> <p
v-if="participants.length === 0"
class="rounded-2xl border border-dashed border-stone-300 p-4 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400"
>
No one's in this Pot yet. Add people from the settings page. No one's in this Pot yet. Add people from the settings page.
</p> </p>
@@ -100,12 +105,21 @@ async function markSettled(settlement: SettlementView) {
<button <button
type="button" type="button"
class="flex min-w-0 items-center gap-3 text-left" class="flex min-w-0 items-center gap-3 text-left"
@click="editingId === participant.id ? cancelEdit() : startEdit(participant)" @click="
editingId === participant.id
? cancelEdit()
: startEdit(participant)
"
>
<div
class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-orange-100 text-sm font-semibold text-orange-700 dark:bg-orange-900/40 dark:text-orange-300"
> >
<div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-orange-100 text-sm font-semibold text-orange-700 dark:bg-orange-900/40 dark:text-orange-300">
{{ initialOf(participant.name) }} {{ initialOf(participant.name) }}
</div> </div>
<span class="truncate font-medium text-stone-900 dark:text-stone-100">{{ participant.name }}</span> <span
class="truncate font-medium text-stone-900 dark:text-stone-100"
>{{ participant.name }}</span
>
</button> </button>
<div class="flex shrink-0 items-center gap-3"> <div class="flex shrink-0 items-center gap-3">
<a <a
@@ -121,23 +135,37 @@ async function markSettled(settlement: SettlementView) {
<span <span
class="text-sm font-semibold" class="text-sm font-semibold"
:class="{ :class="{
'text-emerald-600 dark:text-emerald-400': (netBalances[participant.id] ?? 0) > 0, 'text-emerald-600 dark:text-emerald-400':
'text-rose-600 dark:text-rose-400': (netBalances[participant.id] ?? 0) < 0, (netBalances[participant.id] ?? 0) > 0,
'text-stone-400 dark:text-stone-500': (netBalances[participant.id] ?? 0) === 0, 'text-rose-600 dark:text-rose-400':
(netBalances[participant.id] ?? 0) < 0,
'text-stone-400 dark:text-stone-500':
(netBalances[participant.id] ?? 0) === 0,
}" }"
> >
<template v-if="(netBalances[participant.id] ?? 0) === 0"> <template v-if="(netBalances[participant.id] ?? 0) === 0">
settled up settled up
</template> </template>
<template v-else> <template v-else>
{{ (netBalances[participant.id] ?? 0) > 0 ? '+' : '' }}{{ formatCurrency(Math.abs(netBalances[participant.id] ?? 0), currency) }} {{ (netBalances[participant.id] ?? 0) > 0 ? '+' : ''
}}{{
formatCurrency(
Math.abs(netBalances[participant.id] ?? 0),
currency,
)
}}
</template> </template>
</span> </span>
</div> </div>
</div> </div>
<div v-if="editingId === participant.id" class="mt-3 space-y-2 border-t border-stone-100 pt-3 dark:border-stone-800"> <div
<label class="block text-xs font-medium text-stone-500 dark:text-stone-400"> v-if="editingId === participant.id"
class="mt-3 space-y-2 border-t border-stone-100 pt-3 dark:border-stone-800"
>
<label
class="block text-xs font-medium text-stone-500 dark:text-stone-400"
>
Payment link for {{ participant.name }} Payment link for {{ participant.name }}
</label> </label>
<div class="flex gap-2"> <div class="flex gap-2">
@@ -147,7 +175,7 @@ async function markSettled(settlement: SettlementView) {
placeholder="https://paypal.me/yourname" placeholder="https://paypal.me/yourname"
class="block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-sm text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900" class="block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-sm text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900"
@keyup.enter="saveEdit(participant)" @keyup.enter="saveEdit(participant)"
> />
<button <button
type="button" type="button"
:disabled="savingLink" :disabled="savingLink"
@@ -176,7 +204,10 @@ async function markSettled(settlement: SettlementView) {
Suggested payments Suggested payments
</h2> </h2>
<p v-if="settlements.length === 0" class="text-sm text-stone-500 dark:text-stone-400"> <p
v-if="settlements.length === 0"
class="text-sm text-stone-500 dark:text-stone-400"
>
Everyone is settled up. Everyone is settled up.
</p> </p>
<ul v-else class="space-y-2"> <ul v-else class="space-y-2">
@@ -187,22 +218,42 @@ async function markSettled(settlement: SettlementView) {
> >
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<div class="flex min-w-0 flex-1 items-center gap-2"> <div class="flex min-w-0 flex-1 items-center gap-2">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white text-xs font-semibold text-orange-700 shadow-sm ring-1 ring-orange-200 dark:bg-stone-900 dark:text-orange-300 dark:ring-orange-800"> <div
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white text-xs font-semibold text-orange-700 shadow-sm ring-1 ring-orange-200 dark:bg-stone-900 dark:text-orange-300 dark:ring-orange-800"
>
{{ initialOf(nameOf(settlement.fromId)) }} {{ initialOf(nameOf(settlement.fromId)) }}
</div> </div>
<span class="truncate text-sm font-medium text-stone-700 dark:text-stone-300">{{ nameOf(settlement.fromId) }}</span> <span
class="truncate text-sm font-medium text-stone-700 dark:text-stone-300"
>{{ nameOf(settlement.fromId) }}</span
>
<svg class="h-4 w-4 shrink-0 text-orange-400 dark:text-orange-500" viewBox="0 0 20 20" fill="currentColor"> <svg
<path fill-rule="evenodd" d="M3 10a.75.75 0 0 1 .75-.75h10.638L11.29 6.15a.75.75 0 1 1 1.02-1.1l4.5 4.25a.75.75 0 0 1 0 1.1l-4.5 4.25a.75.75 0 1 1-1.02-1.1l3.098-3.1H3.75A.75.75 0 0 1 3 10Z" clip-rule="evenodd" /> class="h-4 w-4 shrink-0 text-orange-400 dark:text-orange-500"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M3 10a.75.75 0 0 1 .75-.75h10.638L11.29 6.15a.75.75 0 1 1 1.02-1.1l4.5 4.25a.75.75 0 0 1 0 1.1l-4.5 4.25a.75.75 0 1 1-1.02-1.1l3.098-3.1H3.75A.75.75 0 0 1 3 10Z"
clip-rule="evenodd"
/>
</svg> </svg>
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white text-xs font-semibold text-orange-700 shadow-sm ring-1 ring-orange-200 dark:bg-stone-900 dark:text-orange-300 dark:ring-orange-800"> <div
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white text-xs font-semibold text-orange-700 shadow-sm ring-1 ring-orange-200 dark:bg-stone-900 dark:text-orange-300 dark:ring-orange-800"
>
{{ initialOf(nameOf(settlement.toId)) }} {{ initialOf(nameOf(settlement.toId)) }}
</div> </div>
<span class="truncate text-sm font-medium text-stone-700 dark:text-stone-300">{{ nameOf(settlement.toId) }}</span> <span
class="truncate text-sm font-medium text-stone-700 dark:text-stone-300"
>{{ nameOf(settlement.toId) }}</span
>
</div> </div>
<span class="shrink-0 rounded-full bg-white px-2.5 py-1 text-sm font-bold text-orange-700 shadow-sm dark:bg-stone-900 dark:text-orange-300"> <span
class="shrink-0 rounded-full bg-white px-2.5 py-1 text-sm font-bold text-orange-700 shadow-sm dark:bg-stone-900 dark:text-orange-300"
>
{{ formatCurrency(settlement.amountCents, currency) }} {{ formatCurrency(settlement.amountCents, currency) }}
</span> </span>
</div> </div>
@@ -223,7 +274,9 @@ async function markSettled(settlement: SettlementView) {
class="rounded-full bg-orange-500 px-3 py-1 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-orange-600 disabled:opacity-50" class="rounded-full bg-orange-500 px-3 py-1 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-orange-600 disabled:opacity-50"
@click="markSettled(settlement)" @click="markSettled(settlement)"
> >
{{ settlingKey === keyOf(settlement) ? 'Marking…' : 'Mark as paid' }} {{
settlingKey === keyOf(settlement) ? 'Marking' : 'Mark as paid'
}}
</button> </button>
</div> </div>
</li> </li>
+67 -24
View File
@@ -1,34 +1,42 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ExpenseView, ParticipantView } from '../types' import type { ExpenseView, ParticipantView } from '../types';
const props = defineProps<{ const props = defineProps<{
expenses: ExpenseView[] expenses: ExpenseView[];
participants: ParticipantView[] participants: ParticipantView[];
currency: string currency: string;
}>() }>();
const emit = defineEmits<{ edit: [expense: ExpenseView], remove: [id: number] }>() const emit = defineEmits<{
edit: [expense: ExpenseView];
remove: [id: number];
}>();
const expandedId = ref<number | null>(null) const expandedId = ref<number | null>(null);
function nameOf(id: number) { function nameOf(id: number) {
return props.participants.find(p => p.id === id)?.name ?? 'Unknown' return props.participants.find((p) => p.id === id)?.name ?? 'Unknown';
} }
function namesOf(ids: number[]) { function namesOf(ids: number[]) {
return ids.map(nameOf).join(', ') return ids.map(nameOf).join(', ');
} }
function toggle(id: number) { function toggle(id: number) {
expandedId.value = expandedId.value === id ? null : id expandedId.value = expandedId.value === id ? null : id;
} }
const sorted = computed(() => [...props.expenses].sort((a, b) => b.createdAt - a.createdAt)) const sorted = computed(() =>
[...props.expenses].sort((a, b) => b.createdAt - a.createdAt),
);
</script> </script>
<template> <template>
<div class="space-y-3"> <div class="space-y-3">
<p v-if="expenses.length === 0" class="rounded-2xl border border-dashed border-stone-300 p-4 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400"> <p
v-if="expenses.length === 0"
class="rounded-2xl border border-dashed border-stone-300 p-4 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400"
>
No expenses yet. Add the first one below. No expenses yet. Add the first one below.
</p> </p>
@@ -36,17 +44,37 @@ const sorted = computed(() => [...props.expenses].sort((a, b) => b.createdAt - a
v-for="expense in sorted" v-for="expense in sorted"
:key="expense.id" :key="expense.id"
class="rounded-2xl border p-4 shadow-sm" class="rounded-2xl border p-4 shadow-sm"
:class="expense.type === 'payment' :class="
expense.type === 'payment'
? 'border-emerald-100 bg-emerald-50/60 dark:border-emerald-900/60 dark:bg-emerald-950/20' ? 'border-emerald-100 bg-emerald-50/60 dark:border-emerald-900/60 dark:bg-emerald-950/20'
: 'border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-900'" : 'border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-900'
"
> >
<button type="button" class="flex w-full items-start justify-between gap-2 text-left" @click="toggle(expense.id)"> <button
<div v-if="expense.type === 'payment'" class="flex min-w-0 items-center gap-2"> type="button"
<svg class="h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400" viewBox="0 0 20 20" fill="currentColor"> class="flex w-full items-start justify-between gap-2 text-left"
<path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z" clip-rule="evenodd" /> @click="toggle(expense.id)"
>
<div
v-if="expense.type === 'payment'"
class="flex min-w-0 items-center gap-2"
>
<svg
class="h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z"
clip-rule="evenodd"
/>
</svg> </svg>
<p class="truncate font-medium text-emerald-800 dark:text-emerald-300"> <p
{{ nameOf(expense.payerId) }} paid {{ nameOf(expense.participantIds[0]!) }} class="truncate font-medium text-emerald-800 dark:text-emerald-300"
>
{{ nameOf(expense.payerId) }} paid
{{ nameOf(expense.participantIds[0]!) }}
</p> </p>
</div> </div>
<div v-else class="min-w-0"> <div v-else class="min-w-0">
@@ -60,7 +88,11 @@ const sorted = computed(() => [...props.expenses].sort((a, b) => b.createdAt - a
<div class="flex shrink-0 items-center gap-2"> <div class="flex shrink-0 items-center gap-2">
<span <span
class="font-medium" class="font-medium"
:class="expense.type === 'payment' ? 'text-emerald-700 dark:text-emerald-300' : 'text-stone-900 dark:text-stone-100'" :class="
expense.type === 'payment'
? 'text-emerald-700 dark:text-emerald-300'
: 'text-stone-900 dark:text-stone-100'
"
> >
{{ formatCurrency(expense.amountCents, currency) }} {{ formatCurrency(expense.amountCents, currency) }}
</span> </span>
@@ -70,7 +102,11 @@ const sorted = computed(() => [...props.expenses].sort((a, b) => b.createdAt - a
viewBox="0 0 20 20" viewBox="0 0 20 20"
fill="currentColor" fill="currentColor"
> >
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.148l3.71-3.918a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" /> <path
fill-rule="evenodd"
d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.148l3.71-3.918a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z"
clip-rule="evenodd"
/>
</svg> </svg>
</div> </div>
</button> </button>
@@ -78,9 +114,16 @@ const sorted = computed(() => [...props.expenses].sort((a, b) => b.createdAt - a
<div <div
v-if="expandedId === expense.id" v-if="expandedId === expense.id"
class="mt-3 space-y-3 border-t pt-3" class="mt-3 space-y-3 border-t pt-3"
:class="expense.type === 'payment' ? 'border-emerald-100 dark:border-emerald-900/60' : 'border-stone-100 dark:border-stone-800'" :class="
expense.type === 'payment'
? 'border-emerald-100 dark:border-emerald-900/60'
: 'border-stone-100 dark:border-stone-800'
"
>
<p
v-if="expense.type === 'expense'"
class="text-xs text-stone-400 dark:text-stone-500"
> >
<p v-if="expense.type === 'expense'" class="text-xs text-stone-400 dark:text-stone-500">
split among {{ namesOf(expense.participantIds) }} split among {{ namesOf(expense.participantIds) }}
</p> </p>
<div class="flex gap-3"> <div class="flex gap-3">
+11 -8
View File
@@ -1,20 +1,23 @@
<script setup lang="ts"> <script setup lang="ts">
const props = defineProps<{ title?: string, buttonLabel?: string }>() const props = defineProps<{ title?: string; buttonLabel?: string }>();
const emit = defineEmits<{ submit: [name: string] }>() const emit = defineEmits<{ submit: [name: string] }>();
const name = ref('') const name = ref('');
function onSubmit() { function onSubmit() {
if (!name.value.trim()) return if (!name.value.trim()) return;
emit('submit', name.value.trim()) emit('submit', name.value.trim());
} }
</script> </script>
<template> <template>
<form class="space-y-3" @submit.prevent="onSubmit"> <form class="space-y-3" @submit.prevent="onSubmit">
<div> <div>
<label for="name" class="block text-sm font-medium text-stone-700 dark:text-stone-300"> <label
{{ props.title ?? 'What\'s your name?' }} for="name"
class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>
{{ props.title ?? "What's your name?" }}
</label> </label>
<input <input
id="name" id="name"
@@ -24,7 +27,7 @@ function onSubmit() {
required required
class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900" class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900"
placeholder="Your name" placeholder="Your name"
> />
</div> </div>
<button <button
type="submit" type="submit"
+12 -11
View File
@@ -1,21 +1,22 @@
import { readIdentity, writeIdentity } from '../utils/identity' import { readIdentity, writeIdentity } from '../utils/identity';
export function useIdentity() { export function useIdentity() {
const name = useState<string | null>('identity-name', () => null) const name = useState<string | null>('identity-name', () => null);
const loaded = useState('identity-loaded', () => false) const loaded = useState('identity-loaded', () => false);
if (import.meta.client && !loaded.value) { if (import.meta.client && !loaded.value) {
const identity = readIdentity(window.localStorage) const identity = readIdentity(window.localStorage);
name.value = identity?.name ?? null name.value = identity?.name ?? null;
loaded.value = true loaded.value = true;
} }
function setName(newName: string) { function setName(newName: string) {
const trimmed = newName.trim() const trimmed = newName.trim();
if (!trimmed) return if (!trimmed) return;
name.value = trimmed name.value = trimmed;
if (import.meta.client) writeIdentity(window.localStorage, { name: trimmed }) if (import.meta.client)
writeIdentity(window.localStorage, { name: trimmed });
} }
return { name, setName } return { name, setName };
} }
+10 -7
View File
@@ -1,17 +1,20 @@
import { readCachedPaymentLink, writeCachedPaymentLink } from '../utils/paymentLinkCache' import {
readCachedPaymentLink,
writeCachedPaymentLink,
} from '../utils/paymentLinkCache';
export function usePaymentLinkCache() { export function usePaymentLinkCache() {
const lastLink = useState<string | null>('payment-link-cache', () => null) const lastLink = useState<string | null>('payment-link-cache', () => null);
if (import.meta.client && lastLink.value === null) { if (import.meta.client && lastLink.value === null) {
lastLink.value = readCachedPaymentLink(window.localStorage) lastLink.value = readCachedPaymentLink(window.localStorage);
} }
function rememberLink(link: string) { function rememberLink(link: string) {
if (!import.meta.client || !link) return if (!import.meta.client || !link) return;
lastLink.value = link lastLink.value = link;
writeCachedPaymentLink(window.localStorage, link) writeCachedPaymentLink(window.localStorage, link);
} }
return { lastLink, rememberLink } return { lastLink, rememberLink };
} }
+11 -7
View File
@@ -1,18 +1,22 @@
import { readVisitedPots, recordVisitedPot, type VisitedPot } from '../utils/visitedPots' import {
readVisitedPots,
recordVisitedPot,
type VisitedPot,
} from '../utils/visitedPots';
export function useVisitedPots() { export function useVisitedPots() {
const stored = useState<VisitedPot[] | null>('visited-pots', () => null) const stored = useState<VisitedPot[] | null>('visited-pots', () => null);
if (import.meta.client && stored.value === null) { if (import.meta.client && stored.value === null) {
stored.value = readVisitedPots(window.localStorage) stored.value = readVisitedPots(window.localStorage);
} }
const pots = computed(() => stored.value ?? []) const pots = computed(() => stored.value ?? []);
function recordVisit(pot: Omit<VisitedPot, 'visitedAt'>) { function recordVisit(pot: Omit<VisitedPot, 'visitedAt'>) {
if (!import.meta.client) return if (!import.meta.client) return;
stored.value = recordVisitedPot(window.localStorage, pot) stored.value = recordVisitedPot(window.localStorage, pot);
} }
return { pots, recordVisit } return { pots, recordVisit };
} }
+45 -28
View File
@@ -1,30 +1,32 @@
<script setup lang="ts"> <script setup lang="ts">
const { name, setName } = useIdentity() const { name, setName } = useIdentity();
const { pots: visitedPots } = useVisitedPots() const { pots: visitedPots } = useVisitedPots();
const potName = ref('') const potName = ref('');
const currency = ref('EUR') const currency = ref('EUR');
const creating = ref(false) const creating = ref(false);
const error = ref('') const error = ref('');
const currencies = ['EUR', 'USD', 'GBP', 'CHF'] const currencies = ['EUR', 'USD', 'GBP', 'CHF'];
async function createPot() { async function createPot() {
if (!potName.value.trim()) return if (!potName.value.trim()) return;
creating.value = true creating.value = true;
error.value = '' error.value = '';
try { try {
const pot = await $fetch('/api/pots', { const pot = await $fetch('/api/pots', {
method: 'POST', method: 'POST',
body: { name: potName.value.trim(), currency: currency.value, creatorName: name.value }, body: {
}) name: potName.value.trim(),
await navigateTo(`/p/${pot.slug}/setup`) currency: currency.value,
} creatorName: name.value,
catch { },
error.value = 'Could not create the Pot. Please try again.' });
} await navigateTo(`/p/${pot.slug}/setup`);
finally { } catch {
creating.value = false error.value = 'Could not create the Pot. Please try again.';
} finally {
creating.value = false;
} }
} }
</script> </script>
@@ -32,9 +34,7 @@ async function createPot() {
<template> <template>
<div class="space-y-8"> <div class="space-y-8">
<div class="space-y-1 text-center"> <div class="space-y-1 text-center">
<div class="text-4xl"> <div class="text-4xl">🍯</div>
🍯
</div>
<h1 class="text-2xl font-bold text-stone-900 dark:text-stone-100"> <h1 class="text-2xl font-bold text-stone-900 dark:text-stone-100">
Splitt the Bill Splitt the Bill
</h1> </h1>
@@ -53,8 +53,13 @@ async function createPot() {
:to="`/p/${pot.slug}`" :to="`/p/${pot.slug}`"
class="flex items-center justify-between gap-3 rounded-2xl border border-stone-200 bg-white p-3 shadow-sm transition-colors hover:border-orange-300 dark:border-stone-800 dark:bg-stone-900 dark:hover:border-orange-700" class="flex items-center justify-between gap-3 rounded-2xl border border-stone-200 bg-white p-3 shadow-sm transition-colors hover:border-orange-300 dark:border-stone-800 dark:bg-stone-900 dark:hover:border-orange-700"
> >
<span class="font-medium text-stone-900 dark:text-stone-100">{{ pot.name }}</span> <span class="font-medium text-stone-900 dark:text-stone-100">{{
<span class="shrink-0 text-xs font-medium text-stone-400 dark:text-stone-500">{{ pot.currency }}</span> pot.name
}}</span>
<span
class="shrink-0 text-xs font-medium text-stone-400 dark:text-stone-500"
>{{ pot.currency }}</span
>
</NuxtLink> </NuxtLink>
</li> </li>
</ul> </ul>
@@ -62,13 +67,21 @@ async function createPot() {
<NameForm v-if="!name" @submit="setName" /> <NameForm v-if="!name" @submit="setName" />
<form v-else class="space-y-4 rounded-2xl border border-stone-200 bg-white p-5 shadow-sm dark:border-stone-800 dark:bg-stone-900" @submit.prevent="createPot"> <form
v-else
class="space-y-4 rounded-2xl border border-stone-200 bg-white p-5 shadow-sm dark:border-stone-800 dark:bg-stone-900"
@submit.prevent="createPot"
>
<p class="text-sm text-stone-600 dark:text-stone-400"> <p class="text-sm text-stone-600 dark:text-stone-400">
Hi {{ name }}! Create a new Pot to start splitting costs. Hi {{ name }}! Create a new Pot to start splitting costs.
</p> </p>
<div> <div>
<label for="pot-name" class="block text-sm font-medium text-stone-700 dark:text-stone-300">Pot name</label> <label
for="pot-name"
class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>Pot name</label
>
<input <input
id="pot-name" id="pot-name"
v-model="potName" v-model="potName"
@@ -76,11 +89,15 @@ async function createPot() {
required required
class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900" class="mt-1 block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900"
placeholder="Weekend in Lisbon" placeholder="Weekend in Lisbon"
> />
</div> </div>
<div> <div>
<label for="currency" class="block text-sm font-medium text-stone-700 dark:text-stone-300">Currency</label> <label
for="currency"
class="block text-sm font-medium text-stone-700 dark:text-stone-300"
>Currency</label
>
<select <select
id="currency" id="currency"
v-model="currency" v-model="currency"
+87 -49
View File
@@ -1,77 +1,98 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ExpenseView, PotView } from '~/types' import type { ExpenseView, PotView } from '~/types';
const route = useRoute() const route = useRoute();
const slug = route.params.slug as string const slug = route.params.slug as string;
const { name, setName } = useIdentity() const { name, setName } = useIdentity();
const { data, refresh, error } = await useFetch<PotView>(`/api/pots/${slug}`) const { data, refresh, error } = await useFetch<PotView>(`/api/pots/${slug}`);
const { recordVisit } = useVisitedPots() const { recordVisit } = useVisitedPots();
const me = computed(() => const me = computed(() =>
data.value?.participants.find(p => p.name.toLowerCase() === name.value?.toLowerCase()), data.value?.participants.find(
) (p) => p.name.toLowerCase() === name.value?.toLowerCase(),
),
);
watch(data, (pot) => { watch(
if (!pot) return data,
recordVisit({ slug: pot.pot.slug, name: pot.pot.name, currency: pot.pot.currency }) (pot) => {
}, { immediate: true }) if (!pot) return;
recordVisit({
slug: pot.pot.slug,
name: pot.pot.name,
currency: pot.pot.currency,
});
},
{ immediate: true },
);
const activeTab = ref<'people' | 'expenses'>('people') const activeTab = ref<'people' | 'expenses'>('people');
const showExpenseForm = ref(false) const showExpenseForm = ref(false);
const editingExpense = ref<ExpenseView | null>(null) const editingExpense = ref<ExpenseView | null>(null);
const linkCopied = ref(false) const linkCopied = ref(false);
async function addMyself() { async function addMyself() {
if (!name.value) return if (!name.value) return;
await $fetch(`/api/pots/${slug}/participants`, { method: 'POST', body: { name: name.value } }) await $fetch(`/api/pots/${slug}/participants`, {
await refresh() method: 'POST',
body: { name: name.value },
});
await refresh();
} }
async function submitExpense(payload: { description: string, amountCents: number, payerId: number, participantIds: number[] }) { async function submitExpense(payload: {
description: string;
amountCents: number;
payerId: number;
participantIds: number[];
}) {
if (editingExpense.value) { if (editingExpense.value) {
await $fetch(`/api/pots/${slug}/expenses/${editingExpense.value.id}`, { method: 'PATCH', body: payload }) await $fetch(`/api/pots/${slug}/expenses/${editingExpense.value.id}`, {
method: 'PATCH',
body: payload,
});
} else {
await $fetch(`/api/pots/${slug}/expenses`, {
method: 'POST',
body: payload,
});
} }
else { editingExpense.value = null;
await $fetch(`/api/pots/${slug}/expenses`, { method: 'POST', body: payload }) showExpenseForm.value = false;
} await refresh();
editingExpense.value = null
showExpenseForm.value = false
await refresh()
} }
function editExpense(expense: ExpenseView) { function editExpense(expense: ExpenseView) {
editingExpense.value = expense editingExpense.value = expense;
showExpenseForm.value = true showExpenseForm.value = true;
} }
function newExpense() { function newExpense() {
editingExpense.value = null editingExpense.value = null;
showExpenseForm.value = true showExpenseForm.value = true;
} }
function cancelExpenseForm() { function cancelExpenseForm() {
editingExpense.value = null editingExpense.value = null;
showExpenseForm.value = false showExpenseForm.value = false;
} }
async function removeExpense(id: number) { async function removeExpense(id: number) {
await $fetch(`/api/pots/${slug}/expenses/${id}`, { method: 'DELETE' }) await $fetch(`/api/pots/${slug}/expenses/${id}`, { method: 'DELETE' });
await refresh() await refresh();
} }
async function copyLink() { async function copyLink() {
await navigator.clipboard.writeText(window.location.href) await navigator.clipboard.writeText(window.location.href);
linkCopied.value = true linkCopied.value = true;
setTimeout(() => (linkCopied.value = false), 2000) setTimeout(() => (linkCopied.value = false), 2000);
} }
</script> </script>
<template> <template>
<div v-if="error" class="space-y-3 text-center"> <div v-if="error" class="space-y-3 text-center">
<p class="text-rose-600 dark:text-rose-400"> <p class="text-rose-600 dark:text-rose-400">This Pot couldn't be found.</p>
This Pot couldn't be found.
</p>
<NuxtLink to="/" class="font-medium text-orange-600 dark:text-orange-400"> <NuxtLink to="/" class="font-medium text-orange-600 dark:text-orange-400">
Go home Go home
</NuxtLink> </NuxtLink>
@@ -85,7 +106,11 @@ async function copyLink() {
class="inline-flex items-center gap-1 text-sm font-medium text-stone-500 transition-colors hover:text-orange-600 dark:text-stone-400 dark:hover:text-orange-400" class="inline-flex items-center gap-1 text-sm font-medium text-stone-500 transition-colors hover:text-orange-600 dark:text-stone-400 dark:hover:text-orange-400"
> >
<svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"> <svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M17 10a.75.75 0 0 1-.75.75H5.612l4.158 3.96a.75.75 0 1 1-1.04 1.08l-5.5-5.25a.75.75 0 0 1 0-1.08l5.5-5.25a.75.75 0 1 1 1.04 1.08L5.612 9.25H16.25A.75.75 0 0 1 17 10Z" clip-rule="evenodd" /> <path
fill-rule="evenodd"
d="M17 10a.75.75 0 0 1-.75.75H5.612l4.158 3.96a.75.75 0 1 1-1.04 1.08l-5.5-5.25a.75.75 0 0 1 0-1.08l5.5-5.25a.75.75 0 1 1 1.04 1.08L5.612 9.25H16.25A.75.75 0 0 1 17 10Z"
clip-rule="evenodd"
/>
</svg> </svg>
All Pots All Pots
</NuxtLink> </NuxtLink>
@@ -113,13 +138,20 @@ async function copyLink() {
aria-label="Pot settings" aria-label="Pot settings"
> >
<svg class="h-4.5 w-4.5" viewBox="0 0 20 20" fill="currentColor"> <svg class="h-4.5 w-4.5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M8.34 1.804A1 1 0 0 1 9.32 1h1.36a1 1 0 0 1 .98.804l.24 1.192c.428.183.83.41 1.2.674l1.146-.386a1 1 0 0 1 1.212.464l.68 1.178a1 1 0 0 1-.208 1.267l-.912.816a6.5 6.5 0 0 1 0 1.382l.912.816a1 1 0 0 1 .208 1.267l-.68 1.178a1 1 0 0 1-1.212.464l-1.146-.386c-.37.264-.772.49-1.2.674l-.24 1.192a1 1 0 0 1-.98.804H9.32a1 1 0 0 1-.98-.804l-.24-1.192a6.5 6.5 0 0 1-1.2-.674l-1.146.386a1 1 0 0 1-1.212-.464l-.68-1.178a1 1 0 0 1 .208-1.267l.912-.816a6.5 6.5 0 0 1 0-1.382l-.912-.816a1 1 0 0 1-.208-1.267l.68-1.178a1 1 0 0 1 1.212-.464l1.146.386c.37-.264.772-.49 1.2-.674l.24-1.192ZM10 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" clip-rule="evenodd" /> <path
fill-rule="evenodd"
d="M8.34 1.804A1 1 0 0 1 9.32 1h1.36a1 1 0 0 1 .98.804l.24 1.192c.428.183.83.41 1.2.674l1.146-.386a1 1 0 0 1 1.212.464l.68 1.178a1 1 0 0 1-.208 1.267l-.912.816a6.5 6.5 0 0 1 0 1.382l.912.816a1 1 0 0 1 .208 1.267l-.68 1.178a1 1 0 0 1-1.212.464l-1.146-.386c-.37.264-.772.49-1.2.674l-.24 1.192a1 1 0 0 1-.98.804H9.32a1 1 0 0 1-.98-.804l-.24-1.192a6.5 6.5 0 0 1-1.2-.674l-1.146.386a1 1 0 0 1-1.212-.464l-.68-1.178a1 1 0 0 1 .208-1.267l.912-.816a6.5 6.5 0 0 1 0-1.382l-.912-.816a1 1 0 0 1-.208-1.267l.68-1.178a1 1 0 0 1 1.212-.464l1.146.386c.37-.264.772-.49 1.2-.674l.24-1.192ZM10 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"
clip-rule="evenodd"
/>
</svg> </svg>
</NuxtLink> </NuxtLink>
</div> </div>
</div> </div>
<div v-if="!me" class="rounded-2xl border border-orange-200 bg-orange-50 p-4 text-sm dark:border-orange-900 dark:bg-orange-950/40"> <div
v-if="!me"
class="rounded-2xl border border-orange-200 bg-orange-50 p-4 text-sm dark:border-orange-900 dark:bg-orange-950/40"
>
<p class="mb-2 text-stone-700 dark:text-stone-300"> <p class="mb-2 text-stone-700 dark:text-stone-300">
You're not in this Pot's participant list yet. You're not in this Pot's participant list yet.
</p> </p>
@@ -132,13 +164,17 @@ async function copyLink() {
</button> </button>
</div> </div>
<div class="grid grid-cols-2 gap-1 rounded-xl bg-stone-100 p-1 dark:bg-stone-900"> <div
class="grid grid-cols-2 gap-1 rounded-xl bg-stone-100 p-1 dark:bg-stone-900"
>
<button <button
type="button" type="button"
class="rounded-lg py-2 text-sm font-medium transition-colors" class="rounded-lg py-2 text-sm font-medium transition-colors"
:class="activeTab === 'people' :class="
activeTab === 'people'
? 'bg-white text-stone-900 shadow-sm dark:bg-stone-800 dark:text-stone-100' ? 'bg-white text-stone-900 shadow-sm dark:bg-stone-800 dark:text-stone-100'
: 'text-stone-500 dark:text-stone-400'" : 'text-stone-500 dark:text-stone-400'
"
@click="activeTab = 'people'" @click="activeTab = 'people'"
> >
People &amp; balances People &amp; balances
@@ -146,9 +182,11 @@ async function copyLink() {
<button <button
type="button" type="button"
class="rounded-lg py-2 text-sm font-medium transition-colors" class="rounded-lg py-2 text-sm font-medium transition-colors"
:class="activeTab === 'expenses' :class="
activeTab === 'expenses'
? 'bg-white text-stone-900 shadow-sm dark:bg-stone-800 dark:text-stone-100' ? 'bg-white text-stone-900 shadow-sm dark:bg-stone-800 dark:text-stone-100'
: 'text-stone-500 dark:text-stone-400'" : 'text-stone-500 dark:text-stone-400'
"
@click="activeTab = 'expenses'" @click="activeTab = 'expenses'"
> >
Expenses Expenses
+53 -35
View File
@@ -1,49 +1,49 @@
<script setup lang="ts"> <script setup lang="ts">
import type { PotView } from '~/types' import type { PotView } from '~/types';
const route = useRoute() const route = useRoute();
const slug = route.params.slug as string const slug = route.params.slug as string;
const { data, refresh, error } = await useFetch<PotView>(`/api/pots/${slug}`) const { data, refresh, error } = await useFetch<PotView>(`/api/pots/${slug}`);
const adding = ref(false) const adding = ref(false);
const removingId = ref<number | null>(null) const removingId = ref<number | null>(null);
const removeError = ref('') const removeError = ref('');
async function addParticipant(participantName: string) { async function addParticipant(participantName: string) {
adding.value = true adding.value = true;
try { try {
await $fetch(`/api/pots/${slug}/participants`, { method: 'POST', body: { name: participantName } }) await $fetch(`/api/pots/${slug}/participants`, {
await refresh() method: 'POST',
} body: { name: participantName },
finally { });
adding.value = false await refresh();
} finally {
adding.value = false;
} }
} }
async function removeParticipant(participant: { id: number, name: string }) { async function removeParticipant(participant: { id: number; name: string }) {
if (!window.confirm(`Remove ${participant.name} from this Pot?`)) return if (!window.confirm(`Remove ${participant.name} from this Pot?`)) return;
removeError.value = '' removeError.value = '';
removingId.value = participant.id removingId.value = participant.id;
try { try {
await $fetch(`/api/pots/${slug}/participants/${participant.id}`, { method: 'DELETE' }) await $fetch(`/api/pots/${slug}/participants/${participant.id}`, {
await refresh() method: 'DELETE',
} });
catch { await refresh();
removeError.value = `Couldn't remove ${participant.name}. They may have expenses or payments recorded.` } catch {
} removeError.value = `Couldn't remove ${participant.name}. They may have expenses or payments recorded.`;
finally { } finally {
removingId.value = null removingId.value = null;
} }
} }
</script> </script>
<template> <template>
<div v-if="error" class="space-y-3 text-center"> <div v-if="error" class="space-y-3 text-center">
<p class="text-rose-600 dark:text-rose-400"> <p class="text-rose-600 dark:text-rose-400">This Pot couldn't be found.</p>
This Pot couldn't be found.
</p>
<NuxtLink to="/" class="font-medium text-orange-600 dark:text-orange-400"> <NuxtLink to="/" class="font-medium text-orange-600 dark:text-orange-400">
Go home Go home
</NuxtLink> </NuxtLink>
@@ -57,7 +57,11 @@ async function removeParticipant(participant: { id: number, name: string }) {
aria-label="Back to Pot" aria-label="Back to Pot"
> >
<svg class="h-4.5 w-4.5" viewBox="0 0 20 20" fill="currentColor"> <svg class="h-4.5 w-4.5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M12.79 5.23a.75.75 0 0 1 0 1.06L9.06 10l3.73 3.71a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd" /> <path
fill-rule="evenodd"
d="M12.79 5.23a.75.75 0 0 1 0 1.06L9.06 10l3.73 3.71a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z"
clip-rule="evenodd"
/>
</svg> </svg>
</NuxtLink> </NuxtLink>
<div> <div>
@@ -71,7 +75,9 @@ async function removeParticipant(participant: { id: number, name: string }) {
</div> </div>
<section class="space-y-3"> <section class="space-y-3">
<h2 class="text-sm font-semibold uppercase tracking-wide text-stone-500 dark:text-stone-400"> <h2
class="text-sm font-semibold uppercase tracking-wide text-stone-500 dark:text-stone-400"
>
Participants Participants
</h2> </h2>
<ul class="space-y-2"> <ul class="space-y-2">
@@ -80,10 +86,15 @@ async function removeParticipant(participant: { id: number, name: string }) {
:key="participant.id" :key="participant.id"
class="flex items-center gap-3 rounded-2xl border border-stone-200 bg-white p-3 shadow-sm dark:border-stone-800 dark:bg-stone-900" class="flex items-center gap-3 rounded-2xl border border-stone-200 bg-white p-3 shadow-sm dark:border-stone-800 dark:bg-stone-900"
> >
<div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-orange-100 text-sm font-semibold text-orange-700 dark:bg-orange-900/40 dark:text-orange-300"> <div
class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-orange-100 text-sm font-semibold text-orange-700 dark:bg-orange-900/40 dark:text-orange-300"
>
{{ participant.name.trim().charAt(0).toUpperCase() || '?' }} {{ participant.name.trim().charAt(0).toUpperCase() || '?' }}
</div> </div>
<span class="min-w-0 flex-1 truncate font-medium text-stone-900 dark:text-stone-100">{{ participant.name }}</span> <span
class="min-w-0 flex-1 truncate font-medium text-stone-900 dark:text-stone-100"
>{{ participant.name }}</span
>
<button <button
type="button" type="button"
:disabled="removingId === participant.id" :disabled="removingId === participant.id"
@@ -93,7 +104,10 @@ async function removeParticipant(participant: { id: number, name: string }) {
{{ removingId === participant.id ? 'Removing' : 'Remove' }} {{ removingId === participant.id ? 'Removing' : 'Remove' }}
</button> </button>
</li> </li>
<li v-if="data.participants.length === 0" class="rounded-2xl border border-dashed border-stone-300 p-4 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400"> <li
v-if="data.participants.length === 0"
class="rounded-2xl border border-dashed border-stone-300 p-4 text-center text-sm text-stone-500 dark:border-stone-700 dark:text-stone-400"
>
No one's in this Pot yet. No one's in this Pot yet.
</li> </li>
</ul> </ul>
@@ -102,8 +116,12 @@ async function removeParticipant(participant: { id: number, name: string }) {
</p> </p>
</section> </section>
<section class="space-y-3 rounded-2xl border border-stone-200 bg-white p-4 shadow-sm dark:border-stone-800 dark:bg-stone-900"> <section
<h2 class="text-sm font-semibold uppercase tracking-wide text-stone-500 dark:text-stone-400"> class="space-y-3 rounded-2xl border border-stone-200 bg-white p-4 shadow-sm dark:border-stone-800 dark:bg-stone-900"
>
<h2
class="text-sm font-semibold uppercase tracking-wide text-stone-500 dark:text-stone-400"
>
Add a participant Add a participant
</h2> </h2>
<NameForm <NameForm
+13 -16
View File
@@ -1,41 +1,38 @@
<script setup lang="ts"> <script setup lang="ts">
const route = useRoute() const route = useRoute();
const slug = route.params.slug as string const slug = route.params.slug as string;
const names = ref(['']) const names = ref(['']);
const saving = ref(false) const saving = ref(false);
function addRow() { function addRow() {
names.value.push('') names.value.push('');
} }
async function continueToPot() { async function continueToPot() {
saving.value = true saving.value = true;
const toAdd = names.value.map(n => n.trim()).filter(Boolean) const toAdd = names.value.map((n) => n.trim()).filter(Boolean);
try { try {
for (const participantName of toAdd) { for (const participantName of toAdd) {
await $fetch(`/api/pots/${slug}/participants`, { await $fetch(`/api/pots/${slug}/participants`, {
method: 'POST', method: 'POST',
body: { name: participantName }, body: { name: participantName },
}) });
} }
} } finally {
finally { await navigateTo(`/p/${slug}`);
await navigateTo(`/p/${slug}`)
} }
} }
function skip() { function skip() {
navigateTo(`/p/${slug}`) navigateTo(`/p/${slug}`);
} }
</script> </script>
<template> <template>
<div class="space-y-6"> <div class="space-y-6">
<div class="space-y-1 text-center"> <div class="space-y-1 text-center">
<div class="text-3xl"> <div class="text-3xl">👋</div>
👋
</div>
<h1 class="text-xl font-bold text-stone-900 dark:text-stone-100"> <h1 class="text-xl font-bold text-stone-900 dark:text-stone-100">
Add the rest of the group Add the rest of the group
</h1> </h1>
@@ -52,7 +49,7 @@ function skip() {
type="text" type="text"
class="block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900" class="block w-full rounded-xl border border-stone-300 bg-white px-3 py-2 text-base text-stone-900 shadow-sm placeholder:text-stone-400 focus:border-orange-400 focus:outline-none focus:ring-2 focus:ring-orange-200 dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100 dark:placeholder:text-stone-500 dark:focus:ring-orange-900"
placeholder="Participant name" placeholder="Participant name"
> />
</div> </div>
<button <button
+19 -19
View File
@@ -1,31 +1,31 @@
export interface ParticipantView { export interface ParticipantView {
id: number id: number;
name: string name: string;
paymentLink: string | null paymentLink: string | null;
} }
export type ExpenseType = 'expense' | 'payment' export type ExpenseType = 'expense' | 'payment';
export interface ExpenseView { export interface ExpenseView {
id: number id: number;
type: ExpenseType type: ExpenseType;
description: string description: string;
amountCents: number amountCents: number;
payerId: number payerId: number;
participantIds: number[] participantIds: number[];
createdAt: number createdAt: number;
} }
export interface SettlementView { export interface SettlementView {
fromId: number fromId: number;
toId: number toId: number;
amountCents: number amountCents: number;
} }
export interface PotView { export interface PotView {
pot: { slug: string, name: string, currency: string } pot: { slug: string; name: string; currency: string };
participants: ParticipantView[] participants: ParticipantView[];
expenses: ExpenseView[] expenses: ExpenseView[];
netBalances: Record<number, number> netBalances: Record<number, number>;
settlements: SettlementView[] settlements: SettlementView[];
} }
+27 -25
View File
@@ -1,45 +1,47 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { readIdentity, writeIdentity } from './identity' import { readIdentity, writeIdentity } from './identity';
function createMockStorage(): Storage { function createMockStorage(): Storage {
const store = new Map<string, string>() const store = new Map<string, string>();
return { return {
getItem: (key: string) => store.get(key) ?? null, getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => void store.set(key, value), setItem: (key: string, value: string) => void store.set(key, value),
removeItem: (key: string) => void store.delete(key), removeItem: (key: string) => void store.delete(key),
clear: () => store.clear(), clear: () => store.clear(),
key: () => null, key: () => null,
get length() { return store.size }, get length() {
} return store.size;
},
};
} }
describe('identity storage', () => { describe('identity storage', () => {
it('returns null when nothing is stored', () => { it('returns null when nothing is stored', () => {
expect(readIdentity(createMockStorage())).toBeNull() expect(readIdentity(createMockStorage())).toBeNull();
}) });
it('round-trips a written identity', () => { it('round-trips a written identity', () => {
const storage = createMockStorage() const storage = createMockStorage();
writeIdentity(storage, { name: 'Alice' }) writeIdentity(storage, { name: 'Alice' });
expect(readIdentity(storage)).toEqual({ name: 'Alice' }) expect(readIdentity(storage)).toEqual({ name: 'Alice' });
}) });
it('ignores malformed JSON', () => { it('ignores malformed JSON', () => {
const storage = createMockStorage() const storage = createMockStorage();
storage.setItem('stb:identity', '{not json') storage.setItem('stb:identity', '{not json');
expect(readIdentity(storage)).toBeNull() expect(readIdentity(storage)).toBeNull();
}) });
it('ignores an empty stored name', () => { it('ignores an empty stored name', () => {
const storage = createMockStorage() const storage = createMockStorage();
storage.setItem('stb:identity', JSON.stringify({ name: ' ' })) storage.setItem('stb:identity', JSON.stringify({ name: ' ' }));
expect(readIdentity(storage)).toBeNull() expect(readIdentity(storage)).toBeNull();
}) });
it('overwrites a previously stored identity', () => { it('overwrites a previously stored identity', () => {
const storage = createMockStorage() const storage = createMockStorage();
writeIdentity(storage, { name: 'Alice' }) writeIdentity(storage, { name: 'Alice' });
writeIdentity(storage, { name: 'Bob' }) writeIdentity(storage, { name: 'Bob' });
expect(readIdentity(storage)).toEqual({ name: 'Bob' }) expect(readIdentity(storage)).toEqual({ name: 'Bob' });
}) });
}) });
+11 -12
View File
@@ -1,26 +1,25 @@
const STORAGE_KEY = 'stb:identity' const STORAGE_KEY = 'stb:identity';
export interface Identity { export interface Identity {
name: string name: string;
} }
type StorageLike = Pick<Storage, 'getItem' | 'setItem'> type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
export function readIdentity(storage: StorageLike): Identity | null { export function readIdentity(storage: StorageLike): Identity | null {
const raw = storage.getItem(STORAGE_KEY) const raw = storage.getItem(STORAGE_KEY);
if (!raw) return null if (!raw) return null;
try { try {
const parsed = JSON.parse(raw) const parsed = JSON.parse(raw);
if (typeof parsed?.name !== 'string' || !parsed.name.trim()) return null if (typeof parsed?.name !== 'string' || !parsed.name.trim()) return null;
return { name: parsed.name } return { name: parsed.name };
} } catch {
catch { return null;
return null
} }
} }
export function writeIdentity(storage: StorageLike, identity: Identity): void { export function writeIdentity(storage: StorageLike, identity: Identity): void {
storage.setItem(STORAGE_KEY, JSON.stringify(identity)) storage.setItem(STORAGE_KEY, JSON.stringify(identity));
} }
+22 -17
View File
@@ -1,33 +1,38 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { readCachedPaymentLink, writeCachedPaymentLink } from './paymentLinkCache' import {
readCachedPaymentLink,
writeCachedPaymentLink,
} from './paymentLinkCache';
function createMockStorage(): Storage { function createMockStorage(): Storage {
const store = new Map<string, string>() const store = new Map<string, string>();
return { return {
getItem: (key: string) => store.get(key) ?? null, getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => void store.set(key, value), setItem: (key: string, value: string) => void store.set(key, value),
removeItem: (key: string) => void store.delete(key), removeItem: (key: string) => void store.delete(key),
clear: () => store.clear(), clear: () => store.clear(),
key: () => null, key: () => null,
get length() { return store.size }, get length() {
} return store.size;
},
};
} }
describe('payment link cache', () => { describe('payment link cache', () => {
it('returns null when nothing is cached', () => { it('returns null when nothing is cached', () => {
expect(readCachedPaymentLink(createMockStorage())).toBeNull() expect(readCachedPaymentLink(createMockStorage())).toBeNull();
}) });
it('round-trips a cached link', () => { it('round-trips a cached link', () => {
const storage = createMockStorage() const storage = createMockStorage();
writeCachedPaymentLink(storage, 'https://paypal.me/alice') writeCachedPaymentLink(storage, 'https://paypal.me/alice');
expect(readCachedPaymentLink(storage)).toBe('https://paypal.me/alice') expect(readCachedPaymentLink(storage)).toBe('https://paypal.me/alice');
}) });
it('overwrites a previously cached link', () => { it('overwrites a previously cached link', () => {
const storage = createMockStorage() const storage = createMockStorage();
writeCachedPaymentLink(storage, 'https://paypal.me/alice') writeCachedPaymentLink(storage, 'https://paypal.me/alice');
writeCachedPaymentLink(storage, 'https://paypal.me/bob') writeCachedPaymentLink(storage, 'https://paypal.me/bob');
expect(readCachedPaymentLink(storage)).toBe('https://paypal.me/bob') expect(readCachedPaymentLink(storage)).toBe('https://paypal.me/bob');
}) });
}) });
+8 -5
View File
@@ -1,11 +1,14 @@
const STORAGE_KEY = 'stb:last-payment-link' const STORAGE_KEY = 'stb:last-payment-link';
type StorageLike = Pick<Storage, 'getItem' | 'setItem'> type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
export function readCachedPaymentLink(storage: StorageLike): string | null { export function readCachedPaymentLink(storage: StorageLike): string | null {
return storage.getItem(STORAGE_KEY) || null return storage.getItem(STORAGE_KEY) || null;
} }
export function writeCachedPaymentLink(storage: StorageLike, link: string): void { export function writeCachedPaymentLink(
storage.setItem(STORAGE_KEY, link) storage: StorageLike,
link: string,
): void {
storage.setItem(STORAGE_KEY, link);
} }
+76 -38
View File
@@ -1,67 +1,105 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { readVisitedPots, recordVisitedPot } from './visitedPots' import { readVisitedPots, recordVisitedPot } from './visitedPots';
function createMockStorage(): Storage { function createMockStorage(): Storage {
const store = new Map<string, string>() const store = new Map<string, string>();
return { return {
getItem: (key: string) => store.get(key) ?? null, getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => void store.set(key, value), setItem: (key: string, value: string) => void store.set(key, value),
removeItem: (key: string) => void store.delete(key), removeItem: (key: string) => void store.delete(key),
clear: () => store.clear(), clear: () => store.clear(),
key: () => null, key: () => null,
get length() { return store.size }, get length() {
} return store.size;
},
};
} }
describe('visited pots storage', () => { describe('visited pots storage', () => {
it('returns an empty list when nothing is stored', () => { it('returns an empty list when nothing is stored', () => {
expect(readVisitedPots(createMockStorage())).toEqual([]) expect(readVisitedPots(createMockStorage())).toEqual([]);
}) });
it('records a visited pot', () => { it('records a visited pot', () => {
const storage = createMockStorage() const storage = createMockStorage();
recordVisitedPot(storage, { slug: 'abc', name: 'Lisbon Trip', currency: 'EUR' }) recordVisitedPot(storage, {
slug: 'abc',
name: 'Lisbon Trip',
currency: 'EUR',
});
expect(readVisitedPots(storage)).toEqual([ expect(readVisitedPots(storage)).toEqual([
expect.objectContaining({ slug: 'abc', name: 'Lisbon Trip', currency: 'EUR' }), expect.objectContaining({
]) slug: 'abc',
}) name: 'Lisbon Trip',
currency: 'EUR',
}),
]);
});
it('moves a re-visited pot to the front instead of duplicating it', () => { it('moves a re-visited pot to the front instead of duplicating it', () => {
const storage = createMockStorage() const storage = createMockStorage();
recordVisitedPot(storage, { slug: 'abc', name: 'Lisbon Trip', currency: 'EUR' }) recordVisitedPot(storage, {
recordVisitedPot(storage, { slug: 'def', name: 'Ski Weekend', currency: 'CHF' }) slug: 'abc',
recordVisitedPot(storage, { slug: 'abc', name: 'Lisbon Trip', currency: 'EUR' }) name: 'Lisbon Trip',
currency: 'EUR',
});
recordVisitedPot(storage, {
slug: 'def',
name: 'Ski Weekend',
currency: 'CHF',
});
recordVisitedPot(storage, {
slug: 'abc',
name: 'Lisbon Trip',
currency: 'EUR',
});
const pots = readVisitedPots(storage) const pots = readVisitedPots(storage);
expect(pots).toHaveLength(2) expect(pots).toHaveLength(2);
expect(pots[0]?.slug).toBe('abc') expect(pots[0]?.slug).toBe('abc');
}) });
it('updates the stored name and currency on revisit', () => { it('updates the stored name and currency on revisit', () => {
const storage = createMockStorage() const storage = createMockStorage();
recordVisitedPot(storage, { slug: 'abc', name: 'Old Name', currency: 'EUR' }) recordVisitedPot(storage, {
recordVisitedPot(storage, { slug: 'abc', name: 'New Name', currency: 'USD' }) slug: 'abc',
name: 'Old Name',
currency: 'EUR',
});
recordVisitedPot(storage, {
slug: 'abc',
name: 'New Name',
currency: 'USD',
});
expect(readVisitedPots(storage)).toEqual([ expect(readVisitedPots(storage)).toEqual([
expect.objectContaining({ slug: 'abc', name: 'New Name', currency: 'USD' }), expect.objectContaining({
]) slug: 'abc',
}) name: 'New Name',
currency: 'USD',
}),
]);
});
it('ignores malformed JSON', () => { it('ignores malformed JSON', () => {
const storage = createMockStorage() const storage = createMockStorage();
storage.setItem('stb:visited-pots', '{not json') storage.setItem('stb:visited-pots', '{not json');
expect(readVisitedPots(storage)).toEqual([]) expect(readVisitedPots(storage)).toEqual([]);
}) });
it('caps the list at 20 entries, keeping the most recent', () => { it('caps the list at 20 entries, keeping the most recent', () => {
const storage = createMockStorage() const storage = createMockStorage();
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
recordVisitedPot(storage, { slug: `pot-${i}`, name: `Pot ${i}`, currency: 'EUR' }) recordVisitedPot(storage, {
slug: `pot-${i}`,
name: `Pot ${i}`,
currency: 'EUR',
});
} }
const pots = readVisitedPots(storage) const pots = readVisitedPots(storage);
expect(pots).toHaveLength(20) expect(pots).toHaveLength(20);
expect(pots[0]?.slug).toBe('pot-24') expect(pots[0]?.slug).toBe('pot-24');
expect(pots.some(p => p.slug === 'pot-0')).toBe(false) expect(pots.some((p) => p.slug === 'pot-0')).toBe(false);
}) });
}) });
+29 -25
View File
@@ -1,40 +1,44 @@
const STORAGE_KEY = 'stb:visited-pots' const STORAGE_KEY = 'stb:visited-pots';
const MAX_ENTRIES = 20 const MAX_ENTRIES = 20;
export interface VisitedPot { export interface VisitedPot {
slug: string slug: string;
name: string name: string;
currency: string currency: string;
visitedAt: number visitedAt: number;
} }
type StorageLike = Pick<Storage, 'getItem' | 'setItem'> type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
export function readVisitedPots(storage: StorageLike): VisitedPot[] { export function readVisitedPots(storage: StorageLike): VisitedPot[] {
const raw = storage.getItem(STORAGE_KEY) const raw = storage.getItem(STORAGE_KEY);
if (!raw) return [] if (!raw) return [];
try { try {
const parsed = JSON.parse(raw) const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [] if (!Array.isArray(parsed)) return [];
return parsed.filter((item): item is VisitedPot => return parsed.filter(
typeof item?.slug === 'string' && item.slug.trim() !== '' (item): item is VisitedPot =>
&& typeof item?.name === 'string' typeof item?.slug === 'string' &&
&& typeof item?.currency === 'string' item.slug.trim() !== '' &&
&& typeof item?.visitedAt === 'number', typeof item?.name === 'string' &&
) typeof item?.currency === 'string' &&
} typeof item?.visitedAt === 'number',
catch { );
return [] } catch {
return [];
} }
} }
export function recordVisitedPot(storage: StorageLike, pot: Omit<VisitedPot, 'visitedAt'>): VisitedPot[] { export function recordVisitedPot(
const rest = readVisitedPots(storage).filter(p => p.slug !== pot.slug) storage: StorageLike,
pot: Omit<VisitedPot, 'visitedAt'>,
): VisitedPot[] {
const rest = readVisitedPots(storage).filter((p) => p.slug !== pot.slug);
const updated = [{ ...pot, visitedAt: Date.now() }, ...rest] const updated = [{ ...pot, visitedAt: Date.now() }, ...rest]
.sort((a, b) => b.visitedAt - a.visitedAt) .sort((a, b) => b.visitedAt - a.visitedAt)
.slice(0, MAX_ENTRIES) .slice(0, MAX_ENTRIES);
storage.setItem(STORAGE_KEY, JSON.stringify(updated)) storage.setItem(STORAGE_KEY, JSON.stringify(updated));
return updated return updated;
} }
+5 -4
View File
@@ -1,11 +1,12 @@
import { defineConfig } from 'drizzle-kit' import { defineConfig } from 'drizzle-kit';
import 'dotenv/config';
export default defineConfig({ export default defineConfig({
dialect: 'turso', dialect: 'turso',
schema: './server/database/schema.ts', schema: './server/database/schema.ts',
out: './server/database/migrations', out: './server/database/migrations',
dbCredentials: { dbCredentials: {
url: process.env.DATABASE_URL || 'file:./.data/db.sqlite', url: process.env.NUXT_DATABASE_URL || 'file:./.data/db.sqlite',
authToken: process.env.DATABASE_AUTH_TOKEN, authToken: process.env.NUXT_DATABASE_AUTH_TOKEN,
}, },
}) });
+6 -4
View File
@@ -1,4 +1,4 @@
import tailwindcss from '@tailwindcss/vite' import tailwindcss from '@tailwindcss/vite';
// https://nuxt.com/docs/api/configuration/nuxt-config // https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({ export default defineNuxtConfig({
@@ -9,7 +9,9 @@ export default defineNuxtConfig({
plugins: [tailwindcss()], plugins: [tailwindcss()],
}, },
runtimeConfig: { runtimeConfig: {
databaseUrl: process.env.DATABASE_URL || 'file:./.data/db.sqlite', database: {
databaseAuthToken: process.env.DATABASE_AUTH_TOKEN || '', url: 'file:./.data/db.sqlite',
authToken: '',
}, },
}) },
});
+1
View File
@@ -22,6 +22,7 @@
"@nuxt/test-utils": "^4.1.0", "@nuxt/test-utils": "^4.1.0",
"@tailwindcss/vite": "^4.3.3", "@tailwindcss/vite": "^4.3.3",
"drizzle-kit": "^0.31.10", "drizzle-kit": "^0.31.10",
"prettier": "^3.9.6",
"tailwindcss": "^4.3.3", "tailwindcss": "^4.3.3",
"typescript": "^6.0.2", "typescript": "^6.0.2",
"vitest": "^4.1.10", "vitest": "^4.1.10",
+3409 -852
View File
File diff suppressed because it is too large Load Diff
+24 -14
View File
@@ -1,22 +1,32 @@
import { generateSlug } from '~~/shared/utils/slug' import { generateSlug } from '~~/shared/utils/slug';
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { participants, pots } from '~~/server/database/schema' import { participants, pots } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const body = await readBody(event) const body = await readBody(event);
const name = typeof body?.name === 'string' ? body.name.trim() : '' const name = typeof body?.name === 'string' ? body.name.trim() : '';
const currency = typeof body?.currency === 'string' ? body.currency.trim().toUpperCase() : '' const currency =
const creatorName = typeof body?.creatorName === 'string' ? body.creatorName.trim() : '' typeof body?.currency === 'string'
? body.currency.trim().toUpperCase()
: '';
const creatorName =
typeof body?.creatorName === 'string' ? body.creatorName.trim() : '';
if (!name || !currency || !creatorName) { if (!name || !currency || !creatorName) {
throw createError({ statusCode: 400, statusMessage: 'name, currency and creatorName are required' }) throw createError({
statusCode: 400,
statusMessage: 'name, currency and creatorName are required',
});
} }
const db = useDb() const db = useDb(event);
const slug = generateSlug() const slug = generateSlug();
await db.insert(pots).values({ slug, name, currency }) await db.insert(pots).values({ slug, name, currency });
const [creator] = await db.insert(participants).values({ potSlug: slug, name: creatorName }).returning() const [creator] = await db
.insert(participants)
.values({ potSlug: slug, name: creatorName })
.returning();
return { slug, name, currency, creator } return { slug, name, currency, creator };
}) });
+11 -8
View File
@@ -1,12 +1,15 @@
import { calculateBalances } from '~~/shared/utils/balances' import { calculateBalances } from '~~/shared/utils/balances';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
const pot = await getPotOrThrow(slug) const pot = await getPotOrThrow(slug);
const participants = await getParticipants(slug) const participants = await getParticipants(slug);
const expenses = await getExpensesWithParticipants(slug) const expenses = await getExpensesWithParticipants(slug);
const { netBalances, settlements } = calculateBalances(participants, expenses) const { netBalances, settlements } = calculateBalances(
participants,
expenses,
);
return { pot, participants, expenses, netBalances, settlements } return { pot, participants, expenses, netBalances, settlements };
}) });
+48 -21
View File
@@ -1,35 +1,62 @@
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { expenseParticipants, expenses } from '~~/server/database/schema' import { expenseParticipants, expenses } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
await getPotOrThrow(slug) await getPotOrThrow(slug);
const body = await readBody(event) const body = await readBody(event);
const description = typeof body?.description === 'string' ? body.description.trim() : '' const description =
const amountCents = Number(body?.amountCents) typeof body?.description === 'string' ? body.description.trim() : '';
const payerId = Number(body?.payerId) const amountCents = Number(body?.amountCents);
const participantIds: number[] = Array.isArray(body?.participantIds) ? body.participantIds.map(Number) : [] const payerId = Number(body?.payerId);
const participantIds: number[] = Array.isArray(body?.participantIds)
? body.participantIds.map(Number)
: [];
if (!description) { if (!description) {
throw createError({ statusCode: 400, statusMessage: 'description is required' }) throw createError({
statusCode: 400,
statusMessage: 'description is required',
});
} }
if (!Number.isInteger(amountCents) || amountCents <= 0) { if (!Number.isInteger(amountCents) || amountCents <= 0) {
throw createError({ statusCode: 400, statusMessage: 'amountCents must be a positive integer' }) throw createError({
statusCode: 400,
statusMessage: 'amountCents must be a positive integer',
});
} }
if (participantIds.length === 0) { if (participantIds.length === 0) {
throw createError({ statusCode: 400, statusMessage: 'at least one participant must be selected' }) throw createError({
statusCode: 400,
statusMessage: 'at least one participant must be selected',
});
} }
const potParticipants = await getParticipants(slug) const potParticipants = await getParticipants(slug);
const validIds = new Set(potParticipants.map(p => p.id)) const validIds = new Set(potParticipants.map((p) => p.id));
if (!validIds.has(payerId) || participantIds.some(id => !validIds.has(id))) { if (
throw createError({ statusCode: 400, statusMessage: 'payerId and participantIds must reference participants of this Pot' }) !validIds.has(payerId) ||
participantIds.some((id) => !validIds.has(id))
) {
throw createError({
statusCode: 400,
statusMessage:
'payerId and participantIds must reference participants of this Pot',
});
} }
const db = useDb() const db = useDb(event);
const [expense] = await db.insert(expenses).values({ potSlug: slug, description, amountCents, payerId }).returning() const [expense] = await db
await db.insert(expenseParticipants).values(participantIds.map(participantId => ({ expenseId: expense!.id, participantId }))) .insert(expenses)
.values({ potSlug: slug, description, amountCents, payerId })
.returning();
await db.insert(expenseParticipants).values(
participantIds.map((participantId) => ({
expenseId: expense!.id,
participantId,
})),
);
return { ...expense, participantIds } return { ...expense, participantIds };
}) });
+18 -13
View File
@@ -1,20 +1,25 @@
import { and, eq } from 'drizzle-orm' import { and, eq } from 'drizzle-orm';
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { expenseParticipants, expenses } from '~~/server/database/schema' import { expenseParticipants, expenses } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
const id = Number(getRouterParam(event, 'id')) const id = Number(getRouterParam(event, 'id'));
await getPotOrThrow(slug) await getPotOrThrow(slug);
const db = useDb() const db = useDb(event);
const [existing] = await db.select().from(expenses).where(and(eq(expenses.id, id), eq(expenses.potSlug, slug))) const [existing] = await db
.select()
.from(expenses)
.where(and(eq(expenses.id, id), eq(expenses.potSlug, slug)));
if (!existing) { if (!existing) {
throw createError({ statusCode: 404, statusMessage: 'Expense not found' }) throw createError({ statusCode: 404, statusMessage: 'Expense not found' });
} }
await db.delete(expenseParticipants).where(eq(expenseParticipants.expenseId, id)) await db
await db.delete(expenses).where(eq(expenses.id, id)) .delete(expenseParticipants)
.where(eq(expenseParticipants.expenseId, id));
await db.delete(expenses).where(eq(expenses.id, id));
return { success: true } return { success: true };
}) });
+57 -26
View File
@@ -1,43 +1,74 @@
import { and, eq } from 'drizzle-orm' import { and, eq } from 'drizzle-orm';
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { expenseParticipants, expenses } from '~~/server/database/schema' import { expenseParticipants, expenses } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
const id = Number(getRouterParam(event, 'id')) const id = Number(getRouterParam(event, 'id'));
await getPotOrThrow(slug) await getPotOrThrow(slug);
const body = await readBody(event) const body = await readBody(event);
const description = typeof body?.description === 'string' ? body.description.trim() : '' const description =
const amountCents = Number(body?.amountCents) typeof body?.description === 'string' ? body.description.trim() : '';
const payerId = Number(body?.payerId) const amountCents = Number(body?.amountCents);
const participantIds: number[] = Array.isArray(body?.participantIds) ? body.participantIds.map(Number) : [] const payerId = Number(body?.payerId);
const participantIds: number[] = Array.isArray(body?.participantIds)
? body.participantIds.map(Number)
: [];
if (!description) { if (!description) {
throw createError({ statusCode: 400, statusMessage: 'description is required' }) throw createError({
statusCode: 400,
statusMessage: 'description is required',
});
} }
if (!Number.isInteger(amountCents) || amountCents <= 0) { if (!Number.isInteger(amountCents) || amountCents <= 0) {
throw createError({ statusCode: 400, statusMessage: 'amountCents must be a positive integer' }) throw createError({
statusCode: 400,
statusMessage: 'amountCents must be a positive integer',
});
} }
if (participantIds.length === 0) { if (participantIds.length === 0) {
throw createError({ statusCode: 400, statusMessage: 'at least one participant must be selected' }) throw createError({
statusCode: 400,
statusMessage: 'at least one participant must be selected',
});
} }
const potParticipants = await getParticipants(slug) const potParticipants = await getParticipants(slug);
const validIds = new Set(potParticipants.map(p => p.id)) const validIds = new Set(potParticipants.map((p) => p.id));
if (!validIds.has(payerId) || participantIds.some(pid => !validIds.has(pid))) { if (
throw createError({ statusCode: 400, statusMessage: 'payerId and participantIds must reference participants of this Pot' }) !validIds.has(payerId) ||
participantIds.some((pid) => !validIds.has(pid))
) {
throw createError({
statusCode: 400,
statusMessage:
'payerId and participantIds must reference participants of this Pot',
});
} }
const db = useDb() const db = useDb(event);
const [existing] = await db.select().from(expenses).where(and(eq(expenses.id, id), eq(expenses.potSlug, slug))) const [existing] = await db
.select()
.from(expenses)
.where(and(eq(expenses.id, id), eq(expenses.potSlug, slug)));
if (!existing) { if (!existing) {
throw createError({ statusCode: 404, statusMessage: 'Expense not found' }) throw createError({ statusCode: 404, statusMessage: 'Expense not found' });
} }
await db.update(expenses).set({ description, amountCents, payerId }).where(eq(expenses.id, id)) await db
await db.delete(expenseParticipants).where(eq(expenseParticipants.expenseId, id)) .update(expenses)
await db.insert(expenseParticipants).values(participantIds.map(participantId => ({ expenseId: id, participantId }))) .set({ description, amountCents, payerId })
.where(eq(expenses.id, id));
await db
.delete(expenseParticipants)
.where(eq(expenseParticipants.expenseId, id));
await db
.insert(expenseParticipants)
.values(
participantIds.map((participantId) => ({ expenseId: id, participantId })),
);
return { id, description, amountCents, payerId, participantIds } return { id, description, amountCents, payerId, participantIds };
}) });
+14 -11
View File
@@ -1,17 +1,20 @@
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { participants } from '~~/server/database/schema' import { participants } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
await getPotOrThrow(slug) await getPotOrThrow(slug);
const body = await readBody(event) const body = await readBody(event);
const name = typeof body?.name === 'string' ? body.name.trim() : '' const name = typeof body?.name === 'string' ? body.name.trim() : '';
if (!name) { if (!name) {
throw createError({ statusCode: 400, statusMessage: 'name is required' }) throw createError({ statusCode: 400, statusMessage: 'name is required' });
} }
const db = useDb() const db = useDb(event);
const [participant] = await db.insert(participants).values({ potSlug: slug, name }).returning() const [participant] = await db
return participant .insert(participants)
}) .values({ potSlug: slug, name })
.returning();
return participant;
});
@@ -1,25 +1,46 @@
import { and, eq } from 'drizzle-orm' import { and, eq } from 'drizzle-orm';
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { expenseParticipants, expenses, participants } from '~~/server/database/schema' import {
expenseParticipants,
expenses,
participants,
} from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
const id = Number(getRouterParam(event, 'id')) const id = Number(getRouterParam(event, 'id'));
await getPotOrThrow(slug) await getPotOrThrow(slug);
const db = useDb() const db = useDb(event);
const [existing] = await db.select().from(participants).where(and(eq(participants.id, id), eq(participants.potSlug, slug))) const [existing] = await db
.select()
.from(participants)
.where(and(eq(participants.id, id), eq(participants.potSlug, slug)));
if (!existing) { if (!existing) {
throw createError({ statusCode: 404, statusMessage: 'Participant not found' }) throw createError({
statusCode: 404,
statusMessage: 'Participant not found',
});
} }
const [asPayer] = await db.select().from(expenses).where(eq(expenses.payerId, id)).limit(1) const [asPayer] = await db
const [asSplit] = await db.select().from(expenseParticipants).where(eq(expenseParticipants.participantId, id)).limit(1) .select()
.from(expenses)
.where(eq(expenses.payerId, id))
.limit(1);
const [asSplit] = await db
.select()
.from(expenseParticipants)
.where(eq(expenseParticipants.participantId, id))
.limit(1);
if (asPayer || asSplit) { if (asPayer || asSplit) {
throw createError({ statusCode: 409, statusMessage: 'Cannot remove a participant with expenses or payments' }) throw createError({
statusCode: 409,
statusMessage: 'Cannot remove a participant with expenses or payments',
});
} }
await db.delete(participants).where(eq(participants.id, id)) await db.delete(participants).where(eq(participants.id, id));
return { success: true } return { success: true };
}) });
@@ -1,29 +1,40 @@
import { and, eq } from 'drizzle-orm' import { and, eq } from 'drizzle-orm';
import { isValidPaymentLink } from '~~/shared/utils/paymentLink' import { isValidPaymentLink } from '~~/shared/utils/paymentLink';
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { participants } from '~~/server/database/schema' import { participants } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
const id = Number(getRouterParam(event, 'id')) const id = Number(getRouterParam(event, 'id'));
await getPotOrThrow(slug) await getPotOrThrow(slug);
const body = await readBody(event) const body = await readBody(event);
const paymentLink = typeof body?.paymentLink === 'string' ? body.paymentLink.trim() : '' const paymentLink =
typeof body?.paymentLink === 'string' ? body.paymentLink.trim() : '';
if (paymentLink && !isValidPaymentLink(paymentLink)) { if (paymentLink && !isValidPaymentLink(paymentLink)) {
throw createError({ statusCode: 400, statusMessage: 'paymentLink must be a valid http(s) URL' }) throw createError({
statusCode: 400,
statusMessage: 'paymentLink must be a valid http(s) URL',
});
} }
const db = useDb() const db = useDb(event);
const [existing] = await db.select().from(participants).where(and(eq(participants.id, id), eq(participants.potSlug, slug))) const [existing] = await db
.select()
.from(participants)
.where(and(eq(participants.id, id), eq(participants.potSlug, slug)));
if (!existing) { if (!existing) {
throw createError({ statusCode: 404, statusMessage: 'Participant not found' }) throw createError({
statusCode: 404,
statusMessage: 'Participant not found',
});
} }
const [updated] = await db.update(participants) const [updated] = await db
.update(participants)
.set({ paymentLink: paymentLink || null }) .set({ paymentLink: paymentLink || null })
.where(eq(participants.id, id)) .where(eq(participants.id, id))
.returning() .returning();
return updated return updated;
}) });
+38 -20
View File
@@ -1,33 +1,51 @@
import { useDb } from '~~/server/database/client' import { useDb } from '~~/server/database/client';
import { expenseParticipants, expenses } from '~~/server/database/schema' import { expenseParticipants, expenses } from '~~/server/database/schema';
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')! const slug = getRouterParam(event, 'slug')!;
await getPotOrThrow(slug) await getPotOrThrow(slug);
const body = await readBody(event) const body = await readBody(event);
const fromId = Number(body?.fromId) const fromId = Number(body?.fromId);
const toId = Number(body?.toId) const toId = Number(body?.toId);
const amountCents = Number(body?.amountCents) const amountCents = Number(body?.amountCents);
if (!Number.isInteger(amountCents) || amountCents <= 0) { if (!Number.isInteger(amountCents) || amountCents <= 0) {
throw createError({ statusCode: 400, statusMessage: 'amountCents must be a positive integer' }) throw createError({
statusCode: 400,
statusMessage: 'amountCents must be a positive integer',
});
} }
if (fromId === toId) { if (fromId === toId) {
throw createError({ statusCode: 400, statusMessage: 'fromId and toId must differ' }) throw createError({
statusCode: 400,
statusMessage: 'fromId and toId must differ',
});
} }
const potParticipants = await getParticipants(slug) const potParticipants = await getParticipants(slug);
const validIds = new Set(potParticipants.map(p => p.id)) const validIds = new Set(potParticipants.map((p) => p.id));
if (!validIds.has(fromId) || !validIds.has(toId)) { if (!validIds.has(fromId) || !validIds.has(toId)) {
throw createError({ statusCode: 400, statusMessage: 'fromId and toId must reference participants of this Pot' }) throw createError({
statusCode: 400,
statusMessage: 'fromId and toId must reference participants of this Pot',
});
} }
const db = useDb() const db = useDb(event);
const [payment] = await db.insert(expenses) const [payment] = await db
.values({ potSlug: slug, type: 'payment', description: 'Settlement', amountCents, payerId: fromId }) .insert(expenses)
.returning() .values({
await db.insert(expenseParticipants).values({ expenseId: payment!.id, participantId: toId }) potSlug: slug,
type: 'payment',
return { ...payment, participantIds: [toId] } description: 'Settlement',
amountCents,
payerId: fromId,
}) })
.returning();
await db
.insert(expenseParticipants)
.values({ expenseId: payment!.id, participantId: toId });
return { ...payment, participantIds: [toId] };
});
+12 -11
View File
@@ -1,17 +1,18 @@
import { createClient } from '@libsql/client' import { createClient } from '@libsql/client';
import { drizzle } from 'drizzle-orm/libsql' import { drizzle } from 'drizzle-orm/libsql';
import * as schema from './schema' import * as schema from './schema';
import type { H3Event } from 'h3';
let instance: ReturnType<typeof drizzle<typeof schema>> | undefined let instance: ReturnType<typeof drizzle<typeof schema>> | undefined;
export function useDb() { export function useDb(event: H3Event) {
if (!instance) { if (!instance) {
const config = useRuntimeConfig() const config = useRuntimeConfig(event);
const client = createClient({ const client = createClient({
url: config.databaseUrl, url: config.database.url,
authToken: config.databaseAuthToken || undefined, authToken: config.database.authToken || undefined,
}) });
instance = drizzle(client, { schema }) instance = drizzle(client, { schema });
} }
return instance return instance;
} }
@@ -25,9 +25,7 @@
"indexes": { "indexes": {
"expense_participants_expense_id_idx": { "expense_participants_expense_id_idx": {
"name": "expense_participants_expense_id_idx", "name": "expense_participants_expense_id_idx",
"columns": [ "columns": ["expense_id"],
"expense_id"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -36,12 +34,8 @@
"name": "expense_participants_expense_id_expenses_id_fk", "name": "expense_participants_expense_id_expenses_id_fk",
"tableFrom": "expense_participants", "tableFrom": "expense_participants",
"tableTo": "expenses", "tableTo": "expenses",
"columnsFrom": [ "columnsFrom": ["expense_id"],
"expense_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@@ -49,12 +43,8 @@
"name": "expense_participants_participant_id_participants_id_fk", "name": "expense_participants_participant_id_participants_id_fk",
"tableFrom": "expense_participants", "tableFrom": "expense_participants",
"tableTo": "participants", "tableTo": "participants",
"columnsFrom": [ "columnsFrom": ["participant_id"],
"participant_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -113,9 +103,7 @@
"indexes": { "indexes": {
"expenses_pot_slug_idx": { "expenses_pot_slug_idx": {
"name": "expenses_pot_slug_idx", "name": "expenses_pot_slug_idx",
"columns": [ "columns": ["pot_slug"],
"pot_slug"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -124,12 +112,8 @@
"name": "expenses_pot_slug_pots_slug_fk", "name": "expenses_pot_slug_pots_slug_fk",
"tableFrom": "expenses", "tableFrom": "expenses",
"tableTo": "pots", "tableTo": "pots",
"columnsFrom": [ "columnsFrom": ["pot_slug"],
"pot_slug" "columnsTo": ["slug"],
],
"columnsTo": [
"slug"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@@ -137,12 +121,8 @@
"name": "expenses_payer_id_participants_id_fk", "name": "expenses_payer_id_participants_id_fk",
"tableFrom": "expenses", "tableFrom": "expenses",
"tableTo": "participants", "tableTo": "participants",
"columnsFrom": [ "columnsFrom": ["payer_id"],
"payer_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -187,9 +167,7 @@
"indexes": { "indexes": {
"participants_pot_slug_idx": { "participants_pot_slug_idx": {
"name": "participants_pot_slug_idx", "name": "participants_pot_slug_idx",
"columns": [ "columns": ["pot_slug"],
"pot_slug"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -198,12 +176,8 @@
"name": "participants_pot_slug_pots_slug_fk", "name": "participants_pot_slug_pots_slug_fk",
"tableFrom": "participants", "tableFrom": "participants",
"tableTo": "pots", "tableTo": "pots",
"columnsFrom": [ "columnsFrom": ["pot_slug"],
"pot_slug" "columnsTo": ["slug"],
],
"columnsTo": [
"slug"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -25,9 +25,7 @@
"indexes": { "indexes": {
"expense_participants_expense_id_idx": { "expense_participants_expense_id_idx": {
"name": "expense_participants_expense_id_idx", "name": "expense_participants_expense_id_idx",
"columns": [ "columns": ["expense_id"],
"expense_id"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -36,12 +34,8 @@
"name": "expense_participants_expense_id_expenses_id_fk", "name": "expense_participants_expense_id_expenses_id_fk",
"tableFrom": "expense_participants", "tableFrom": "expense_participants",
"tableTo": "expenses", "tableTo": "expenses",
"columnsFrom": [ "columnsFrom": ["expense_id"],
"expense_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@@ -49,12 +43,8 @@
"name": "expense_participants_participant_id_participants_id_fk", "name": "expense_participants_participant_id_participants_id_fk",
"tableFrom": "expense_participants", "tableFrom": "expense_participants",
"tableTo": "participants", "tableTo": "participants",
"columnsFrom": [ "columnsFrom": ["participant_id"],
"participant_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -121,9 +111,7 @@
"indexes": { "indexes": {
"expenses_pot_slug_idx": { "expenses_pot_slug_idx": {
"name": "expenses_pot_slug_idx", "name": "expenses_pot_slug_idx",
"columns": [ "columns": ["pot_slug"],
"pot_slug"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -132,12 +120,8 @@
"name": "expenses_pot_slug_pots_slug_fk", "name": "expenses_pot_slug_pots_slug_fk",
"tableFrom": "expenses", "tableFrom": "expenses",
"tableTo": "pots", "tableTo": "pots",
"columnsFrom": [ "columnsFrom": ["pot_slug"],
"pot_slug" "columnsTo": ["slug"],
],
"columnsTo": [
"slug"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@@ -145,12 +129,8 @@
"name": "expenses_payer_id_participants_id_fk", "name": "expenses_payer_id_participants_id_fk",
"tableFrom": "expenses", "tableFrom": "expenses",
"tableTo": "participants", "tableTo": "participants",
"columnsFrom": [ "columnsFrom": ["payer_id"],
"payer_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -202,9 +182,7 @@
"indexes": { "indexes": {
"participants_pot_slug_idx": { "participants_pot_slug_idx": {
"name": "participants_pot_slug_idx", "name": "participants_pot_slug_idx",
"columns": [ "columns": ["pot_slug"],
"pot_slug"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -213,12 +191,8 @@
"name": "participants_pot_slug_pots_slug_fk", "name": "participants_pot_slug_pots_slug_fk",
"tableFrom": "participants", "tableFrom": "participants",
"tableTo": "pots", "tableTo": "pots",
"columnsFrom": [ "columnsFrom": ["pot_slug"],
"pot_slug" "columnsTo": ["slug"],
],
"columnsTo": [
"slug"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -25,9 +25,7 @@
"indexes": { "indexes": {
"expense_participants_expense_id_idx": { "expense_participants_expense_id_idx": {
"name": "expense_participants_expense_id_idx", "name": "expense_participants_expense_id_idx",
"columns": [ "columns": ["expense_id"],
"expense_id"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -36,12 +34,8 @@
"name": "expense_participants_expense_id_expenses_id_fk", "name": "expense_participants_expense_id_expenses_id_fk",
"tableFrom": "expense_participants", "tableFrom": "expense_participants",
"tableTo": "expenses", "tableTo": "expenses",
"columnsFrom": [ "columnsFrom": ["expense_id"],
"expense_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@@ -49,12 +43,8 @@
"name": "expense_participants_participant_id_participants_id_fk", "name": "expense_participants_participant_id_participants_id_fk",
"tableFrom": "expense_participants", "tableFrom": "expense_participants",
"tableTo": "participants", "tableTo": "participants",
"columnsFrom": [ "columnsFrom": ["participant_id"],
"participant_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -121,9 +111,7 @@
"indexes": { "indexes": {
"expenses_pot_slug_idx": { "expenses_pot_slug_idx": {
"name": "expenses_pot_slug_idx", "name": "expenses_pot_slug_idx",
"columns": [ "columns": ["pot_slug"],
"pot_slug"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -132,12 +120,8 @@
"name": "expenses_pot_slug_pots_slug_fk", "name": "expenses_pot_slug_pots_slug_fk",
"tableFrom": "expenses", "tableFrom": "expenses",
"tableTo": "pots", "tableTo": "pots",
"columnsFrom": [ "columnsFrom": ["pot_slug"],
"pot_slug" "columnsTo": ["slug"],
],
"columnsTo": [
"slug"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
@@ -145,12 +129,8 @@
"name": "expenses_payer_id_participants_id_fk", "name": "expenses_payer_id_participants_id_fk",
"tableFrom": "expenses", "tableFrom": "expenses",
"tableTo": "participants", "tableTo": "participants",
"columnsFrom": [ "columnsFrom": ["payer_id"],
"payer_id" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -202,9 +182,7 @@
"indexes": { "indexes": {
"participants_pot_slug_idx": { "participants_pot_slug_idx": {
"name": "participants_pot_slug_idx", "name": "participants_pot_slug_idx",
"columns": [ "columns": ["pot_slug"],
"pot_slug"
],
"isUnique": false "isUnique": false
} }
}, },
@@ -213,12 +191,8 @@
"name": "participants_pot_slug_pots_slug_fk", "name": "participants_pot_slug_pots_slug_fk",
"tableFrom": "participants", "tableFrom": "participants",
"tableTo": "pots", "tableTo": "pots",
"columnsFrom": [ "columnsFrom": ["pot_slug"],
"pot_slug" "columnsTo": ["slug"],
],
"columnsTo": [
"slug"
],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
} }
+45 -23
View File
@@ -1,41 +1,63 @@
import { sql } from 'drizzle-orm' import { sql } from 'drizzle-orm';
import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core' import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
export const pots = sqliteTable('pots', { export const pots = sqliteTable('pots', {
slug: text('slug').primaryKey(), slug: text('slug').primaryKey(),
name: text('name').notNull(), name: text('name').notNull(),
currency: text('currency').notNull(), currency: text('currency').notNull(),
createdAt: integer('created_at').notNull().default(sql`(unixepoch())`), createdAt: integer('created_at')
}) .notNull()
.default(sql`(unixepoch())`),
});
export const participants = sqliteTable('participants', { export const participants = sqliteTable(
'participants',
{
id: integer('id').primaryKey({ autoIncrement: true }), id: integer('id').primaryKey({ autoIncrement: true }),
potSlug: text('pot_slug').notNull().references(() => pots.slug), potSlug: text('pot_slug')
.notNull()
.references(() => pots.slug),
name: text('name').notNull(), name: text('name').notNull(),
paymentLink: text('payment_link'), paymentLink: text('payment_link'),
createdAt: integer('created_at').notNull().default(sql`(unixepoch())`), createdAt: integer('created_at')
}, table => [ .notNull()
index('participants_pot_slug_idx').on(table.potSlug), .default(sql`(unixepoch())`),
]) },
(table) => [index('participants_pot_slug_idx').on(table.potSlug)],
);
export const expenses = sqliteTable('expenses', { export const expenses = sqliteTable(
'expenses',
{
id: integer('id').primaryKey({ autoIncrement: true }), id: integer('id').primaryKey({ autoIncrement: true }),
potSlug: text('pot_slug').notNull().references(() => pots.slug), potSlug: text('pot_slug')
.notNull()
.references(() => pots.slug),
// 'payment' rows are settlements: payerId is who paid, and the single row // 'payment' rows are settlements: payerId is who paid, and the single row
// in expenseParticipants is who received it — same shape as a one-person // in expenseParticipants is who received it — same shape as a one-person
// split expense, which is mathematically what a settlement is. // split expense, which is mathematically what a settlement is.
type: text('type').notNull().default('expense'), type: text('type').notNull().default('expense'),
description: text('description').notNull(), description: text('description').notNull(),
amountCents: integer('amount_cents').notNull(), amountCents: integer('amount_cents').notNull(),
payerId: integer('payer_id').notNull().references(() => participants.id), payerId: integer('payer_id')
createdAt: integer('created_at').notNull().default(sql`(unixepoch())`), .notNull()
}, table => [ .references(() => participants.id),
index('expenses_pot_slug_idx').on(table.potSlug), createdAt: integer('created_at')
]) .notNull()
.default(sql`(unixepoch())`),
},
(table) => [index('expenses_pot_slug_idx').on(table.potSlug)],
);
export const expenseParticipants = sqliteTable('expense_participants', { export const expenseParticipants = sqliteTable(
expenseId: integer('expense_id').notNull().references(() => expenses.id), 'expense_participants',
participantId: integer('participant_id').notNull().references(() => participants.id), {
}, table => [ expenseId: integer('expense_id')
index('expense_participants_expense_id_idx').on(table.expenseId), .notNull()
]) .references(() => expenses.id),
participantId: integer('participant_id')
.notNull()
.references(() => participants.id),
},
(table) => [index('expense_participants_expense_id_idx').on(table.expenseId)],
);
+6 -4
View File
@@ -1,6 +1,8 @@
import { migrate } from 'drizzle-orm/libsql/migrator' import { migrate } from 'drizzle-orm/libsql/migrator';
import { useDb } from '../database/client' import { useDb } from '../database/client';
export default defineNitroPlugin(async () => { export default defineNitroPlugin(async () => {
await migrate(useDb(), { migrationsFolder: 'server/database/migrations' }) await migrate(useDb(event), {
}) migrationsFolder: 'server/database/migrations',
});
});
+42 -28
View File
@@ -1,47 +1,61 @@
import { eq, inArray } from 'drizzle-orm' import { eq, inArray } from 'drizzle-orm';
import { useDb } from '../database/client' import { useDb } from '../database/client';
import { expenseParticipants, expenses, participants, pots } from '../database/schema' import {
expenseParticipants,
expenses,
participants,
pots,
} from '../database/schema';
export interface ExpenseWithDetails { export interface ExpenseWithDetails {
id: number id: number;
type: string type: string;
description: string description: string;
amountCents: number amountCents: number;
payerId: number payerId: number;
participantIds: number[] participantIds: number[];
createdAt: number createdAt: number;
} }
export async function getPotOrThrow(slug: string) { export async function getPotOrThrow(slug: string) {
const db = useDb() const db = useDb(event);
const [pot] = await db.select().from(pots).where(eq(pots.slug, slug)) const [pot] = await db.select().from(pots).where(eq(pots.slug, slug));
if (!pot) { if (!pot) {
throw createError({ statusCode: 404, statusMessage: 'Pot not found' }) throw createError({ statusCode: 404, statusMessage: 'Pot not found' });
} }
return pot return pot;
} }
export async function getParticipants(slug: string) { export async function getParticipants(slug: string) {
const db = useDb() const db = useDb(event);
return db.select().from(participants).where(eq(participants.potSlug, slug)) return db.select().from(participants).where(eq(participants.potSlug, slug));
} }
export async function getExpensesWithParticipants(slug: string): Promise<ExpenseWithDetails[]> { export async function getExpensesWithParticipants(
const db = useDb() slug: string,
const expenseRows = await db.select().from(expenses).where(eq(expenses.potSlug, slug)).orderBy(expenses.createdAt) ): Promise<ExpenseWithDetails[]> {
if (expenseRows.length === 0) return [] const db = useDb(event);
const expenseRows = await db
.select()
.from(expenses)
.where(eq(expenses.potSlug, slug))
.orderBy(expenses.createdAt);
if (expenseRows.length === 0) return [];
const expenseIds = expenseRows.map(row => row.id) const expenseIds = expenseRows.map((row) => row.id);
const links = await db.select().from(expenseParticipants).where(inArray(expenseParticipants.expenseId, expenseIds)) const links = await db
.select()
.from(expenseParticipants)
.where(inArray(expenseParticipants.expenseId, expenseIds));
const participantIdsByExpense = new Map<number, number[]>() const participantIdsByExpense = new Map<number, number[]>();
for (const link of links) { for (const link of links) {
const list = participantIdsByExpense.get(link.expenseId) ?? [] const list = participantIdsByExpense.get(link.expenseId) ?? [];
list.push(link.participantId) list.push(link.participantId);
participantIdsByExpense.set(link.expenseId, list) participantIdsByExpense.set(link.expenseId, list);
} }
return expenseRows.map(row => ({ return expenseRows.map((row) => ({
id: row.id, id: row.id,
type: row.type, type: row.type,
description: row.description, description: row.description,
@@ -49,5 +63,5 @@ export async function getExpensesWithParticipants(slug: string): Promise<Expense
payerId: row.payerId, payerId: row.payerId,
participantIds: participantIdsByExpense.get(row.id) ?? [], participantIds: participantIdsByExpense.get(row.id) ?? [],
createdAt: row.createdAt, createdAt: row.createdAt,
})) }));
} }
+10 -10
View File
@@ -1,19 +1,19 @@
export type ParticipantId = number export type ParticipantId = number;
export interface Participant { export interface Participant {
id: ParticipantId id: ParticipantId;
name: string name: string;
} }
export interface Expense { export interface Expense {
id: number id: number;
amountCents: number amountCents: number;
payerId: ParticipantId payerId: ParticipantId;
participantIds: ParticipantId[] participantIds: ParticipantId[];
} }
export interface Settlement { export interface Settlement {
fromId: ParticipantId fromId: ParticipantId;
toId: ParticipantId toId: ParticipantId;
amountCents: number amountCents: number;
} }
+48 -39
View File
@@ -1,48 +1,54 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import type { Expense, Participant } from '../types' import type { Expense, Participant } from '../types';
import { calculateBalances } from './balances' import { calculateBalances } from './balances';
const participants: Participant[] = [ const participants: Participant[] = [
{ id: 1, name: 'Alice' }, { id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }, { id: 2, name: 'Bob' },
{ id: 3, name: 'Carol' }, { id: 3, name: 'Carol' },
] ];
describe('calculateBalances', () => { describe('calculateBalances', () => {
it('nets an equal split expense among all participants', () => { it('nets an equal split expense among all participants', () => {
const expenses: Expense[] = [ const expenses: Expense[] = [
{ id: 1, amountCents: 900, payerId: 1, participantIds: [1, 2, 3] }, { id: 1, amountCents: 900, payerId: 1, participantIds: [1, 2, 3] },
] ];
const { netBalances, settlements } = calculateBalances(participants, expenses) const { netBalances, settlements } = calculateBalances(
participants,
expenses,
);
expect(netBalances).toEqual({ 1: 600, 2: -300, 3: -300 }) expect(netBalances).toEqual({ 1: 600, 2: -300, 3: -300 });
expect(settlements).toEqual( expect(settlements).toEqual(
expect.arrayContaining([ expect.arrayContaining([
{ fromId: 2, toId: 1, amountCents: 300 }, { fromId: 2, toId: 1, amountCents: 300 },
{ fromId: 3, toId: 1, amountCents: 300 }, { fromId: 3, toId: 1, amountCents: 300 },
]), ]),
) );
expect(settlements).toHaveLength(2) expect(settlements).toHaveLength(2);
}) });
it('handles an expense split among a subset of participants', () => { it('handles an expense split among a subset of participants', () => {
const expenses: Expense[] = [ const expenses: Expense[] = [
{ id: 1, amountCents: 1000, payerId: 2, participantIds: [2, 3] }, { id: 1, amountCents: 1000, payerId: 2, participantIds: [2, 3] },
] ];
const { netBalances } = calculateBalances(participants, expenses) const { netBalances } = calculateBalances(participants, expenses);
expect(netBalances).toEqual({ 1: 0, 2: 500, 3: -500 }) expect(netBalances).toEqual({ 1: 0, 2: 500, 3: -500 });
}) });
it('produces a zero-sum, fully-settled group when expenses cancel out', () => { it('produces a zero-sum, fully-settled group when expenses cancel out', () => {
const expenses: Expense[] = [ const expenses: Expense[] = [
{ id: 1, amountCents: 900, payerId: 1, participantIds: [1, 2, 3] }, { id: 1, amountCents: 900, payerId: 1, participantIds: [1, 2, 3] },
{ id: 2, amountCents: 900, payerId: 2, participantIds: [1, 2, 3] }, { id: 2, amountCents: 900, payerId: 2, participantIds: [1, 2, 3] },
{ id: 3, amountCents: 900, payerId: 3, participantIds: [1, 2, 3] }, { id: 3, amountCents: 900, payerId: 3, participantIds: [1, 2, 3] },
] ];
const { netBalances, settlements } = calculateBalances(participants, expenses) const { netBalances, settlements } = calculateBalances(
expect(Object.values(netBalances).every(v => v === 0)).toBe(true) participants,
expect(settlements).toEqual([]) expenses,
}) );
expect(Object.values(netBalances).every((v) => v === 0)).toBe(true);
expect(settlements).toEqual([]);
});
it('folds in a settlement payment recorded as a one-person split expense', () => { it('folds in a settlement payment recorded as a one-person split expense', () => {
const expenses: Expense[] = [ const expenses: Expense[] = [
@@ -50,21 +56,24 @@ describe('calculateBalances', () => {
// Bob (2) settles 300 with Alice (1): payerId is who pays, the sole // Bob (2) settles 300 with Alice (1): payerId is who pays, the sole
// participant is who receives it. // participant is who receives it.
{ id: 2, amountCents: 300, payerId: 2, participantIds: [1] }, { id: 2, amountCents: 300, payerId: 2, participantIds: [1] },
] ];
const { netBalances, settlements } = calculateBalances(participants, expenses) const { netBalances, settlements } = calculateBalances(
expect(netBalances).toEqual({ 1: 300, 2: 0, 3: -300 }) participants,
expect(settlements).toEqual([{ fromId: 3, toId: 1, amountCents: 300 }]) expenses,
}) );
expect(netBalances).toEqual({ 1: 300, 2: 0, 3: -300 });
expect(settlements).toEqual([{ fromId: 3, toId: 1, amountCents: 300 }]);
});
it('handles a single-participant Pot (self-paid expense nets to zero)', () => { it('handles a single-participant Pot (self-paid expense nets to zero)', () => {
const solo: Participant[] = [{ id: 1, name: 'Alice' }] const solo: Participant[] = [{ id: 1, name: 'Alice' }];
const expenses: Expense[] = [ const expenses: Expense[] = [
{ id: 1, amountCents: 500, payerId: 1, participantIds: [1] }, { id: 1, amountCents: 500, payerId: 1, participantIds: [1] },
] ];
const { netBalances, settlements } = calculateBalances(solo, expenses) const { netBalances, settlements } = calculateBalances(solo, expenses);
expect(netBalances).toEqual({ 1: 0 }) expect(netBalances).toEqual({ 1: 0 });
expect(settlements).toEqual([]) expect(settlements).toEqual([]);
}) });
it('produces a minimal number of settlements for a multi-person scenario', () => { it('produces a minimal number of settlements for a multi-person scenario', () => {
const four: Participant[] = [ const four: Participant[] = [
@@ -72,18 +81,18 @@ describe('calculateBalances', () => {
{ id: 2, name: 'B' }, { id: 2, name: 'B' },
{ id: 3, name: 'C' }, { id: 3, name: 'C' },
{ id: 4, name: 'D' }, { id: 4, name: 'D' },
] ];
// A pays 400 split 4 ways (each owes 100), B pays 800 split 4 ways (each owes 200). // A pays 400 split 4 ways (each owes 100), B pays 800 split 4 ways (each owes 200).
const expenses: Expense[] = [ const expenses: Expense[] = [
{ id: 1, amountCents: 400, payerId: 1, participantIds: [1, 2, 3, 4] }, { id: 1, amountCents: 400, payerId: 1, participantIds: [1, 2, 3, 4] },
{ id: 2, amountCents: 800, payerId: 2, participantIds: [1, 2, 3, 4] }, { id: 2, amountCents: 800, payerId: 2, participantIds: [1, 2, 3, 4] },
] ];
const { netBalances, settlements } = calculateBalances(four, expenses) const { netBalances, settlements } = calculateBalances(four, expenses);
// A: +400-100-200=100, B: +800-100-200=500, C: -300, D: -300 // A: +400-100-200=100, B: +800-100-200=500, C: -300, D: -300
expect(netBalances).toEqual({ 1: 100, 2: 500, 3: -300, 4: -300 }) expect(netBalances).toEqual({ 1: 100, 2: 500, 3: -300, 4: -300 });
// 2 creditors, 2 debtors -> minimal settlement count is at most 3 (n-1 participants with nonzero balance) // 2 creditors, 2 debtors -> minimal settlement count is at most 3 (n-1 participants with nonzero balance)
expect(settlements.length).toBeLessThanOrEqual(3) expect(settlements.length).toBeLessThanOrEqual(3);
const total = settlements.reduce((sum, s) => sum + s.amountCents, 0) const total = settlements.reduce((sum, s) => sum + s.amountCents, 0);
expect(total).toBe(600) expect(total).toBe(600);
}) });
}) });
+37 -30
View File
@@ -1,63 +1,70 @@
import type { Expense, Participant, ParticipantId, Settlement } from '../types' import type { Expense, Participant, ParticipantId, Settlement } from '../types';
import { computeSplit } from './split' import { computeSplit } from './split';
export function calculateBalances( export function calculateBalances(
participants: Participant[], participants: Participant[],
expenses: Expense[], expenses: Expense[],
): { netBalances: Record<ParticipantId, number>, settlements: Settlement[] } { ): { netBalances: Record<ParticipantId, number>; settlements: Settlement[] } {
const netBalances: Record<ParticipantId, number> = {} const netBalances: Record<ParticipantId, number> = {};
for (const participant of participants) { for (const participant of participants) {
netBalances[participant.id] = 0 netBalances[participant.id] = 0;
} }
// A settlement payment (fromId pays toId) is folded in as a regular // A settlement payment (fromId pays toId) is folded in as a regular
// expense: payerId = fromId, participantIds = [toId]. The math is // expense: payerId = fromId, participantIds = [toId]. The math is
// identical to a one-person split, so no separate handling is needed here. // identical to a one-person split, so no separate handling is needed here.
for (const expense of expenses) { for (const expense of expenses) {
netBalances[expense.payerId] = (netBalances[expense.payerId] ?? 0) + expense.amountCents netBalances[expense.payerId] =
const shares = computeSplit(expense.amountCents, expense.participantIds) (netBalances[expense.payerId] ?? 0) + expense.amountCents;
const shares = computeSplit(expense.amountCents, expense.participantIds);
for (const [participantId, share] of Object.entries(shares)) { for (const [participantId, share] of Object.entries(shares)) {
const id = Number(participantId) const id = Number(participantId);
netBalances[id] = (netBalances[id] ?? 0) - share netBalances[id] = (netBalances[id] ?? 0) - share;
} }
} }
const settlements = simplifyDebts(netBalances) const settlements = simplifyDebts(netBalances);
return { netBalances, settlements } return { netBalances, settlements };
} }
function simplifyDebts(netBalances: Record<ParticipantId, number>): Settlement[] { function simplifyDebts(
const creditors: { id: ParticipantId, amount: number }[] = [] netBalances: Record<ParticipantId, number>,
const debtors: { id: ParticipantId, amount: number }[] = [] ): Settlement[] {
const creditors: { id: ParticipantId; amount: number }[] = [];
const debtors: { id: ParticipantId; amount: number }[] = [];
for (const [id, amount] of Object.entries(netBalances)) { for (const [id, amount] of Object.entries(netBalances)) {
if (amount > 0) creditors.push({ id: Number(id), amount }) if (amount > 0) creditors.push({ id: Number(id), amount });
else if (amount < 0) debtors.push({ id: Number(id), amount: -amount }) else if (amount < 0) debtors.push({ id: Number(id), amount: -amount });
} }
creditors.sort((a, b) => b.amount - a.amount) creditors.sort((a, b) => b.amount - a.amount);
debtors.sort((a, b) => b.amount - a.amount) debtors.sort((a, b) => b.amount - a.amount);
const settlements: Settlement[] = [] const settlements: Settlement[] = [];
let ci = 0 let ci = 0;
let di = 0 let di = 0;
while (ci < creditors.length && di < debtors.length) { while (ci < creditors.length && di < debtors.length) {
const creditor = creditors[ci]! const creditor = creditors[ci]!;
const debtor = debtors[di]! const debtor = debtors[di]!;
const amount = Math.min(creditor.amount, debtor.amount) const amount = Math.min(creditor.amount, debtor.amount);
if (amount > 0) { if (amount > 0) {
settlements.push({ fromId: debtor.id, toId: creditor.id, amountCents: amount }) settlements.push({
fromId: debtor.id,
toId: creditor.id,
amountCents: amount,
});
} }
creditor.amount -= amount creditor.amount -= amount;
debtor.amount -= amount debtor.amount -= amount;
if (creditor.amount === 0) ci++ if (creditor.amount === 0) ci++;
if (debtor.amount === 0) di++ if (debtor.amount === 0) di++;
} }
return settlements return settlements;
} }
+11 -11
View File
@@ -1,18 +1,18 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { formatCurrency, fromCents, toCents } from './money' import { formatCurrency, fromCents, toCents } from './money';
describe('money helpers', () => { describe('money helpers', () => {
it('converts amounts to cents', () => { it('converts amounts to cents', () => {
expect(toCents(12.34)).toBe(1234) expect(toCents(12.34)).toBe(1234);
expect(toCents(5)).toBe(500) expect(toCents(5)).toBe(500);
}) });
it('converts cents back to amounts', () => { it('converts cents back to amounts', () => {
expect(fromCents(1234)).toBe(12.34) expect(fromCents(1234)).toBe(12.34);
}) });
it('formats cents as a localized currency string', () => { it('formats cents as a localized currency string', () => {
expect(formatCurrency(1234, 'EUR')).toContain('12') expect(formatCurrency(1234, 'EUR')).toContain('12');
expect(formatCurrency(1234, 'EUR')).toContain('34') expect(formatCurrency(1234, 'EUR')).toContain('34');
}) });
}) });
+6 -3
View File
@@ -1,11 +1,14 @@
export function toCents(amount: number): number { export function toCents(amount: number): number {
return Math.round(amount * 100) return Math.round(amount * 100);
} }
export function fromCents(cents: number): number { export function fromCents(cents: number): number {
return cents / 100 return cents / 100;
} }
export function formatCurrency(cents: number, currency: string): string { export function formatCurrency(cents: number, currency: string): string {
return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(fromCents(cents)) return new Intl.NumberFormat(undefined, {
style: 'currency',
currency,
}).format(fromCents(cents));
} }
+13 -13
View File
@@ -1,24 +1,24 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { isValidPaymentLink } from './paymentLink' import { isValidPaymentLink } from './paymentLink';
describe('isValidPaymentLink', () => { describe('isValidPaymentLink', () => {
it('accepts an https PayPal.me link', () => { it('accepts an https PayPal.me link', () => {
expect(isValidPaymentLink('https://paypal.me/janedoe')).toBe(true) expect(isValidPaymentLink('https://paypal.me/janedoe')).toBe(true);
}) });
it('accepts an http link', () => { it('accepts an http link', () => {
expect(isValidPaymentLink('http://paypal.me/janedoe')).toBe(true) expect(isValidPaymentLink('http://paypal.me/janedoe')).toBe(true);
}) });
it('rejects an empty string', () => { it('rejects an empty string', () => {
expect(isValidPaymentLink('')).toBe(false) expect(isValidPaymentLink('')).toBe(false);
}) });
it('rejects a javascript: URI', () => { it('rejects a javascript: URI', () => {
expect(isValidPaymentLink('javascript:alert(1)')).toBe(false) expect(isValidPaymentLink('javascript:alert(1)')).toBe(false);
}) });
it('rejects a value that is not a URL at all', () => { it('rejects a value that is not a URL at all', () => {
expect(isValidPaymentLink('not a link')).toBe(false) expect(isValidPaymentLink('not a link')).toBe(false);
}) });
}) });
+5 -6
View File
@@ -1,11 +1,10 @@
export function isValidPaymentLink(value: string): boolean { export function isValidPaymentLink(value: string): boolean {
if (!value.trim()) return false if (!value.trim()) return false;
try { try {
const url = new URL(value) const url = new URL(value);
return url.protocol === 'https:' || url.protocol === 'http:' return url.protocol === 'https:' || url.protocol === 'http:';
} } catch {
catch { return false;
return false
} }
} }
+8 -8
View File
@@ -1,13 +1,13 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { generateSlug } from './slug' import { generateSlug } from './slug';
describe('generateSlug', () => { describe('generateSlug', () => {
it('produces an adjective-noun-suffix slug', () => { it('produces an adjective-noun-suffix slug', () => {
expect(generateSlug()).toMatch(/^[a-z]+-[a-z]+-[a-z0-9]{6}$/) expect(generateSlug()).toMatch(/^[a-z]+-[a-z]+-[a-z0-9]{6}$/);
}) });
it('produces distinct slugs across calls', () => { it('produces distinct slugs across calls', () => {
const slugs = new Set(Array.from({ length: 20 }, () => generateSlug())) const slugs = new Set(Array.from({ length: 20 }, () => generateSlug()));
expect(slugs.size).toBeGreaterThan(1) expect(slugs.size).toBeGreaterThan(1);
}) });
}) });
+67 -15
View File
@@ -1,23 +1,75 @@
import { customAlphabet } from 'nanoid' import { customAlphabet } from 'nanoid';
const ADJECTIVES = [ const ADJECTIVES = [
'drunken', 'sleepy', 'grumpy', 'jolly', 'quiet', 'brave', 'clever', 'eager', 'drunken',
'fuzzy', 'gentle', 'happy', 'icy', 'jumpy', 'kind', 'lively', 'mighty', 'sleepy',
'noisy', 'orange', 'proud', 'quick', 'rusty', 'silly', 'tidy', 'upbeat', 'grumpy',
'vivid', 'witty', 'zesty', 'bold', 'calm', 'dizzy', 'jolly',
] 'quiet',
'brave',
'clever',
'eager',
'fuzzy',
'gentle',
'happy',
'icy',
'jumpy',
'kind',
'lively',
'mighty',
'noisy',
'orange',
'proud',
'quick',
'rusty',
'silly',
'tidy',
'upbeat',
'vivid',
'witty',
'zesty',
'bold',
'calm',
'dizzy',
];
const NOUNS = [ const NOUNS = [
'wizard', 'tiger', 'otter', 'falcon', 'penguin', 'dragon', 'panda', 'raven', 'wizard',
'walrus', 'yeti', 'badger', 'comet', 'ember', 'fox', 'goose', 'heron', 'tiger',
'igloo', 'jackal', 'koala', 'lemur', 'mango', 'newt', 'oasis', 'puffin', 'otter',
'quokka', 'robin', 'sloth', 'toucan', 'unicorn', 'viper', 'falcon',
] 'penguin',
'dragon',
'panda',
'raven',
'walrus',
'yeti',
'badger',
'comet',
'ember',
'fox',
'goose',
'heron',
'igloo',
'jackal',
'koala',
'lemur',
'mango',
'newt',
'oasis',
'puffin',
'quokka',
'robin',
'sloth',
'toucan',
'unicorn',
'viper',
];
const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 6) const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 6);
export function generateSlug(): string { export function generateSlug(): string {
const adjective = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)] const adjective = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];
const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)] const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];
return `${adjective}-${noun}-${nanoid()}` return `${adjective}-${noun}-${nanoid()}`;
} }
+17 -17
View File
@@ -1,30 +1,30 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
import { computeSplit } from './split' import { computeSplit } from './split';
describe('computeSplit', () => { describe('computeSplit', () => {
it('divides evenly when amount divides cleanly', () => { it('divides evenly when amount divides cleanly', () => {
expect(computeSplit(1000, [1, 2, 4])).toEqual({ 1: 334, 2: 333, 4: 333 }) expect(computeSplit(1000, [1, 2, 4])).toEqual({ 1: 334, 2: 333, 4: 333 });
}) });
it('sums back exactly to the original amount', () => { it('sums back exactly to the original amount', () => {
const shares = computeSplit(1001, [1, 2, 3, 4, 5, 6, 7]) const shares = computeSplit(1001, [1, 2, 3, 4, 5, 6, 7]);
const total = Object.values(shares).reduce((sum, share) => sum + share, 0) const total = Object.values(shares).reduce((sum, share) => sum + share, 0);
expect(total).toBe(1001) expect(total).toBe(1001);
}) });
it('distributes remainder cents one-each to the first participants in order', () => { it('distributes remainder cents one-each to the first participants in order', () => {
expect(computeSplit(10, [1, 2, 3])).toEqual({ 1: 4, 2: 3, 3: 3 }) expect(computeSplit(10, [1, 2, 3])).toEqual({ 1: 4, 2: 3, 3: 3 });
}) });
it('gives the full amount to a single participant', () => { it('gives the full amount to a single participant', () => {
expect(computeSplit(1234, [9])).toEqual({ 9: 1234 }) expect(computeSplit(1234, [9])).toEqual({ 9: 1234 });
}) });
it('handles a zero amount', () => { it('handles a zero amount', () => {
expect(computeSplit(0, [1, 2])).toEqual({ 1: 0, 2: 0 }) expect(computeSplit(0, [1, 2])).toEqual({ 1: 0, 2: 0 });
}) });
it('throws when given no participants', () => { it('throws when given no participants', () => {
expect(() => computeSplit(1000, [])).toThrow() expect(() => computeSplit(1000, [])).toThrow();
}) });
}) });
+12 -9
View File
@@ -1,21 +1,24 @@
import type { ParticipantId } from '../types' import type { ParticipantId } from '../types';
/** /**
* Splits amountCents equally among participantIds. Any remainder cents (from * Splits amountCents equally among participantIds. Any remainder cents (from
* integer division) go one-each to the first participants in the given * integer division) go one-each to the first participants in the given
* order, so the shares always sum exactly back to amountCents. * order, so the shares always sum exactly back to amountCents.
*/ */
export function computeSplit(amountCents: number, participantIds: ParticipantId[]): Record<ParticipantId, number> { export function computeSplit(
amountCents: number,
participantIds: ParticipantId[],
): Record<ParticipantId, number> {
if (participantIds.length === 0) { if (participantIds.length === 0) {
throw new Error('computeSplit requires at least one participant') throw new Error('computeSplit requires at least one participant');
} }
const base = Math.floor(amountCents / participantIds.length) const base = Math.floor(amountCents / participantIds.length);
const remainder = amountCents - base * participantIds.length const remainder = amountCents - base * participantIds.length;
const shares: Record<ParticipantId, number> = {} const shares: Record<ParticipantId, number> = {};
participantIds.forEach((id, index) => { participantIds.forEach((id, index) => {
shares[id] = base + (index < remainder ? 1 : 0) shares[id] = base + (index < remainder ? 1 : 0);
}) });
return shares return shares;
} }
+202 -108
View File
@@ -1,198 +1,292 @@
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto';
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url';
import os from 'node:os' import os from 'node:os';
import path from 'node:path' import path from 'node:path';
import { $fetch, setup } from '@nuxt/test-utils/e2e' import { $fetch, setup } from '@nuxt/test-utils/e2e';
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest';
describe('Pot API', async () => { describe('Pot API', async () => {
const dbPath = path.join(os.tmpdir(), `stb-test-${randomUUID()}.sqlite`) const dbPath = path.join(os.tmpdir(), `stb-test-${randomUUID()}.sqlite`);
await setup({ await setup({
rootDir: fileURLToPath(new URL('../..', import.meta.url)), rootDir: fileURLToPath(new URL('../..', import.meta.url)),
dev: true, dev: true,
env: { DATABASE_URL: `file:${dbPath}` }, env: { DATABASE_URL: `file:${dbPath}` },
}) });
it('creates a Pot with the creator as first participant', async () => { it('creates a Pot with the creator as first participant', async () => {
const result = await $fetch('/api/pots', { const result = await $fetch('/api/pots', {
method: 'POST', method: 'POST',
body: { name: 'Weekend Trip', currency: 'eur', creatorName: 'Alice' }, body: { name: 'Weekend Trip', currency: 'eur', creatorName: 'Alice' },
}) });
expect(result.slug).toMatch(/^[a-z]+-[a-z]+-[a-z0-9]{6}$/) expect(result.slug).toMatch(/^[a-z]+-[a-z]+-[a-z0-9]{6}$/);
expect(result.name).toBe('Weekend Trip') expect(result.name).toBe('Weekend Trip');
expect(result.currency).toBe('EUR') expect(result.currency).toBe('EUR');
expect(result.creator.name).toBe('Alice') expect(result.creator.name).toBe('Alice');
}) });
it('rejects Pot creation with missing fields', async () => { it('rejects Pot creation with missing fields', async () => {
await expect( await expect(
$fetch('/api/pots', { method: 'POST', body: { name: '', currency: 'EUR', creatorName: 'Alice' } }), $fetch('/api/pots', {
).rejects.toMatchObject({ statusCode: 400 }) method: 'POST',
}) body: { name: '', currency: 'EUR', creatorName: 'Alice' },
}),
).rejects.toMatchObject({ statusCode: 400 });
});
it('adds a participant and fetches the Pot with balances', async () => { it('adds a participant and fetches the Pot with balances', async () => {
const pot = await $fetch('/api/pots', { const pot = await $fetch('/api/pots', {
method: 'POST', method: 'POST',
body: { name: 'Flat Share', currency: 'USD', creatorName: 'Alice' }, body: { name: 'Flat Share', currency: 'USD', creatorName: 'Alice' },
}) });
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, { const bob = await $fetch(`/api/pots/${pot.slug}/participants`, {
method: 'POST', method: 'POST',
body: { name: 'Bob' }, body: { name: 'Bob' },
}) });
expect(bob.name).toBe('Bob') expect(bob.name).toBe('Bob');
const fetched = await $fetch(`/api/pots/${pot.slug}`) const fetched = await $fetch(`/api/pots/${pot.slug}`);
expect(fetched.pot.slug).toBe(pot.slug) expect(fetched.pot.slug).toBe(pot.slug);
expect(fetched.participants).toHaveLength(2) expect(fetched.participants).toHaveLength(2);
expect(fetched.expenses).toEqual([]) expect(fetched.expenses).toEqual([]);
expect(fetched.netBalances).toEqual({ expect(fetched.netBalances).toEqual({
[pot.creator.id]: 0, [pot.creator.id]: 0,
[bob.id]: 0, [bob.id]: 0,
}) });
expect(fetched.settlements).toEqual([]) expect(fetched.settlements).toEqual([]);
}) });
it('supports full expense CRUD and recomputes balances', async () => { it('supports full expense CRUD and recomputes balances', async () => {
const pot = await $fetch('/api/pots', { const pot = await $fetch('/api/pots', {
method: 'POST', method: 'POST',
body: { name: 'Birthday Gift', currency: 'EUR', creatorName: 'Alice' }, body: { name: 'Birthday Gift', currency: 'EUR', creatorName: 'Alice' },
}) });
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, { method: 'POST', body: { name: 'Bob' } }) const bob = await $fetch(`/api/pots/${pot.slug}/participants`, {
const alice = pot.creator method: 'POST',
body: { name: 'Bob' },
});
const alice = pot.creator;
const expense = await $fetch(`/api/pots/${pot.slug}/expenses`, { const expense = await $fetch(`/api/pots/${pot.slug}/expenses`, {
method: 'POST', method: 'POST',
body: { description: 'Cake', amountCents: 1000, payerId: alice.id, participantIds: [alice.id, bob.id] }, body: {
}) description: 'Cake',
expect(expense.participantIds).toEqual([alice.id, bob.id]) amountCents: 1000,
payerId: alice.id,
participantIds: [alice.id, bob.id],
},
});
expect(expense.participantIds).toEqual([alice.id, bob.id]);
let fetched = await $fetch(`/api/pots/${pot.slug}`) let fetched = await $fetch(`/api/pots/${pot.slug}`);
expect(fetched.expenses).toHaveLength(1) expect(fetched.expenses).toHaveLength(1);
expect(fetched.netBalances[alice.id]).toBe(500) expect(fetched.netBalances[alice.id]).toBe(500);
expect(fetched.netBalances[bob.id]).toBe(-500) expect(fetched.netBalances[bob.id]).toBe(-500);
expect(fetched.settlements).toEqual([{ fromId: bob.id, toId: alice.id, amountCents: 500 }]) expect(fetched.settlements).toEqual([
{ fromId: bob.id, toId: alice.id, amountCents: 500 },
]);
await $fetch(`/api/pots/${pot.slug}/expenses/${expense.id}`, { await $fetch(`/api/pots/${pot.slug}/expenses/${expense.id}`, {
method: 'PATCH', method: 'PATCH',
body: { description: 'Cake', amountCents: 2000, payerId: alice.id, participantIds: [alice.id, bob.id] }, body: {
}) description: 'Cake',
fetched = await $fetch(`/api/pots/${pot.slug}`) amountCents: 2000,
expect(fetched.netBalances[bob.id]).toBe(-1000) payerId: alice.id,
participantIds: [alice.id, bob.id],
},
});
fetched = await $fetch(`/api/pots/${pot.slug}`);
expect(fetched.netBalances[bob.id]).toBe(-1000);
await $fetch(`/api/pots/${pot.slug}/expenses/${expense.id}`, { method: 'DELETE' }) await $fetch(`/api/pots/${pot.slug}/expenses/${expense.id}`, {
fetched = await $fetch(`/api/pots/${pot.slug}`) method: 'DELETE',
expect(fetched.expenses).toEqual([]) });
expect(fetched.netBalances[bob.id]).toBe(0) fetched = await $fetch(`/api/pots/${pot.slug}`);
}) expect(fetched.expenses).toEqual([]);
expect(fetched.netBalances[bob.id]).toBe(0);
});
it('rejects an expense referencing a participant from another Pot', async () => { it('rejects an expense referencing a participant from another Pot', async () => {
const potA = await $fetch('/api/pots', { method: 'POST', body: { name: 'A', currency: 'EUR', creatorName: 'Alice' } }) const potA = await $fetch('/api/pots', {
const potB = await $fetch('/api/pots', { method: 'POST', body: { name: 'B', currency: 'EUR', creatorName: 'Zara' } }) method: 'POST',
body: { name: 'A', currency: 'EUR', creatorName: 'Alice' },
});
const potB = await $fetch('/api/pots', {
method: 'POST',
body: { name: 'B', currency: 'EUR', creatorName: 'Zara' },
});
await expect( await expect(
$fetch(`/api/pots/${potA.slug}/expenses`, { $fetch(`/api/pots/${potA.slug}/expenses`, {
method: 'POST', method: 'POST',
body: { description: 'x', amountCents: 100, payerId: potB.creator.id, participantIds: [potA.creator.id] }, body: {
description: 'x',
amountCents: 100,
payerId: potB.creator.id,
participantIds: [potA.creator.id],
},
}), }),
).rejects.toMatchObject({ statusCode: 400 }) ).rejects.toMatchObject({ statusCode: 400 });
}) });
it('returns 404 for an unknown Pot slug', async () => { it('returns 404 for an unknown Pot slug', async () => {
await expect($fetch('/api/pots/does-not-exist-123456')).rejects.toMatchObject({ statusCode: 404 }) await expect(
}) $fetch('/api/pots/does-not-exist-123456'),
).rejects.toMatchObject({ statusCode: 404 });
});
it('records a settlement payment as a payment-type expense and recomputes balances', async () => { it('records a settlement payment as a payment-type expense and recomputes balances', async () => {
const pot = await $fetch('/api/pots', { method: 'POST', body: { name: 'Ski Trip', currency: 'EUR', creatorName: 'Alice' } }) const pot = await $fetch('/api/pots', {
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, { method: 'POST', body: { name: 'Bob' } }) method: 'POST',
const alice = pot.creator body: { name: 'Ski Trip', currency: 'EUR', creatorName: 'Alice' },
});
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, {
method: 'POST',
body: { name: 'Bob' },
});
const alice = pot.creator;
await $fetch(`/api/pots/${pot.slug}/expenses`, { await $fetch(`/api/pots/${pot.slug}/expenses`, {
method: 'POST', method: 'POST',
body: { description: 'Lift pass', amountCents: 1000, payerId: alice.id, participantIds: [alice.id, bob.id] }, body: {
}) description: 'Lift pass',
amountCents: 1000,
payerId: alice.id,
participantIds: [alice.id, bob.id],
},
});
const payment = await $fetch(`/api/pots/${pot.slug}/payments`, { const payment = await $fetch(`/api/pots/${pot.slug}/payments`, {
method: 'POST', method: 'POST',
body: { fromId: bob.id, toId: alice.id, amountCents: 500 }, body: { fromId: bob.id, toId: alice.id, amountCents: 500 },
}) });
expect(payment.type).toBe('payment') expect(payment.type).toBe('payment');
expect(payment.payerId).toBe(bob.id) expect(payment.payerId).toBe(bob.id);
expect(payment.participantIds).toEqual([alice.id]) expect(payment.participantIds).toEqual([alice.id]);
const fetched = await $fetch(`/api/pots/${pot.slug}`) const fetched = await $fetch(`/api/pots/${pot.slug}`);
expect(fetched.expenses).toHaveLength(2) expect(fetched.expenses).toHaveLength(2);
expect(fetched.expenses.filter(e => e.type === 'payment')).toHaveLength(1) expect(fetched.expenses.filter((e) => e.type === 'payment')).toHaveLength(
expect(fetched.netBalances[alice.id]).toBe(0) 1,
expect(fetched.netBalances[bob.id]).toBe(0) );
expect(fetched.settlements).toEqual([]) expect(fetched.netBalances[alice.id]).toBe(0);
}) expect(fetched.netBalances[bob.id]).toBe(0);
expect(fetched.settlements).toEqual([]);
});
it('rejects a payment with a non-positive amount or matching from/to', async () => { it('rejects a payment with a non-positive amount or matching from/to', async () => {
const pot = await $fetch('/api/pots', { method: 'POST', body: { name: 'Retreat', currency: 'EUR', creatorName: 'Alice' } }) const pot = await $fetch('/api/pots', {
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, { method: 'POST', body: { name: 'Bob' } }) method: 'POST',
const alice = pot.creator body: { name: 'Retreat', currency: 'EUR', creatorName: 'Alice' },
});
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, {
method: 'POST',
body: { name: 'Bob' },
});
const alice = pot.creator;
await expect( await expect(
$fetch(`/api/pots/${pot.slug}/payments`, { method: 'POST', body: { fromId: bob.id, toId: alice.id, amountCents: 0 } }), $fetch(`/api/pots/${pot.slug}/payments`, {
).rejects.toMatchObject({ statusCode: 400 }) method: 'POST',
body: { fromId: bob.id, toId: alice.id, amountCents: 0 },
}),
).rejects.toMatchObject({ statusCode: 400 });
await expect( await expect(
$fetch(`/api/pots/${pot.slug}/payments`, { method: 'POST', body: { fromId: alice.id, toId: alice.id, amountCents: 100 } }), $fetch(`/api/pots/${pot.slug}/payments`, {
).rejects.toMatchObject({ statusCode: 400 }) method: 'POST',
}) body: { fromId: alice.id, toId: alice.id, amountCents: 100 },
}),
).rejects.toMatchObject({ statusCode: 400 });
});
it('deletes a settlement payment via the regular expense delete route', async () => { it('deletes a settlement payment via the regular expense delete route', async () => {
const pot = await $fetch('/api/pots', { method: 'POST', body: { name: 'Housewarming', currency: 'EUR', creatorName: 'Alice' } }) const pot = await $fetch('/api/pots', {
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, { method: 'POST', body: { name: 'Bob' } }) method: 'POST',
const alice = pot.creator body: { name: 'Housewarming', currency: 'EUR', creatorName: 'Alice' },
});
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, {
method: 'POST',
body: { name: 'Bob' },
});
const alice = pot.creator;
const payment = await $fetch(`/api/pots/${pot.slug}/payments`, { const payment = await $fetch(`/api/pots/${pot.slug}/payments`, {
method: 'POST', method: 'POST',
body: { fromId: bob.id, toId: alice.id, amountCents: 500 }, body: { fromId: bob.id, toId: alice.id, amountCents: 500 },
}) });
await $fetch(`/api/pots/${pot.slug}/expenses/${payment.id}`, { method: 'DELETE' }) await $fetch(`/api/pots/${pot.slug}/expenses/${payment.id}`, {
method: 'DELETE',
});
const fetched = await $fetch(`/api/pots/${pot.slug}`) const fetched = await $fetch(`/api/pots/${pot.slug}`);
expect(fetched.expenses).toEqual([]) expect(fetched.expenses).toEqual([]);
}) });
it('sets a valid payment link on a participant and rejects an invalid one', async () => { it('sets a valid payment link on a participant and rejects an invalid one', async () => {
const pot = await $fetch('/api/pots', { method: 'POST', body: { name: 'Reunion', currency: 'EUR', creatorName: 'Alice' } }) const pot = await $fetch('/api/pots', {
const alice = pot.creator method: 'POST',
body: { name: 'Reunion', currency: 'EUR', creatorName: 'Alice' },
});
const alice = pot.creator;
const updated = await $fetch(`/api/pots/${pot.slug}/participants/${alice.id}`, { const updated = await $fetch(
`/api/pots/${pot.slug}/participants/${alice.id}`,
{
method: 'PATCH', method: 'PATCH',
body: { paymentLink: 'https://paypal.me/alice' }, body: { paymentLink: 'https://paypal.me/alice' },
}) },
expect(updated.paymentLink).toBe('https://paypal.me/alice') );
expect(updated.paymentLink).toBe('https://paypal.me/alice');
await expect( await expect(
$fetch(`/api/pots/${pot.slug}/participants/${alice.id}`, { method: 'PATCH', body: { paymentLink: 'javascript:alert(1)' } }), $fetch(`/api/pots/${pot.slug}/participants/${alice.id}`, {
).rejects.toMatchObject({ statusCode: 400 }) method: 'PATCH',
}) body: { paymentLink: 'javascript:alert(1)' },
}),
).rejects.toMatchObject({ statusCode: 400 });
});
it('removes a participant without expenses but blocks removing one with expenses', async () => { it('removes a participant without expenses but blocks removing one with expenses', async () => {
const pot = await $fetch('/api/pots', { method: 'POST', body: { name: 'Ski Trip', currency: 'EUR', creatorName: 'Alice' } }) const pot = await $fetch('/api/pots', {
const alice = pot.creator method: 'POST',
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, { method: 'POST', body: { name: 'Bob' } }) body: { name: 'Ski Trip', currency: 'EUR', creatorName: 'Alice' },
});
const alice = pot.creator;
const bob = await $fetch(`/api/pots/${pot.slug}/participants`, {
method: 'POST',
body: { name: 'Bob' },
});
await $fetch(`/api/pots/${pot.slug}/expenses`, { await $fetch(`/api/pots/${pot.slug}/expenses`, {
method: 'POST', method: 'POST',
body: { description: 'Lift pass', amountCents: 1000, payerId: alice.id, participantIds: [alice.id, bob.id] }, body: {
}) description: 'Lift pass',
amountCents: 1000,
payerId: alice.id,
participantIds: [alice.id, bob.id],
},
});
await expect( await expect(
$fetch(`/api/pots/${pot.slug}/participants/${bob.id}`, { method: 'DELETE' }), $fetch(`/api/pots/${pot.slug}/participants/${bob.id}`, {
).rejects.toMatchObject({ statusCode: 409 }) method: 'DELETE',
}),
).rejects.toMatchObject({ statusCode: 409 });
const carol = await $fetch(`/api/pots/${pot.slug}/participants`, { method: 'POST', body: { name: 'Carol' } }) const carol = await $fetch(`/api/pots/${pot.slug}/participants`, {
const result = await $fetch(`/api/pots/${pot.slug}/participants/${carol.id}`, { method: 'DELETE' }) method: 'POST',
expect(result.success).toBe(true) body: { name: 'Carol' },
});
const result = await $fetch(
`/api/pots/${pot.slug}/participants/${carol.id}`,
{ method: 'DELETE' },
);
expect(result.success).toBe(true);
const fetched = await $fetch(`/api/pots/${pot.slug}`) const fetched = await $fetch(`/api/pots/${pot.slug}`);
expect(fetched.participants.map(p => p.id)).not.toContain(carol.id) expect(fetched.participants.map((p) => p.id)).not.toContain(carol.id);
}) });
}) });
+2 -2
View File
@@ -1,4 +1,4 @@
import { defineConfig } from 'vitest/config' import { defineConfig } from 'vitest/config';
export default defineConfig({ export default defineConfig({
test: { test: {
@@ -7,4 +7,4 @@ export default defineConfig({
testTimeout: 60000, testTimeout: 60000,
hookTimeout: 60000, hookTimeout: 60000,
}, },
}) });