Skip to the lesson
CivOps AI Academy · M15Customers and CRM: Accounts, Pipeline and Quotes on One Spine
0%

Chapter 1 · Sessions 1–2

What the old CRM holds, and one record per customer

Session 1 maps how your business keeps customers, deals and quotes today, from the tool's own pages and bills, without copying anyone's personal details. Session 2 builds the module's thirteen tables on your Foundation spine, so a company is stored once for the whole business and every stage change of a deal is kept for good.

25 min4 steps13 tablesAbout 8 hours hands-on across six sessions

By the end of this chapter you can

  • Map the old CRM from its admin, billing and export pages, with record numbers instead of names.
  • Say why an account points at the shared party record and why stage history is never overwritten.
  • Have Claude Code build the tables, their tests and a seed, and try them on the development project yourself.

What the module replaces

The module manages the revenue pipeline from a first enquiry to a won order: accounts and contacts, leads and how they are qualified, deals that move through stages, the calls and emails around them, and quotes priced from a price book. It replaces Salesforce Sales Cloud, HubSpot Sales Hub, Microsoft Dynamics 365 Sales, Pipedrive, Zoho CRM, Close, and the quoting tools Salesforce Revenue Cloud, DealHub and Paperless Parts. HubSpot describes its data as a small set of linked objects: contacts, companies, deals [1]. This module keeps the same objects, on your own spine.

Inside this moduleLeft toOwner
Accounts, contacts, leads, conversion, duplicate mergingMarketing campaigns, scoring and nurtureM16
Pipelines, stages, stage history, contact roles, forecastSupport ticketsM19
Activities, price books, quotes, approvals, acceptanceOrder fulfilment and invoicingM12, M22 and accounting
Step 1

Session 1: Map the old CRM from its own pages

60 minutes

Why

You cannot replace what you have not written down. The map names every place customers and deals are kept, what each costs from the invoice, what people work around, and whether the old tool can export stage history, which decides how Session 5 loads it. Record numbers instead of names keep personal data out of the repository from the first day.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch crm/inventory, write docs/crm-inventory.md for how we keep customers, deals and quotes today. Do not invent any number: write every figure as a blank with where to read it, and "Unknown: ask <who>" where nobody knows. Never write a person's name, email or phone in this file; use the old tool's record numbers.

Sections:
1. Places customers and deals are kept: the CRM, spreadsheets, a shared inbox, phones, a drawer of quotes. Owner and sign-in for each.
2. Counts from the main tool's admin and report pages: users and what each does, accounts, contacts, open deals, deals won and lost in the last twelve months, activities.
3. Cost: plan, paid seats, add-ons, renewal date, yearly total from the latest invoice.
4. Exports: which of accounts, contacts, deals, activities and stage history the plan gives, CSV or API, and any limit.
5. Stage history: for one won and one lost deal (record numbers), does the tool show every stage with its date, or only the current stage?
6. Consent: for three contacts (record numbers), where consent and do-not-contact are recorded, if anywhere.
7. Workarounds, from a salesperson, the person who approves discounts and someone in service: what they do outside the tool, retype, or do not trust.
8. Three records sorted into the module's shapes (account, contact, lead, opportunity), by record number, with every field that has no column.

Open a pull request titled "CRM inventory" and show me the link.

Fill the blanks from the tool's own admin, billing and export pages and the three interviews; one of the three people reads it before owner two approves.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/crm-inventory.md)
+## 5. Stage history
+Won deal (record ____): every stage with its date shown? Yes / No
+Lost deal (record ____): every stage with its date shown? Yes / No
+If No: Session 5 can load only the current stage; say so in the import plan.
1
⏺ Write(docs/crm-inventory.md)
+## 3. Cost (from the latest invoice, not the price page)
+Plan ____ Seats ____ Add-ons ____ Renewal ____ Yearly ____
2
⏺ Pull request #81 adds docs/crm-inventory.md: 8 sections, 37 blanks, no personal data. Every figure names the page it comes from.
Blanks with their source, and record numbers where a lesser tool would put names.
  1. The stage history answer decides how much of your past the new reports can rebuild.
  2. Costs come from your invoice. List prices are wrong for most businesses once discounts and seats are counted.

Check it worked

docs/crm-inventory.md is merged with every blank filled from a page or marked Unknown with who to ask, record numbers only, and the stage-history answer for one won and one lost deal.

Fastest path

Ask for the tool's admin and billing access the day before; most of the session is reading pages you could not otherwise open.

If it goes wrong

Claude Code wrote a customer's name or email into the file

Say: Replace every name, email and phone with the record number. This file goes into the repository. Then check the commit history: if it was pushed, ask Claude Code how to remove it from the pull request before it merges.

The plan you pay for does not export stage history

Write it down. Do not buy a higher plan only to export unless the saving is written down first. Session 5 then loads one starting row per deal and says analytics before the import date cannot be rebuilt.

A company is stored once

The Foundation spine holds one list of companies and people. A CRM account is not a second company record: it is a crm_account row whose party_id points at the one core_party row, one to one, and adds only what sales needs. A contact is a crm_contact that also points at a core_person. The shapes follow the Microsoft Common Data Model's reference entities [2].

The party modelA core_party row is the company once. A crm_account points at it one to one and can point at a parent account. A crm_contact belongs to an account and points at a core_person. A separate company table is shown as the pitfall to avoid. A company is stored once, in the shared party table. Sales adds a view of it.core_partythe company, oncecrm_accountthe sales view of itcrm_contacta person at the accountparty_idone to oneaccount_idparent_account_idcore_persona human, onceperson_idA separate company tableduplicates core_partyA second company table is the pitfall: two records for one customer drift apart.
One company, one record. The account and the contact are views of rows in the shared party and person tables. A separate company table drifts away from the real record the moment one of them is edited.
TableColumns: type, req = required
crm_accountparty_id → core_party req, unique; account_type req: prospect, customer, partner, competitor or distributor; industry, segment text; owner_id → core_person; parent_account_id → crm_account; employee_band, revenue_band text; lifecycle_stage: target, engaged, opportunity, customer or churned
crm_contactperson_id → core_person; account_id → crm_account; first_name, last_name text req; title, email, phone text; owner_id → core_person; lifecycle_stage: subscriber, lead, mql, sql, opportunity, customer, evangelist or other; do_not_contact bool req; source text
crm_leadfirst_name, last_name, company_name, email, phone, source text; status req: new, working, nurturing, qualified, unqualified or converted; owner_id → core_person; score num; qualification json; utm json; converted_contact_id → crm_contact; converted_account_id → crm_account; converted_opportunity_id → crm_opportunity; converted_at ts
crm_pipelinename text req; object_type req: opportunity or lead; is_default bool
crm_pipeline_stagepipeline_id → crm_pipeline req; name text req; seq int req; probability num req; is_won, is_lost bool req; required_fields json
crm_opportunityname text req; account_id → crm_account req; primary_contact_id → crm_contact; pipeline_id → crm_pipeline req; stage_id → crm_pipeline_stage req; amount money; currency text; close_date date; probability num; forecast_category req: pipeline, best_case, commit, closed or omitted; owner_id → core_person req; source text; lost_reason_code_id → core_reason_code; competitor_party_id → core_party; next_step text
crm_stage_history (never updated or deleted)opportunity_id → crm_opportunity req; from_stage_id → crm_pipeline_stage; to_stage_id → crm_pipeline_stage req; changed_at ts req; changed_by → core_person; amount_at_change money
crm_contact_roleopportunity_id → crm_opportunity req; contact_id → crm_contact req; role req: decision_maker, economic_buyer, champion, influencer, technical_evaluator, user or blocker
crm_activityactivity_type req: call, email, meeting, task, note, sms or site_visit; subject text req; body text; due_at, completed_at ts; owner_id → core_person; related_type text req; related_id uuid req (no foreign key: it can point at any record); direction: inbound, outbound or internal; outcome text; external_id text
crm_price_bookname text req; currency text req; segment text; active bool req
crm_price_book_entryprice_book_id → crm_price_book req; item_id → core_item req; list_price money req; valid_from, valid_to date
crm_quotequote_no text req, unique; version int req; opportunity_id → crm_opportunity; account_id → crm_account req; contact_id → crm_contact; status req: draft, in_review, approved, sent, accepted, rejected, expired or superseded; valid_until date; currency text req; subtotal, discount_total, tax_total, total money; terms text; approved_by → core_person; accepted_at ts; acceptance_ref text; pdf_attachment_id → core_attachment
crm_quote_linequote_id → crm_quote req; line_no int req; item_id → core_item; description text req; qty qty req; uom_id → core_uom; unit_price money req; discount_pct num; line_total money; configuration json; lead_time_days int

