Backend/Database

Database

Replace the demo records with a real database. This guide uses Supabase (hosted Postgres) as the example; any Postgres database, or your own API, works the same way.

The plan

  1. Create a database project.
  2. Create tables for the main records: customers, contracts, invoices, tasks and so on.
  3. Load records on the server and hand them to the providers.
  4. Switch one screen first (Customers), check it end to end, then do the rest.

Supabase is one option among many. Neon, a managed Postgres from your host, or an API you already have all fit the same steps: only the client code changes.

Create the project and tables

Create a Supabase project and copy its URL and keys into .env.local. Supabase's Next.js guide lists the exact variable names and sets up a server client for you.

Create a table for each kind of record. Use the TypeScript types in src/lib/data as your guide: Customer in customers.ts, Contract and Invoice in records.ts, tasks and messages in comms.ts.

A first table (SQL)
create table customers (
  id bigint generated always as identity primary key,
  owner_id uuid not null references auth.users default auth.uid(),
  name text not null,
  email text,
  created_at timestamptz not null default now()
);

alter table customers enable row level security;

create policy "Owners manage their customers" on customers
  for all using (owner_id = auth.uid());

This example ties each customer to the person who created it. A team product usually ties records to a workspace instead, with a members table that says who belongs where.

Load records on the server

Today each provider imports its starting records from src/lib/data. Change it to take them as a prop, and load them on the server: for example in the layout that sets up the providers. Keys stay on the server, and the page arrives with data in it.

Loading customers on the server
// createClient: the server client from Supabase's Next.js guide
const supabase = await createClient()
const { data: customers, error } = await supabase.from("customers").select("*")
if (error) throw error

// then: <CustomersProvider initialCustomers={customers}>

For changes, keep each provider action's instant update on screen, then send the change to a Server Action or Route Handler that writes to the database. If the write fails, undo the change and show a message.

Switch Customers first

Customers is a good first module: one main table and a profile page. Once it loads, edits, sorts and filters with real records, and survives a reload, move on to contracts, invoices, then the rest. Remove each module's demo file once nothing imports it anymore.

A few places still read the demo files directly, for counts and pickers: the dashboard cards and Balances (invoices), search, the chat composer's customer and contract menus, the customer filters and Settings › Tags. Point them at the providers as you switch each module.

Leads data model

A lead is its own record, separate from customers, defined by Lead in src/lib/data/leads.ts. It is either a new company (kind: "new") or more business from a customer you already have (kind: "upsell", with customerId set).

FieldWhat it holds
stagenew, qualified, proposal, negotiation, won or lost
probabilityOptional; otherwise the stage's chance to close
valueUsd, plan, seatsThe deal: yearly value and what it buys
expectedCloseThe forecast groups leads by this date's month
contactsPeople on the deal, copied to the customer on a win
source, ownerWhere it came from and who works it
lostReason, lostNoteWhy it was lost; a lost lead can reopen
historyEvery stage change with when and who, for the timeline
customerId, contractIdSet when the lead is won and converted

Stage names, colours and chances live in workspace settings (Settings › Pipeline) and are applied in src/lib/workspace-config.ts. The order of stages is fixed, so reports stay comparable. Tasks, notes and meetings on a lead that isn't a customer yet point at the lead and use customerId: -1 until it converts; converting moves them to the new customer.

Connect a real pipeline

The pipeline runs through one provider, src/components/providers/leads-provider.tsx. Load leads into it the same way as customers, and send its actions (create, update, move stage, mark won or lost, reopen) to the server.

Leads and stage history (SQL)
create table leads (
  id text primary key,                 -- LD-1001
  workspace_id uuid not null,
  kind text not null check (kind in ('new', 'upsell')),
  name text not null,
  domain text,
  customer_id bigint references customers(id),
  contract_id text references contracts(id),
  stage text not null default 'new',
  probability int,
  value_usd numeric not null default 0,
  plan text, seats int,
  expected_close date,
  source text, owner_id uuid,
  lost_reason text, lost_note text,
  last_activity_at timestamptz not null default now(),
  closed_at date,
  created_at timestamptz not null default now()
);

create table lead_stage_changes (
  lead_id text references leads(id) on delete cascade,
  stage text not null,
  changed_by uuid,
  changed_at timestamptz not null default now()
);
  • Convert in one transaction. Marking a lead won creates the customer, its contacts and a draft contract, moves tasks, notes and meetings across, then sets customer_id and contract_id. Do it in one database transaction (or one Server Action) so a failure leaves nothing half done.
  • Log every stage change in lead_stage_changes. Win rate, days to close and the funnel are all worked out from it.
  • Update last activity when an email, meeting, task or note touches the lead. "Gone quiet" is any open lead with no activity for 7 days.
  • Run lead workflows on the server. New leads, stage changes and quiet leads trigger workflows; run them from your database events or a scheduled job (see Workflows). Leads covers the rest of the pipeline.

Security basics

  • Environment variables for the database URL and keys, in .env.local and in your host's settings. Never commit them.
  • Row-level security on every table (or the same checks in your own API), so people can only read and change their own data, even if a request is forged.
  • No admin keys in the browser. Supabase's service role key skips row-level security: use it only in server code, if at all.