Tutorial: a client portal

Agencies and B2B tools need the same thing: every client signs in and sees only their own projects and invoices, while your team sees everything. You will build that with four tables and a handful of policies, invite a client by email, let a payment provider mark an invoice paid through a signed webhook, and send your team a Monday digest.

What you will learn

  • A profile table for a role, and invites that claim a row by email.
  • Per-client isolation: a client reads only rows that point at their own client row (ctx.profile_id).
  • A table clients can't reach at all: no policy for them is the whole rule.
  • A webhook verified with your own signing secret, a lifecycle that lets an invoice be paid once, and a weekly schedule.

1. Ask your agent, or write the files

Use appbricx. Create "Portal", code-first. Account managers (staff) run
client accounts, projects and invoices. Clients are invited, never sign up,
and see only their own projects and invoices, read only. A payment provider
POSTs {invoice_number, amount, provider_ref} to a webhook signed with
HMAC-SHA256 in x-signature: record it and mark the invoice paid when the
amount covers it, then notify the managers. Every Monday 08:00 London,
notify managers of the week's new projects by status. Seed two clients.

These are the files, ready to push with appbricx push <project-id> portal --apply:

app.config.ts

// app.config.ts: clients are invited, account managers run the portal.
import { defineApp } from "@appbricx/define";

export default defineApp({
  brand: { name: "Portal", tagline: "Your projects and invoices in one place" },
  locale: { language: "en-GB", currency: "GBP", timezone: "Europe/London" },
  auth: { signup: "invite", admin: "manager" },
  roles: {
    client: { kind: "consumer", label: "Client", profile: "client" },
    manager: { kind: "staff", label: "Account manager" },
  },
});

db/schema/client.sql

-- db/schema/client.sql: one row per client account (the client role's profile table).
create table if not exists client (
  id         uuid primary key default gen_random_uuid(),
  user_id    uuid unique,          -- set when the client's account claims the row
  name       text not null,
  email      ctx.email unique,     -- an invite to this address claims the row
  created_at timestamptz not null default now()
);
comment on column client.email is '@pii';

db/schema/invoice.sql

-- db/schema/invoice.sql: invoices move from due to paid, once.
create table if not exists invoice (
  id         uuid primary key default gen_random_uuid(),
  client_id  uuid not null references client on delete cascade,
  project_id uuid references project on delete set null,
  number     text not null unique,
  amount     ctx.money not null,
  status     text not null default 'due',
  paid_at    timestamptz,
  created_at timestamptz not null default now()
);
create index if not exists invoice_client on invoice (client_id);
select ctx.lifecycle('invoice', 'status', $$ due -> paid $$);

-- What the payment provider sent: for the managers, never served to clients.
create table if not exists payment_event (
  id             uuid primary key default gen_random_uuid(),
  invoice_number text not null,
  amount         ctx.money not null,
  provider_ref   text not null unique,
  received_at    timestamptz not null default now()
);

db/schema/project.sql

-- db/schema/project.sql
create table if not exists project (
  id         uuid primary key default gen_random_uuid(),
  client_id  uuid not null references client on delete cascade,
  title      text not null,
  status     text not null default 'planned',
  due_on     date,
  created_at timestamptz not null default now(),
  constraint project_status_known check (status in ('planned', 'active', 'done'))
);
create index if not exists project_client on project (client_id);

db/access/portal.sql

-- db/access/portal.sql: a client reads only rows that point at their client row; managers do everything.
drop policy if exists client_self_read on client;
create policy client_self_read on client for select using (user_id = (select ctx.uid()));

drop policy if exists project_client_read on project;
create policy project_client_read on project for select
  using (client_id = (select ctx.profile_id('client')));

drop policy if exists invoice_client_read on invoice;
create policy invoice_client_read on invoice for select
  using (client_id = (select ctx.profile_id('client')));

drop policy if exists client_manager_all on client;
create policy client_manager_all on client for all using ((select ctx.has_role('manager')));
drop policy if exists project_manager_all on project;
create policy project_manager_all on project for all using ((select ctx.has_role('manager')));
drop policy if exists invoice_manager_all on invoice;
create policy invoice_manager_all on invoice for all using ((select ctx.has_role('manager')));
drop policy if exists payment_event_manager_read on payment_event;
create policy payment_event_manager_read on payment_event for select using ((select ctx.has_role('manager')));

db/seeds/portal.sql

-- db/seeds/portal.sql: two clients. Northwind has no email, so the client demo sign-in takes it;
-- Kite's row waits for an invite to ops@kite.example.
insert into client (id, name, email) values
  (ctx.seed_id('cl-northwind'), 'Northwind Studio', null),
  (ctx.seed_id('cl-kite'),      'Kite Logistics',   'ops@kite.example')
on conflict (id) do nothing;

insert into project (id, client_id, title, status, due_on) values
  (ctx.seed_id('pr-site'),   ctx.seed_id('cl-northwind'), 'New website',     'active',  '2026-12-15'),
  (ctx.seed_id('pr-brand'),  ctx.seed_id('cl-northwind'), 'Brand refresh',   'planned', null),
  (ctx.seed_id('pr-portal'), ctx.seed_id('cl-kite'),      'Driver app',      'active',  '2027-01-31')
on conflict (id) do nothing;

insert into invoice (id, client_id, project_id, number, amount) values
  (ctx.seed_id('in-1001'), ctx.seed_id('cl-northwind'), ctx.seed_id('pr-site'),   'INV-1001', 4200.00),
  (ctx.seed_id('in-1002'), ctx.seed_id('cl-kite'),      ctx.seed_id('pr-portal'), 'INV-1002', 1800.00)
on conflict (id) do nothing;

routes/_layout.tsx

// routes/_layout.tsx: NavLink shows each role only the pages it may open.
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-slate-50 text-slate-900">
      <header className="flex items-center gap-5 border-b bg-white px-6 py-4">
        <Link to="/" className="font-semibold">Portal</Link>
        <NavLink to="/invoices">Invoices</NavLink>
        <NavLink to="/payments">Payments</NavLink>
        {auth.user ? (
          <button type="button" className="ml-auto" onClick={() => void auth.signOut()}>Sign out</button>
        ) : null}
      </header>
      {children}
    </div>
  );
}

