Splitter
Shared expenses split between a group, with join links.
20 files, 1366 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in apps/splitter.
Files
server/index.ts280server/seed.ts70shared/fields.ts14shared/split.ts52src/main.tsx6src/routes/__root.tsx15src/routes/404.tsx21src/routes/groups/$group.tsx67src/routes/index.tsx93src/routes/join/$code.tsx63src/routes/join/index.tsx36src/components/AddExpense.tsx73src/components/Balances.tsx71src/components/Expenses.tsx61src/components/Money.tsx9src/components/NewGroup.tsx33src/styles.css4src/theme.css60server/index.test.ts205src/app.test.tsx133
server/index.ts280 lines
import {
and,
asc,
count,
desc,
eq,
id,
inArray,
mutation,
number,
query,
Random,
schema,
sql,
sum,
table,
TaggedError,
userId,
Viewer,
type Id,
} from "canica/server"
import { amount, description, displayName, groupName, inviteCode, participants, payer } from "../shared/fields.ts"
import { settle, splitEqually } from "../shared/split.ts"
export const { app, Db, tables } = schema({
groups: table({ name: groupName, code: inviteCode, createdBy: userId() }).unique("by_code", ["code"]),
members: table({ group: id("groups").onDelete("cascade"), user: userId(), name: displayName })
.index("by_group", ["group"])
.index("by_user", ["user"])
.unique("by_group_user", ["group", "user"])
.unique("by_group_name", ["group", "name"], { caseInsensitive: true }),
expenses: table({
group: id("groups").onDelete("cascade"),
description,
amount,
payer: id("members"),
createdBy: userId(),
}).index("by_group", ["group"]),
// What each member owes for an expense, fixed when the expense is added (remainder cents included).
shares: table({
group: id("groups").onDelete("cascade"),
expense: id("expenses").onDelete("cascade"),
member: id("members"),
amount: number().int().min(0),
})
.index("by_group", ["group"])
.index("by_expense", ["expense"]),
})
const { groups, members, expenses, shares } = tables
export class NotMember extends TaggedError("NotMember") {}
export class NotCreator extends TaggedError("NotCreator") {}
export class InvalidCode extends TaggedError("InvalidCode") {}
export class NameTaken extends TaggedError("NameTaken")<{ readonly name: string }> {}
export class NotInGroup extends TaggedError("NotInGroup") {}
/** Access control is code: every handler that touches a group goes through here. Returns the viewer's member row. */
function* requireMember(group: Id<"groups">) {
const db = yield* Db
yield* db.get(groups, group) // NotFound first
const viewer = yield* Viewer
const [me] = yield* db
.select()
.from(members)
.where(and(eq(members.group, group), eq(members.user, viewer.userId)))
.limit(1)
if (!me) return yield* new NotMember()
return me
}
/** Members in join order (the order remainder cents are handed out in). */
const joinOrder = <T extends { readonly id: string; readonly createdAt: number }>(rows: ReadonlyArray<T>) =>
[...rows].sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1))
function* nameTaken(group: Id<"groups">, name: string) {
const db = yield* Db
const [taken] = yield* db
.select({ id: members.id })
.from(members)
.where(and(eq(members.group, group), eq(sql`lower(${members.name})`, name.toLowerCase())))
.limit(1)
return taken !== undefined
}
export default app({
name: "Splitter",
queries: {
/** The groups I belong to, with a few facts for each row. `net` is what I am owed (negative: what I owe). */
myGroups: query(function* () {
const db = yield* Db
const viewer = yield* Viewer
const mine = yield* db
.select()
.from(members)
.innerJoin(groups, eq(members.group, groups.id))
.where(eq(members.user, viewer.userId))
.orderBy(desc(members.createdAt))
.limit(200)
const groupIds = mine.map((m) => m.groups.id)
const memberIds = mine.map((m) => m.members.id)
const counts = yield* db
.select({ group: members.group, n: count() })
.from(members)
.where(inArray(members.group, groupIds))
.groupBy(members.group)
const spent = yield* db
.select({ group: expenses.group, total: sum(expenses.amount) })
.from(expenses)
.where(inArray(expenses.group, groupIds))
.groupBy(expenses.group)
const paid = yield* db
.select({ group: expenses.group, total: sum(expenses.amount) })
.from(expenses)
.where(inArray(expenses.payer, memberIds))
.groupBy(expenses.group)
const owed = yield* db
.select({ group: shares.group, total: sum(shares.amount) })
.from(shares)
.where(inArray(shares.member, memberIds))
.groupBy(shares.group)
const pick = (rows: ReadonlyArray<{ group: Id<"groups">; total: string | null }>, group: Id<"groups">) =>
Number(rows.find((r) => r.group === group)?.total ?? 0)
return mine.map(({ groups: g }) => ({
id: g.id,
name: g.name,
members: counts.find((c) => c.group === g.id)?.n ?? 0,
spent: pick(spent, g.id),
net: pick(paid, g.id) - pick(owed, g.id),
}))
}),
/** The group header and its members. Members only. */
group: query({ group: id("groups") }, function* ({ group }) {
const me = yield* requireMember(group)
const db = yield* Db
const g = yield* db.get(groups, group)
const people = yield* db.select().from(members).where(eq(members.group, group)).orderBy(asc(members.createdAt)).limit(200)
return {
id: g.id,
name: g.name,
code: g.code,
me: me.id,
members: joinOrder(people).map((m) => ({ id: m.id, name: m.name, isMe: m.id === me.id })),
}
}),
/** Newest first. `mine` says whether the viewer added it (and so may delete it). */
expenses: query({ group: id("groups") }, function* ({ group }) {
yield* requireMember(group)
const db = yield* Db
const viewer = yield* Viewer
const [rows, parts, people] = [
yield* db.select().from(expenses).where(eq(expenses.group, group)).orderBy(desc(expenses.createdAt), desc(expenses.id)).limit(500),
yield* db.select().from(shares).where(eq(shares.group, group)).limit(10_000),
yield* db.select({ id: members.id, name: members.name }).from(members).where(eq(members.group, group)).limit(200),
]
const name = (m: string) => people.find((p) => p.id === m)?.name ?? "Someone"
return rows.map((e) => ({
id: e.id,
description: e.description,
amount: e.amount,
createdAt: e.createdAt,
payer: e.payer,
payerName: name(e.payer),
mine: e.createdBy === viewer.userId,
shares: parts
.filter((s) => s.expense === e.id)
.map((s) => ({ member: s.member, name: name(s.member), amount: s.amount }))
.sort((a, b) => (a.name < b.name ? -1 : 1)),
}))
}),
/** Net balance per member (paid minus owed; positive = is owed) and the transfers that settle everyone. */
balances: query({ group: id("groups") }, function* ({ group }) {
yield* requireMember(group)
const db = yield* Db
const people = yield* db.select({ id: members.id, name: members.name, createdAt: members.createdAt }).from(members).where(eq(members.group, group)).limit(200)
const paid = yield* db
.select({ member: expenses.payer, total: sum(expenses.amount) })
.from(expenses)
.where(eq(expenses.group, group))
.groupBy(expenses.payer)
const owed = yield* db
.select({ member: shares.member, total: sum(shares.amount) })
.from(shares)
.where(eq(shares.group, group))
.groupBy(shares.member)
const rows = joinOrder(people).map((p) => {
const p1 = Number(paid.find((x) => x.member === p.id)?.total ?? 0)
const o1 = Number(owed.find((x) => x.member === p.id)?.total ?? 0)
return { member: p.id, name: p.name, paid: p1, owed: o1, net: p1 - o1 }
})
const name = (m: string) => people.find((p) => p.id === m)?.name ?? "Someone"
const transfers = settle(rows).map((t) => ({ ...t, fromName: name(t.from), toName: name(t.to) }))
return { members: rows, transfers }
}),
/** What the join page shows for an invite code: the group's name. Anyone with the code may look. */
invite: query({ code: inviteCode }, function* ({ code }) {
const db = yield* Db
const viewer = yield* Viewer
const [g] = yield* db.select().from(groups).where(eq(groups.code, code)).limit(1)
if (!g) return yield* new InvalidCode()
const [mine] = yield* db
.select({ id: members.id })
.from(members)
.where(and(eq(members.group, g.id), eq(members.user, viewer.userId)))
.limit(1)
const people = yield* db.count(members, eq(members.group, g.id))
return { group: g.id, name: g.name, members: people, joined: mine !== undefined }
}),
},
mutations: {
createGroup: mutation({ name: groupName, myName: displayName }, function* ({ name, myName }) {
const db = yield* Db
const viewer = yield* Viewer
const random = yield* Random
let code = random.string(6)
for (let tries = 0; tries < 20; tries++) {
const [clash] = yield* db.select({ id: groups.id }).from(groups).where(eq(groups.code, code)).limit(1)
if (!clash) break
code = random.string(6)
}
const [g] = yield* db.insert(groups).values({ name, code, createdBy: viewer.userId }).returning({ id: groups.id })
yield* db.insert(members).values({ group: g!.id, user: viewer.userId, name: myName })
return g!.id
}),
/** Join with an invite code. Joining a group you are already in just returns it. */
joinGroup: mutation({ code: inviteCode, name: displayName }, function* ({ code, name }) {
const db = yield* Db
const viewer = yield* Viewer
const [g] = yield* db.select().from(groups).where(eq(groups.code, code)).limit(1)
if (!g) return yield* new InvalidCode()
const [existing] = yield* db
.select({ id: members.id })
.from(members)
.where(and(eq(members.group, g.id), eq(members.user, viewer.userId)))
.limit(1)
if (existing) return g.id
if (yield* nameTaken(g.id, name)) return yield* new NameTaken({ name })
yield* db.insert(members).values({ group: g.id, user: viewer.userId, name })
return g.id
}),
addExpense: mutation(
{ group: id("groups"), description, amount, payer, participants },
function* ({ group, description, amount, payer, participants }) {
yield* requireMember(group)
const db = yield* Db
const viewer = yield* Viewer
const wanted = [...new Set([payer, ...participants])]
const found = yield* db.select().from(members).where(and(eq(members.group, group), inArray(members.id, wanted))).limit(200)
if (found.length !== wanted.length) return yield* new NotInGroup()
const splitters = joinOrder(found.filter((m) => participants.includes(m.id)))
const parts = splitEqually(amount, splitters.length)
const [e] = yield* db
.insert(expenses)
.values({ group, description, amount, payer, createdBy: viewer.userId })
.returning({ id: expenses.id })
for (const [i, m] of splitters.entries()) {
yield* db.insert(shares).values({ group, expense: e!.id, member: m.id, amount: parts[i]! })
}
return e!.id
},
),
/** Only whoever added an expense can delete it. */
removeExpense: mutation({ expense: id("expenses") }, function* ({ expense }) {
const db = yield* Db
const viewer = yield* Viewer
const e = yield* db.get(expenses, expense)
yield* requireMember(e.group)
if (e.createdBy !== viewer.userId) return yield* new NotCreator()
yield* db.delete(expenses).where(eq(expenses.id, expense)) // its shares go with it
}),
},
})
server/seed.ts70 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"
// Sample data for `pnpm storyboard`, created through the real mutations.
// "viewer" is the user the storyboard browses as; the others are other people.
export default defineSeed(app, ({ as, at, day }) => {
const me = as("viewer")
const ana = as("Ana")
const marc = as("Marc")
const sofia = as("Sofia")
// A trip with four people and a week of expenses (some do not divide evenly).
at(-9, "10:00")
const lisbon = me.mutationOk("createGroup", { name: "Lisbon trip", myName: "Alex" })
const lisbonCode = me.queryOk("group", { group: lisbon }).code
at(-9, "10:30")
ana.mutationOk("joinGroup", { code: lisbonCode, name: "Ana" })
marc.mutationOk("joinGroup", { code: lisbonCode, name: "Marc" })
sofia.mutationOk("joinGroup", { code: lisbonCode, name: "Sofia" })
const lisbonMembers = Object.fromEntries(me.queryOk("group", { group: lisbon }).members.map((m) => [m.name, m.id]))
const everyone = Object.values(lisbonMembers)
const [alex, anaM, marcM, sofiaM] = [lisbonMembers.Alex!, lisbonMembers.Ana!, lisbonMembers.Marc!, lisbonMembers.Sofia!]
at(-8, "14:20")
me.mutationOk("addExpense", { group: lisbon, description: "Airbnb, 5 nights", amount: 62000, payer: alex, participants: everyone })
at(-8, "21:15")
ana.mutationOk("addExpense", { group: lisbon, description: "Dinner at Cervejaria Ramiro", amount: 14850, payer: anaM, participants: everyone })
at(-7, "13:05")
marc.mutationOk("addExpense", { group: lisbon, description: "Pastéis de Belém", amount: 1000, payer: marcM, participants: [alex, marcM, sofiaM] })
at(-6, "09:40")
sofia.mutationOk("addExpense", { group: lisbon, description: "Train to Sintra", amount: 2260, payer: sofiaM, participants: everyone })
at(-5, "19:30")
me.mutationOk("addExpense", { group: lisbon, description: "Groceries", amount: 8743, payer: alex, participants: [alex, anaM, sofiaM] })
at(-3, "23:10")
const taxi = marc.mutationOk("addExpense", { group: lisbon, description: "Taxi back from the bar", amount: 1850, payer: marcM, participants: everyone })
marc.mutationOk("removeExpense", { expense: taxi })
at(-2, "12:00")
ana.mutationOk("addExpense", { group: lisbon, description: "Tuk-tuk tour", amount: 6000, payer: anaM, participants: [anaM, marcM] })
// A flat Alex joined: already roughly even.
at(-20, "18:00")
const flat = ana.mutationOk("createGroup", { name: "Flat 4B", myName: "Ana" })
const flatCode = ana.queryOk("group", { group: flat }).code
at(-19, "09:00")
me.mutationOk("joinGroup", { code: flatCode, name: "Alex" })
const flatMembers = ana.queryOk("group", { group: flat }).members
const [flatAna, flatAlex] = [flatMembers[0]!.id, flatMembers[1]!.id]
at(-14, "20:00")
ana.mutationOk("addExpense", { group: flat, description: "Internet, October", amount: 3990, payer: flatAna, participants: [flatAna, flatAlex] })
at(-12, "11:00")
me.mutationOk("addExpense", { group: flat, description: "Cleaning supplies", amount: 3990, payer: flatAlex, participants: [flatAna, flatAlex] })
// A fresh group with nothing in it yet (the empty state).
at(-1, "08:30")
const dinner = me.mutationOk("createGroup", { name: "Birthday dinner", myName: "Alex" })
// A group Alex has not joined (the join page).
at(-1, "17:00")
const ski = marc.mutationOk("createGroup", { name: "Ski weekend", myName: "Marc" })
const skiCode = marc.queryOk("group", { group: ski }).code
day(0)
return {
captures: {
"/groups/$group": [{ group: lisbon }, { group: flat }, { group: dinner }],
"/join/$code": [{ code: skiCode }],
},
}
})
src/main.tsx6 lines
import { start } from "canica/client"
import { routes } from "./routes.gen.ts"
import "./styles.css"
start(routes)
src/routes/__root.tsx15 lines
import { layout, Link } from "canica/client"
import { AppHeader, PageContainer, UserMenu } from "canica/ui"
export default layout({
view: ({ children }) => (
<div className="min-h-screen">
<AppHeader brand={<Link to="/">Splitter</Link>}>
<UserMenu />
</AppHeader>
{/* Frames every page, loading and error states included. */}
<PageContainer>{children}</PageContainer>
</div>
),
})
src/routes/404.tsx21 lines
import { Link, page } from "canica/client"
import { Button, EmptyBlock, PageContainer } from "canica/ui"
/** Shown for a URL that matches no route, or whose params are invalid. */
export default page({
title: "Not found",
view: () => (
<PageContainer>
<EmptyBlock
title="This page does not exist"
description="The link may be wrong, or what it pointed to was deleted."
action={
<Button asChild>
<Link to="/">Back home</Link>
</Button>
}
/>
</PageContainer>
),
})
src/routes/groups/$group.tsx67 lines
import { id, Link, page, plural, useQuery } from "canica/client"
import { Button, CopyButton, ErrorState, Loading, PageContainer, PageHeader, Section } from "canica/ui"
import { AddExpense } from "../../components/AddExpense.tsx"
import { Balances } from "../../components/Balances.tsx"
import { Expenses } from "../../components/Expenses.tsx"
export default page({
params: { group: id("groups") },
title: "Group",
view: ({ params }) => {
const group = useQuery("group", { group: params.group })
return group.match({
loading: () => <Loading shape="list" />,
failure: (error) => (
<ErrorState
error={error}
states={{
NotFound: {
title: "This group does not exist",
description: "The link may be wrong, or the group was deleted.",
action: (
<Button asChild variant="outline">
<Link to="/">Back to your groups</Link>
</Button>
),
},
NotMember: {
title: "You are not in this group",
description: "Ask a member for the invite code to join.",
action: (
<Button asChild>
<Link to="/join">Join with a code</Link>
</Button>
),
},
}}
/>
),
success: (g) => (
<PageContainer>
<PageHeader
title={g.name}
back={<Link to="/">Your groups</Link>}
description={
<span>
{plural(g.members.length, "member")} · invite code <span className="font-mono font-semibold">{g.code}</span>
</span>
}
actions={
<>
<CopyButton value={g.code}>Copy code</CopyButton>
<Button aria-haspopup="dialog" onClick={() => void AddExpense.open({ group: g.id })}>
Add expense
</Button>
</>
}
/>
<Balances group={g.id} />
<Section title="Expenses">
<Expenses group={g.id} />
</Section>
</PageContainer>
),
})
},
})
src/routes/index.tsx93 lines
import { formatCents, Link, page, plural, useNavigate, useQuery } from "canica/client"
import {
Badge,
Button,
EmptyBlock,
ErrorState,
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemTitle,
List,
Loading,
PageContainer,
PageHeader,
} from "canica/ui"
import { CURRENCY } from "../../shared/fields.ts"
import { Money } from "../components/Money.tsx"
import { NewGroup } from "../components/NewGroup.tsx"
export default page({
title: "Your groups",
view: () => {
const groups = useQuery("myGroups")
const openGroup = useNavigate("/groups/$group")
const create = async () => {
const result = await NewGroup.open()
result.match({ done: (group) => openGroup({ group }), cancelled: () => undefined })
}
return (
<PageContainer>
<PageHeader
title="Your groups"
description="Shared expenses, split fairly."
actions={
<>
<Button variant="outline" asChild>
<Link to="/join">Join with a code</Link>
</Button>
<Button aria-haspopup="dialog" onClick={() => void create()}>
New group
</Button>
</>
}
/>
{groups.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) =>
list.length === 0 ? (
<EmptyBlock
title="No groups yet"
description="Start one and share its invite code, or join a friend's group with theirs."
action={
<Button aria-haspopup="dialog" onClick={() => void create()}>
New group
</Button>
}
/>
) : (
<List>
{list.map((g) => (
<Item key={g.id}>
<ItemContent>
<ItemTitle>
<Link to="/groups/$group" params={{ group: g.id }}>
{g.name}
</Link>
</ItemTitle>
<ItemDescription>
{plural(g.members, "member")} · {formatCents(g.spent, CURRENCY)} spent
</ItemDescription>
</ItemContent>
<ItemActions>
{g.net === 0 ? (
<Badge variant="outline">Settled up</Badge>
) : (
<Badge variant={g.net > 0 ? "default" : "destructive"}>
{g.net > 0 ? "You are owed " : "You owe "}
<Money cents={Math.abs(g.net)} />
</Badge>
)}
</ItemActions>
</Item>
))}
</List>
),
})}
</PageContainer>
)
},
})
src/routes/join/$code.tsx63 lines
import { Link, page, plural, string, useForm, useMutation, useNavigate, useQuery } from "canica/client"
import { Button, ErrorState, Form, FormField, Input, Loading, PageContainer, PageHeader, SubmitButton } from "canica/ui"
import { displayName } from "../../../shared/fields.ts"
export default page({
params: { code: string() },
title: "Join a group",
view: ({ params }) => {
const invite = useQuery("invite", { code: params.code })
const join = useMutation("joinGroup")
const openGroup = useNavigate("/groups/$group")
const form = useForm("join with link", { name: displayName }, (values) => join({ code: params.code, ...values }), {
onSuccess: (group) => openGroup({ group }),
})
return invite.match({
loading: () => <Loading shape="text" />,
failure: (error) => (
<ErrorState
error={error}
states={{
InvalidCode: {
title: "No group has this code",
description: "Check the code with whoever invited you.",
action: (
<Button asChild variant="outline">
<Link to="/join">Try another code</Link>
</Button>
),
},
}}
/>
),
success: (g) => (
<PageContainer>
<PageHeader
title={`Join ${g.name}`}
description={plural(g.members, "member") + " so far"}
back={<Link to="/">Your groups</Link>}
/>
{g.joined ? (
<Button asChild className="self-start">
<Link to="/groups/$group" params={{ group: g.group }}>
You are already in: open the group
</Link>
</Button>
) : (
<Form
form={form}
className="max-w-md"
describeError={(e) => (e._tag === "NameTaken" ? `Someone in the group is already called ${e.name}.` : undefined)}
>
<FormField form={form} name="name" label="Your name in the group">
<Input name="name" placeholder="Marc" autoComplete="off" autoFocus />
</FormField>
<SubmitButton form={form}>Join group</SubmitButton>
</Form>
)}
</PageContainer>
),
})
},
})
src/routes/join/index.tsx36 lines
import { page, useForm, useMutation, useNavigate } from "canica/client"
import { Form, FormField, Input, PageContainer, PageHeader, SubmitButton } from "canica/ui"
import { displayName, inviteCode } from "../../../shared/fields.ts"
import { Link } from "canica/client"
export default page({
title: "Join a group",
view: () => {
const join = useMutation("joinGroup")
const openGroup = useNavigate("/groups/$group")
const form = useForm("join group", { code: inviteCode, name: displayName }, (values) => join(values), {
onSuccess: (group) => openGroup({ group }),
})
return (
<PageContainer>
<PageHeader title="Join a group" description="Ask a member for the invite code." back={<Link to="/">Your groups</Link>} />
<Form
form={form}
className="max-w-md"
describeError={(e) =>
e._tag === "InvalidCode" ? "No group has that code." : e._tag === "NameTaken" ? `Someone in the group is already called ${e.name}.` : undefined
}
>
<FormField form={form} name="code" label="Invite code">
<Input name="code" placeholder="K7M2QX" autoComplete="off" className="font-mono uppercase" />
</FormField>
<FormField form={form} name="name" label="Your name in the group">
<Input name="name" placeholder="Marc" autoComplete="off" />
</FormField>
<SubmitButton form={form}>Join group</SubmitButton>
</Form>
</PageContainer>
)
},
})
src/components/AddExpense.tsx73 lines
import { useForm, useMutation, useQuery, type Id } from "canica/client"
import {
Button,
ErrorState,
Form,
FormField,
Input,
Checkbox,
Label,
Loading,
modal,
ModalActions,
ModalText,
ModalTitle,
NativeSelect,
NativeSelectOption,
SubmitButton,
} from "canica/ui"
import { amount, description, participants, payer } from "../../shared/fields.ts"
/** `await AddExpense.open({ group })`. The members are read live inside, so the form is never stale. */
export const AddExpense = modal()(({ group }: { group: Id<"groups"> }) => {
const close = AddExpense.useClose()
const current = useQuery("group", { group })
const addExpense = useMutation("addExpense")
const form = useForm("add expense", { description, amount, payer, participants }, (values) => addExpense({ group, ...values }), {
onSuccess: () => close(),
})
return (
<>
<ModalTitle>Add expense</ModalTitle>
<ModalText>The amount is split equally; leftover cents go to the first people in the list.</ModalText>
{current.match({
loading: () => <Loading shape="text" />,
failure: (error) => <ErrorState error={error} />,
success: (g) => (
<Form form={form} describeError={(e) => (e._tag === "NotInGroup" ? "Someone you picked is not in this group." : undefined)}>
<FormField form={form} name="description" label="What was it for?">
<Input name="description" placeholder="Dinner at Cervejaria" autoComplete="off" autoFocus />
</FormField>
<FormField form={form} name="amount" label="Amount (EUR)">
<Input name="amount" inputMode="decimal" placeholder="45.60" autoComplete="off" />
</FormField>
<FormField form={form} name="payer" label="Paid by">
<NativeSelect name="payer" defaultValue={g.me} className="w-full">
{g.members.map((m) => (
<NativeSelectOption key={m.id} value={m.id}>
{m.isMe ? `${m.name} (you)` : m.name}
</NativeSelectOption>
))}
</NativeSelect>
</FormField>
<FormField form={form} name="participants" label="Split equally between">
{g.members.map((m) => (
<Label key={m.id}>
<Checkbox name="participants" value={m.id} defaultChecked />
{m.name}
</Label>
))}
</FormField>
<ModalActions>
<Button type="button" variant="outline" onClick={close.cancel}>
Cancel
</Button>
<SubmitButton form={form}>Add expense</SubmitButton>
</ModalActions>
</Form>
),
})}
</>
)
})
src/components/Balances.tsx71 lines
import { type Id, plural, useQuery } from "canica/client"
import { Badge, EmptyBlock, ErrorState, Item, ItemActions, ItemContent, ItemDescription, ItemTitle, List, Loading, Section, Stat, Stats } from "canica/ui"
import { Money } from "./Money.tsx"
/** The totals row, every member's net balance and the transfers that settle everyone. */
export function Balances({ group }: { readonly group: Id<"groups"> }) {
const balances = useQuery("balances", { group })
const info = useQuery("group", { group })
return balances.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (b) => {
const total = b.members.reduce((sum, m) => sum + m.paid, 0)
const me = info._tag === "Success" ? b.members.find((m) => m.member === info.value.me) : undefined
return (
<>
<Stats>
<Stat label="Total spent" value={<Money cents={total} />} hint={plural(b.members.length, "member")} />
<Stat
label="Your balance"
value={<Money cents={me?.net ?? 0} signed />}
tone={!me || me.net === 0 ? "default" : me.net > 0 ? "positive" : "negative"}
hint={!me || me.net === 0 ? "You are even" : me.net > 0 ? "You are owed" : "You owe"}
/>
</Stats>
<Section title="Settle up" description="The fewest payments that clear every balance.">
{b.transfers.length === 0 ? (
<EmptyBlock title="All settled up" description="Nobody owes anybody anything right now." />
) : (
<List>
{b.transfers.map((t) => (
<Item key={`${t.from}-${t.to}`}>
<ItemContent>
<ItemTitle>{`${t.fromName} pays ${t.toName}`}</ItemTitle>
</ItemContent>
<ItemActions>
<Money cents={t.amount} />
</ItemActions>
</Item>
))}
</List>
)}
</Section>
<Section title="Members">
<List>
{b.members.map((m) => (
<Item key={m.member}>
<ItemContent>
<ItemTitle>
<span>{m.name}</span>
{info._tag === "Success" && info.value.me === m.member && <Badge variant="secondary">You</Badge>}
</ItemTitle>
<ItemDescription>
Paid <Money cents={m.paid} /> · share <Money cents={m.owed} />
</ItemDescription>
</ItemContent>
<ItemActions>
<Badge variant={m.net === 0 ? "outline" : m.net > 0 ? "default" : "destructive"}>
<Money cents={m.net} signed />
</Badge>
</ItemActions>
</Item>
))}
</List>
</Section>
</>
)
},
})
}
src/components/Expenses.tsx61 lines
import { formatDate, type Id, plural, useMutation, useQuery, type QueryValue } from "canica/client"
import { Button, confirm, EmptyBlock, ErrorState, Item, ItemActions, ItemContent, ItemDescription, ItemTitle, List, Loading } from "canica/ui"
import { Trash2Icon } from "canica/icons"
import { Money } from "./Money.tsx"
type Expense = QueryValue<"expenses">[number]
function ExpenseRow({ expense }: { readonly expense: Expense }) {
const remove = useMutation("removeExpense")
return (
<Item>
<ItemContent>
<ItemTitle>{expense.description}</ItemTitle>
<ItemDescription>
{`${expense.payerName} paid · split between ${plural(expense.shares.length, "person", "people")} · ${formatDate(expense.createdAt)}`}
</ItemDescription>
</ItemContent>
<ItemActions>
<Money cents={expense.amount} />
{expense.mine && (
<Button
variant="ghost"
size="icon-sm"
aria-label={`Delete ${expense.description}`}
aria-haspopup="dialog"
onClick={async () => {
const answer = await confirm({
title: `Delete "${expense.description}"?`,
description: "Balances are recalculated without it.",
confirm: "Delete",
})
if (answer._tag === "Done") await remove({ expense: expense.id })
}}
>
<Trash2Icon />
</Button>
)}
</ItemActions>
</Item>
)
}
/** The group's expenses, newest first, live. */
export function Expenses({ group }: { readonly group: Id<"groups"> }) {
const expenses = useQuery("expenses", { group })
return expenses.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) =>
list.length === 0 ? (
<EmptyBlock title="No expenses yet" description="Add the first one and everyone sees it right away." />
) : (
<List>
{list.map((e) => (
<ExpenseRow key={e.id} expense={e} />
))}
</List>
),
})
}
src/components/Money.tsx9 lines
import { formatCents } from "canica/client"
import { CURRENCY } from "../../shared/fields.ts"
/** An amount of money, aligned in columns. `signed` shows "+" for credit and "−" for debt. */
export function Money({ cents, signed = false }: { readonly cents: number; readonly signed?: boolean }) {
const sign = !signed || cents === 0 ? "" : cents > 0 ? "+" : "−"
return <span className="tabular-nums">{sign + formatCents(Math.abs(cents), CURRENCY)}</span>
}
src/components/NewGroup.tsx33 lines
import { useForm, useMutation, type Id } from "canica/client"
import { Form, FormField, Input, modal, ModalActions, ModalText, ModalTitle, SubmitButton, Button } from "canica/ui"
import { displayName, groupName } from "../../shared/fields.ts"
/** `const r = await NewGroup.open()`: done with the new group's id. */
export const NewGroup = modal<Id<"groups">>()(() => {
const close = NewGroup.useClose()
const createGroup = useMutation("createGroup")
const form = useForm("create group", { name: groupName, myName: displayName }, (values) => createGroup(values), {
onSuccess: (group) => close(group),
})
return (
<>
<ModalTitle>New group</ModalTitle>
<ModalText>You get an invite code to share with the others.</ModalText>
<Form form={form}>
<FormField form={form} name="name" label="Group name">
<Input name="name" placeholder="Lisbon trip" autoComplete="off" autoFocus />
</FormField>
<FormField form={form} name="myName" label="Your name in the group">
<Input name="myName" placeholder="Ana" autoComplete="off" />
</FormField>
<ModalActions>
<Button type="button" variant="outline" onClick={close.cancel}>
Cancel
</Button>
<SubmitButton form={form}>Create group</SubmitButton>
</ModalActions>
</Form>
</>
)
})
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
* App theme: shadcn preset b3HHrTwgna (style rhea, green on neutral, font instrument-serif, radius medium).
* Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b3HHrTwgna
* and apply the new code with `pnpm exec canica theme <code>`, or edit these tokens by hand.
*/
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.527 0.154 150.069);
--primary-foreground: oklch(0.982 0.018 155.826);
--secondary: oklch(0.967 0.001 286.375);
--secondary-foreground: oklch(0.21 0.006 285.885);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.527 0.154 150.069);
--accent-foreground: oklch(0.982 0.018 155.826);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.897 0.196 126.665);
--chart-2: oklch(0.768 0.233 130.85);
--chart-3: oklch(0.648 0.2 131.684);
--chart-4: oklch(0.532 0.157 131.589);
--chart-5: oklch(0.453 0.124 130.933);
--radius: 0.625rem;
--font-body: "Instrument Serif", ui-sans-serif, system-ui, sans-serif;
--font-display: "JetBrains Mono", ui-serif, Georgia, serif;
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.448 0.119 151.328);
--primary-foreground: oklch(0.982 0.018 155.826);
--secondary: oklch(0.274 0.006 286.033);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.448 0.119 151.328);
--accent-foreground: oklch(0.982 0.018 155.826);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.897 0.196 126.665);
--chart-2: oklch(0.768 0.233 130.85);
--chart-3: oklch(0.648 0.2 131.684);
--chart-4: oklch(0.532 0.157 131.589);
--chart-5: oklch(0.453 0.124 130.933);
}
server/index.test.ts205 lines
import { describe, expect, it } from "vitest"
import type { Id } from "canica/server"
import { missingId, testApp } from "canica/testing"
import { settle, splitEqually } from "../shared/split.ts"
import app from "./index.ts"
/** Ana creates "Trip"; Marc and Sofia join. Returns the ids tests need. */
const trip = () => {
const t = testApp(app)
const ana = t.as("ana")
const marc = t.as("marc")
const sofia = t.as("sofia")
const group = ana.mutationOk("createGroup", { name: "Trip", myName: "Ana" })
const { code } = ana.queryOk("group", { group })
marc.mutationOk("joinGroup", { code, name: "Marc" })
sofia.mutationOk("joinGroup", { code, name: "Sofia" })
const ids = Object.fromEntries(ana.queryOk("group", { group }).members.map((m) => [m.name, m.id])) as Record<string, Id<"members">>
return { t, ana, marc, sofia, group, code, ids }
}
describe("membership and permissions", () => {
it("non-members cannot read or write a group", () => {
const { t, group, ids } = trip()
const eve = t.as("eve")
for (const q of ["group", "expenses", "balances"] as const) {
expect(eve.query(q, { group })).toMatchObject({ _tag: "Failure", error: { _tag: "NotMember" } })
}
expect(
eve.mutation("addExpense", { group, description: "Sneaky", amount: 100, payer: ids.Ana!, participants: [ids.Ana!] }),
).toMatchObject({ _tag: "Failure", error: { _tag: "NotMember" } })
expect(eve.queryOk("myGroups")).toEqual([])
})
it("an unknown group is NotFound, not NotMember", () => {
const { ana } = trip()
expect(ana.query("group", { group: missingId("groups") })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
})
it("joins by code (any case), picks a unique name, and joining twice is harmless", () => {
const { t, ana, group, code } = trip()
const eve = t.as("eve")
expect(eve.mutation("joinGroup", { code: "NOPE00", name: "Eve" })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidCode" } })
expect(eve.mutation("joinGroup", { code, name: "ana" })).toMatchObject({ _tag: "Failure", error: { _tag: "NameTaken", name: "ana" } })
expect(eve.mutationOk("joinGroup", { code: code.toLowerCase(), name: " Eve " })).toBe(group)
expect(eve.mutationOk("joinGroup", { code, name: "Other" })).toBe(group)
expect(ana.queryOk("group", { group }).members.map((m) => m.name)).toEqual(["Ana", "Marc", "Sofia", "Eve"])
expect(eve.queryOk("group", { group }).members.filter((m) => m.isMe)).toHaveLength(1)
})
it("the invite lookup shows only the name, and whether you are already in", () => {
const { t, ana, code, group } = trip()
expect(t.as("eve").queryOk("invite", { code })).toEqual({ group, name: "Trip", members: 3, joined: false })
expect(ana.queryOk("invite", { code })).toMatchObject({ joined: true })
expect(t.as("eve").query("invite", { code: "ZZZZZZ" })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidCode" } })
})
it("home lists only my groups", () => {
const { t, ana, marc } = trip()
const other = t.as("zoe").mutationOk("createGroup", { name: "Zoe's", myName: "Zoe" })
expect(ana.queryOk("myGroups")).toMatchObject([{ name: "Trip", members: 3, spent: 0, net: 0 }])
expect(marc.queryOk("myGroups").map((g) => g.name)).toEqual(["Trip"])
expect(t.as("zoe").queryOk("myGroups").map((g) => g.id)).toEqual([other])
})
it("only the creator deletes an expense, and only members can try", () => {
const { t, ana, marc, group, ids } = trip()
const expense = ana.mutationOk("addExpense", { group, description: "Taxi", amount: 3000, payer: ids.Ana!, participants: [ids.Ana!, ids.Marc!] })
expect(marc.mutation("removeExpense", { expense })).toMatchObject({ _tag: "Failure", error: { _tag: "NotCreator" } })
expect(t.as("eve").mutation("removeExpense", { expense })).toMatchObject({ _tag: "Failure", error: { _tag: "NotMember" } })
expect(marc.queryOk("expenses", { group })).toHaveLength(1)
expect(marc.queryOk("expenses", { group })[0]).toMatchObject({ mine: false })
expect(ana.queryOk("expenses", { group })[0]).toMatchObject({ mine: true })
expect(ana.mutation("removeExpense", { expense })._tag).toBe("Success")
expect(ana.queryOk("expenses", { group })).toEqual([])
// its shares went with it
expect(ana.queryOk("balances", { group }).members.every((m) => m.owed === 0 && m.paid === 0)).toBe(true)
expect(ana.mutation("removeExpense", { expense })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
})
it("payer and participants must belong to the group", () => {
const { t, ana, group, ids } = trip()
const stranger = t.as("zoe").mutationOk("createGroup", { name: "Zoe's", myName: "Zoe" })
const zoe = t.as("zoe").queryOk("group", { group: stranger }).me
expect(ana.mutation("addExpense", { group, description: "x", amount: 100, payer: zoe, participants: [ids.Ana!] })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotInGroup" },
})
expect(ana.mutation("addExpense", { group, description: "x", amount: 100, payer: ids.Ana!, participants: [zoe] })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotInGroup" },
})
})
it("validates the expense fields", () => {
const { ana, group, ids } = trip()
const base = { group, description: "Lunch", amount: 1000, payer: ids.Ana!, participants: [ids.Ana!] }
expect(ana.mutation("addExpense", { ...base, description: " " })).toMatchObject({ error: { _tag: "InvalidArgs", issues: [{ path: ["description"] }] } })
expect(ana.mutation("addExpense", { ...base, amount: 0 })).toMatchObject({ error: { _tag: "InvalidArgs", issues: [{ path: ["amount"] }] } })
expect(ana.mutation("addExpense", { ...base, amount: 10.5 })).toMatchObject({ error: { _tag: "InvalidArgs", issues: [{ path: ["amount"] }] } })
expect(ana.mutation("addExpense", { ...base, participants: [] })).toMatchObject({ error: { _tag: "InvalidArgs", issues: [{ path: ["participants"] }] } })
})
})
describe("rounding and balances", () => {
it("splitEqually hands leftover cents to the first shares and always adds up", () => {
expect(splitEqually(100, 3)).toEqual([34, 33, 33])
expect(splitEqually(1, 3)).toEqual([1, 0, 0])
expect(splitEqually(1000, 4)).toEqual([250, 250, 250, 250])
for (let total = 1; total < 400; total++) {
for (let parts = 1; parts <= 9; parts++) {
const shares = splitEqually(total, parts)
expect(shares.reduce((a, b) => a + b, 0)).toBe(total)
expect(Math.max(...shares) - Math.min(...shares)).toBeLessThanOrEqual(1)
}
}
})
it("settle clears every balance with at most n-1 transfers, deterministically", () => {
const nets = [
{ member: "a", net: 5000 },
{ member: "b", net: -2000 },
{ member: "c", net: -1500 },
{ member: "d", net: -1500 },
]
const transfers = settle(nets)
expect(transfers).toEqual([
{ from: "b", to: "a", amount: 2000 },
{ from: "c", to: "a", amount: 1500 },
{ from: "d", to: "a", amount: 1500 },
])
expect(settle([...nets].reverse())).toEqual(transfers)
expect(settle([{ member: "a", net: 0 }])).toEqual([])
})
it("a 100.00 expense between three adds up to the cent; the first member in join order pays the extra cent", () => {
const { ana, group, ids } = trip()
ana.mutationOk("addExpense", { group, description: "Dinner", amount: 10000, payer: ids.Ana!, participants: [ids.Sofia!, ids.Ana!, ids.Marc!] })
const [expense] = ana.queryOk("expenses", { group })
expect(expense!.shares.map((s) => [s.name, s.amount])).toEqual([
["Ana", 3334],
["Marc", 3333],
["Sofia", 3333],
])
const { members, transfers } = ana.queryOk("balances", { group })
expect(members.map((m) => [m.name, m.paid, m.owed, m.net])).toEqual([
["Ana", 10000, 3334, 6666],
["Marc", 0, 3333, -3333],
["Sofia", 0, 3333, -3333],
])
expect(members.reduce((a, m) => a + m.net, 0)).toBe(0)
expect(transfers.map((x) => [x.fromName, x.toName, x.amount]).sort()).toEqual([
["Marc", "Ana", 3333],
["Sofia", "Ana", 3333],
])
})
it("the payer need not take part in the split", () => {
const { ana, group, ids } = trip()
ana.mutationOk("addExpense", { group, description: "Gift for Sofia", amount: 3000, payer: ids.Ana!, participants: [ids.Marc!, ids.Sofia!] })
const { members } = ana.queryOk("balances", { group })
expect(members.map((m) => m.net)).toEqual([3000, -1500, -1500])
})
it("balances always sum to zero and transfers settle them, across many expenses", () => {
const { ana, marc, sofia, group, ids } = trip()
const all = [ids.Ana!, ids.Marc!, ids.Sofia!]
ana.mutationOk("addExpense", { group, description: "a", amount: 1001, payer: ids.Ana!, participants: all })
marc.mutationOk("addExpense", { group, description: "b", amount: 3333, payer: ids.Marc!, participants: [ids.Marc!, ids.Sofia!] })
sofia.mutationOk("addExpense", { group, description: "c", amount: 777, payer: ids.Sofia!, participants: all })
ana.mutationOk("addExpense", { group, description: "d", amount: 1, payer: ids.Ana!, participants: all })
const { members, transfers } = ana.queryOk("balances", { group })
expect(members.reduce((a, m) => a + m.net, 0)).toBe(0)
expect(members.reduce((a, m) => a + m.paid, 0)).toBe(1001 + 3333 + 777 + 1)
expect(members.reduce((a, m) => a + m.owed, 0)).toBe(1001 + 3333 + 777 + 1)
const after = new Map(members.map((m) => [m.member, m.net]))
for (const x of transfers) {
after.set(x.from, after.get(x.from)! + x.amount)
after.set(x.to, after.get(x.to)! - x.amount)
}
expect([...after.values()]).toEqual([0, 0, 0])
expect(transfers.length).toBeLessThanOrEqual(2)
})
it("deleting an expense takes it out of the balances; the home list shows my net", () => {
const { ana, marc, group, ids } = trip()
ana.mutationOk("addExpense", { group, description: "Dinner", amount: 9000, payer: ids.Ana!, participants: [ids.Ana!, ids.Marc!, ids.Sofia!] })
const second = marc.mutationOk("addExpense", { group, description: "Drinks", amount: 3000, payer: ids.Marc!, participants: [ids.Ana!, ids.Marc!] })
expect(ana.queryOk("myGroups")).toMatchObject([{ spent: 12000, net: 6000 - 1500 }])
expect(marc.queryOk("myGroups")).toMatchObject([{ spent: 12000, net: -3000 + 1500 }])
marc.mutationOk("removeExpense", { expense: second })
expect(ana.queryOk("myGroups")).toMatchObject([{ spent: 9000, net: 6000 }])
expect(ana.queryOk("balances", { group }).transfers.map((x) => x.amount)).toEqual([3000, 3000])
})
it("expenses list newest first with who paid and who shares", () => {
const { t, ana, group, ids } = trip()
ana.mutationOk("addExpense", { group, description: "First", amount: 500, payer: ids.Ana!, participants: [ids.Ana!] })
t.advance(60_000)
ana.mutationOk("addExpense", { group, description: "Second", amount: 700, payer: ids.Marc!, participants: [ids.Ana!, ids.Marc!] })
const list = ana.queryOk("expenses", { group })
expect(list.map((e) => e.description)).toEqual(["Second", "First"])
expect(list[0]).toMatchObject({ payerName: "Marc", amount: 700, shares: [{ name: "Ana", amount: 350 }, { name: "Marc", amount: 350 }] })
})
})
src/app.test.tsx133 lines
import { describe, it } from "vitest"
import { as, choose, click, label, meanwhile, missingId, notSee, role, scene, see, testApp, text, type, visit, within } from "canica/testing"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"
describe("splitter (scenes)", () => {
it("two people: create, join with the code, add expenses, balances update live, delete", async () => {
const t = testApp(app)
let code = ""
await scene(t, routes,
as("ana"),
visit("/"),
see(text("No groups yet")),
click(role("button", { name: "New group" })),
within(
role("dialog"),
type(label("Group name"), "Lisbon trip"),
type(label("Your name in the group"), "Ana"),
click(role("button", { name: "Create group" })),
),
see(role("heading", { name: "Lisbon trip" })),
see(text("All settled up")),
see(text("No expenses yet")),
meanwhile(() => {
const [g] = t.as("ana").queryOk("myGroups")
code = t.as("ana").queryOk("group", { group: g!.id }).code
}),
// Marc joins with the code from the join page.
as("marc"),
visit("/join"),
type(label("Invite code"), () => code.toLowerCase()),
type(label("Your name in the group"), "Marc"),
click(role("button", { name: "Join group" })),
see(role("heading", { name: "Lisbon trip" })),
see(text("Marc")),
see(text(/Total spent/)),
)
})
it("expenses and balances show up live for both people", async () => {
const t = testApp(app)
const group = t.as("ana").mutationOk("createGroup", { name: "Flat", myName: "Ana" })
const { code } = t.as("ana").queryOk("group", { group })
await scene(t, routes,
as("ana"),
visit("/groups/$group", { group }),
see(role("heading", { name: "Flat" })),
meanwhile(() => void t.as("marc").mutationOk("joinGroup", { code, name: "Marc" })),
see(role("heading", { name: "Flat" })),
see(text("Marc")),
// Ana pays 100.00 for both of them.
click(role("button", { name: "Add expense" })),
within(
role("dialog"),
type(label("What was it for?"), "Groceries"),
type(label("Amount (EUR)"), "100.00"),
click(role("button", { name: "Add expense" })),
),
see(text("Groceries")),
see(text(/Ana paid · split between 2 people/)),
see(text("Marc pays Ana")),
see(role("button", { name: "Delete Groceries" })),
// Marc sees it live, cannot delete Ana's expense, and adds one paid by himself for only Ana.
as("marc"),
see(text("Groceries")),
notSee(role("button", { name: "Delete Groceries" })),
click(role("button", { name: "Add expense" })),
within(
role("dialog"),
type(label("What was it for?"), "Cinema"),
type(label("Amount (EUR)"), "9.99"),
choose(label("Paid by"), "Marc (you)"),
click(role("checkbox", { name: "Marc" })),
click(role("button", { name: "Add expense" })),
),
see(text("Cinema")),
see(role("button", { name: "Delete Cinema" })),
// Marc owes Ana 50.00 and Ana owes Marc 9.99: net Marc → Ana 40.01.
see(text("Marc pays Ana")),
see(text("€40.01")),
// Back on Ana's side the same numbers, live; then she deletes her expense.
as("ana"),
see(text("Cinema")),
see(text("Marc pays Ana")),
click(role("button", { name: "Delete Groceries" })),
see(role("alertdialog")),
within(role("alertdialog"), click(role("button", { name: "Delete" }))),
notSee(text("Groceries")),
see(text("Ana pays Marc")),
see(text("€9.99")),
)
})
it("someone outside the group sees a join offer, not its data; unknown groups and codes say so", async () => {
const t = testApp(app)
const group = t.as("ana").mutationOk("createGroup", { name: "Secret trip", myName: "Ana" })
const { code } = t.as("ana").queryOk("group", { group })
t.as("ana").mutationOk("addExpense", {
group,
description: "Hidden hotel",
amount: 5000,
payer: t.as("ana").queryOk("group", { group }).me,
participants: [t.as("ana").queryOk("group", { group }).me],
})
await scene(t, routes,
as("eve"),
visit("/groups/$group", { group }),
see(text("You are not in this group")),
notSee(text("Hidden hotel")),
notSee(text("Secret trip")),
visit("/"),
see(text("No groups yet")),
visit("/join/$code", { code }),
see(role("heading", { name: "Join Secret trip" })),
type(label("Your name in the group"), "Ana"),
click(role("button", { name: "Join group" })),
see(text("Someone in the group is already called Ana.")),
type(label("Your name in the group"), "Eve"),
click(role("button", { name: "Join group" })),
see(role("heading", { name: "Secret trip" })),
see(text("Hidden hotel")),
visit("/groups/$group", { group: missingId("groups") }),
see(text("This group does not exist")),
visit("/join/$code", { code: "NOPE00" }),
see(text("No group has this code")),
)
})
})