Le Studio
Booking and studio management for a two-location Pilates studio, rules enforced in Postgres.
- SaaS platforms
- Web products
- Role
- Freelance engineer: discovery, data model, build and delivery
- Client
- Le Studio, Pilates & Gyrotonic (Sousse and Monastir, Tunisia)
- Timeline
- Aug - Sep 2026
- Status
- Live in productionlestudio-pilate.vercel.app

- first commit to all five build plans shipped
- 2 days
- first commit to all five build plans shipped
- Postgres RPCs carrying the business rules
- 9
- Postgres RPCs carrying the business rules
- SQL migrations, 15 tables under RLS
- 17
- SQL migrations, 15 tables under RLS
- Vitest cases and Playwright E2E tests
- 93 + 43
- Vitest cases and Playwright E2E tests
- hero canvas main-thread time on a throttled phone, down from 9-19%
- 3-5%
- hero canvas main-thread time on a throttled phone, down from 9-19%
The problem
Le Studio runs two Pilates and Gyrotonic studios, in Sousse and Monastir. Schedules and bookings lived on paper and WhatsApp, and members paid for packs in cash. The owner's first request was to build each week's schedule herself and let members book against their pack.
Off-the-shelf booking tools only count credits. These packs carry two independent limits: a session balance and a hard weekly cap. A 12-month member with 90 unused sessions still cannot book a third class in a week on a twice-a-week pack, and late cancellations and no-shows must use up both. Prices are in Tunisian dinars (three decimals). The two studios must be fully separated, and the owner must see both.
Architecture
Sign in, land by role
proxy.ts revalidates the session with getUser() on each request and sends each role to its own space. Server Components then read as that user, so RLS decides what each role sees.
- Service
- Data
- AI model
- External
Hard problems I solved
Two limits on every booking, enforced in Postgres
A booking must pass both the credit balance and the weekly quota. A late cancel or no-show must use up both, and only a cancel more than 24 hours ahead refunds both. Rules in app code would not hold against a direct API call made with the public anon key.
Approach. reserver() and annuler() are SECURITY DEFINER functions with a pinned search_path. They re-check role, studio, published week, start time, duplicates, capacity, active pack, and expiry against the class's local date. The balance is the SUM of an append-only ledger. Weekly use is a count of every booking except cancelled ones on a denormalised week_start, so a late cancel needs no ledger entry at all. Refusals state both numbers.
Integration tests call the real RPCs. They check that the fourth booking is refused even with credits left, that a late cancel uses up both limits, and that the ledger balances against live bookings.
Invariants that hold under concurrent writes
A check followed by a write can race: two requests both pass the check and both write. A coach booked in two rooms, a member with two active packs, or a double booking would corrupt schedules and credits.
Approach. The important invariants are structural. A btree_gist exclusion constraint on tstzrange keeps a coach out of two places at once. A partial unique index allows one active pack per member, and unique(session_id, member_id) blocks double booking. Balances are never stored, and money is integer millimes. One gap remains: capacity is a count then an insert under READ COMMITTED, so two members could race for the last place. Locking the session row with SELECT ... FOR UPDATE is the next fix.
A cross-studio leak, reproduced in production and closed
The helper is_staff_or_owner() answered two questions at once. The owner spans both studios; a front desk should not. Using the public anon key, the Sousse desk could read Monastir's bookings, credit ledger and member health notes, and a POST into Monastir's schedule returned 201 Created.
Approach. Two Postgres details made the leak wider. FOR ALL policies also cover SELECT, and permissive policies OR together, so unscoped write policies re-opened reads that were scoped correctly. SECURITY DEFINER functions also skip RLS, so the desk RPCs needed their own checks. Migration 0016 adds private.atteint(studio): the owner reaches every studio, staff only their own. It now guards seven policy pairs and both desk RPCs.
9 new isolation tests. In the fix commit, 93 Vitest cases passed, and 55 Playwright tests passed against production.
Closing PostgREST's open door
PostgREST publishes every function in the public schema at /rest/v1/rpc/<name>, and the anon key ships in the browser. An anonymous visitor could reach the body of creer_membre, a function that writes auth.users. Only a check inside the function stopped them.
Approach. Migration 0014 revokes EXECUTE from both anon and PUBLIC, because Supabase grants to PUBLIC and revoking from anon alone leaves the function open. Only authenticated users keep EXECUTE, so callers are refused before the function body runs. Front-desk sign-ups write GoTrue's auth.users through a definer function. Getting this right meant setting GoTrue's token columns to '' instead of NULL; otherwise sign-in fails with 'Database error querying schema'.
A hand-drawn canvas hero that stays smooth on phones
The landing page's gyroscope lagged on phones. Each frame drew every ring segment as its own stroke, parsed a colour string per particle, built nine gradients and read scrollHeight. Meanwhile, every card's backdrop blur re-rendered behind it.
Approach. Geometry is precomputed into typed arrays. Strokes are batched by depth and particles by colour band, and lit nodes are drawn as sprites. Layout is measured on resize only. Motion is time-based with a capped dt. When frames run long, the loop drops to every other frame at double the step. Below 45 delivered fps (iOS Low Power Mode gives 30), it switches to a short trail. A ?perf readout shows these numbers on the device.
Main-thread script time fell from 9-19% to 3-5% in a phone-sized Chromium throttled 4-8x. WebKit at an iPhone viewport rendered it at 60 fps with no long frames.
Code
This runs inside public.reserver(), a SECURITY DEFINER function, so the rule holds for the member app, the front desk and anyone with the anon key. Refusals come back as French JSON that the UI shows as is.
-- Capacity is physical: count only live bookings.
select count(*) into v_pris from booking where session_id = p_session and status <> 'cancelled';
if v_pris >= v_session.capacity then
return jsonb_build_object('ok', false, 'error', 'Séance complète. Vous pouvez rejoindre la liste d''attente.');
end if;
...
-- LIMIT 1: the credit balance.
v_solde := private.solde(v_member);
if v_solde <= 0 then
return jsonb_build_object('ok', false, 'error', 'Plus de séances sur votre pack.');
end if;
-- LIMIT 2: the weekly quota. NULL means no cap (Flexible, Pack fidélité).
select weekly_quota into v_quota from pack where id = v_purchase.pack_id;
if v_quota is not null then
v_utilise := private.utilise_semaine(v_member, v_week);
if v_utilise >= v_quota then
return jsonb_build_object('ok', false, 'error', format(
'Plafond atteint : %s séances par semaine avec votre pack. Il vous reste %s séances au total.',
v_quota, v_solde));
end if;
end if;
insert into booking (session_id, member_id, week_start)
values (p_session, v_member, v_week) returning id into v_booking;
insert into credit_ledger (member_id, purchase_id, delta, reason, booking_id, author_id)
values (v_member, v_purchase.id, -1, 'reservation', v_booking, v_member);-- A coach cannot be in two places at once. Enforced structurally rather
-- than defended against in application code.
constraint coach_not_double_booked
exclude using gist (
coach_id with =,
tstzrange(starts_at, ends_at) with &&
)
-- Exactly one active pack per member.
create unique index one_active_pack_per_member
on pack_purchase (member_id) where active;
-- Append-only. Balance is the sum of the entries, never a stored number.
create or replace function private.solde(p_member uuid)
returns int language sql stable security definer set search_path = public as $$
select coalesce(sum(l.delta), 0)::int
from credit_ledger l join pack_purchase p on p.id = l.purchase_id
where l.member_id = p_member and p.active;
$$;
-- A late-cancel or no-show consumes the weekly slot as well as the credit.
create or replace function private.utilise_semaine(p_member uuid, p_week date)
returns int language sql stable security definer set search_path = public as $$
select count(*)::int from booking
where member_id = p_member and week_start = p_week and status <> 'cancelled';
$$;create or replace function private.atteint(cible uuid)
returns boolean
language sql stable security definer set search_path = public
as $$
select private.current_role_is('owner')
or (private.current_role_is('staff')
and cible is not distinct from private.current_studio());
$$;
-- booking: studio comes from the séance.
drop policy if exists booking_privileged on booking;
drop policy if exists booking_staff_write on booking;
create policy booking_privileged on booking
for select using (
private.atteint((select s.studio_id from session s where s.id = booking.session_id))
);
create policy booking_staff_write on booking
for all using (
private.atteint((select s.studio_id from session s where s.id = booking.session_id))
) with check (
private.atteint((select s.studio_id from session s where s.id = booking.session_id))
);What I built
Owner
- Weekly schedule builder per studio: type, level, intention, capacity and coach, saved as a draft then published
- Duplicate last week; a database trigger blocks deleting any class that has live bookings
- Dashboard across both studios: revenue in TND, fill rate, no-show and late-cancel rates, occupancy per coach
- Anonymous coach ratings, aggregated per coach, never showing who wrote them
Members and coaches
- Published week, book and cancel, with quota pips for credits left and classes used this week
- Refusals that state both limits, so members do not need to call the desk
- Class history and a 1-5 coach review after attending
- Coach week, class roster and attendance marking (present or no-show)
Front desk
- Create member accounts through a definer function, with no service-role key in the app
- Sell a pack (cash), book on a member's behalf, open a member file
- Every desk action limited to the desk's own studio
Public site and auth
- French landing page in the client's brand chart, with the logo vectorised from the brand PDF
- Hand-written Canvas 2D gyroscope with cursor parallax, scroll waypoints and an on-device ?perf readout
- One /connexion page; proxy.ts revalidates with getUser() and sends each role to its own space
- Every failed login returns the same message, so attackers cannot discover which accounts exist
Screens
A sample week on the public page: level, intention, coach and places left per class, per studio.
Every pack carries a session count and a weekly cap. Those are the two limits the database enforces.
Two studios with their own capacities and schedules. One studio's front desk cannot read the other's data.
Preview of the member space: booked classes and sessions remaining.
One sign-in page for all four roles. Each role lands in its own space, and every failed login gets the same message.
Stack
App
- Next.js 16 (App Router, Server Actions, proxy.ts)
- React 19
- TypeScript
- CSS Modules + design tokens
Data and auth
- Supabase Postgres
- PL/pgSQL SECURITY DEFINER RPCs
- Row-Level Security
- btree_gist
- Supabase Auth via @supabase/ssr
Graphics
- Canvas 2D
- Typed arrays + pre-rendered sprites
- Adaptive frame pacing
- prefers-reduced-motion
Quality and infra
- Vitest 4 (DB integration)
- Playwright (E2E, also against production)
- Vercel
- Local Homebrew Postgres
How it was built
A freelance engagement built in an AI-native workflow. I ran discovery with the owner, won the design with a clickable prototype, and wrote the research brief, system overview and build plans. Claude Code implemented them: 33 of 39 commits carry its co-author trailer. The quality gates were mine: DB integration tests on the real RPCs, Playwright runs against production, and raw REST calls with the public key to reproduce the studio leak before fixing it.
The quote, demo accounts and member data are withheld. The code is private, and the screenshots show only public pages.