Build a booking app with Claude Code
In this tutorial Claude Code builds Stillwater, a booking app for a yoga and pilates studio: members book a mat in one tap and see only their own bookings, a full or started class can't be booked whoever asks, instructors get a desk with a chart and check-in, garden classes show the weather, an AI suggests a class, and people sign in with Google. The project is plain TypeScript and SQL, and every file is on this page.
What you need
- An Appbricx account (free).
- Claude Code. Any MCP client works the same way.
- About 30 minutes.
1. Connect Claude Code
In your project folder, add the Appbricx MCP server:
claude mcp add --transport http appbricx https://appbricx.com/api/mcpOr commit this .mcp.json so everyone on the project gets it:
{
"mcpServers": {
"appbricx": {
"type": "http",
"url": "https://appbricx.com/api/mcp"
}
}
}
Start claude, run /mcp, pick appbricx and choose Authenticate. Sign in in the browser, pick your workspace, leave read, apply and deploy ticked and authorize. No token to copy.
2. The prompt
Use appbricx. Create a code-first project "Studio Bookings" for Stillwater,
a yoga and pilates studio in Lisbon (brand colour #2F7D6D).
- Members sign up (also with Google), see the week's classes, book a mat in
one tap and cancel. They see only their own bookings and profile.
- Instructors see the week's load as a chart and check people in or mark
no-shows.
- Never let a full class or one that has started be booked, whoever calls.
- Tell instructors about each new booking, and send them a digest at 07:00
Lisbon time.
- Garden classes get a "check the forecast" button that calls Open-Meteo on
the server. Add an AI "Not sure what to take?" box that suggests one class.
- Seed a few classes over the next days and two members.
Check every file, apply, try it as each role with call_app and screenshots,
dry-run the workflows, verify until it passes, then deploy with the
subdomain stillwater.Claude reads the guide (get_guide), creates the project (create_project), writes each file with the code tool and adds the chart library with packages. The rest of this page is what it wrote and how each part was checked.
code { "project_id": "…", "action": "create", "kind": "table", "name": "booking",
"content": "<db/schema/booking.sql>", "then": "check" }
packages { "project_id": "…", "action": "add", "packages": ["recharts"], "then": "check" }
code { "project_id": "…", "action": "list" }
project_files { "project_id": "…", "action": "apply" }3. The app: app.config.ts
app.config.ts
// app.config.ts: Stillwater's brand, sign-in, roles and what streams live.
import { defineApp } from "@appbricx/define";
export default defineApp({
brand: { name: "Stillwater", tagline: "Yoga and pilates in Lisbon", color: "#2F7D6D" },
locale: { language: "en-GB", currency: "EUR", timezone: "Europe/Lisbon" },
auth: {
providers: ["password", "google", "magicLink"],
signup: { as: ["member"] },
admin: "instructor",
},
roles: {
member: { kind: "consumer", label: "Member", profile: { table: "member_profile", create: true } },
instructor: { kind: "staff", label: "Instructor" },
},
http: { allow: ["api.open-meteo.com"] },
realtime: { live: ["class_session", "booking"] },
});
- Roles: members sign themselves up (
consumer); instructors run the studio (staff) and the built-in admin sign-in is one (auth.admin). profile: { table: "member_profile", create: true }: the platform inserts each new member's row (name and email) at sign-up, Google sign-in or invite.auth.providersturns on Google next to passwords and sign-in links: that list is the whole setup for Google sign-in.http.allow: server code may reach Open-Meteo and nothing else.realtime.live: changes to classes and bookings stream to the pages that follow them.
4. The database
Tables are plain SQL, written as what the database should look like. Each apply works out the change and keeps the rows.
db/schema/profiles.sql
-- db/schema/profiles.sql: one row per member, linked to their account by user_id.
create table if not exists member_profile (
id uuid primary key default gen_random_uuid(),
user_id uuid unique default ctx.uid(), -- null until someone signs in as this member
name text not null,
email ctx.email,
created_at timestamptz not null default now()
);
comment on column member_profile.email is '@pii';
db/schema/class_session.sql
-- db/schema/class_session.sql: the timetable.
create table if not exists class_session (
id uuid primary key default gen_random_uuid(),
title text not null,
style text not null default 'vinyasa',
instructor text not null,
starts_at timestamptz not null,
duration_min int not null default 60,
capacity int not null,
booked int not null default 0,
garden boolean not null default false,
created_at timestamptz not null default now(),
constraint class_session_style_known check (style in ('vinyasa', 'pilates', 'yin', 'breathwork')),
constraint class_session_capacity_positive check (capacity > 0),
constraint class_session_never_overbooked check (booked between 0 and capacity)
);
create index if not exists class_session_starts on class_session (starts_at);
db/schema/booking.sql
-- db/schema/booking.sql: a member's mat in a class.
create table if not exists booking (
id uuid primary key default gen_random_uuid(),
session_id uuid not null references class_session on delete cascade,
member_id uuid not null references member_profile on delete cascade default ctx.profile_id('member'),
status text not null default 'booked',
created_at timestamptz not null default now()
);
create index if not exists booking_session on booking (session_id);
create index if not exists booking_member on booking (member_id);
create unique index if not exists booking_once on booking (session_id, member_id) where status = 'booked';
select ctx.lifecycle('booking', 'status', $$
booked -> cancelled | attended | no_show
$$);
-- Seats: refuse a full or started class, keep class_session.booked current.
-- @definer members can't update class_session; this only moves its booked count for the class being booked or cancelled
create or replace function booking_seats() returns trigger
language plpgsql security definer set search_path = public as $$
declare
s class_session%rowtype;
begin
if tg_op = 'INSERT' then
-- Seeds run on every apply: a booking that already exists was counted.
if exists (select 1 from booking where id = new.id) then
return new;
end if;
select * into s from class_session where id = new.session_id for update;
if not found then
raise exception 'That class is no longer on the schedule.';
end if;
if s.starts_at <= now() then
raise exception 'That class has already started.';
end if;
if s.booked >= s.capacity then
raise exception 'That class is full. Try another time.';
end if;
update class_session set booked = booked + 1 where id = s.id;
elsif new.session_id is distinct from old.session_id then
raise exception 'Cancel this booking and book the other class instead.';
elsif old.status = 'booked' and new.status = 'cancelled' then
update class_session set booked = greatest(booked - 1, 0) where id = new.session_id;
end if;
return new;
end $$;
create or replace trigger booking_seats before insert or update on booking
for each row execute function booking_seats();
member_id … default ctx.profile_id('member'): a booking is the booker's. The page sends only the class.booking_once: a partial unique index, so a member can't hold two mats in one class (a cancelled booking doesn't count).ctx.lifecycle: a booking moves frombookedtocancelled,attendedorno_show, and nowhere after.- The
booking_seatstrigger is the rule that matters: it locks the class, refuses a full or started one with a message the member reads, and keepsbookedcurrent. It issecurity definerbecause members can't updateclass_session; the-- @definerline above it is the reviewer's sign-off, and verify lists it under functions with elevated rights.
5. Who may do what
db/access/profiles.sql
-- db/access/profiles.sql: members see their own profile; instructors see everyone.
drop policy if exists member_profile_self on member_profile;
create policy member_profile_self on member_profile for all
using (user_id = (select ctx.uid())) with check (user_id = (select ctx.uid()));
drop policy if exists member_profile_instructor_read on member_profile;
create policy member_profile_instructor_read on member_profile for select
using ((select ctx.has_role('instructor')));
db/access/classes.sql
-- db/access/classes.sql: the timetable is public; instructors run it.
drop policy if exists class_session_public_read on class_session;
create policy class_session_public_read on class_session for select using (true);
drop policy if exists class_session_instructor_all on class_session;
create policy class_session_instructor_all on class_session for all
using ((select ctx.has_role('instructor')));
db/access/booking.sql
-- db/access/booking.sql: members book and cancel their own mats; instructors see all.
drop policy if exists booking_member_read on booking;
create policy booking_member_read on booking for select
using (member_id = (select ctx.profile_id('member')));
drop policy if exists booking_member_create on booking;
create policy booking_member_create on booking for insert
with check (member_id = (select ctx.profile_id('member')) and status = 'booked');
drop policy if exists booking_member_cancel on booking;
create policy booking_member_cancel on booking for update
using (member_id = (select ctx.profile_id('member')))
with check (member_id = (select ctx.profile_id('member')) and status = 'cancelled');
drop policy if exists booking_instructor_all on booking;
create policy booking_instructor_all on booking for all
using ((select ctx.has_role('instructor')));
A table with no policy for a role gives that role nothing, and a signed-out visitor has no role. So guests read the timetable and nothing else; members read and cancel only their own bookings (the with check on booking_member_cancel allows exactly one change, to cancelled); instructors do everything. Postgres checks this on every statement, from pages, actions, the API or SQL.
db/queries/week-load.sql
-- db/queries/week-load.sql: mats booked against capacity for the next seven days.
-- @roles instructor
select to_char(starts_at at time zone 'Europe/Lisbon', 'Dy DD') as day,
sum(booked)::int as booked, sum(capacity)::int as capacity
from class_session
where starts_at >= now() and starts_at < now() + interval '7 days'
group by 1, date_trunc('day', starts_at at time zone 'Europe/Lisbon')
order by date_trunc('day', starts_at at time zone 'Europe/Lisbon');
db/seeds/stillwater.sql
-- db/seeds/stillwater.sql: a week of classes and two members.
insert into class_session (id, title, style, instructor, starts_at, duration_min, capacity, garden) values
(ctx.seed_id('cls-sunrise'), 'Sunrise Flow', 'vinyasa', 'Inês', date_trunc('day', now()) + interval '1 day 6 hours 30 minutes', 60, 14, true),
(ctx.seed_id('cls-desk'), 'Desk Reset Pilates', 'pilates', 'Marta', date_trunc('day', now()) + interval '1 day 17 hours 30 minutes', 45, 10, false),
(ctx.seed_id('cls-yin'), 'Slow Yin', 'yin', 'Inês', date_trunc('day', now()) + interval '2 days 18 hours', 75, 12, false),
(ctx.seed_id('cls-breath'), 'Breath and Stretch', 'breathwork', 'João', date_trunc('day', now()) + interval '3 days 7 hours', 45, 1, true)
on conflict (id) do nothing;
-- Ana has no email: the member demo sign-in takes her row. Rui's row waits for rui@example.com.
insert into member_profile (id, name, email) values
(ctx.seed_id('mem-ana'), 'Ana', null),
(ctx.seed_id('mem-rui'), 'Rui', 'rui@example.com')
on conflict (id) do nothing;
insert into booking (id, session_id, member_id) values
(ctx.seed_id('bk-ana-sunrise'), ctx.seed_id('cls-sunrise'), ctx.seed_id('mem-ana')),
(ctx.seed_id('bk-rui-breath'), ctx.seed_id('cls-breath'), ctx.seed_id('mem-rui'))
on conflict (id) do nothing;
Seeds run on every apply, so each insert has on conflict … do nothing, and the seats trigger skips a booking that already exists. Ana has no email: in dev, the member demo sign-in takes her row. Rui's row waits for whoever signs up as rui@example.com.
6. Pages and components
Each file in routes/ is a page; its meta says who may open it. Reads and writes go through @appbricx/ui as the signed-in user, so the policies above decide what each one sees.
routes/_layout.tsx
// routes/_layout.tsx: the header around every page.
import type { ReactNode } from "react";
import { Link, NavLink, useAuth } from "@appbricx/ui";
export default function Layout({ children }: { children: ReactNode }) {
const auth = useAuth();
return (
<div className="min-h-screen bg-[#f6f4ef] text-stone-900">
<header className="flex flex-wrap items-center gap-4 border-b bg-white px-6 py-4">
<Link to="/" className="font-semibold text-[#2F7D6D]">Stillwater</Link>
<NavLink to="/my-classes">My classes</NavLink>
<NavLink to="/desk">Desk</NavLink>
{auth.user ? (
<button type="button" className="ml-auto" onClick={() => void auth.signOut()}>Sign out</button>
) : (
<span className="ml-auto flex gap-4">
<Link to="/signin">Sign in</Link>
<Link to="/signup">Join</Link>
</span>
)}
</header>
{children}
</div>
);
}
lib/format.ts
// lib/format.ts: times in the studio's zone, the same on the server and in the browser.
const when = new Intl.DateTimeFormat("en-GB", {
timeZone: "Europe/Lisbon", weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit",
});
export function classTime(iso: string): string {
return when.format(new Date(iso));
}
routes/index.tsx
// routes/index.tsx: the public timetable, server-rendered; members book in one tap.
import { useState } from "react";
import { defineRoute, Link, useAuth, useLive, useQuery, useTable } from "@appbricx/ui";
import { classForecast } from "../server/forecast";
import { ClassFinder } from "../components/ClassFinder";
import { classTime } from "../lib/format";
export const meta = defineRoute({
public: true,
title: "This week at Stillwater",
seo: { description: "Yoga and pilates classes in Lisbon. Book a mat in one tap." },
});
export default function Schedule() {
const auth = useAuth();
const { rows, loading } = useQuery("class_session", { sort: "starts_at", limit: 50 });
const bookings = useTable("booking");
useLive("class_session"); // the "mats left" counts follow other people's bookings
const [note, setNote] = useState<Record<string, string>>({});
const say = (id: string, text: string) => setNote((n) => ({ ...n, [id]: text }));
const book = async (id: string) => {
try {
await bookings.create({ session_id: id });
say(id, "Booked. See you on the mat.");
} catch (e) {
say(id, e instanceof Error ? e.message : String(e)); // "That class is full. Try another time."
}
};
const forecast = async (id: string) => {
try {
const f = await classForecast({ session: id });
say(id, f.summary + (f.tempC === null ? "" : ", " + Math.round(f.tempC) + "°C"));
} catch (e) {
say(id, e instanceof Error ? e.message : String(e));
}
};
return (
<main className="mx-auto max-w-3xl p-6">
<h1 className="mb-4 text-3xl font-semibold">This week at Stillwater</h1>
{auth.user?.role === "member" ? <ClassFinder classes={rows.map((s) => s.title + " (" + s.style + ") " + classTime(s.starts_at))} /> : null}
{loading ? <p>Loading…</p> : null}
<ul className="grid gap-3">
{rows.map((s) => (
<li key={s.id} className="rounded-lg border bg-white p-4">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h2 className="text-lg font-semibold">{s.title}</h2>
<span className="text-sm text-stone-600">{classTime(s.starts_at)} · {s.duration_min} min · {s.instructor}</span>
</div>
<p className="text-sm text-stone-600">{s.capacity - s.booked} of {s.capacity} mats left</p>
<div className="mt-2 flex gap-3">
{auth.user?.role === "member" ? (
<button type="button" className="rounded bg-[#2F7D6D] px-3 py-1 text-white" disabled={s.booked >= s.capacity} onClick={() => void book(s.id)}>
{s.booked >= s.capacity ? "Full" : "Book a mat"}
</button>
) : auth.user ? null : (
<Link to="/signup" className="underline">Join to book</Link>
)}
{s.garden && auth.user ? (
<button type="button" className="underline" onClick={() => void forecast(s.id)}>Check the forecast</button>
) : null}
</div>
{note[s.id] ? <p role="status" className="mt-2 text-sm">{note[s.id]}</p> : null}
</li>
))}
</ul>
</main>
);
}
- Public and server-rendered: a visitor gets the timetable in the first HTML, read with a guest's rights, and the page hydrates from the same reads. Times are formatted with an explicit time zone so the server and the browser agree.
bookings.create({ session_id })is the whole booking. When the trigger refuses, the promise rejects with its message and the page shows it.useLive("class_session")refetches the page's reads when any class changes, so "mats left" follows other people's bookings.
routes/signup.tsx
// routes/signup.tsx: a visitor becomes a member (the platform creates their member_profile row).
import { useState } from "react";
import { defineRoute, useAuth, useNavigate } from "@appbricx/ui";
export const meta = defineRoute({ public: true, title: "Join Stillwater" });
export default function Join() {
const auth = useAuth();
const navigate = useNavigate();
const [form, setForm] = useState({ name: "", email: "", password: "" });
const [error, setError] = useState("");
const field = (k: "name" | "email" | "password") => ({
value: form[k],
onChange: (e: { target: { value: string } }) => setForm({ ...form, [k]: e.target.value }),
});
const join = async () => {
setError("");
try {
await auth.signUp({ ...form, role: "member" });
navigate("/");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
};
return (
<main className="mx-auto max-w-sm p-6">
<h1 className="mb-4 text-2xl font-semibold">Join Stillwater</h1>
<form className="grid gap-3" onSubmit={(e) => { e.preventDefault(); void join(); }}>
<label className="grid gap-1">Name<input className="rounded border px-3 py-2" required {...field("name")} /></label>
<label className="grid gap-1">Email<input type="email" className="rounded border px-3 py-2" required {...field("email")} /></label>
<label className="grid gap-1">Password<input type="password" className="rounded border px-3 py-2" required {...field("password")} /></label>
<button type="submit" className="rounded bg-[#2F7D6D] px-4 py-2 text-white">Create account</button>
</form>
{error ? <p role="alert" className="mt-3 text-red-700">{error}</p> : null}
</main>
);
}
routes/my-classes.tsx
// routes/my-classes.tsx: a member's own bookings; cancel frees the mat.
import { defineRoute, useQuery, useTable } from "@appbricx/ui";
import { classTime } from "../lib/format";
export const meta = defineRoute({ roles: ["member"], title: "My classes" });
type WithClass = { class_session: { title: string; starts_at: string } | null };
export default function MyClasses() {
const q = useQuery("booking", { sort: "-created_at", embed: "class_session(title,starts_at)" });
const rows = q.rows as (typeof q.rows[number] & WithClass)[]; // embedded rows aren't in the row type
const bookings = useTable("booking");
return (
<main className="mx-auto max-w-3xl p-6">
<h1 className="mb-4 text-2xl font-semibold">My classes</h1>
{!q.loading && rows.length === 0 ? <p>No bookings yet.</p> : null}
<ul className="grid gap-2">
{rows.map((b) => (
<li key={b.id} className="flex items-center gap-3 rounded border bg-white px-4 py-3">
<span className="flex-1">
{b.class_session?.title ?? "A class"} · {b.class_session ? classTime(b.class_session.starts_at) : ""}
</span>
<span className="text-sm text-stone-600">{b.status}</span>
{b.status === "booked" ? (
<button type="button" className="underline" onClick={() => void bookings.update(b.id, { status: "cancelled" })}>
Cancel
</button>
) : null}
</li>
))}
</ul>
</main>
);
}
routes/desk.tsx
// routes/desk.tsx: instructors see the week's load and check people in.
import { defineRoute, useLive, useNamedQuery, useQuery, useTable } from "@appbricx/ui";
import { WeekChart } from "../components/WeekChart";
import { classTime } from "../lib/format";
export const meta = defineRoute({ roles: ["instructor"], title: "Studio desk" });
type Embedded = { class_session: { title: string; starts_at: string } | null; member_profile: { name: string } | null };
export default function Desk() {
const load = useNamedQuery("week-load", {});
const q = useQuery("booking", { where: { status: "booked" }, embed: "class_session(title,starts_at),member_profile(name)", limit: 100 });
const rows = q.rows as (typeof q.rows[number] & Embedded)[];
const bookings = useTable("booking");
useLive("booking"); // new bookings appear as members make them
return (
<main className="mx-auto max-w-4xl p-6">
<h1 className="mb-4 text-2xl font-semibold">Studio desk</h1>
<WeekChart days={load.rows.map((d) => ({ day: String(d.day), booked: Number(d.booked), capacity: Number(d.capacity) }))} />
<h2 className="mb-2 mt-6 text-lg font-semibold">Booked mats</h2>
<ul className="grid gap-2">
{rows.map((b) => (
<li key={b.id} className="flex flex-wrap items-center gap-3 rounded border bg-white px-4 py-3">
<span className="flex-1">
{b.member_profile?.name ?? "A member"} · {b.class_session?.title} · {b.class_session ? classTime(b.class_session.starts_at) : ""}
</span>
<button type="button" className="underline" onClick={() => void bookings.update(b.id, { status: "attended" })}>Here</button>
<button type="button" className="underline" onClick={() => void bookings.update(b.id, { status: "no_show" })}>No-show</button>
</li>
))}
</ul>
</main>
);
}
components/WeekChart.tsx
// components/WeekChart.tsx: mats booked against capacity (recharts, drawn in the browser).
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { defineComponent, p } from "@appbricx/ui";
type Day = { day: string; booked: number; capacity: number };
export const WeekChart = defineComponent({
name: "WeekChart",
props: { days: p.json<Day[]>().default([]) },
client: true, // ResponsiveContainer measures the page: render it after the first paint
skeleton: <div className="h-56 rounded border bg-white" aria-busy="true" />,
render: ({ days }) => (
<div className="h-56 rounded border bg-white p-2">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={days}>
<XAxis dataKey="day" />
<YAxis allowDecimals={false} />
<Tooltip />
<Bar dataKey="capacity" fill="#d6d3cb" />
<Bar dataKey="booked" fill="#2F7D6D" />
</BarChart>
</ResponsiveContainer>
</div>
),
});
embed reads the related rows in the same request (the class of each booking, the member's name). Embedded rows aren't in the generated row types, hence the cast. The chart is a recharts component added with packages; it is client: true because it measures the page, so the server and the first paint render its skeleton.
7. A server action
Pages can't call other hosts, so the forecast runs on the server. The page imports the action and calls it like a function; the build puts a typed call to POST /__appbricx/actions/classForecast in its place, and no server code reaches the browser.
server/forecast.ts
// server/forecast.ts: the weather for a garden class, from Open-Meteo (no key needed).
import { defineAction, v } from "@appbricx/server";
type Hourly = { time?: string[]; temperature_2m?: number[]; precipitation_probability?: number[]; weather_code?: number[] };
export const classForecast = defineAction({
input: v.object({ session: v.uuid() }),
roles: ["member", "instructor"],
handler: async (ctx, input) => {
const s = await ctx.db.get("class_session", input.session); // as the caller: row-level security applies
if (!s) throw new Error("That class isn't on the schedule.");
const hour = new Date(String(s.starts_at)).toISOString().slice(0, 13) + ":00";
const day = hour.slice(0, 10);
const res = await ctx.http.fetch(
"https://api.open-meteo.com/v1/forecast?latitude=38.7223&longitude=-9.1393" +
"&hourly=temperature_2m,precipitation_probability,weather_code&timezone=UTC&start_date=" + day + "&end_date=" + day,
);
if (!res.ok) throw new Error("The forecast service answered " + res.status + ". Try again later.");
const h = res.json<{ hourly?: Hourly }>()?.hourly;
const i = h?.time ? h.time.indexOf(hour) : -1;
if (!h || i < 0) return { tempC: null, rainChance: null, summary: "No forecast yet" };
const code = h.weather_code?.[i] ?? 0;
const summary = code === 0 ? "Clear sky" : code <= 3 ? "Some cloud" : code <= 67 ? "Rain likely" : "Showers";
return { tempC: h.temperature_2m?.[i] ?? null, rainChance: h.precipitation_probability?.[i] ?? null, summary };
},
});
Claude tried it as a member before touching the page:
call_app { "project_id": "…", "kind": "action", "name": "classForecast",
"input": { "session": "<a garden class id>" }, "as": { "kind": "user", "role": "member" } }
// status 200 and { "result": { "tempC": …, "rainChance": …, "summary": "…" } }, or the thrown messageThe input is checked before the handler runs: a session that isn't a uuid is refused with INVALID_INPUT naming the field. See server actions.
8. An AI feature
components/ClassFinder.tsx
// components/ClassFinder.tsx: "Not sure what to take?" on the app's AI, with a fallback.
import { useState } from "react";
import { useAppHandle } from "@appbricx/ui";
const FALLBACK = "Try Sunrise Flow: it suits every level.";
export function ClassFinder({ classes }: { classes: string[] }) {
const app = useAppHandle();
const [feeling, setFeeling] = useState("");
const [advice, setAdvice] = useState("");
const [busy, setBusy] = useState(false);
const ask = async () => {
if (!feeling.trim()) return;
setBusy(true);
try {
const answer = await app.ai.ask("How I feel today: " + feeling + "\n\nClasses this week:\n" + classes.join("\n"), {
system: "You are the front desk of a small yoga and pilates studio. Recommend ONE class from the list and say why in two short sentences. Never invent classes.",
maxTokens: 600,
});
setAdvice(answer.trim() || FALLBACK); // an empty answer counts as a failure
} catch {
setAdvice(FALLBACK); // AI off, over budget, or no credits
} finally {
setBusy(false);
}
};
return (
<form className="mb-6 rounded-lg border bg-white p-4" onSubmit={(e) => { e.preventDefault(); void ask(); }}>
<label className="grid gap-1">
Not sure what to take?
<input className="rounded border px-3 py-2" value={feeling} onChange={(e) => setFeeling(e.target.value)} placeholder="Stiff back after a long week" />
</label>
<button type="submit" className="mt-2 rounded border px-3 py-1" disabled={busy}>{busy ? "Thinking…" : "Suggest a class"}</button>
{advice ? <p role="status" className="mt-2">{advice}</p> : null}
</form>
);
}
app.ai.ask runs on the app's AI with the key kept on the server. The component treats an empty answer as a failure and has a fallback, so the schedule works with AI off, over budget or out of credits. See AI in your app.
9. Workflows and messages
workflows/bookings.ts
// workflows/bookings.ts: tell instructors about bookings, and a morning digest.
import { cron, on } from "@appbricx/workflows";
type Booking = { id: string; session_id: string; member_id: string; status: string };
export const bookingMade = on.created<Booking>("booking", async ({ row }, step) => {
const s = await step.run("class", () => step.ctx.db.get("class_session", row.session_id));
if (!s) return { skipped: "no class" };
await step.send.notify("new-booking", {
role: "instructor",
vars: { title: String(s.title), booked: Number(s.booked), capacity: Number(s.capacity) },
});
return { notified: true };
});
export const morningDigest = cron("07:00", { tz: "Europe/Lisbon" }, async (_event, step) => {
const rows = await step.sql(
"today",
"select count(*)::int as classes, coalesce(sum(booked), 0)::int as mats from class_session " +
"where starts_at >= now() and starts_at < now() + interval '1 day'",
);
const classes = Number(rows[0]?.classes ?? 0);
const mats = Number(rows[0]?.mats ?? 0);
if (classes > 0) await step.send.notify("morning-digest", { role: "instructor", vars: { classes, mats } });
return { classes, mats };
});
messages/notify/new-booking.md
---
title: "New booking: {{title}}"
link: /desk
vars:
title: string
booked: number
capacity: number
sample:
title: Sunrise Flow
booked: 9
capacity: 14
---
{{booked}} of {{capacity}} mats booked.
messages/notify/morning-digest.md
---
title: "Today: {{classes}} {{plural classes \"class\" \"classes\"}}"
link: /desk
vars:
classes: number
mats: number
sample:
classes: 3
mats: 21
---
{{mats}} {{plural mats "mat is" "mats are"}} booked for the next 24 hours.
Both were dry-run before anything was sent: the real code against the dev data, with every effect listed instead of made.
workflows { "project_id": "…", "action": "dry_run", "id": "bookingmade",
"row": { "id": "…", "session_id": "<a class id>", "member_id": "…", "status": "booked" } }
workflows { "project_id": "…", "action": "dry_run", "id": "morningdigest" }
message_previews { "project_id": "…" } // each template rendered with its sample10. Google sign-in
providers: ["password", "google", "magicLink"] in app.config.ts is the setup: the built-in sign-in screen now offers Continue with Google. Where the platform has a shared Google client it works with no setup, for testing (the consent screen names Appbricx). Before launch, put your own Google client in so it shows your name:
sign_in_providers { "project_id": "…", "provider": "google", "client": "own",
"client_id": "…apps.googleusercontent.com", "client_secret": "…" }
// redirect URI to register: https://<app host>/__appbricx/auth/oauth/google/callback11. Try it as each role, then verify
The apply answer lists one demo sign-in per role. Claude then tried what must work and what must fail:
call_app { "project_id": "…", "method": "POST", "path": "/__appbricx/api/v1/booking",
"input": { "session_id": "<Breath and Stretch id>" }, "as": { "kind": "user", "role": "member" } }
// 422 "That class is full. Try another time." (its one mat is Rui's)
explain { "project_id": "…", "about": "access", "table": "booking", "op": "read", "as": "guest" }
// denied, with booking's policies and why none of them passes for a signed-out visitor
screenshot { "project_id": "…", "route": "/", "as": "member",
"steps": [{ "click": "Book a mat" }, { "wait": "Booked" }] }
screenshot { "project_id": "…", "route": "/desk", "as": "instructor" }Then the full check:
verify { "project_id": "…" }
// static: contract, reachability, access-patterns, indexes, workflows
// matrix: role-matrix (member and instructor against every table, writes rolled back), signed-out
// production: logins, secrets, sign-in-providers
// browser: walk:member, walk:instructor, walk:guest, nav-scope
// plus elevated-functions: booking_seats, with its @definer reasonEach failing check comes back with evidence and a fix. The sign-in-providers check warns on production while Google still uses the shared test client. See verify.
12. Deploy
deploy { "project_id": "…", "dry_run": true } // host, first publish or migration, the SQL, workflows armed
deploy { "project_id": "…", "subdomain": "stillwater" }The deploy runs verify again, snapshots production and publishes the same bundle dev runs. The first publish builds production from db/ with only the -- @env prod seeds (no dev test rows); later ones migrate it additively and never drop a column without your say-so.
13. Edit a row on production, and undo it
The studio asks for two more mats in Sunrise Flow. "On prod, set the capacity of Sunrise Flow to 16."
edit_rows { "project_id": "…", "env": "prod", "table": "class_session", "op": "update",
"id": "<Sunrise Flow id>", "patch": { "capacity": 16 } }
// { "succeeded": 1, "snapshotId": "…" }: production was snapshotted first
snapshots { "project_id": "…", "action": "restore", "env": "prod", "id": "<that snapshotId>" }
// restores the database and answers undoSnapshotId, so even the undo can be undoneedit_rows goes through the app's own data API, so the policies and the trigger behave as for a person. See operating your app.
14. The result
- A live app with two roles, three tables, four pages, an action and two workflows, all in files you own.
- Access enforced by Postgres and tested by verify; one trigger that stops overbooking for every caller.
- Live counts, a chart, AI, Google sign-in, and a snapshot before every publish and every production edit.
Make it yours
- Ask Claude for a waitlist: "when a class is full, let members join a waitlist and notify the first one when a mat frees up" (an
on.transitiononcancelled). - Pull the project into your editor with
appbricx pull <project-id> stillwaterand keep going by hand: export. - Take payment per class: payments.
Gotchas
- A trigger runs as the writer. Without
security definerthe seats check would read the class under the member's rights and couldn't update its count. - Seeds run on every apply, and row triggers fire for them: a
BEFORE INSERTtrigger must accept a seed row that already exists. - Times are stored in UTC and formatted in
Europe/Lisbonon purpose: a locale or time zone left to the visitor makes the server render and the browser disagree. - Read the
signed-outline in verify on every app: it says which tables visitors can read.