When a multi-brand business tracks leads in shared spreadsheets and email threads, two expensive things happen at the same time: sales teams complain that marketing leads are junk, and marketing has no proof of where leads actually stalled or why they went cold.
I built a multi-entity CRM in Next.js, TypeScript and Supabase Postgres across three business entities and 15+ operational modules to solve a COO and RevOps problem, not a software exercise: put every lead from ad click to closed outcome in one system of record, scoped cleanly by company, with zero blind spots.
Below is the schema shape, entity isolation model, stuck-lead diagnostic logic, and why recording structured cold reasons fixes paid media faster than changing ad copy.
1. The operational problem off-the-shelf sheets hide
Before replacing spreadsheets with a database-backed CRM, three failure modes show up in almost every growing lead-gen team:
- Cross-entity leakage: Staff working on Brand A see leads belonging to Brand B, or exports accidentally mix conversion funnels with completely different deal cycles and ticket sizes.
- Invisible bottlenecks: Leadership knows total leads and total sales, but cannot see whether leads are stuck waiting on sales follow-up or held in an AI/qualification review queue.
- Unstructured "cold" excuses: When a lead doesn't buy, reps mark it "not interested" or leave it blank. Marketing gets zero feedback on whether the problem was geography, price mismatch, wrong search intent, or slow response time.
2. Entity-scoped schema and RBAC in Supabase Postgres
Every table carries an explicit entity_id (representing the business unit) alongside normalised contact keys (phone_normalized, email_normalized) so identity resolution works without creating cross-company duplicates.
-- Synthetic multi-entity schema pattern
create table entities (
id uuid primary key default gen_random_uuid(),
code text unique not null, -- e.g. 'brand_a', 'brand_b', 'brand_c'
name text not null
);
create table leads (
id uuid primary key default gen_random_uuid(),
entity_id uuid not null references entities(id),
phone_normalized text,
email_normalized text,
first_touch_source text not null,
stage text not null check (stage in (
'new', 'ai_qualification', 'assigned_sales', 'proposal', 'converted', 'cold'
)),
assigned_to uuid references auth.users(id),
cold_reason_code text, -- mandatory via trigger/constraint when stage = 'cold'
stage_entered_at timestamptz not null default now(),
created_at timestamptz not null default now()
);
-- Enforce structured cold reasons at the database layer, not just the UI
alter table leads add constraint cold_requires_reason
check (stage <> 'cold' or cold_reason_code is not null);
Enforcing Row-Level Security (RLS) in Postgres guarantees that even if a frontend query forgets an entity_id filter, a user belonging to Entity A can never read or mutate Entity B's rows:
alter table leads enable row level security;
create policy "entity_scoped_access" on leads
for all
using (
entity_id in (
select entity_id from user_entity_roles where user_id = auth.uid()
)
);
Role-based access splits permissions cleanly across Admin / Leadership (cross-entity reporting + routing rules), Sales Manager (reassignment + cold-reason audits within their entity), and Sales Rep (assigned leads only).
3. Making "where leads get stuck" visible in real time
A conversion rate alone tells a COO nothing about who needs to act today. Tracking stage_entered_at on every transition separates two completely different operational queues:
- Stuck in AI / qualification check: Inbound leads awaiting first-touch voice/intent scoring or human confirmation before reaching sales.
- Stuck with sales: Qualified leads that passed intent checks but sat unworked past the response SLA.
Every stage change writes an append-only event row (lead_stage_history). That lets the team calculate median time-in-stage per rep and per lead source — exposing whether a "bad campaign" was actually a 36-hour response delay.
4. Why mandatory cold-lead reasons fix paid media
Requiring a controlled cold_reason_code before a rep can close a lead as cold turns sales feedback into direct ad-buying leverage:
| Recorded cold reason | What it actually means | Immediate marketing action |
|---|---|---|
out_of_service_area |
Geo-targeting leak or broad location settings | Switch Google Ads location option to Presence only and tighten Meta radius |
price_mismatch |
Ad copy attracted bargain hunters | Put starting price or qualification framing directly in ad headline and landing page |
wrong_intent |
Informational searchers filling consultation forms | Add negative keywords and split informational SEO pages from commercial CTAs |
unreachable_after_3_attempts |
Instant-form friction too low (accidental taps) | Add a higher-intent qualifier question or route through first-touch qualification |
duplicate_existing_customer |
Retargeting hitting active buyers | Exclude converted CRM segments and deduplicate via phone_normalized |
Because the CRM shares the same Postgres database as our Meta Lead Ads → Sheets → Supabase pipeline and CRM-verified ROAS engine, every cold reason rolls back up to the exact campaign and creative that generated the lead.
5. Integrating human-gated AI qualification cleanly
Inside the same CRM, an AI voice qualification stage calls inbound leads, scores intent (High, Medium, Low), and logs sent/received status and summaries. Crucially, 100% of routing decisions are confirmed by a human before moving a lead to sales — protecting senior sales capacity from low-intent noise without letting an unconstrained agent mutate pipeline state blindly.
For how to evaluate AI stages against real revenue rather than activity metrics, see why AI marketing agents don't show ROI — and how to measure them like CRM ROAS.
How this pattern applies across industries
| Industry | Entities / units isolated | Highest-leverage CRM diagnostic |
|---|---|---|
| E-commerce (Multi-brand) | Individual D2C storefronts + B2B wholesale | Separating wholesale inquiries from retail support tickets |
| B2B | Regional sales pods or product lines | SLA aging between MQL handoff and first SDR touch |
| Education | Campuses or degree programs | Tracking why qualified applicants drop before fee payment |
| Services & Hospitality | Properties, clinics, or franchise locations | Pinpointing whether lost bookings stem from lead quality or follow-up speed |
For the automated reporting layer that sits on top of this database, see building a self-refreshing marketing dashboard with GitHub Actions and a parity gate or view all systems I've built.
FAQ
Why build a custom multi-entity CRM in Next.js and Supabase instead of buying SaaS?
Off-the-shelf CRMs are strong for standard single-brand sales teams, but per-seat multi-entity pricing, rigid attribution joins, and custom AI qualification gates get expensive fast. When your lead pipeline and attribution warehouse already run on Supabase Postgres, putting a lightweight, RLS-scoped CRM on the same database eliminates connector drift completely.
How does Supabase Row-Level Security isolate multiple business entities?
Every record stores an entity_id, and Postgres RLS policies check the authenticated user's user_entity_roles membership on every read and write. Even if an API route omits a WHERE clause, the database itself blocks cross-entity data access.
Why enforce cold-lead reasons at the database constraint level?
UI-only validation gets bypassed by bulk imports, webhooks, and quick edits. A Postgres CHECK constraint guarantees no lead can enter the cold stage without a structured reason code, keeping marketing feedback clean enough to act on.
How does CRM stage tracking improve ROAS?
It separates ad-targeting problems (wrong geo, price mismatch, spam leads) from operational problems (slow sales follow-up). Fixing response SLA or cutting one leaking geo often improves verified ROAS faster than rewriting ad creatives.
Need a lead pipeline, attribution warehouse, or multi-entity CRM tied directly to verified revenue? See my consulting work, message me on LinkedIn, or email rohan.sgtb@gmail.com.