routes/index.tsx

// routes/index.tsx: projects. A client sees theirs, a manager sees every client's.
import { defineRoute, useAuth, useQuery } from "@appbricx/ui";

export const meta = defineRoute({ roles: ["client", "manager"], title: "Projects" });

export default function Projects() {
  const auth = useAuth();
  const q = useQuery("project", { sort: "due_on", embed: "client(name)" });
  const rows = q.rows as (typeof q.rows[number] & { client: { name: string } | null })[];
  return (
    <main className="mx-auto max-w-3xl p-6">
      <h1 className="mb-4 text-2xl font-semibold">Projects</h1>
      <table className="w-full text-left">
        <thead>
          <tr>{auth.user?.role === "manager" ? <th>Client</th> : null}<th>Project</th><th>Status</th><th>Due</th></tr>
        </thead>
        <tbody>
          {rows.map((p) => (
            <tr key={p.id} className="border-t">
              {auth.user?.role === "manager" ? <td>{p.client?.name}</td> : null}
              <td>{p.title}</td>
              <td>{p.status}</td>
              <td>{p.due_on ?? ""}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </main>
  );
}

routes/invoices.tsx

// routes/invoices.tsx
import { defineRoute, useLive, useQuery } from "@appbricx/ui";

export const meta = defineRoute({ roles: ["client", "manager"], title: "Invoices" });

export default function Invoices() {
  const { rows } = useQuery("invoice", { sort: "-created_at" });
  useLive("invoice"); // "paid" shows up as soon as the webhook marks it
  return (
    <main className="mx-auto max-w-3xl p-6">
      <h1 className="mb-4 text-2xl font-semibold">Invoices</h1>
      <ul className="grid gap-2">
        {rows.map((i) => (
          <li key={i.id} className="flex gap-4 rounded border bg-white px-4 py-3">
            <span className="flex-1">{i.number}</span>
            <span>£{i.amount}</span>
            <span className={i.status === "paid" ? "text-green-700" : "text-amber-700"}>{i.status}</span>
          </li>
        ))}
      </ul>
    </main>
  );
}

routes/payments.tsx

// routes/payments.tsx: what the provider sent (managers only: clients have no policy on payment_event).
import { defineRoute, useQuery } from "@appbricx/ui";

export const meta = defineRoute({ roles: ["manager"], title: "Payments" });

export default function Payments() {
  const { rows } = useQuery("payment_event", { sort: "-received_at" });
  return (
    <main className="mx-auto max-w-3xl p-6">
      <h1 className="mb-4 text-2xl font-semibold">Payments received</h1>
      <ul className="grid gap-2">
        {rows.map((e) => (
          <li key={e.id} className="rounded border bg-white px-4 py-3">
            {e.invoice_number} · £{e.amount} · {e.provider_ref}
          </li>
        ))}
      </ul>
    </main>
  );
}

workflows/payments.ts

// workflows/payments.ts: the payment provider's callback, and the Monday digest.
import { cron, webhook } from "@appbricx/workflows";

type Payment = { invoice_number?: unknown; amount?: unknown; provider_ref?: unknown };

// POST /hooks/<project-id>/payment-received, signed with PAYMENT_WEBHOOK_SECRET.
export const paymentReceived = webhook(
  "payment-received",
  { verify: { provider: "generic-hmac", secret: "PAYMENT_WEBHOOK_SECRET", header: "x-signature" } },
  async ({ body, row }, step) => {
    const p = (body ?? row ?? {}) as Payment; // body: the request; row: the same JSON (what a dry run passes)
    const number = String(p.invoice_number ?? "");
    const amount = Number(p.amount);
    const ref = String(p.provider_ref ?? "");
    if (!number || !ref || !Number.isFinite(amount)) throw new Error("invoice_number, amount and provider_ref are required");
    await step.sql(
      "record",
      "insert into payment_event (invoice_number, amount, provider_ref) values ($1, $2, $3) on conflict (provider_ref) do nothing",
      [number, amount, ref],
    );
    const paid = await step.sql(
      "mark paid",
      "update invoice set status = 'paid', paid_at = now() where number = $1 and status = 'due' and amount <= $2 returning number",
      [number, amount],
    );
    if (paid.length > 0) await step.send.notify("invoice-paid", { role: "manager", vars: { number, amount } });
    return { paid: paid.length > 0 };
  },
);

export const mondayDigest = cron("weekly mon 08:00", { tz: "Europe/London" }, async (_event, step) => {
  const rows = await step.sql(
    "new projects",
    "select status, count(*)::int as n from project where created_at > now() - interval '7 days' group by status order by status",
  );
  if (rows.length === 0) return { projects: 0 };
  const summary = rows.map((r) => String(r.n) + " " + String(r.status)).join(", ");
  await step.send.notify("weekly-projects", { role: "manager", vars: { summary } });
  return { summary };
});

messages/notify/invoice-paid.md

---
title: "Invoice {{number}} paid"
link: /invoices
vars:
  number: string
  amount: number
sample:
  number: INV-1001
  amount: 4200
---
£{{amount}} received for {{number}}.

messages/notify/weekly-projects.md

---
title: New projects this week
link: /
vars:
  summary: string
sample:
  summary: 2 active, 1 planned
---
{{summary}}

How the isolation works

  • client is the client role's profile table. Its user_id links the row to an account. ctx.profile_id('client') answers the signed-in client's own row id (null for anyone else), so client_id = (select ctx.profile_id('client')) is "rows of my company".
  • Clients only read. There is no insert, update or delete policy for them, so Postgres refuses those writes whatever the page sends.
  • payment_event has no client policy, so clients can't read it at all. Managers read it; only the webhook writes it.
  • auth.signup: "invite" closes self sign-up. Managers are staff and see everything through their manager_all policies.
  • ctx.lifecycle('invoice', 'status', $$ due -> paid $$): an invoice can be paid, never moved back to due. A second payment for the same invoice changes nothing.

2. Invite a client

The seed gives Northwind no email, so in dev the client demo sign-in takes that row. Kite's row carries ops@kite.example and waits: inviting that address links the new account to it.

app_users { "project_id": "…", "action": "invite", "email": "ops@kite.example",
            "name": "Kite operations", "role": "client" }
// the person gets a link to choose a password (one hour, single use); signed in, they see Kite's rows only

Check it as each side:

query_data { "project_id": "…", "entity": "invoice", "as": { "role": "client" } }       // Northwind's INV-1001 only
query_data { "project_id": "…", "entity": "payment_event", "as": { "role": "client" } } // nothing
explain { "project_id": "…", "about": "access", "table": "project", "op": "create",
          "as": { "role": "client" }, "values": { "client_id": "…", "title": "Sneaky" } }
// denied: no insert policy lets a client write a project

3. The webhook

paymentReceived answers at POST /hooks/<project-id>/payment-received.get_contract lists it under webhooks with who signs it. The platform checks the x-signature header (hex HMAC-SHA256 of the raw body) against the project secret PAYMENT_WEBHOOK_SECRET before your code runs; the code never holds the secret.

First, a dry run with a made-up body: nothing is written or notified.

workflows { "project_id": "…", "action": "dry_run", "id": "paymentreceived",
            "row": { "invoice_number": "INV-1001", "amount": 4200, "provider_ref": "test_1" } }
// effects: step.sql "record", step.sql "mark paid" (with what the database answered), the invoice-paid notification

Then set the secret and send a signed call, as the provider would:

secrets { "project_id": "…", "action": "set", "name": "PAYMENT_WEBHOOK_SECRET", "value": "…", "env": "dev" }
BODY='{"invoice_number":"INV-1001","amount":4200,"provider_ref":"test_1"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$PAYMENT_WEBHOOK_SECRET" -hex | sed 's/^.* //')
curl -sS -X POST "https://<your-app-host>/hooks/$PROJECT_ID/payment-received" \
  -H "content-type: application/json" -H "x-signature: $SIG" -d "$BODY"

INV-1001 moves to paid, the managers get "Invoice INV-1001 paid", and the client's Invoices page shows it without a reload (useLive("invoice")). Sending the same body again records nothing new: provider_ref is unique and the invoice is no longer due.

4. Verify and deploy

  1. verify: the role matrix tries every table as client and manager with rolled-back writes, and the signed-out check proves visitors read nothing.
  2. deploy with a subdomain, then add your domain (portal.youragency.com).
  3. Set PAYMENT_WEBHOOK_SECRET for production ("env": "prod") and give the provider the production webhook URL.

Gotchas

  • One account per client row. user_id is unique. For several people per company, add a contact table that references the client, make it the role's profile, and point the policies through it.
  • Sign the exact raw body. A body re-serialised after signing fails the signature (401).
  • Webhooks run as the app, past row-level security, so the code checks its input before it writes, and the SQL only touches the invoice it names.
  • Don't trust an amount you can't check. For Stripe or Razorpay, use their own signature with verify and confirm the payment; see payments.

Related