Every table also has the standard columns id, site_id (where the specification says tenant_id; docs/spine-map.md records the change), created_at, created_by, updated_at, updated_by, row_version, archived_at and ext. The specification also defines crm_cost_estimate (an estimate from a routing and a bill of materials, which needs the manufacturing modules) and crm_territory; this course does not build them.

Step 2

Session 2: Check the spine tables the module points at

15 minutes

Why

The CRM must not keep its own company, people, item or file lists: it points at the spine's. If a spine table is missing, the migration fails, or Claude Code quietly builds a second company table inside the module, which is exactly the pitfall the specification warns about. Checking first keeps one record per customer.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
Read supabase/migrations/, docs/SCHEMA-PLAN.md and docs/spine-map.md if another module has written it. Do not write anything yet.

The CRM module points at: core_party, core_person, core_item, core_uom, core_attachment, core_reason_code, core_number_sequence, core_approval, core_comment, core_event_outbox; and the helpers core_current_actor(), core_touch_row(), core_audit_row() with core_audit_log, and core_block_mutation() (refuses update and delete).

For each, tell me: present (which migration), present under another name (for example parts for core_item), or missing.

Then, without asking again:
- where we already hold the same thing under another name, the module keeps its column names and points at our table with its id type; write the mapping as a CRM section of the one shared docs/spine-map.md (create it if no module has yet; never a second map file), and record there that our module tables carry site_id in place of the specification's tenant_id;
- whatever is missing goes in ONE spine migration on a branch crm/spine, with row-level security on and pgTAP tests, never inside the module's migration.

If anything is missing, open a pull request titled "Spine for CRM", wait for the schema check to finish and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ core_item: present as parts. core_reason_code, core_number_sequence, core_approval: present (M12 spine migration). core_party, core_person, core_attachment, core_event_outbox, core_current_actor(): missing.1
⏺ Bash(npx supabase migration new spine_for_crm)
⎿ Created new migration at supabase/migrations/20261109080000_spine_for_crm.sql
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m12s
⏺ Pull request #82 adds 4 spine tables and 1 helper, row-level security on, 18 tests. docs/spine-map.md has a CRM section: item_id → public.parts, site_id in place of tenant_id.
The check, then only what is missing.
  1. If you built another module first, part of the spine is already there; only the rest is added.

Check it worked

Pull request Spine for CRM is green (or nothing was missing), and the CRM section of docs/spine-map.md maps each module column to an existing table.

If it goes wrong

Claude Code created a crm_company table

Say: Remove crm_company. A company is a core_party; the account points at it with party_id, one to one. This is the pitfall the specification names.

core_party exists but has no status column

Say: Add the missing column to core_party in a new spine migration, with a test; do not edit the migration that created it.

Step 3

Session 2: One prompt: the thirteen tables, append-only history and their tests

25 minutes

Why

One account per party and a stage history the database refuses to change are the module's two promises; putting them in the tables, with tests that try to break them, means no screen, import or agent can undo them later. One complete prompt replaces a dozen rounds of adding each rule as you notice it.

Do this

Paste into Claude Code
Read docs/spine-map.md, docs/naming-standard.md and the table list in the M15 specification (or the lesson's table).

On a new branch crm/tables:
1. npx supabase migration new crm_tables. Create crm_account, crm_contact, crm_lead, crm_pipeline, crm_pipeline_stage, crm_opportunity, crm_stage_history, crm_contact_role, crm_activity, crm_price_book, crm_price_book_entry, crm_quote and crm_quote_line with every column in the list. Required means not null; listed values are check constraints; money numeric(18,4); qty numeric(18,6); times timestamptz. Every table gets the standard columns (site_id in place of tenant_id, as docs/spine-map.md records), row-level security on with no policies, the core_touch_row() and core_audit_row() triggers. Foreign keys only to our spine tables (by docs/spine-map.md) and to each other.
2. crm_account: no name or address columns; unique (party_id).
3. crm_stage_history: a before update or delete trigger with core_block_mutation().
4. crm_quote: quote_no unique; version a separate number.
5. crm_activity: index on (related_type, related_id); no foreign key there, on purpose.
6. pgTAP tests in supabase/tests/crm-tables.test.sql proving the database refuses: a second account for the same party, an account_type outside the list, an opportunity with no stage, an update and a delete of a stage history row. And row-level security on for all thirteen tables.
Do not connect to any Supabase project. Push, open a pull request titled "CRM tables", wait for the schema check to finish and tell me the result in plain words. If it fails, fix it and wait again.

You will see recreated screen

claude — acme-platform
⏺ Write(supabase/migrations/20261109091500_crm_tables.sql)
+alter table public.crm_account add constraint crm_account_one_per_party unique (party_id);
+create trigger crm_stage_history_append_only before update or delete
+ on public.crm_stage_history for each row execute function public.core_block_mutation();
1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m35s
⏺ Pull request #83 is green: 13 tables with row-level security on and no policies; 24 tests, 7 of them try bad data and are refused, including a second account for one company and any edit of stage history.2
The two promises, written into the tables.
  1. One account per company and unchangeable history, kept by the database.
  2. Read how many tests try to break a rule; those are the ones that protect you.

Check it worked

Pull request CRM tables is green and the summary names the refused duplicate account and the refused history edit.

If it goes wrong

Claude Code added policies so the screens can read

Say: Remove every policy. Access comes from docs/matrix.json in Session 3. A policy written before the matrix is a guess about who may read your customers' details.

It reports success but the check on GitHub is red

Say: The schema check is red. Run gh pr checks, read the failed log, fix the cause and wait for green before you report. We trust the check on GitHub, never the summary.

After merging main, a table or test you added has gone

An undo on main took your change with it, with no conflict reported. We hit this. Say: I just merged main. List every schema change and test this branch added and confirm each is still there.

Step 4

Session 2: Seed the made-up pipeline, keep the hand count as a fixture, and try it on the development project yourself

20 minutes

Why

Session 4 proves the module rebuilds the pipeline as of any past date by comparing its answer with a count you can do by hand, so that hand-worked example keeps its fixed dates as a test fixture, and the seed holds the same deals shifted onto today so the screens show the same shape. Trying the migration and seed on the development project first, from your own terminal, shows they work on a real Supabase database before the deploy pipeline applies the migration to production on merge.

Do this

Paste into Claude Code
On the branch crm/tables, write the CRM seed in supabase/seeds/crm.sql and list it under [db.seed] sql_paths in supabase/config.toml (never add it to supabase/seed.sql): marked SYNTHETIC as Session 6 requires, made-up companies and people with example.com addresses only, shifted onto today, and safe to run twice:
- pipeline Sales with stages Qualify, Propose, Negotiate, Won (is_won) and Lost (is_lost), probabilities rising from Qualify to Negotiate;
- six core_party rows each with a crm_account (those owning won opportunities 1, 2, 4 and 6 are customers, status active; the rest prospects);
- eight contacts, one with do_not_contact true; three leads (new, working, qualified), each with utm; the working one has the company name of a customer;
- a price book with three made-up items; a number sequence for crm_quote (prefix Q-, padding 5); two loss reasons; two made-up salespeople;
- ten opportunities, opportunity n worth n x 1000, each with a next_step; 1 to 6 closed, 7 to 10 open (pipeline, close date 60 days from the day the seed runs);
- 24 stage history rows, amount_at_change = the deal's amount, on these dates, all moved by the same number of days so that 31 Mar falls on the day the seed runs:
  1: Qualify 5 Jan, Propose 12 Jan, Won 20 Feb. 2: Qualify 8 Jan, Propose 2 Feb, Won 10 Mar. 3: Qualify 15 Jan, Lost 25 Feb.
  4: Qualify 20 Jan, Propose 10 Feb, Negotiate 5 Mar, Won 18 Mar. 5: Qualify 2 Feb, Propose 20 Feb, Lost 12 Mar.
  6: Qualify 9 Feb, Propose 3 Mar, Won 25 Mar. 7: Qualify 16 Feb, Propose 14 Mar. 8: Qualify 23 Feb.
  9: Qualify 2 Mar, Propose 20 Mar. 10: Qualify 16 Mar.
Also write tests/fixtures/crm-pipeline.json: the same ten deals and 24 history rows on exactly these 2026 dates. It is the hand-worked example Session 4's tests load; no test counts on the seed's dates. Add supabase/tests/crm-seed.test.sql: 10 opportunities, 24 history rows, each opportunity's stage equals its latest history row. Push to the same pull request, wait for the checks and report.

Then, in your own terminal (not inside Claude Code), try the branch on the development project; its password is in the password manager under Supabase: acme-platform-dev database password.

Terminal (Mac) or PowerShell (Windows)
git fetch && git switch crm/tables && npx supabase link --project-ref tsrqponmlkjihgfedcba
Terminal (Mac) or PowerShell (Windows)
npx supabase db push --include-seed

That loads the made-up rows the first time. After that, reload them with npm run seed:dev.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new

The development project's SQL editor. Run select count(*) from crm_opportunity; select count(*) from crm_stage_history;: 10 and 24.

You will see recreated screen

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261109080000_spine_for_crm.sql • 20261109091500_crm_tables.sql [Y/n] y1
Seeding data from supabase/seeds/crm.sql...
Finished supabase db push.
db push on the development project. Read the reference before you answer y.
  1. Only the new files. If it lists anything else, answer n and ask why.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
SQL Editor · acme-platform-dev
1
opportunitieshistory rows
1024
The counts in the development project.
  1. The same ten deals and 24 rows as the hand-worked example, moved onto today.

Check it worked

The pull request is green; the development project shows 10 opportunities and 24 history rows; after owner two approves and you merge, the deploy workflow run on github.com/acme-ops/acme-platform/actions is green (the seed never goes to acme-platform-prod).

If it goes wrong

The link command shows abcdefghijklmnopqrst instead of tsrqponmlkjihgfedcba

Stop and answer n. Link again with tsrqponmlkjihgfedcba. Made-up data never enters production, and from Session 11 production changes only through the pipeline.

After Session 4, npm run seed:dev gives more than 24 history rows

Session 4's trigger writes a history row for every opportunity inserted. Say: Make the seed load opportunities with the history trigger disabled for that load only, and re-enable it; keep the seed test at 24.

A later step expects a count the seed does not create

Reviews of five Academy modules found this fault. Say: List every count the later CRM steps and tests expect, and show the seed line that creates each. Fix the seed, not the check.

Knowledge check

A company you already invoice becomes a sales prospect. What does the CRM add?

Knowledge check

Why is crm_stage_history protected by a trigger that refuses update and delete?

References

  1. HubSpot developers: understanding the CRM. https://developers.hubspot.com/docs/api/crm/understanding-the-crm
  2. Microsoft Learn: Common Data Model. https://learn.microsoft.com/en-us/common-data-model/
  3. EUR-Lex: Regulation (EU) 2016/679, the General Data Protection Regulation. https://eur-lex.europa.eu/eli/reg/2016/679/oj
  4. Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
  5. PostgreSQL documentation: constraints. https://www.postgresql.org/docs/current/ddl-constraints.html

Chapter 2 · Session 3

Who may see customers, deals and quotes

Session 3 writes the CRM's roles into your role matrix, generates the access rules from it, proves that service staff see customers but never deals, that nobody approves their own quote and that an opted-out person cannot be messaged, and builds the screens behind the sign-in that denies by default, with one public address for the web form.

25 min3 steps3 roles + intake and importer5 screens

By the end of this chapter you can

  • Write the CRM's roles, routes and rules into docs/matrix.json, as jobs not names.
  • Generate the access rules and prove each refused cell, the do-not-contact rule and self-approval with tests.
  • Build the screens behind default-deny sign-in, opening exactly one public address for the form.
Role or routeMayMay not
Sales repRead all accounts and contacts (so nobody creates a company twice); own leads, deals, activities and quotes; claim, qualify, convert, move stages, build and send quotesApprove any quote; see other reps' deals
Sales managerRead every crm_ table; stages, price books, discount threshold; approve or reject quotes; reassign; merge and anonymise contactsApprove a quote they created
Service staffRead accounts and contacts, with do_not_contact as a wordSee any deal, quote, lead or amount
Lead intake (system)Insert one crm_lead from the web formRead anything, even the lead it wrote
CRM importer (machine, Sessions 5–6)Insert the old CRM's records, only through the import workflowUpdate or delete anything; sign in after cut-over
Step 5

Session 3: Write the roles, routes and rules into the matrix

25 minutes

Why

The access rules, the route guard and their tests are generated from docs/matrix.json, so a right missing there is refused later, in the middle of the session that needs it. Writing every role and route now, and walking Sessions 4 to 6 against it, prevents those refusals and makes sure customer data is visible only to those who need it.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
Read docs/matrix.json and docs/spine-map.md. On a new branch crm/matrix, add the CRM module to docs/matrix.json. No delete right anywhere. "Own" means owner_id is the signed-in person (created_by for quotes; the parent's owner for quote lines, contact roles and stage history).

Roles: sales_rep, sales_manager, service_staff, the system person lead_intake, and the machine account crm_importer (Sessions 5 and 6).
- sales_rep: read all core_party, core_person, crm_account, crm_contact, pipelines, stages, active price books and entries, items, units, loss reasons; read own leads (and unowned), opportunities, history, contact roles, activities, quotes and lines, and their approvals, comments, attachments; insert those; update own leads, opportunities (not owner_id), activities, and quotes (to in_review, sent, accepted, rejected, superseded; never approved); lines only while draft; set do_not_contact true but never clear it; read and update the crm_quote number sequence row.
- sales_manager: read every crm_ table; insert and update pipelines, stages, price books (discount threshold in ext), entries, loss reasons; update every lead, account, contact (may clear do_not_contact with a comment), opportunity (including owner_id), customer_contact persons; set a quote approved or rejected and approved_by, never on a quote they created; core_approval decisions.
- service_staff: read core_party (customer or partner), core_person, crm_account, crm_contact; nothing else.
- lead_intake: insert crm_lead only; no read, so no RETURNING.
- crm_importer: insert only, never update or delete: core_party, core_person, crm_account, crm_contact, crm_opportunity, crm_stage_history, crm_contact_role, crm_activity and crm_lead rows carrying ext.import_batch; no screen and no route.

Rules: an outbound call, email or sms crm_activity on a contact with do_not_contact (directly, or as the opportunity's primary contact) is refused, except rows the import loads (ext.import_batch, only for crm_importer); a rep cannot change do_not_contact from true to false; nobody approves a quote they created; an ended role sees nothing.

Screens: /crm/leads, /crm/pipeline, /crm/quotes (rep, manager); /crm/accounts (rep, manager, service); /crm/reports (manager).
Routes: POST /api/crm/leads/capture (lead_intake; the ONE public address, by exact path), /api/crm/leads/convert, /api/crm/opportunities/stage, /api/crm/activities (rep, manager), /api/crm/quotes, /submit, /send, /accept (rep), /api/crm/quotes/decide (manager), /api/crm/contacts/merge, /api/crm/contacts/anonymise (manager).

Then write docs/crm-rights-walk.md: each action Sessions 4 to 6 ask for, with the role, table and right, and the matrix cell that grants it. Do not generate anything yet. Open a pull request titled "CRM roles" and show me the link.

Read it with a salesperson and the discount approver for ten minutes each.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/crm-rights-walk.md)
+| Action (session) | Role | Table, right | Cell |
+| Convert a lead (4) | sales_rep | crm_opportunity insert | ✓ |
+| Anonymise a contact (5) | sales_manager | core_person update (customer_contact) | ✓ |
+| Read the as-of pipeline (6) | sales_manager | crm_stage_history read | ✓ |
1
⏺ Write(docs/matrix.json)
+"/api/crm/leads/capture": { "lead_intake": "call", "public": "exact path" },
2
⏺ Pull request #86 adds 4 roles, the importer account, 5 screens and 11 routes. 31 later actions walked; each has a cell. One public address, by exact path.
The rights walk: every later action matched to a cell before anything is built.
  1. A row with no cell is a refusal you would otherwise meet halfway through Session 5.
  2. The web form's address is the only public one, and it is opened by its exact path, never by its folder.

Check it worked

The pull request adds the roles, screens and routes; docs/crm-rights-walk.md shows every later action with a cell; no cell grants delete; the salesperson and approver have read it.

If it goes wrong

Claude Code opened /api/crm/leads/ as a public folder

Say: Open only POST /api/crm/leads/capture by its exact path. When we opened one public download, re-opening its exact address, not its folder, kept everything filed there later private.

Service staff are given read on opportunities "to help customers"

Say no, and write the reason in docs/access-review.md. Amounts and deals are sales data; service sees the customer and whether they may be contacted.

Step 6

Session 3: Generate the access rules, and prove the refusals

25 minutes

Why

A right in the matrix only protects anyone once it is a policy and a route rule, and only stays protected if a test tries the refused cell on every change. The CRM holds personal data, so the refusals matter most: service staff reading deals, a rep approving their own discount, an email logged to someone who opted out.

Do this

Paste into Claude Code
On the branch crm/matrix:
1. Run node scripts/gen-policies.mjs for the new CRM rows and regenerate lib/access/routes.ts with node scripts/gen-routes.mjs, as Session 9 does. Do not edit generated files by hand.
2. Write the two rules as triggers: refuse an outbound call, email or sms activity on a do_not_contact contact (directly or as the opportunity's primary contact), letting through rows with ext.import_batch only when the caller is crm_importer; refuse a rep changing do_not_contact from true to false.
3. supabase/tests/crm-access.test.sql generated from the matrix, one allowed and one refused test per cell, with test users sales.rep.test@example.com, sales.manager.test@example.com, service.test@example.com. Plus: service staff read zero rows from crm_opportunity, crm_quote and crm_lead; a rep sees no deal of another rep; a rep cannot set a quote approved; a manager cannot approve a quote they created (set created_by inside a rolled-back transaction); lead_intake can insert a lead and cannot read it back; outbound email to the flagged seed contact is refused; another site's rows are invisible; every update is checked by reading the row back.
4. Show each new test failing with its rule removed, then passing.
Push, wait for every check on the pull request, and tell me the counts in plain words. Never loosen a test to make it pass: if one fails, explain why and wait.

You will see recreated screen

claude — acme-platform
⏺ Bash(node scripts/gen-policies.mjs)
⎿ wrote supabase/migrations/20261111100000_policies_crm.sql (74 policies)
⏺ Shown red first: with the do-not-contact trigger removed, 'outbound email to flagged contact is refused' fails; restored, it passes. Same for self-approval and service staff reading deals.1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 3m30s clamps pass 1m02s
⏺ Pull request #86 is green: 74 policies from the matrix; 142 access tests, 71 refusals. Service staff read 0 deals, 0 quotes, 0 leads.2
Generated rules, and the refusals shown red before green.
  1. A test never seen failing may never fail. We had checks green for weeks while the thing they guarded was broken.
  2. Zero rows for service staff is the proof that amounts and deals stay with sales.

Check it worked

Pull request CRM roles is green with the refusal counts in the summary; owner two approves and you merge; the deploy workflow applies the policies to acme-platform-prod.

If it goes wrong

Claude Code calls a security warning on a route a "false positive"

Ask for each one separately: the request made signed out and the response. We hit this: survey routes dismissed as false positives were open on production and returned 23 named customer staff to anyone.

A quote status change says Saved but nothing changed

In Postgres an update only finds rows the role can read, and the new row must still pass the read rule. We hit this in three modules. Say: Check the read rule covers the quote before and after the change; make the test read the row back.

Claude Code suggests relaxing a refusal test

Say no. If a refusal is wrong, the matrix is wrong: change the matrix row with the sales manager and regenerate.

Step 7

Session 3: The four working screens, behind default-deny sign-in

30 minutes

Why

Reps work from a phone between visits and at a desk; service staff look customers up while someone waits on the phone. Building the screens on the Foundation surfaces, behind the route guard that refuses everything not in lib/access/routes.ts, means a new CRM screen is invisible to everyone until the matrix says otherwise.

Do this

Paste into Claude Code
Before writing any page or route, read the guides in node_modules/next/dist/docs/ for this version of Next.js (request middleware lives in proxy.ts). Then, on a new branch crm/screens, on the surfaces from Sessions 12 and 13:
- /crm/leads: leads, new first, claim, status, qualification, convert.
- /crm/pipeline: one column per stage; on a phone one stage at a time with a stage picker, never sideways scrolling; the manager's settings panel for stages, probabilities and required fields.
- /crm/quotes: items from the price book, totals as the server computes them; the manager's approval queue and discount threshold.
- /crm/accounts: accounts and contacts; do_not_contact shown as the words "Do not contact", not only a colour.
Every screen and /api/crm/ route is in lib/access/routes.ts and refused by proxy.ts for everyone else, except POST /api/crm/leads/capture. The server takes the user from the session, never from the page. No screen shows a number that is not stored.
Screen tests: each at 360 and 390 px (no sideways scroll, 44 px targets, 16 px fields, 15 px text); each screen and route signed out lands on sign-in or 401; service staff see /crm/accounts only. Push, open a pull request titled "CRM screens", wait for every check and the Vercel preview, and give me the preview address.

You will see recreated screen

acme-platform-git-crm-screens-acme-ops.vercel.app/crm/accounts
Accounts
SearchNorthwind Stamping (example)
Northwind Stamping · customer3 contacts1
J. Example · PurchasingDo not contact2
The account lookup as service staff see it on a phone, with the made-up seed.
  1. Service staff see who the customer is, never the deals or amounts.
  2. The flag is a word, so it reads the same in any colour scheme and to a screen reader.

You will see recreated screen

Terminal
✓ /crm/pipeline signed out → /sign-in
✓ /api/crm/quotes/decide signed out → 401
✓ POST /api/crm/leads/capture signed out → 202 (the one public address)1
52 passed
The signed-out tests.
  1. The form route answers signed out because it must; it can only insert a lead.

Check it worked

Pull request CRM screens is green, the preview shows each screen at phone width, and service staff see only the account lookup.

If it goes wrong

Claude Code wrote middleware.ts

This version of Next.js calls it proxy.ts. Say: Read node_modules/next/dist/docs/ for request middleware in this version and use proxy.ts as Session 9 did.

Every quote shows the same author whoever is signed in

The page sent the user and the server trusted it. We hit this. Say: Take the user from the signed-in session on the server and ignore any user the page sends; add a test with two users.

The preview answers 401 before any sign-in page

That can be Vercel's preview protection, not your code. Sign in to Vercel in the same browser and open the preview again.

Knowledge check

Service staff need to look a customer up while they are on the phone. What may they read?

Knowledge check

How is the public web form's address opened past default-deny sign-in?

References

  1. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  2. Federal Trade Commission: CAN-SPAM Act, a compliance guide for business. https://www.ftc.gov/business-guidance/resources/can-spam-act-compliance-guide-business
  3. California Attorney General: California Consumer Privacy Act. https://oag.ca.gov/privacy/ccpa
  4. Next.js Docs: proxy.ts (request middleware). https://nextjs.org/docs/app/api-reference/file-conventions/proxy

Chapter 3 · Session 4

From lead to accepted quote

Session 4 builds the sales workflow end to end: a web form becomes a lead with its campaign tags, conversion keeps the original lead, every stage change writes history, a quote is priced on the server, approved above your threshold, versioned and accepted, and the pipeline as of any past date matches a count you can do by hand.

30 min4 stepsAbout 90 minutesThe hand-counted pipeline

By the end of this chapter you can

  • Have Claude Code build lead capture and a conversion that keeps the original lead and its UTM data.
  • Prove stage history rebuilds the pipeline as of 1 March and 31 March against a hand count.
  • Price, approve, version and accept a quote, and see self-approval refused yourself.
Converting a leadA qualified crm_lead enters crm_convert_lead, one transaction that makes or reuses an account, makes a contact, makes an opportunity and writes a crm.lead.converted event. The original lead row is kept with its status set to converted. crm_leadstatus: qualifiedcrm_convert_leadone transactioncrm_accountreused or new, via core_partycrm_contactwith its core_personcrm_opportunityfirst stage, owner, next stepcore_event_outboxcrm.lead.convertedThe lead is kept, not overwrittenstatus converted, three new ids, converted_at; utm copied
Converting a lead. Four things are created and one is kept. The lead's name, company, email, phone, source and utm never change, which is how you later ask which campaign produced which customer.
Step 8

Session 4: Lead capture and conversion that keeps the original

25 minutes

Why

The definition of done says conversion preserves the original lead and its UTM data: they are the only evidence of where a customer came from. Conversion in one database transaction that reuses an existing company also stops the commonest CRM fault, the same customer twice.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch crm/leads:
1. POST /api/crm/leads/capture (lead_intake only): validates fields; refuses more than a few posts a minute from one address (counts kept outside the crm_ tables); inserts one crm_lead, status new, source the form name, utm from utm_source, utm_medium, utm_campaign, utm_term, utm_content in the page address, ext.consent with the wording version, server time and the lawful basis we choose (read from a setting in config/crm-consent.json that I fill in; never invent one). Ignores extra fields such as owner_id. No RETURNING.
2. crm_convert_lead, one transaction: reuse the core_party if the company exists, else insert (prospect); reuse its crm_account if one exists, else insert; insert core_person (customer_contact) and crm_contact with the lead's consent; insert the crm_opportunity at the first stage with next_step and owner the caller, and a crm_contact_role; on a reused account raise account_type and lifecycle_stage only if lower; mark the lead converted with the three ids and converted_at; copy utm to the opportunity's ext; write crm.lead.converted to core_event_outbox.
3. A trigger refusing any later change to the lead's name, company, email, phone, source or utm.
Tests: utm stored; owner_id ignored; intake cannot read back; converting the seed's qualified lead leaves it unchanged apart from the converted fields; a second conversion refused; converting the working lead reuses the existing customer account and keeps it a customer.
Show each test failing first. Push, open a pull request titled "CRM leads", wait for every check and report in plain words.

Before merging, write the lawful basis you rely on for web-form contacts in config/crm-consent.json, after asking whoever advises your business on privacy. It is a business decision, not a technical one.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ crm-leads.test.sql .. ok 11/11
⏺ Converted the qualified seed lead: new account, contact and opportunity; the lead row is unchanged except status converted, the three ids and converted_at; utm utm_source=trade-show copied to the opportunity. Converting the working lead reused the existing customer account (no second account).1
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
The conversion test: four rows made, one kept untouched.
  1. Two proofs in one line: the original kept, and no duplicate company.

Check it worked

Pull request CRM leads is green; the summary says the lead was kept and the existing account reused; config/crm-consent.json holds the basis your adviser chose.

If it goes wrong

A form post creates a second account for a customer you already have

The conversion matched on the exact name. Say: Match the company by website, or by name after lowercasing, removing punctuation and endings such as Inc and Ltd; test with a seed customer written differently. We hit three names for one company live at once.

The form posts succeed but no lead appears

The route asked for the new row back (RETURNING) and lead_intake cannot read. Say: Insert without returning the row, and test that the intake role cannot read it.

Every stage change is kept

One deal in stage historyA timeline in days, to scale. A deal is in Qualify for 14 days, then in Propose for 31 days, then won on day 45. Three crm_stage_history rows mark the three changes. Every stage change adds a row. Nothing is overwritten.Row 1from none to QualifyRow 2from Qualify to ProposeRow 3from Propose to WonQualifyProposeday 0day 10day 20day 30day 40day 50day 6014 days in Qualify, 31 days in Propose, 45 days from created to won.With only the current stage stored, rows 1 and 2 are gone, and so are those 14 and 31 days.
One deal, three rows. Drawn to scale in days. From the rows you read the time in each stage and the cycle time; with only the current stage stored, none of it can be recovered.

A trigger on crm_opportunity writes a crm_stage_history row on every insert and every change of stage, so even a change made by hand in SQL leaves a row. The move function adds the rules: no stage from another pipeline, no empty required field, no open stage without a next step. Won sets forecast_category closed and makes the account a customer; lost also needs a reason.

Pipeline as of a past dateFour bars to scale. On 1 March the hand-worked example had 3 open deals worth 21000 in Qualify and 3 worth 11000 in Propose. On 31 March it had 2 worth 18000 in Qualify and 2 worth 16000 in Propose. Open deals, grouped by stage, as of the end of each date (hand-worked example)1 March · Qualify3 deals, 210001 March · Propose3 deals, 1100031 March · Qualify2 deals, 1800031 March · Propose2 deals, 16000Both pictures come from the same crm_stage_history rows. The bars share one scale.
The same table, two dates. In the hand-worked example (tests/fixtures/crm-pipeline.json) the open pipeline on 1 March is 6 deals worth 32000; on 31 March it is 4 deals worth 34000. The count fell while the value rose.
MeasureDefinitionHand count
Pipeline on 1 March 2026Last history row per deal at or before the date, won and lost left out, by stageQualify 3 (21000), Propose 3 (11000)
Pipeline on 31 March 2026The sameQualify 2 (18000), Propose 2 (16000)
Win rateWon ÷ (won + lost), by count and by value4 of 6; 13000 of 21000
Sales cycle lengthMedian days from first stage to won51.5 days
Step 9

Session 4: Stages, history and activities, proven against the hand count

25 minutes

Why

The first item of the definition of done is that stage history rebuilds the pipeline as of any past date. Proving it against numbers you can count by hand from the seed, and keeping that proof as a test, means no later change can quietly break the history every sales report depends on.

Do this

Paste into Claude Code
On a new branch crm/stages:
1. crm_move_stage(opportunity, stage, next_step): refuses a stage from another pipeline, a stage whose required_fields are empty (naming the field), an open stage with no next_step; sets probability from the stage; writes crm.opportunity.stage_changed to the outbox. Won: forecast_category closed, account customer (partner and distributor keep their type), party active, crm.opportunity.won. Lost: closed, and lost_reason_code_id required.
2. A trigger on crm_opportunity writing crm_stage_history on every insert and every change of stage_id, with server time, changed_by and amount_at_change.
3. POST /api/crm/activities (rep, manager), and one timeline per opportunity: history and activities, newest first.
4. crm_pipeline_as_of(date, pipeline), crm_win_rate(pipeline) and crm_cycle_median(pipeline).
Tests load tests/fixtures/crm-pipeline.json into a pipeline of its own, inside transactions that are rolled back, so no seed row can change a hand count: moving opportunity 8 to Propose writes one history row; an empty next step is refused; a loss with no reason is refused; a hand-written SQL update of stage_id still writes history; as of 2026-03-01: Qualify 3 worth 21000, Propose 3 worth 11000; as of 2026-03-31: Qualify 2 worth 18000, Propose 2 worth 16000; win rate 4 of 6 and 13000 of 21000; median 51.5 days; an outbound email on the flagged contact is refused.
If a number disagrees, fix the query, never the expected number. Push, open a pull request titled "CRM stages", wait for every check and report the numbers.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ crm-stages.test.sql .. ok 14/14
⏺ As of 2026-03-01: Qualify 3 (21000), Propose 3 (11000). As of 2026-03-31: Qualify 2 (18000), Propose 2 (16000). Win rate 4/6 by count, 13000/21000 by value; median cycle 51.5 days. A stage change made by hand in SQL wrote its history row.1
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass
The as-of answers, next to the hand count.
  1. Compare each number with the table above. They must be identical, not close.

Check it worked

Pull request CRM stages is green and the summary's as-of, win-rate and median numbers equal the table above.

If it goes wrong

Claude Code proposes changing the expected numbers to match its result

Say no. Say: Show me, deal by deal, which history row you took for each date, and fix the query. The hand count is the specification.

Claude Code says all tests pass but did not show them failing

Say: Remove the history trigger, run the tests, show me which fail and the exit code; restore it. We recorded a run that printed npm: not found and then reported 1,326 tests passing.

Quotes: the price is the server's

Pricing a quoteBars to scale for a worked example. Line 1 is 10 at 25.00, which is 250.00. Line 2 is 4 at 100.00, which is 400.00. The subtotal is 650.00, the discount is 25.00 and the total is 625.00. The server reads the list price; the browser sends only item_id, qty and discount_pct.Line 1: 10 × 25.00250.00Line 2: 4 × 100.00400.00Subtotal650.00Discount: 10% of line 125.00Total625.00Bars share one scale. Discount 25.00 is 10% of 250.00; total = 650.00 − 25.00 = 625.00.
A worked example, to scale. Ten at 25.00 with 10% off and four at 100.00 give a subtotal of 650.00, a discount of 25.00 and a total of 625.00. The stored numbers must equal your hand calculation.
Quote statusesEight quote statuses. A draft goes to in_review, then approved, then sent, or straight to sent when no discount is above the threshold. In review a manager approves or rejects. A sent quote is accepted, rejected or superseded. Approved and rejected quotes can be superseded by a new version. Expired marks a quote past valid_until. no discount above the threshold: straight to sentdraftlines can changein_reviewwaits for a managerapprovedapproved_by is setsentPDF is storedrejectedwith a commentsupersededa newer version existsacceptedaccepted_at is setexpiredvalid_until has passedFrom sent, a quote is accepted, rejected or superseded. Lines of a quote that is not a draft never change.
Quote statuses. A quote is edited only while it is a draft. Approved, sent and rejected quotes become superseded when a newer version is made; a quote past valid_until shows as expired.
Step 10

Session 4: Quotes priced on the server, approved, versioned and accepted

25 minutes

Why

A quote is a promise with a price on it. Computing every price on the server from the price book, requiring a manager's approval above your discount threshold from someone other than its author, and keeping each change as a new version means no quote can carry a price nobody agreed to, and acceptance hands an exact order to the next module.

Do this

Paste into Claude Code
On a new branch crm/quotes:
1. crm_build_quote: quote_no from core_number_sequence (crm_quote) in the same transaction; created_by = core_current_actor(); the browser sends only item_id, qty and discount_pct (0 to 100); the server copies list_price from the active entry valid today into unit_price and computes line_total, subtotal, discount_total and total. Add the live project's number sequence row in this migration if missing.
2. Submit: if any line's discount is above the threshold in crm_price_book.ext, draft to in_review with a pending core_approval; otherwise it may go to sent. /api/crm/quotes/decide: the manager approves or rejects with a comment; never the creator. Allowed moves only: draft→in_review|sent; in_review→approved|rejected; approved→sent; sent→accepted|rejected|superseded; rejected|approved→superseded. Lines never change after draft. Expired is computed from valid_until, never set.
3. Send: a PDF made on the server, stored in a PRIVATE storage bucket with a policy letting only roles that may read the quote read it; pdf_attachment_id, status sent. The module sends no email: the rep sends the PDF from their own mail.
4. A change makes a new row: version + 1, quote_no with -v2, ext.quote_base, lines copied, old row superseded.
5. crm_accept_quote: accepted, accepted_at server time, acceptance_ref (the customer's reply or signed PDF reference), crm.quote.accepted in the outbox with quote_no, total, currency and one entry per line.
Tests: a posted price of 1.00 is ignored; the worked example stores 650.00, 25.00, 625.00; the creator cannot approve; a sent quote's lines cannot change; v2 supersedes v1; the accepted event's line count and total match the quote. Push, open a pull request titled "CRM quotes", wait for every check and report.

Then, on the preview, with owner two: you build a quote with one line at 20% off and submit it; owner two, as sales manager, approves it; then owner two builds one and tries to approve their own.

You will see recreated screen

acme-platform-git-crm-quotes-acme-ops.vercel.app/crm/quotes
Q-00001 · v1 · draft
1
ItemQtyUnit priceDisc %Line total
Bracket kit (example)1025.0010225.00
Die set (example)4100.000400.00
Total625.00
Submit
The quote builder on the preview: totals from the server.
  1. Unit prices come from the price book; you can change quantity and discount only.

You will see recreated screen

acme-platform-git-crm-quotes-acme-ops.vercel.app/crm/quotes
Owner two, trying to approve a quote they built.
  1. The separation of duties auditors look for, refused in the database as well as here.

Check it worked

Pull request CRM quotes is green; the worked example stored 625.00; on the preview owner two's self-approval was refused with a message that says why.

If it goes wrong

A Send button says the quote was emailed

The module sends no email; a button claiming it did is a stand-in pretending. We hit this: "Send all" marked every recipient sent and no email left. Say: Remove the email action; the rep sends the PDF from their own mail and records sent.

The quote PDF opens from a plain address without sign-in

The bucket is public, or the file is under public/. We hit customer files served from public/ with no gate. Say: Make the bucket private with a policy per quote reader, and add a signed-out test that is refused.

A customer acceptance link opens the internal quote screen with edit buttons

We hit a customer "read-only" link that opened the internal console. Online acceptance is a stretch goal with its own route and matrix row; until then the rep records acceptance from the customer's reply.

Cost estimate to priceFive cost lines (material, labor, machine, overhead and outside processing) add up to total_cost. The total cost divided by the quantity is the unit cost; with target_margin_pct, the unit price is the unit cost divided by one minus the margin. material_costbill of materialslabor_cost(setup + run × qty) × ratemachine_costmachine time × machine rateoverhead_costyour overhead ruleoutside_costoutside processingtotal_costsum of the five,for the whole jobtarget_margin_pctunit_pricetotal_cost ÷ qty÷ (1 − margin)routing_ref links to the routing and bill of materials from M04 and M14. The estimate reuses them.
From routing and bill of materials to a price. Setup is paid once per job and run time once per part; the target margin turns the unit cost into a unit price.

Knowledge check

As of 1 March 2026 the hand-worked example's open pipeline is 6 deals worth 32000. How is that found?

Knowledge check

A browser posts a unit price of 1.00 for an item whose price book entry is 25.00. What is stored?

References

  1. ISO: ISO 4217, currency codes. https://www.iso.org/iso-4217-currency-codes.html
  2. Metabase: shared sales CRM data model. https://www.metabase.com/integrations/sales-crm
  3. Supabase Docs: Storage access control. https://supabase.com/docs/guides/storage/security/access-control
  4. PostgreSQL documentation: trigger functions. https://www.postgresql.org/docs/current/plpgsql-trigger.html

Chapter 4 · Sessions 5–6

Move the real records in, and switch the old CRM off

Session 5 builds the import, the merge and the anonymise functions, and rehearses the move on the development project with a copy IT and your privacy adviser have approved. Session 6 loads production once, compares the new reports with the old tool's, runs both side by side, cuts over and cancels the subscription with the saving written from the invoice.

25 min4 stepsHistory in fullEnds with the module gate

By the end of this chapter you can

  • Load accounts, contacts, deals, activities and stage history with their source, safe to run twice.
  • Merge duplicates and anonymise a person without changing the pipeline numbers.
  • Reconcile the reports with the old tool's, cut over and record the saving.
Moving the data inEight steps: accounts, contacts, opportunities, stage history with original dates, contact roles, activities, leads, then reconcile the counts for every file. 1 · Accountscore_party + crm_account2 · Contactscore_person + crm_contact3 · Opportunitieswith owner and source4 · Stage historyoriginal dates, in full5 · Contact roleswho is on each deal6 · Activitiesexternal_id is the old id7 · Leadslast8 · Reconcilecounts add up per fileEvery row keeps ext.source_system and ext.source_id, so running the load twice changes nothing.Stage history lands in full before anyone uses the new CRM, so the numbers carry on without a gap.
The load order. Parents before children: a deal needs its account, a history row needs its deal. Stage history keeps its original dates and is loaded in full before anyone uses the new CRM.
  • Write the duplicate rule before loading. A company is the same if its website matches, or its name after lowercasing, removing punctuation and endings such as Inc, LLC and Ltd. A contact is the same if its email matches after lowercasing. A contact with no email is never merged by a script.
  • Carry opt-outs across. Anyone marked unsubscribed or do-not-contact in the old tool gets do_not_contact true. Copy consent only if the old tool holds a record of it: a blank is honest; a guessed lawful basis is a false record.
  • Keep the source of every record in ext.source_system and ext.source_id, with a unique index, so a second run skips what is already there.
Step 11

Session 5: The import, rehearsed on the development project with an approved copy

45 minutes

Why

An import is where a CRM replacement usually goes wrong: duplicate customers, lost opt-outs, history dated the day of the import so last quarter's reports are empty. An import that dry-runs first, keeps every record's source, runs safely twice and loads only files owner two approved, rehearsed end to end on the development project, finds those faults where they cost nothing.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch crm/import:
1. docs/crm-import.md: the mapping (company to core_party + crm_account; person to core_person customer_contact + crm_contact; deal to crm_opportunity; activity to crm_activity with external_id; stage change to crm_stage_history with original dates), docs/crm-stage-map.csv for old stages and loss reasons, the duplicate rule in sentences, and the opt-out rule. Stop and list any old stage, reason or user with no mapping.
2. A spine migration (merged first) and a module migration adding unique indexes on (ext->>'source_system', ext->>'source_id') for each loaded table. The history trigger writes nothing on the insert of an opportunity with ext.import_batch when the caller is crm_importer; a later stage change writes as usual.
3. scripts/import-crm.mjs, signed in as the crm_importer account with the password from the environment variable CRM_IMPORTER_PASSWORD (never printed), and .github/workflows/import-crm.yml: started by hand only (workflow_dispatch) from main, inputs target (dev or production) and dry_run; it downloads the export files from the private Storage bucket imports of the target, refuses any file whose sha256 and expected row count are not recorded in docs/imports/crm-approved.md on main, and fails on any count mismatch. The dry run prints counts per file, duplicates (both source ids) and refusals to the job summary, never a name or email; a real run writes in order: parties and accounts, persons and contacts, opportunities, history (original dates), contact roles, activities (with ext.import_batch), leads. Rows pointing at a skipped duplicate are loaded against the kept record; an opt-out on either copy is kept. Loaded plus duplicates plus refused must equal each file's rows, or the run fails.
4. Tests with MADE-UP rows only: a file whose sha256 or row count is not in docs/imports/crm-approved.md is refused; a second run adds nothing; a duplicate by website is skipped and its deal re-pointed; an imported deal's next stage change writes history; a live outbound email to a flagged contact is still refused; open pipeline at the export date equals a made-up old report.
Push, open a pull request titled "CRM import", wait for every check and report.

When it is merged, ask IT and your privacy adviser in writing to approve a copy of the export for one rehearsal: what it holds, where it goes (acme-platform-dev only), who can see it, and that it is removed the same day. Contacts are personal data, so the copy is redacted: names, emails and phones replaced with made-up values, the same value for the same person, so duplicates still match. As a person, create the crm_importer account on the development project with a password from the password manager, type it into GitHub as CRM_IMPORTER_PASSWORD_DEV, and list the name in docs/KEYS.md.

Open

https://github.com/acme-ops/acme-platform/settings/secrets/actions

GitHub Actions secrets: CRM_IMPORTER_PASSWORD_DEV, the value only.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets

Development project Storage: upload the redacted copy to the private bucket imports.

Terminal (Mac), in the export folder
shasum -a 256 *.csv
Paste into Claude Code, after pasting the values
On a new branch crm/import-approval, write docs/imports/crm-approved.md: each export file's name, sha256 and row count (I paste them below), the date taken, that the copy is redacted, and IT's and the privacy adviser's approval for one rehearsal on acme-platform-dev (date and role). Open a pull request titled "CRM: approve import files".

<paste the shasum lines and row counts>

Owner two approves and you merge. Run the workflow with target dev, dry run first; fix the mapping (never the data) through a pull request; then run it for real, and once more, which must add nothing. Fill the reconciliation table in docs/crm-import.md with counts only. The same day, remove the rehearsal rows (Claude Code gives you the statements by ext.import_batch; you run them in the development project's SQL editor) and the file in the bucket, and record the date in docs/crm-import.md.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-crm.yml

Run workflow: target dev, dry_run true, then false.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-crm.yml
import-crm · target dev · dry_run true
2
FileRowsWould loadDuplicatesRefused
companies.csv812797150
contacts.csv2,1402,071645
deal_stage_history.csv6,9036,90300
Refused rowReason
contacts.csv 1188stage 'Verbal yes' not in docs/crm-stage-map.csv
The dry run in the workflow's summary: counts, duplicates and refusals, and no personal data.
  1. Only the files owner two approved, with the row counts recorded, can be imported.
  2. Loaded plus duplicates plus refused must add up to the rows in each file, or the run fails.

Check it worked

The import's pull request is green with made-up test rows only; on the rehearsal every file's counts add up, a second run added nothing, and the open pipeline at the export date equals the old tool's report; the rehearsal rows were removed the same day and the date is in docs/crm-import.md.

If it goes wrong

IT or your privacy adviser will not approve a copy for the development project

Then rehearse with made-up rows only, and make Session 6's first production run the rehearsal: the workflow's dry run, every count read with them watching, then the real run. Never copy personal data anywhere they have not agreed to.

The open pipeline differs from the old tool's report on a few deals

Usually a deal whose amount was edited after its last stage change: the as-of query sums amount_at_change. Explain each such deal in the reconciliation table rather than changing the query.

Every imported deal shows a history row dated today

The trigger fired on the import's inserts. Say: Skip the history row on insert when ext.import_batch is set and the caller is crm_importer; add the test.

Step 12

Session 5: Merge duplicates and anonymise a person, without changing the numbers

25 minutes

Why

Some duplicates need a person's judgement, and a person may ask you to erase their details. Both must be possible without breaking the sales record: the pipeline as of any date, the win rate and the history stay exactly as they were, and nothing is deleted.

Do this

Paste into Claude Code
On a new branch crm/merge-anonymise:
1. crm_merge_contacts(keep_id, drop_id) behind POST /api/crm/contacts/merge (sales_manager), one transaction: move the dropped contact's contact roles, activities and primary_contact_id references to the kept one; archive the dropped row with ext.merged_into; do_not_contact true on the kept one if either had it. Nothing deleted. Quotes and converted leads keep pointing at the archived contact.
2. crm_anonymise_contact(contact_id) behind POST /api/crm/contacts/anonymise (sales_manager), one transaction: first_name, last_name, email, phone on the contact, display_name, email, phone on its core_person, and name, email, phone on any lead converted to it, all become 'Removed' (the lead trigger allows only this function, only this change); do_not_contact true; ext.anonymised_at. Ids, amounts and history unchanged.
3. Tests on tests/fixtures/crm-pipeline.json, loaded as in Session 4: crm_pipeline_as_of for 2026-03-01 and 2026-03-31 before and after anonymising one of its contacts are identical; the contact, person and lead read 'Removed'; a merge leaves the opportunity history untouched.
4. In docs/crm-import.md, say plainly what anonymising does NOT reach: free-text notes, the append-only audit log and any export or backup taken earlier; those are for the owner and their adviser to decide.
Push, open a pull request titled "CRM merge and anonymise", wait for every check and report.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ crm-anonymise.test.sql .. ok 8/8
⏺ Before and after anonymising contact 3: as of 2026-03-01 Qualify 3 (21000), Propose 3 (11000); as of 2026-03-31 Qualify 2 (18000), Propose 2 (16000). Identical. Contact, person and converted lead read 'Removed'.1
⏺ Write(docs/crm-import.md)
+Not reached by anonymising: free-text activity notes and comments (edit by hand),
+core_audit_log (append-only), and exports or backups taken earlier. Owner and adviser decide.
2
The proof that erasing a person leaves the numbers alone.
  1. The sales record survives; the person's details do not.
  2. Say what is not reached. An honest limit is better than a promise the system cannot keep.

Check it worked

Pull request CRM merge and anonymise is green; the as-of numbers are identical before and after; docs/crm-import.md names what anonymising does not reach.

If it goes wrong

Anonymising is refused by the lead trigger

The trigger must allow exactly this change from this function. Say: Allow the lead's name, email and phone to become 'Removed' only inside crm_anonymise_contact; test that any other change is still refused.

Someone suggests deleting the person instead

Deleting breaks the opportunity history and every report on it. Anonymise; and record in docs/crm-import.md who asked and when, without their details.

Forecast categoriesFour forecast categories in rising confidence: pipeline, best_case, commit and closed. A fifth, omitted, is left out of the roll-ups. Totals roll up by owner, territory and period. pipelineopen, earlybest_casecould closecommitowner stands behind itclosedwonConfidence rises to the rightomittedleft out of the roll-upsRoll-ups add each category by owner, territory and period.Coverage = open pipeline in the period ÷ quota.
The forecast ladder. Confidence rises from pipeline to closed; omitted deals are left out of roll-ups. The reports screen sums open deals by category.
Step 13

Session 6: Load production once, build the reports, and run side by side

60 minutes, then a week

Why

Real customer records go into production only now, through the import workflow a person starts from main, with files owner two approved, as rehearsed. The reports screen gives the sales manager the same numbers the old tool gave, and a week side by side shows every difference while the old tool can still answer for it.

Do this

Paste into Claude Code
On a new branch crm/reports, build /crm/reports (sales_manager): a date picker with crm_pipeline_as_of by stage; win rate by count and by value; median days from first stage to won; the sum of open amounts by forecast_category. Plain tables; no number that is not stored; "No data" when empty. Phone check at 360 and 390 px. Also add docs/cutover.md with two columns, old tool and new module, for: open pipeline by stage at the cutoff, won and lost in the last twelve months by count and value, median cycle, forecast by category; a line per difference with its cause. Push, open a pull request titled "CRM reports", wait for every check and report.

When it is merged and deployed, invite the real reps, managers and service staff with the invitation flow from Foundation Session 9. Take the final export from the old tool at the cutoff. As a person: create the crm_importer account on production, type its password into GitHub as CRM_IMPORTER_PASSWORD_PROD, and record each file's sha256 and row count in docs/imports/crm-approved.md through a pull request owner two approves (target production, date).

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets

Production Storage: upload the final export to the private bucket imports.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-crm.yml

Run workflow from main: target production, dry run; read it against the old tool's own counts; then for real, once. Fill the reconciliation in docs/crm-import.md with counts only.

Open

https://acme-platform.vercel.app/crm/reports

Read the numbers at the cutoff and write them next to the old tool's in docs/cutover.md.

For the next week, enter every new or changed deal in both tools; do not re-run the import. Each day, write the differences and causes in docs/cutover.md.

You will see recreated screen

https://acme-platform.vercel.app/crm/reports
As of2026-11-30
1
MeasureOld toolNew module
Open pipeline47 · 612,40047 · 612,400
Win rate (count)31%31%
Median cycle64 days63.5 days
The reports screen on production, beside the old tool's numbers.
  1. These figures are illustrations; yours come from your own tools.
  2. A difference you cannot explain means you are not ready. A half-day often comes from a cutoff in a different time zone.

Check it worked

Production holds the imported records with their source; the reconciliation adds up for every file; docs/cutover.md shows both columns at the cutoff with every difference explained, and a line for each day of the week.

If it goes wrong

The dashboard shows a revenue or forecast figure nobody entered

We hit screens that showed numbers nobody measured, including a revenue figure the customer never gave. Say: For each number on /crm/reports, show me the query and the rows it comes from; replace any that is not stored with "No data".

The production run stopped halfway

Run the workflow again: the source index makes the second run add only what is missing. Then compare the counts with the dry run.

Someone re-runs the import during the week

It only inserts, so it cannot carry a change made in the old tool, and would add a deal typed into both. Stop it; reconcile by hand from the daily differences.

Step 14

Session 6: Cut over, repoint the form, and cancel with the saving written

40 minutes

Why

The module is finished when everything that pointed at the old CRM points here, the old tool is read-only, the importer can no longer sign in, and the saving is arithmetic from a real invoice. Proving the five checks and the access tests on production first means you switch over on evidence, not on hope.

Do this

Paste into Claude Code
Cutover. On a new branch crm/cutover:
1. In docs/cutover.md, record the result of one query each on production (give me the queries to run in the SQL editor; do not connect yourself): every open opportunity's stage equals its latest history row; no two contacts share a lowercased email (anonymised ones left out); do_not_contact count equals the distinct opted-out people in the old tool; every lead converted this week still holds its original fields and utm; every sent or accepted quote has a pdf_attachment_id.
2. Close the import: remove crm_importer's rights from docs/matrix.json and regenerate with scripts/gen-policies.mjs and scripts/gen-routes.mjs; a migration that sets the crm_importer role to NOLOGIN, applied by the deploy workflow; disable import-crm.yml; a test that the importer can neither sign in nor insert. Tell me which GitHub secrets to delete, and mark them retired in docs/KEYS.md.
3. Add the cutover date and rollback plan: who tells the team, when the old tool becomes read-only, who keeps the old export and where (access limited, with a deletion date), and the date after which a deal only in the old tool no longer counts. List everything in docs/crm-inventory.md that pointed at the old tool and where it points now (the web form to POST /api/crm/leads/capture, the quote template, bookmarks).
Push, open a pull request titled "CRM cutover", wait for every check and report.
Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/sql/new

Run the five queries Claude Code gives you on production and paste only the counts into docs/cutover.md.

Delete the CRM_IMPORTER_PASSWORD secrets on GitHub yourself. Then repoint the website's form, make the old tool read-only, and watch the first day: a form post becomes a lead, a conversion keeps its utm, a stage change writes history, a quote reaches approval. Last, read the cancellation terms on the vendor's account page, cancel (or write the end date), and write the saving: the old yearly cost from the invoice, minus what the module adds to services you already pay for.

You will see recreated screen

claude — acme-platform
⏺ Write(supabase/migrations/20261201090000_close_crm_importer.sql)
+alter role crm_importer nologin;
1
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
⏺ Pull request #97 is green. The importer is NOLOGIN and its insert is refused. docs/cutover.md records the five checks with your counts: 0 stage mismatches, 0 duplicate emails, opt-outs 214 = 214, 9 converted leads intact, 0 sent quotes without a PDF.2
The importer closed, and the five checks on record.
  1. Closing the importer is a reviewed change, applied to production by the pipeline like any other.
  2. Each check is a count from production that you ran yourself.

Check it worked

Pull request CRM cutover is merged; the five checks pass; the importer is NOLOGIN and refused; the form posts to the new route; the old tool is read-only and cancelled (or its end date written) with the saving from the invoice.

If it goes wrong

A web form post after cutover still lands in the old tool

Something still points there. Search docs/crm-inventory.md and the website for the old form address, and repoint each one. Leads that arrived in the old tool are entered by hand, with their source.

The opt-out counts differ by a few

Usually one person opted out on two duplicate records, counted twice in the old tool. Explain each difference in docs/cutover.md; never set or clear the flag to make the count agree.

Before you go on · The module is done whenTick each one

Knowledge check

The old CRM exports every stage change. How is it loaded so reports continue without a gap?

Knowledge check

A contact asks you to erase their personal data. What does the module keep?

References

  1. Syncari: HubSpot database schema compared with Salesforce. https://syncari.com/blog/hubspot-database-schema/
  2. IETF RFC 6350: vCard Format Specification. https://www.rfc-editor.org/rfc/rfc6350
  3. EUR-Lex: Regulation (EU) 2016/679, the General Data Protection Regulation (Article 17). https://eur-lex.europa.eu/eli/reg/2016/679/oj
  4. IETF RFC 5545: iCalendar. https://www.rfc-editor.org/rfc/rfc5545

Chapter 5 · 12 questions · 80% passes

Final assessment

Twelve questions across the element. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.

15 min12 questions≈ 15 minutesRetake allowed

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. What does crm_account.party_id do?
2. Which of these is a valid crm_lead status?
3. Why keep a stage history row for every stage change?
4. How is the open pipeline as of a past date found?
5. Which forecast category is set when a deal moves into a won stage?
6. How is win rate defined?
7. What does pipeline coverage compare?
8. Who decides the unit price on a quote line?
9. A sent quote is changed. What does the module do?
10. A job costs 60 and the target margin is 25%. What is the price?
11. Why does every imported row keep ext.source_system and ext.source_id with a unique index?
12. What may the lead intake route do?