From 57885daa92233984fa695488dc25de09f1519b63 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 23:54:22 +0000 Subject: [PATCH] AT2: Supabase and Hyperdrive from Terraform, the schema through db-migrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit infra/terraform/supabase (supabase-starter's root) creates each environment's Supabase project with Auth pointed at the Worker and sign-up signing straight in, and publishes the database credentials, the wiring document the build and the Worker read (URL and publishable key) and the service-role key, which only the Worker's deploy reads, to store as a Worker secret for the admin functions. infra/terraform/cloudflare-hyperdrive puts a Hyperdrive config, caching off, in front of each project's Postgres. packages/db (@saas/db) carries upstream's 30 supabase/migrations in their order — the history supabase db push applies, which a comparison on a Supabase-shaped Postgres showed to be the schema upstream's declarative files describe, less one grant they still give — then its seed, then the port's outbox: cleanup_note_attachments() queues a note's old and new record, and the Worker's Cron Trigger drains the queue through the Storage API with upstream's own getPathsToDelete, where upstream's trigger called the edge function through pg_net. Three upstream files carry a marked edit (pgjwt, absent on Postgres 17, is not created; http and pg_net are created where installed). infra/db-migrate applies them through the Management API before the Worker deploys. tests/db applies every migration with db-migrate's runner to a Supabase-shaped PGlite, twice, and checks sign-up, the Data API's roles, the bucket and its policies, the seed and the outbox; tests/web covers the drain. tooling/catalog generates each component's docs from its manifests. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- apps/web/component.yaml | 34 + apps/web/docs/architecture.md | 71 ++- apps/web/docs/overview.md | 6 +- apps/web/docs/runbook.md | 51 +- apps/web/worker/cleanup.ts | 75 +++ .../delete_note_attachments/index.ts | 6 +- apps/web/worker/index.ts | 17 +- apps/web/wrangler.jsonc | 5 + apps/web/wrangler.template.jsonc | 5 + infra/db-migrate/component.yaml | 82 +++ infra/db-migrate/docs/architecture.md | 48 ++ infra/db-migrate/docs/overview.md | 21 + infra/db-migrate/docs/runbook.md | 19 + .../cloudflare-hyperdrive/component.yaml | 73 +++ .../docs/architecture.md | 31 + .../cloudflare-hyperdrive/docs/overview.md | 20 + .../cloudflare-hyperdrive/docs/runbook.md | 20 + .../terraform/.terraform.lock.hcl | 50 ++ .../cloudflare-hyperdrive/terraform/adopt.tf | 40 ++ .../terraform/backend.tf | 5 + .../cloudflare-hyperdrive/terraform/main.tf | 174 +++++ .../terraform/outputs.tf | 2 + .../terraform/variables.tf | 2 + infra/terraform/supabase/component.yaml | 76 +++ infra/terraform/supabase/docs/architecture.md | 35 + infra/terraform/supabase/docs/overview.md | 21 + infra/terraform/supabase/docs/runbook.md | 20 + .../supabase/terraform/.terraform.lock.hcl | 73 +++ infra/terraform/supabase/terraform/adopt.tf | 49 ++ infra/terraform/supabase/terraform/main.tf | 285 +++++++++ packages/db/component.yaml | 31 + packages/db/docs/architecture.md | 11 + packages/db/docs/overview.md | 20 + packages/db/docs/runbook.md | 25 + packages/db/eslint.config.js | 2 + packages/db/package.json | 30 + packages/db/src/index.ts | 3 + packages/db/src/manifest.ts | 312 +++++++++ packages/db/src/migrations/000_control/up.sql | 16 + .../migrations/20240730075029_init_db/up.sql | 600 ++++++++++++++++++ .../20240730075425_init_triggers/up.sql | 57 ++ .../20240806124555_task_sales_id/up.sql | 1 + .../20240807082449_remove-aquisition/up.sql | 20 + .../up.sql | 9 + .../20240813084010_tags_policy/up.sql | 18 + .../20241104153231_sales_policies/up.sql | 7 + .../20250109152531_email_jsonb/up.sql | 43 ++ .../20250113132531_phone_jsonb/up.sql | 67 ++ .../up.sql | 153 +++++ .../up.sql | 2 + .../20260108160722_task_default_sales/up.sql | 39 ++ .../20260115150819_snake_case_renaming/up.sql | 158 +++++ .../migrations/20260127140209_imports/up.sql | 206 ++++++ .../20260128165057_sso_handling/up.sql | 52 ++ .../20260211194545_app_configuration/up.sql | 77 +++ .../up.sql | 3 + .../up.sql | 124 ++++ .../up.sql | 18 + .../up.sql | 350 ++++++++++ .../20260314120000_activity_log_view/up.sql | 79 +++ .../up.sql | 86 +++ .../up.sql | 33 + .../up.sql | 3 + .../20260924120000_deals_lost_reason/up.sql | 1 + .../up.sql | 1 + .../up.sql | 53 ++ .../20261010054346_global_search/up.sql | 285 +++++++++ .../up.sql | 84 +++ .../20261026120000_deal_categories/up.sql | 97 +++ .../src/migrations/20261101000000_seed/up.sql | 105 +++ .../up.sql | 47 ++ packages/db/src/runner/cli.ts | 121 ++++ packages/db/src/runner/index.ts | 5 + packages/db/src/runner/runner.ts | 140 ++++ packages/db/src/runner/secrets.ts | 62 ++ .../db/src/runner/supabase-api-adapter.ts | 93 +++ packages/db/src/runner/types.ts | 41 ++ packages/db/src/types.ts | 20 + packages/db/tsconfig.build.json | 7 + packages/db/tsconfig.json | 10 + pnpm-lock.yaml | 61 +- .../epics/atomic-crm/IMPLEMENTATION-STATUS.md | 37 +- tests/db/component.yaml | 32 + tests/db/docs/architecture.md | 8 + tests/db/docs/overview.md | 20 + tests/db/docs/runbook.md | 26 + tests/db/eslint.config.js | 2 + tests/db/package.json | 22 + tests/db/src/fixtures/supabase-shape.sql | 121 ++++ tests/db/src/harness.ts | 97 +++ tests/db/src/migrations.test.ts | 56 ++ tests/db/src/schema.test.ts | 130 ++++ tests/db/tsconfig.json | 11 + tests/db/vitest.config.ts | 8 + tests/web/docs/architecture.md | 58 +- tests/web/docs/overview.md | 14 +- tests/web/docs/runbook.md | 29 +- tests/web/src/worker/cleanup.test.ts | 84 +++ tests/web/src/worker/routes.test.ts | 6 + tests/web/src/worker/wrangler-config.test.ts | 2 + tooling/catalog/gen-component-docs.py | 550 ++++++++++++++++ 101 files changed, 6543 insertions(+), 74 deletions(-) create mode 100644 apps/web/worker/cleanup.ts create mode 100644 infra/db-migrate/component.yaml create mode 100644 infra/db-migrate/docs/architecture.md create mode 100644 infra/db-migrate/docs/overview.md create mode 100644 infra/db-migrate/docs/runbook.md create mode 100644 infra/terraform/cloudflare-hyperdrive/component.yaml create mode 100644 infra/terraform/cloudflare-hyperdrive/docs/architecture.md create mode 100644 infra/terraform/cloudflare-hyperdrive/docs/overview.md create mode 100644 infra/terraform/cloudflare-hyperdrive/docs/runbook.md create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/backend.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/main.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf create mode 100644 infra/terraform/cloudflare-hyperdrive/terraform/variables.tf create mode 100644 infra/terraform/supabase/component.yaml create mode 100644 infra/terraform/supabase/docs/architecture.md create mode 100644 infra/terraform/supabase/docs/overview.md create mode 100644 infra/terraform/supabase/docs/runbook.md create mode 100644 infra/terraform/supabase/terraform/.terraform.lock.hcl create mode 100644 infra/terraform/supabase/terraform/adopt.tf create mode 100644 infra/terraform/supabase/terraform/main.tf create mode 100644 packages/db/component.yaml create mode 100644 packages/db/docs/architecture.md create mode 100644 packages/db/docs/overview.md create mode 100644 packages/db/docs/runbook.md create mode 100644 packages/db/eslint.config.js create mode 100644 packages/db/package.json create mode 100644 packages/db/src/index.ts create mode 100644 packages/db/src/manifest.ts create mode 100644 packages/db/src/migrations/000_control/up.sql create mode 100644 packages/db/src/migrations/20240730075029_init_db/up.sql create mode 100644 packages/db/src/migrations/20240730075425_init_triggers/up.sql create mode 100644 packages/db/src/migrations/20240806124555_task_sales_id/up.sql create mode 100644 packages/db/src/migrations/20240807082449_remove-aquisition/up.sql create mode 100644 packages/db/src/migrations/20240808141826_init_state_configure/up.sql create mode 100644 packages/db/src/migrations/20240813084010_tags_policy/up.sql create mode 100644 packages/db/src/migrations/20241104153231_sales_policies/up.sql create mode 100644 packages/db/src/migrations/20250109152531_email_jsonb/up.sql create mode 100644 packages/db/src/migrations/20250113132531_phone_jsonb/up.sql create mode 100644 packages/db/src/migrations/20251204172855_merge_contacts_function/up.sql create mode 100644 packages/db/src/migrations/20251204201317_drop_merge_contacts_function/up.sql create mode 100644 packages/db/src/migrations/20260108160722_task_default_sales/up.sql create mode 100644 packages/db/src/migrations/20260115150819_snake_case_renaming/up.sql create mode 100644 packages/db/src/migrations/20260127140209_imports/up.sql create mode 100644 packages/db/src/migrations/20260128165057_sso_handling/up.sql create mode 100644 packages/db/src/migrations/20260211194545_app_configuration/up.sql create mode 100644 packages/db/src/migrations/20260226163952_deals_expected_closing_date_date_only/up.sql create mode 100644 packages/db/src/migrations/20260304104600_note_attachments_trigger/up.sql create mode 100644 packages/db/src/migrations/20260307120000_nb_tasks_pending_only/up.sql create mode 100644 packages/db/src/migrations/20260309112831_fix_security_warnings/up.sql create mode 100644 packages/db/src/migrations/20260314120000_activity_log_view/up.sql create mode 100644 packages/db/src/migrations/20260320120000_lowercase_email_website/up.sql create mode 100644 packages/db/src/migrations/20260601120000_grant_init_state_to_api_roles/up.sql create mode 100644 packages/db/src/migrations/20260811131131_sales_secondary_emails/up.sql create mode 100644 packages/db/src/migrations/20260924120000_deals_lost_reason/up.sql create mode 100644 packages/db/src/migrations/20260928120000_drop_deals_lost_reason/up.sql create mode 100644 packages/db/src/migrations/20260929120000_remove_deleted_tag_from_contacts/up.sql create mode 100644 packages/db/src/migrations/20261010054346_global_search/up.sql create mode 100644 packages/db/src/migrations/20261022120000_global_search_per_resource_cap/up.sql create mode 100644 packages/db/src/migrations/20261026120000_deal_categories/up.sql create mode 100644 packages/db/src/migrations/20261101000000_seed/up.sql create mode 100644 packages/db/src/migrations/20261101000100_note_attachments_outbox/up.sql create mode 100644 packages/db/src/runner/cli.ts create mode 100644 packages/db/src/runner/index.ts create mode 100644 packages/db/src/runner/runner.ts create mode 100644 packages/db/src/runner/secrets.ts create mode 100644 packages/db/src/runner/supabase-api-adapter.ts create mode 100644 packages/db/src/runner/types.ts create mode 100644 packages/db/src/types.ts create mode 100644 packages/db/tsconfig.build.json create mode 100644 packages/db/tsconfig.json create mode 100644 tests/db/component.yaml create mode 100644 tests/db/docs/architecture.md create mode 100644 tests/db/docs/overview.md create mode 100644 tests/db/docs/runbook.md create mode 100644 tests/db/eslint.config.js create mode 100644 tests/db/package.json create mode 100644 tests/db/src/fixtures/supabase-shape.sql create mode 100644 tests/db/src/harness.ts create mode 100644 tests/db/src/migrations.test.ts create mode 100644 tests/db/src/schema.test.ts create mode 100644 tests/db/tsconfig.json create mode 100644 tests/db/vitest.config.ts create mode 100644 tests/web/src/worker/cleanup.test.ts create mode 100644 tooling/catalog/gen-component-docs.py diff --git a/apps/web/component.yaml b/apps/web/component.yaml index 5d7f07c..d4c3b13 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -20,6 +20,40 @@ spec: change: inputs: - pnpm-lock.yaml + # The Supabase project and its Hyperdrive config must exist, and the schema + # be applied, before the Worker that reads them deploys: enforced on a push + # to main, advisory on a pull request (which plans and verifies only). + dependsOn: + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # What the deploy lane renders the Worker's config from (the roots' wiring + # documents) and stores as its Worker secrets. Optional: dev, which no root + # applies to, renders from the fixture, and a verify lane pushes nothing. + optionalSecretEnv: + WIRING_SUPABASE_STAGE: "secret://atomic-crm/atomic-crm/stage/WIRING_SUPABASE" + WIRING_SUPABASE_PROD: "secret://atomic-crm/atomic-crm/prod/WIRING_SUPABASE" + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://atomic-crm/atomic-crm/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://atomic-crm/atomic-crm/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + SUPABASE_SERVICE_ROLE_KEY: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_SERVICE_ROLE_KEY" + POSTMARK_WEBHOOK_USER: "secret://atomic-crm/atomic-crm/{{ .environment }}/POSTMARK_WEBHOOK_USER" + POSTMARK_WEBHOOK_PASSWORD: "secret://atomic-crm/atomic-crm/{{ .environment }}/POSTMARK_WEBHOOK_PASSWORD" + POSTMARK_WEBHOOK_AUTHORIZED_IPS: "secret://atomic-crm/atomic-crm/{{ .environment }}/POSTMARK_WEBHOOK_AUTHORIZED_IPS" subscribe: environments: - name: dev diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md index 4779d11..ae12dce 100644 --- a/apps/web/docs/architecture.md +++ b/apps/web/docs/architecture.md @@ -1,31 +1,44 @@ # web — architecture -One Worker per environment, `atomic-crm-web-`. - -``` -browser ──▶ Static Assets (dist/: the React-Admin SPA, hash-routed) - │ - ├──▶ Supabase project: Auth, PostgREST (the data provider), Storage - │ - └──▶ /functions/v1/ ──▶ this Worker (worker/index.ts) - ├─ users, update_password, delete_note_attachments, postmark - │ └─▶ Supabase admin API (service-role key, a Worker secret) - └─ merge_contacts, mcp - └─▶ Postgres through Hyperdrive (HYPERDRIVE binding) -``` - -- **The SPA** is upstream's (`src/`), built by Vite. A build inlines the - project's URL and publishable key from the `vars` of the rendered - `wrangler.jsonc` (`build-env.ts`), so the bundle and the Worker always - name the same project. -- **The edge functions** are upstream's `supabase/functions`, in - `worker/functions`, nearly verbatim: `Deno.env.get` and `Deno.serve` come - from a two-function shim (`worker/functions/_shared/deno.ts`) and the - `jsr:`/`npm:` imports are npm packages. The Supabase client's `fetch` sends - `/functions/v1/*` to the page's own origin, so `supabase.functions.invoke` - reaches them unchanged. -- **Postgres** is reached per request (Kysely over `pg` for - `merge_contacts`, one client per query for the MCP server): a Worker may not - reuse a socket another request opened, and Hyperdrive is the pool. -- `run_worker_first` sends only `/functions/*` and `/api/*` to the Worker; - every other path is a file, or `index.html`. +Built by the turbo pipeline from `apps/web` and deployed with wrangler. + +| | | +| ------------------- | ---------------------------------- | +| Worker config | `apps/web/wrangler.template.jsonc` | +| Entry | `worker/index.ts` | +| Compatibility date | `2026-10-01` | +| Compatibility flags | `nodejs_compat` | + +## Bindings + +| Binding | Kind | Source | +| ------------ | ---------------------------- | -------------------------------------------- | +| `HYPERDRIVE` | Hyperdrive (pooled Postgres) | `hyperdrive_id` from `cloudflare-hyperdrive` | +| `ASSETS` | Static assets | `dist` | + +Identifiers marked _from_ a component are filled in at deploy time from +that component's published outputs for the environment being deployed. + +## Scheduled triggers + +- `*/10 * * * *` + +## Variables + +`SB_PUBLISHABLE_KEY`, `SUPABASE_URL`. + +## Wiring + +Resolved at deploy time from secrets the infrastructure lanes publish (names only): + +- `WIRING_CLOUDFLARE_HYPERDRIVE_PROD` (optional) +- `WIRING_CLOUDFLARE_HYPERDRIVE_STAGE` (optional) +- `WIRING_SUPABASE_PROD` (optional) +- `WIRING_SUPABASE_STAGE` (optional) + +## Secrets resolved by the lane (names only) + +- `POSTMARK_WEBHOOK_AUTHORIZED_IPS` (optional) +- `POSTMARK_WEBHOOK_PASSWORD` (optional) +- `POSTMARK_WEBHOOK_USER` (optional) +- `SUPABASE_SERVICE_ROLE_KEY` (optional) diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md index 5224d66..e079e3c 100644 --- a/apps/web/docs/overview.md +++ b/apps/web/docs/overview.md @@ -2,7 +2,7 @@ The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment -A Cloudflare Worker with Static Assets, deployed per environment by its CI lane. +A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. | | | | ------------ | ------------------------------------------------------------------------------------------------------------------ | @@ -13,7 +13,9 @@ A Cloudflare Worker with Static Assets, deployed per environment by its CI lane. ## Depends on -- (none) +- **supabase** — Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets +- **cloudflare-hyperdrive** — Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases +- **db-migrate** — Applies database migrations to stage and prod Supabase instances ## Depended on by diff --git a/apps/web/docs/runbook.md b/apps/web/docs/runbook.md index ea9ee8f..c7c79b1 100644 --- a/apps/web/docs/runbook.md +++ b/apps/web/docs/runbook.md @@ -1,15 +1,40 @@ # web — runbook -| Symptom | Check | Fix | -|---|---|---| -| The deploy's smoke test fails on `/` | `curl -s https:/// \| grep 'id="root"'` | the build did not produce `dist/`: read the lane's `build-app` step | -| `/api/health` says `"supabase": false` | the rendered `wrangler.jsonc` `vars` | the Supabase root has not applied for this environment, or its `WIRING_SUPABASE` secret is missing: re-run the `supabase` lane | -| `/api/health` says `"admin": false`; inviting a user or resetting a password fails | `wrangler secret list --name atomic-crm-web-` | the deploy found no `SUPABASE_SERVICE_ROLE_KEY`: re-run the `supabase` lane, then this one | -| `/api/health` says `"database": false`; merging contacts fails | the `hyperdrive` block of the rendered config | re-run `cloudflare-hyperdrive`, then this lane | -| Sign-in works but every list is empty | the browser console: PostgREST 401/42501 | the schema is not applied: re-run `db-migrate` | -| `/functions/v1/postmark` answers 503 | — | inbound email is optional: store `POSTMARK_WEBHOOK_USER`, `POSTMARK_WEBHOOK_PASSWORD` and `POSTMARK_WEBHOOK_AUTHORIZED_IPS` as Orun secrets and redeploy | - -Local: `pnpm --filter @app/web preview` builds the app and serves it with the -Worker under `wrangler dev` on :8787 (secrets from `.dev.vars`, see -`.dev.vars.example`); `pnpm --filter @app/web dev:demo` runs upstream's -FakeRest demo with no Supabase at all. +## How it runs + +Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web dev +pnpm --filter @app/web build +pnpm --filter @app/web typecheck +pnpm --filter @app/web lint +pnpm --filter @app/web preview +``` + +## Verify + +After a deploy the lane runs this smoke against the environment it +deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL: + +```bash +html=$(curl -sfL "${DEPLOYED_URL}/") && echo "${html}" | grep -q '
' && health=$(curl -sf "${DEPLOYED_URL}/api/health") && echo "${health}" | grep -q '"ok":true' && test "$(curl -s -o /dev/null -w '%{http_code}' -X PATCH "${DEPLOYED_URL}/functions/v1/update_password")" = 401 +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream + has not applied for this environment yet. Within one convergence the plan + runs it first; on its own, re-run that lane. +- **The smoke fails right after a first deploy**: a new workers.dev route can + answer 4xx for a few seconds and the lane retries. A failure that persists + is a regression in the deployed code. diff --git a/apps/web/worker/cleanup.ts b/apps/web/worker/cleanup.ts new file mode 100644 index 0000000..977d2be --- /dev/null +++ b/apps/web/worker/cleanup.ts @@ -0,0 +1,75 @@ +// The note-attachments clean-up upstream runs as a database webhook: its +// cleanup_note_attachments() trigger posted each changed or deleted note to +// the delete_note_attachments edge function through pg_net. The database has +// no address for this Worker, so the trigger queues the same payload in +// private.note_attachment_cleanups (packages/db, the outbox migration), and +// the Cron Trigger (wrangler.jsonc) drains it here — the paths chosen by +// upstream's own getPathsToDelete, removed through the same Storage API with +// the service-role key. +import pg from "pg"; +import { supabaseAdmin } from "./functions/_shared/supabaseAdmin"; +import { Deno, databaseUrl } from "./functions/_shared/deno"; +import { + ATTACHMENTS_BUCKET, + getPathsToDelete, + type WebhookPayload, +} from "./functions/delete_note_attachments/index"; + +/** A row is retried this many times, then left for a person to read. */ +export const MAX_ATTEMPTS = 5; +/** Rows per run: a run holds their locks while it calls Storage. */ +export const BATCH = 50; + +export interface DrainResult { + processed: number; + removed: number; + failed: number; + skipped?: string; +} + +type Row = { id: number | string; payload: WebhookPayload }; + +export async function drainNoteAttachmentCleanups( + client: Pick | null = null, +): Promise { + if (!Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")) { + return { processed: 0, removed: 0, failed: 0, skipped: "no SUPABASE_SERVICE_ROLE_KEY" }; + } + const own = client ? null : new pg.Client({ connectionString: databaseUrl() }); + const db = client ?? own!; + if (own) await own.connect(); + const result: DrainResult = { processed: 0, removed: 0, failed: 0 }; + try { + await db.query("begin"); + const { rows } = await db.query( + `select id, payload from private.note_attachment_cleanups + where attempts < $1 order by id limit $2 for update skip locked`, + [MAX_ATTEMPTS, BATCH], + ); + for (const row of rows) { + result.processed++; + const paths = getPathsToDelete(row.payload); + if (paths.length > 0) { + const { error } = await supabaseAdmin.storage.from(ATTACHMENTS_BUCKET).remove(paths); + if (error) { + result.failed++; + await db.query( + `update private.note_attachment_cleanups + set attempts = attempts + 1, last_error = $2 where id = $1`, + [row.id, error.message ?? String(error)], + ); + continue; + } + result.removed += paths.length; + } + await db.query("delete from private.note_attachment_cleanups where id = $1", [row.id]); + } + await db.query("commit"); + return result; + } catch (e) { + await db.query("rollback").catch(() => {}); + throw e; + } finally { + if (own) await own.end().catch(() => {}); + } +} diff --git a/apps/web/worker/functions/delete_note_attachments/index.ts b/apps/web/worker/functions/delete_note_attachments/index.ts index 9112518..2f10ce7 100644 --- a/apps/web/worker/functions/delete_note_attachments/index.ts +++ b/apps/web/worker/functions/delete_note_attachments/index.ts @@ -2,7 +2,7 @@ import { Deno } from "../_shared/deno"; import { AuthMiddleware } from "../_shared/authentication"; import { supabaseAdmin } from "../_shared/supabaseAdmin"; -const ATTACHMENTS_BUCKET = +export const ATTACHMENTS_BUCKET = Deno.env.get("VITE_ATTACHMENTS_BUCKET") || "attachments"; type NoteAttachment = { @@ -15,7 +15,7 @@ type NoteRecord = { attachments?: NoteAttachment[] | null; }; -type WebhookPayload = { +export type WebhookPayload = { type?: string | null; old_record?: NoteRecord | null; record?: NoteRecord | null; @@ -58,7 +58,7 @@ export const handler = Deno.serve(async (req: Request) => AuthMiddleware(req, async (req: Request) => deleteNoteAttachments(req)), ); -const getPathsToDelete = (payload: WebhookPayload): string[] => { +export const getPathsToDelete = (payload: WebhookPayload): string[] => { const oldPaths = extractAttachmentPaths(payload.old_record?.attachments); const newPaths = extractAttachmentPaths(payload.record?.attachments); diff --git a/apps/web/worker/index.ts b/apps/web/worker/index.ts index 99d8a96..8f938df 100644 --- a/apps/web/worker/index.ts +++ b/apps/web/worker/index.ts @@ -4,13 +4,15 @@ // upstream deploys to the Supabase project, as this Worker's own routes at the // same /functions/v1/ paths (supabase.functions.invoke is pointed at // this origin, src/components/crm/providers/supabase/supabase.ts), and the -// health check the deploy smoke-tests. +// health check the deploy smoke-tests. Its Cron Trigger drains the queue of +// note attachments to delete (cleanup.ts). import { handler as deleteNoteAttachments } from "./functions/delete_note_attachments/index"; import { handler as mcp } from "./functions/mcp/index"; import { handler as mergeContacts } from "./functions/merge_contacts/index"; import { handler as postmark } from "./functions/postmark/index"; import { handler as updatePassword } from "./functions/update_password/index"; import { handler as users } from "./functions/users/index"; +import { drainNoteAttachmentCleanups } from "./cleanup"; type Handler = (req: Request) => Response | Promise; @@ -60,4 +62,17 @@ export default { if (pathname === "/api/health") return Response.json(health(env)); return env.ASSETS.fetch(req); }, + + async scheduled( + _controller: unknown, + env: Env, + ctx: { waitUntil(promise: Promise): void }, + ): Promise { + if (!env.HYPERDRIVE) return; + ctx.waitUntil( + drainNoteAttachmentCleanups().then((r) => { + if (r.failed || r.skipped) console.warn("note attachments clean-up", JSON.stringify(r)); + }), + ); + }, }; diff --git a/apps/web/wrangler.jsonc b/apps/web/wrangler.jsonc index 629d27c..a9a7490 100644 --- a/apps/web/wrangler.jsonc +++ b/apps/web/wrangler.jsonc @@ -17,6 +17,11 @@ "run_worker_first": ["/functions/*", "/api/*"] }, "observability": { "enabled": true }, + // Drains the queue of note attachments to delete (worker/cleanup.ts), which + // upstream's database webhook did through pg_net. One trigger per Worker. + "triggers": { + "crons": ["*/10 * * * *"] + }, // The Supabase project: what the browser signs in to and reads through // (vite.config.ts inlines both into the build from here), and what the // functions call. The anon key is the project's publishable key. diff --git a/apps/web/wrangler.template.jsonc b/apps/web/wrangler.template.jsonc index 8d09bc0..abd0392 100644 --- a/apps/web/wrangler.template.jsonc +++ b/apps/web/wrangler.template.jsonc @@ -23,6 +23,11 @@ "run_worker_first": ["/functions/*", "/api/*"] }, "observability": { "enabled": true }, + // Drains the queue of note attachments to delete (worker/cleanup.ts), which + // upstream's database webhook did through pg_net. One trigger per Worker. + "triggers": { + "crons": ["*/10 * * * *"] + }, // The Supabase project: what the browser signs in to and reads through // (vite.config.ts inlines both into the build from here), and what the // functions call. The anon key is the project's publishable key. diff --git a/infra/db-migrate/component.yaml b/infra/db-migrate/component.yaml new file mode 100644 index 0000000..fdb8a91 --- /dev/null +++ b/infra/db-migrate/component.yaml @@ -0,0 +1,82 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-migrate + description: Applies database migrations to stage and prod Supabase instances + labels: + domain: infra + scope: database + team: platform + layer: data + +spec: + type: db-migrate + lifecycle: production + owner: platform + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: infra + + # Migrations read the Supabase connection from the orun secrets the + # `supabase` apply lease-publishes, so on main they wait for it — and for + # the Hyperdrive config over that database. Nothing here needs Hyperdrive; + # the edge is there because a migration is the one step of a convergence a + # re-run cannot take back, so it runs only once everything the Worker needs + # besides the schema exists, immediately before the Workers deploy. The + # order on main is supabase → cloudflare-hyperdrive → db-migrate → app and + # api. Enforced on main, advisory on a pull request (which applies nothing). + # + # The composition builds the runner by package name (`turbo run build + # --filter=@saas/db`), so packages/db keeps that name, not an @app/* one. + dependsOn: + - component: db + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + + path: packages/db/src/migrations + + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + owner: sourceplane + repo: atomic-crm + + # The migration runner's Management-API token (required in apply mode) + # resolves from orun secrets — minted fresh per run from the Supabase + # integration (management-access template). Replaces the ambient + # SUPABASE_ACCESS_TOKEN CI value. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + # The runner's DB identity (de-AWS — replaces the Secrets Manager read). + SUPABASE_PROJECT_REF: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_PROJECT_REF" + SUPABASE_DB_PASSWORD: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_DB_PASSWORD" + SUPABASE_DB_URL: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_DB_URL" + + subscribe: + environments: + - name: stage + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/db-migrate/docs/architecture.md b/infra/db-migrate/docs/architecture.md new file mode 100644 index 0000000..f3f5197 --- /dev/null +++ b/infra/db-migrate/docs/architecture.md @@ -0,0 +1,48 @@ +# db-migrate — architecture + +Applies the migrations under `packages/db/src/migrations` in order, recording each one +it applies so a run only ever applies what is new. An already-applied migration +is never edited: a change is a new, later migration. + +## Migrations + +- `000_control` +- `20240730075029_init_db` +- `20240730075425_init_triggers` +- `20240806124555_task_sales_id` +- `20240807082449_remove-aquisition` +- `20240808141826_init_state_configure` +- `20240813084010_tags_policy` +- `20241104153231_sales_policies` +- `20250109152531_email_jsonb` +- `20250113132531_phone_jsonb` +- `20251204172855_merge_contacts_function` +- `20251204201317_drop_merge_contacts_function` +- `20260108160722_task_default_sales` +- `20260115150819_snake_case_renaming` +- `20260127140209_imports` +- `20260128165057_sso_handling` +- `20260211194545_app_configuration` +- `20260226163952_deals_expected_closing_date_date_only` +- `20260304104600_note_attachments_trigger` +- `20260307120000_nb_tasks_pending_only` +- `20260309112831_fix_security_warnings` +- `20260314120000_activity_log_view` +- `20260320120000_lowercase_email_website` +- `20260601120000_grant_init_state_to_api_roles` +- `20260811131131_sales_secondary_emails` +- `20260924120000_deals_lost_reason` +- `20260928120000_drop_deals_lost_reason` +- `20260929120000_remove_deleted_tag_from_contacts` +- `20261010054346_global_search` +- `20261022120000_global_search_per_resource_cap` +- `20261026120000_deal_categories` +- `20261101000000_seed` +- `20261101000100_note_attachments_outbox` + +## Resolved at run time (names only) + +- `SUPABASE_ACCESS_TOKEN` +- `SUPABASE_DB_PASSWORD` +- `SUPABASE_DB_URL` +- `SUPABASE_PROJECT_REF` diff --git a/infra/db-migrate/docs/overview.md b/infra/db-migrate/docs/overview.md new file mode 100644 index 0000000..f9ec7a0 --- /dev/null +++ b/infra/db-migrate/docs/overview.md @@ -0,0 +1,21 @@ +# db-migrate + +Applies database migrations to stage and prod Supabase instances + +Applies this repository's ordered database migrations per environment: plan on pull requests, apply on merge to `main`. + +| | | +| ------------ | ------------------------------------------------------------------------------------------ | +| Type | `db-migrate` | +| Source | `infra/db-migrate` | +| Environments | `stage`: `plan`, `apply` on a push to `main` · `prod`: `plan`, `apply` on a push to `main` | + +## Depends on + +- **db** — The database migrations and their runner (built by the db-migrate component before it plans or applies) +- **supabase** — Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets +- **cloudflare-hyperdrive** — Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases + +## Depended on by + +- **web** — The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment diff --git a/infra/db-migrate/docs/runbook.md b/infra/db-migrate/docs/runbook.md new file mode 100644 index 0000000..04a50d1 --- /dev/null +++ b/infra/db-migrate/docs/runbook.md @@ -0,0 +1,19 @@ +# db-migrate — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **An applied migration's file changed**: the run stops rather than guess. + Restore the file and write the change as a new migration. +- **The database is unreachable**: the infrastructure lane it depends on has + not applied for this environment; that lane runs first in a convergence. diff --git a/infra/terraform/cloudflare-hyperdrive/component.yaml b/infra/terraform/cloudflare-hyperdrive/component.yaml new file mode 100644 index 0000000..7f0792c --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/component.yaml @@ -0,0 +1,73 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-hyperdrive + description: Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases + labels: + domain: infra + scope: runtime-database-gateway + +spec: + type: terraform + lifecycle: production + owner: platform + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: infra + + # Hyperdrive's origin is the Supabase project's Postgres, whose ref and + # password the `supabase` apply lease-publishes (SUPABASE_PROJECT_REF, + # SUPABASE_DB_PASSWORD, read below). A job resolves its secrets when it + # starts, so on main this waits for that apply, `mode: enforced`; a pull + # request applies nothing, so there it is advisory. + dependsOn: + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + + parameters: + orgName: sourceplane + stackName: cloudflare-hyperdrive + terraformDir: terraform + terraformVersion: "1.15.3" + # SEC-JOB: the wiring document (hyperdrive id/name) is lease-published + # post-apply; worker deploys read it back as WIRING_CLOUDFLARE_HYPERDRIVE_. + secretOutputs: "WIRING_CLOUDFLARE_HYPERDRIVE=wiring" + + # All three values resolve from orun secrets (project rung, brokered from + # the Cloudflare integration): the provider credential is minted fresh per + # run from the hyperdrive-edit template (Workers Hyperdrive Write — the + # workers-deploy token deliberately cannot touch Hyperdrive), and the + # account id is a non-secret connection fact (account-id template). + # Component-level because plan-only lanes refresh against the live API too. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://atomic-crm/atomic-crm/{{ .environment }}/CLOUDFLARE_HYPERDRIVE_TOKEN" + CLOUDFLARE_ACCOUNT_ID: "secret://atomic-crm/atomic-crm/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://atomic-crm/atomic-crm/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + # Supabase origin, lease-published by the supabase component's + # secretOutputs — the replacement for the Secrets Manager data source. + TF_VAR_supabase_project_ref: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_PROJECT_REF" + TF_VAR_supabase_db_password: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_DB_PASSWORD" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-hyperdrive/docs/architecture.md b/infra/terraform/cloudflare-hyperdrive/docs/architecture.md new file mode 100644 index 0000000..4cb812f --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/docs/architecture.md @@ -0,0 +1,31 @@ +# cloudflare-hyperdrive — architecture + +A `terraform` root at `infra/terraform/cloudflare-hyperdrive/terraform`. + +- **State** lives in the Orun Cloud HTTP state backend — no local state and + no state bucket to manage. +- **Credentials are brokered per run** from the workspace's provider + connections and resolved by name; none is stored in this repository. +- **Adoption** (`adopt.tf`): when state is empty but the resource already + exists, plan-time import adopts it instead of failing. + +## Resources + +- `cloudflare_hyperdrive_config.postgres` + +## Published outputs + +Written as job-output secrets on each environment after an apply; deploy +lanes downstream resolve them by name. + +| Secret | Terraform output | +| ------------------------------ | ---------------- | +| `WIRING_CLOUDFLARE_HYPERDRIVE` | `wiring` | + +## Resolved at run time (names only) + +- `CLOUDFLARE_ACCOUNT_ID` +- `CLOUDFLARE_API_TOKEN` +- `TF_VAR_cloudflare_account_id` +- `TF_VAR_supabase_db_password` +- `TF_VAR_supabase_project_ref` diff --git a/infra/terraform/cloudflare-hyperdrive/docs/overview.md b/infra/terraform/cloudflare-hyperdrive/docs/overview.md new file mode 100644 index 0000000..44fa2d3 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/docs/overview.md @@ -0,0 +1,20 @@ +# cloudflare-hyperdrive + +Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases + +Terraform-managed infrastructure, planned and applied per environment by its CI lane. + +| | | +| ------------ | ---------------------------------------------------------------------------------------------------- | +| Type | `terraform` | +| Source | `infra/terraform/cloudflare-hyperdrive` | +| Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | + +## Depends on + +- **supabase** — Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets + +## Depended on by + +- **db-migrate** — Applies database migrations to stage and prod Supabase instances +- **web** — The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment diff --git a/infra/terraform/cloudflare-hyperdrive/docs/runbook.md b/infra/terraform/cloudflare-hyperdrive/docs/runbook.md new file mode 100644 index 0000000..016c2b5 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/docs/runbook.md @@ -0,0 +1,20 @@ +# cloudflare-hyperdrive — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **Provider authentication fails**: the workspace's provider connection is + missing or revoked. Reconnect it in the console; credentials are brokered + from it per run. +- **"Already exists" on a first apply**: state is empty but the resource is + not. `adopt.tf` imports it at plan time; if it still fails, the resource was renamed outside Terraform. diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..c133371 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl @@ -0,0 +1,50 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/cloudflare/cloudflare" { + version = "4.52.7" + constraints = "~> 4.30" + hashes = [ + "h1:pPItIWii5oymR+geZB219ROSPuSODPLTlM4S/u8xLvM=", + "h1:uUUa9dY0XQOycI8pxg16PFFtL0WCTi9uEJz8trTQ7pU=", + "h1:y3rV8KF2q6GEMANNlf5EkKJurlfbKlIKpjGcdxoy7pQ=", + "zh:0c904ce31a4c6c4a5b3bf7ff1560e77c0cc7e2450c8553ded8e8c90398e1418b", + "zh:36183d310c36373fe4cb936b83c595c6fd3b0a94bc7827f28e5789ccbf59752e", + "zh:556a568a6f0235e8f41647de9e4d3a1e7b1d6502df8b19b54ec441f1c653ea10", + "zh:633ebbd5b0245e75e500ef9be4d9e62288f97e8da3baaa51323892a786d90285", + "zh:6acfe60cf52a65ba8f044f748548d2119e7f4fd7f8ebcb14698960d87c68f529", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:904acc31ebb9d6ef68c792074b30532ee61bf515f19e0a3c75b46f126cca1f13", + "zh:a1d0a81246afc8750286d3f6fe7a8fbe6460dd2662407b28dbfbabb612e5fa9d", + "zh:a41a36fe253fc365fe2b7ffc749624688b2693b4634862fda161179ab100029f", + "zh:a7ef269e77ffa8715c8945a2c14322c7ff159ea44c15f62505f3cbb2cae3b32d", + "zh:b01aa3bed30610633b762df64332b26f8844a68c3960cebcb30f04918efc67fe", + "zh:b069cc2cd18cae10757df3ae030508eac8d55de7e49eda7a5e3e11f2f7fe6455", + "zh:b2d2c6313729ebb7465dceece374049e2d08bda34473901be9ff46a8836d42b2", + "zh:db0e114edaf4bc2f3d4769958807c83022bfbc619a00bdf4c4bd17faa4ab2d8b", + "zh:ecc0aa8b9044f664fd2aaf8fa992d976578f78478980555b4b8f6148e8d1a5fe", + ] +} + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf b/infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf new file mode 100644 index 0000000..1c58837 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/adopt.tf @@ -0,0 +1,40 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# Same pattern as cloudflare-kv/terraform/adopt.tf: when the platform state +# does not yet track the Hyperdrive config but Cloudflare already has one +# under this name, import it at plan time instead of creating a duplicate. +# Fresh products resolve to id = "" and create normally; a resource already in +# state short-circuits the lookup. Note the origin password still comes from +# config — after adoption the first apply re-asserts the origin credentials +# from SUPABASE_DB_PASSWORD, which is exactly the re-sync the cutover needs. + +data "external" "adopt_hyperdrive_config" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_hyperdrive_config" and .name == "postgres")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/hyperdrive/configs")" + printf '%s' "$resp" | jq -c --arg n "$name" \ + '{id: ([.result[] | select(.name == $n) | .id] | first // "")}' + EOT + ] + query = { + name = local.hyperdrive_name + } +} + +import { + for_each = toset(compact([data.external.adopt_hyperdrive_config.result.id])) + to = cloudflare_hyperdrive_config.postgres + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/backend.tf b/infra/terraform/cloudflare-hyperdrive/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/main.tf b/infra/terraform/cloudflare-hyperdrive/terraform/main.tf new file mode 100644 index 0000000..d2e7473 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/main.tf @@ -0,0 +1,174 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} + + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the +# token is an orun-managed secret resolved into the job env at run time, so it +# never transits Terraform variables. +provider "cloudflare" {} + +# --- Variables (standard Orun parameters) --- + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "atomic-crm" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-hyperdrive" +} + +variable "stackName" { + type = string + default = "cloudflare-hyperdrive" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- Supabase origin (from orun secrets, not Secrets Manager) --- +# +# The supabase component wires its outputs into the workspace's project/{{env}} +# secret rung (wireSecrets → SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD); this +# component declares them in secretEnv as TF_VAR_supabase_project_ref / +# TF_VAR_supabase_db_password. Host/port/db/user derive from the project ref — +# the same derivation the old Secrets Manager payload carried. + +variable "supabase_project_ref" { + type = string + description = "Supabase project reference (from SUPABASE_PROJECT_REF secret)" +} + +variable "supabase_db_password" { + type = string + sensitive = true + description = "Supabase database password (from SUPABASE_DB_PASSWORD secret)" +} + +locals { + database_host = "db.${var.supabase_project_ref}.supabase.co" + database_port = 5432 + database_name = "postgres" + database_user = "postgres" + + hyperdrive_name = "${var.namespacePrefix}${var.repo}-${var.environment}" +} + +# --- Create Hyperdrive resource --- + +resource "cloudflare_hyperdrive_config" "postgres" { + account_id = var.cloudflare_account_id + name = local.hyperdrive_name + + origin = { + scheme = "postgres" + host = local.database_host + port = local.database_port + database = local.database_name + user = local.database_user + password = var.supabase_db_password + } + + # Off: a CRM's reads must see the write before them (a merged contact, a + # drained queue row), and the Worker's queries run in transactions anyway. + caching = { + disabled = true + } +} + +# --- Wiring manifest (BF5, via orun secrets) --- +# +# The consumable outputs of this component are published by the composition's +# wire-secrets step as the WIRING_CLOUDFLARE_HYPERDRIVE secret on the +# project/{{env}} rung; worker deploys read it back as +# WIRING_CLOUDFLARE_HYPERDRIVE_ secretEnv and render committed +# @@wiring(...)@@ tokens from it (BF6). Same document shape the Secrets +# Manager path carried. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + hyperdrive_id = cloudflare_hyperdrive_config.postgres.id + hyperdrive_name = cloudflare_hyperdrive_config.postgres.name + }) +} + +# --- Outputs (non-secret) --- + +output "hyperdrive_id" { + description = "Cloudflare Hyperdrive config ID" + value = cloudflare_hyperdrive_config.postgres.id +} + +output "hyperdrive_name" { + description = "Cloudflare Hyperdrive config name" + value = cloudflare_hyperdrive_config.postgres.name +} + +output "hyperdrive_connection_string" { + description = "Hyperdrive-formatted connection string for Workers (to be used in bindings)" + # Note: actual connection string is built at binding time; this is the resource ID + value = "hyperdrive://${cloudflare_hyperdrive_config.postgres.id}" +} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf b/infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/variables.tf b/infra/terraform/cloudflare-hyperdrive/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/supabase/component.yaml b/infra/terraform/supabase/component.yaml new file mode 100644 index 0000000..57a5e17 --- /dev/null +++ b/infra/terraform/supabase/component.yaml @@ -0,0 +1,76 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: supabase + description: Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets + labels: + domain: infra + scope: database + +spec: + type: terraform + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: infra + + parameters: + orgName: sourceplane + stackName: supabase + terraformDir: terraform + terraformVersion: "1.15.3" + # Supabase region is surfaced to Terraform as TF_VAR_supabaseRegion by the + # terraform composition's parameter→TF_VAR loop. The org id is NOT committed + # here: it is account-specific and injected as TF_VAR_supabaseOrgId from the + # SUPABASE_ORG_ID CI secret (see .github/workflows/ci.yml). Keeping it out of + # parameters also prevents the param→TF_VAR loop from overriding the secret. + supabaseRegion: ap-southeast-1 + # The app's Worker, which Auth's Site URL and redirect allow-list name: + # -web- on this workers.dev subdomain — the same value + # apps/web/component.yaml carries (TF_VAR_workersDevSubdomain). + workersDevSubdomain: your-workers-subdomain + # "false": sign-up signs the user straight in, because a project without + # SMTP of its own emails only its organization's members. "true" once the + # project sends email (the product's README, "Email"). + authEmailConfirmation: "false" + # SEC-JOB: post-apply, these outputs are queued on the runner's sink and + # lease-published onto the project/{{env}} rung by the runner. The + # project's three database credentials; WIRING_SUPABASE — the project URL + # and the publishable (anon) key, the document the app's build and Worker + # config read; and SUPABASE_SERVICE_ROLE_KEY, which only the Worker's + # deploy reads, to store as a Worker secret (the admin functions). + secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri,WIRING_SUPABASE=wiring,SUPABASE_SERVICE_ROLE_KEY=service_role_key" + + # Both values resolve from orun secrets (project rung, brokered from the + # Supabase integration): a short-lived Management-API access token minted + # fresh per run (management-access template — the provider reads + # SUPABASE_ACCESS_TOKEN from env natively), and the org id as a non-secret + # connection fact (org-id template) surfaced straight to Terraform. The + # SUPABASE_ORG_ID CI secret and its TF_VAR mapping are retired. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + TF_VAR_supabaseOrgId: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_ORG_ID" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/supabase/docs/architecture.md b/infra/terraform/supabase/docs/architecture.md new file mode 100644 index 0000000..a4003a1 --- /dev/null +++ b/infra/terraform/supabase/docs/architecture.md @@ -0,0 +1,35 @@ +# supabase — architecture + +A `terraform` root at `infra/terraform/supabase/terraform`. + +- **State** lives in the Orun Cloud HTTP state backend — no local state and + no state bucket to manage. +- **Credentials are brokered per run** from the workspace's provider + connections and resolved by name; none is stored in this repository. +- **Adoption** (`adopt.tf`): when state is empty but the resource already + exists, plan-time import adopts it instead of failing. + +## Resources + +- `random_password.db_password` +- `supabase_project.this` +- `terraform_data.project_ready` +- `supabase_settings.this` + +## Published outputs + +Written as job-output secrets on each environment after an apply; deploy +lanes downstream resolve them by name. + +| Secret | Terraform output | +| --------------------------- | ------------------- | +| `SUPABASE_PROJECT_REF` | `project_ref` | +| `SUPABASE_DB_PASSWORD` | `database_password` | +| `SUPABASE_DB_URL` | `connection_uri` | +| `WIRING_SUPABASE` | `wiring` | +| `SUPABASE_SERVICE_ROLE_KEY` | `service_role_key` | + +## Resolved at run time (names only) + +- `SUPABASE_ACCESS_TOKEN` +- `TF_VAR_supabaseOrgId` diff --git a/infra/terraform/supabase/docs/overview.md b/infra/terraform/supabase/docs/overview.md new file mode 100644 index 0000000..7975fd5 --- /dev/null +++ b/infra/terraform/supabase/docs/overview.md @@ -0,0 +1,21 @@ +# supabase + +Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets + +Terraform-managed infrastructure, planned and applied per environment by its CI lane. + +| | | +| ------------ | ---------------------------------------------------------------------------------------------------- | +| Type | `terraform` | +| Source | `infra/terraform/supabase` | +| Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- **cloudflare-hyperdrive** — Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases +- **db-migrate** — Applies database migrations to stage and prod Supabase instances +- **web** — The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment diff --git a/infra/terraform/supabase/docs/runbook.md b/infra/terraform/supabase/docs/runbook.md new file mode 100644 index 0000000..d240972 --- /dev/null +++ b/infra/terraform/supabase/docs/runbook.md @@ -0,0 +1,20 @@ +# supabase — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **Provider authentication fails**: the workspace's provider connection is + missing or revoked. Reconnect it in the console; credentials are brokered + from it per run. +- **"Already exists" on a first apply**: state is empty but the resource is + not. `adopt.tf` imports it at plan time; if it still fails, the resource was renamed outside Terraform. diff --git a/infra/terraform/supabase/terraform/.terraform.lock.hcl b/infra/terraform/supabase/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..5b4468d --- /dev/null +++ b/infra/terraform/supabase/terraform/.terraform.lock.hcl @@ -0,0 +1,73 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.9.0" + constraints = "~> 3.0" + hashes = [ + "h1:OO+IuvQJSPmWdN8AyyIEvPJbLvDQpgX/zbktoa9KsJE=", + "h1:UlBuNVuCGJ39tTv2c5gz2NRZnQbXfbIWbTzWcth5o74=", + "h1:lVDv+0AjDjrLfpmaJbWqUmIw/k3/AHXLc3N4m55SNdo=", + "zh:161ad0bd9a75768c82f53fb6e7172a9d8be2d4889b012645a34795031aaf1bf1", + "zh:19dc9a5b17729725ccfc4f45b0500af0ee5bc6b6b160c7adb8f2bf617d2c80ea", + "zh:269eda8fe42daa7974d5a34d166c3ba9defe80cde86c01e4dadcfdf2e1f05e5f", + "zh:373f7c65566f8f2cc7f45d698654feb9d988996957e1266a69ca00c52d6d16d0", + "zh:5599d16804c41c83009ec621b6d6b6f74e102f5827678a4750f8809055546b61", + "zh:583be0440469a22bff70dcfa56593b01566860b29607437264adb51060cf46fc", + "zh:5f211d8ec3f2e1f414870d9584bfe26e6995560ef81c748f8447a48164767398", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:7b547fd16216761ef86efc3ed516ac5ac0c5c42b7c7eb24a08cef2d93f69ed5e", + "zh:7e7c0679daf2a382151d05068c8c3f0dae6b7b7dccf818827b73dd08638df2ef", + "zh:8089dec888a8038b9b4fb23b3df7e1057293dbc5b60b42cc47ff690d69d4b61b", + "zh:c51f15a031edfd6f23ce8ced3446ca7f8d8d647e2499890d7d5d10d5016d7257", + "zh:c94784f005708890dc6895afd53636ec00ec1e430b15d41e5aebfb1d4b39bd04", + ] +} + +provider "registry.terraform.io/supabase/supabase" { + version = "1.5.1" + constraints = "~> 1.5.1" + hashes = [ + "h1:A4kqrLbrPeyfOXuk2eN8L15ue7JSRtkV/FhqFyY9Dzg=", + "h1:X1mvSyjaWyaJmhijgpsXMP7UMIE5kuwbq4wfjpfcxBA=", + "h1:rTxTmQ7IGlQNi5H1oS8e2+AgmiXeWM+jnJN5TNS69vU=", + "zh:1834f1cfbab811ca53eae9bdb6485032a674aef5d84fa7fe65342f72e50e3880", + "zh:1d53f3c0c6d82c50a7a29d658f77f3e44db0c0196714f0891ec2cadfdeb58764", + "zh:1f4dda08ccb39790f3c11fb6b4006827f09bfb8fb85082886eb46803f44b1722", + "zh:38dcad29e57c4d06374f4b557108d0877bb3ba628878c6648508110ff34f3d0f", + "zh:63782085e8da25d78de2a080072e7cc6a35c781c2bdb04f5ca46f65a6d6988d6", + "zh:79d7e5fe9d1571aa5357f98b97e3f12e61f68500e4270e855c1bc5e4cc772a56", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:8c8560f8df33c087ab9133fc32b68c4c16c8c1bc32b546c91dc98c2b39f80c3a", + "zh:ab4189d0c843166a1b4eaefe817192c8cee954c441a3a86ef5118931ce0e9d71", + "zh:c9037e7cfadc468ac961786af7e3004c08196543416842746f95b929e6118fd6", + "zh:ca9546b9ca3a27634a6eb37e069e58a44a26fe8c3c6539a17dc4b628ad6e7ae0", + "zh:d0301164210ea4ed0567c9c1c751d1e250ab163a8b0edd8cf256d25d54e4d1e5", + "zh:f048d76cca0083a2b91bef304949d182b3395b3bc013cc8aa1505219538953a1", + "zh:f85b905aa8f049a8769bac933a56ae0ca9c5bb74a6c2376cf9ee4ac8ecf50126", + "zh:fd26c6f338bfab77b145e0755dc39d9873aec8219b3b53909da418250d013973", + ] +} diff --git a/infra/terraform/supabase/terraform/adopt.tf b/infra/terraform/supabase/terraform/adopt.tf new file mode 100644 index 0000000..b5d6feb --- /dev/null +++ b/infra/terraform/supabase/terraform/adopt.tf @@ -0,0 +1,49 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# Same pattern as cloudflare-kv/terraform/adopt.tf: when the platform state +# does not yet track the Supabase project but the organization already has one +# under this name, import it by ref at plan time instead of colliding with the +# duplicate-name guard. Fresh products resolve to id = "" and create normally; +# a resource already in state short-circuits the lookup. +# +# Cutover caveat: database_password is config-driven (random_password). After +# adoption the first apply RESETS the database password to the newly generated +# one and publishes it through the job-output secrets — db-migrate, hyperdrive +# and the worker fleet re-wire from those in the same run, but anything still +# consuming the pre-adoption credentials breaks until that run converges. + +data "external" "adopt_project" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "supabase_project" and .name == "this")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ + "https://api.supabase.com/v1/projects")" + # The org id reaches this job as TF_VAR_supabaseOrgId (the component maps + # the SUPABASE_ORG_ID secret to the terraform variable); plain + # SUPABASE_ORG_ID exists only in older wirings. Accept either; with + # neither set, match by name alone. + org="$${TF_VAR_supabaseOrgId:-$${SUPABASE_ORG_ID:-}}" + printf '%s' "$resp" | jq -c --arg n "$name" --arg org "$org" \ + '{id: ([.[] | select(.name == $n and ($org == "" or .organization_id == $org)) | .id] | first // "")}' + EOT + ] + query = { + name = local.project_name + } +} + +import { + for_each = toset(compact([data.external.adopt_project.result.id])) + to = supabase_project.this + id = each.value +} diff --git a/infra/terraform/supabase/terraform/main.tf b/infra/terraform/supabase/terraform/main.tf new file mode 100644 index 0000000..4481ac5 --- /dev/null +++ b/infra/terraform/supabase/terraform/main.tf @@ -0,0 +1,285 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job + # (address = …/state/tfstate/{component}/{env}, run token as password), so + # this block stays empty — no S3 bucket, no AWS role, no workspaces (the + # environment is in the address). + backend "http" {} + + required_providers { + supabase = { + source = "supabase/supabase" + # Pinned below 1.6: from 1.6.0 the provider reads /billing/addons on + # every project create/read, and Supabase does not serve billing + # endpoints to OAuth tokens yet ("does not support oauth access") — + # which is exactly the credential the platform brokers. + version = "~> 1.5.1" + } + random = { + source = "hashicorp/random" + version = "~> 3.0" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the SUPABASE_ACCESS_TOKEN env var (provider-native): a +# short-lived Management-API token minted per run from the workspace's +# Supabase integration, resolved into the job env by orun. +provider "supabase" {} + +# --- Variables (standard Orun parameters) --- + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "atomic-crm" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "supabase" +} + +variable "stackName" { + type = string + default = "supabase" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# Supabase target identity. supabaseRegion comes from the component's +# `spec.parameters`; supabaseOrgId is injected as TF_VAR_supabaseOrgId from the +# workspace's SUPABASE_ORG_ID secret (org-id connection fact). Both are +# required (no default) so a missing value fails plan loudly instead of +# silently pointing at the wrong org or region. +variable "supabaseOrgId" { + type = string +} + +variable "supabaseRegion" { + type = string +} + +# The workers.dev subdomain the app's Worker answers on (the component's +# `workersDevSubdomain` parameter, surfaced as TF_VAR_workersDevSubdomain — +# the same value apps/web/component.yaml carries). Required, like the two +# above: Supabase Auth sends its links to this origin. +variable "workersDevSubdomain" { + type = string +} + +# Whether a new user must confirm their email before signing in (the +# component's `authEmailConfirmation` parameter). Off by default, because a +# fresh project sends email only to its organization's own members until it +# has an SMTP server of its own: with confirmation on, nobody else could sign +# up. Turn it on once SMTP is set (the product's README, "Email"). +variable "authEmailConfirmation" { + type = bool + default = false +} + +# --- Locals --- + +# The product's own origin when the environment has a custom domain: SITE_URL +# under its `env:` in intent.yaml, which the runner exports to this job as it +# does to the app's build (apps/web/component.yaml) — one setting, so Auth's +# links and the app's absolute URLs name the same origin. Empty when unset. +data "external" "site_url" { + program = ["bash", "-c", "jq -n --arg url \"$${SITE_URL:-}\" '{url: $url}'"] +} + +locals { + supabase_org_id = var.supabaseOrgId + supabase_region = var.supabaseRegion + project_name = "${var.repo}-${var.environment}" + # The environment's Worker, as apps/web/component.yaml names it: + # -web- on the account's workers.dev subdomain — unless SITE_URL + # names the environment's custom domain. + worker_origin = "https://${var.repo}-web-${var.environment}.${var.workersDevSubdomain}.workers.dev" + app_origin = coalesce(trimsuffix(data.external.site_url.result.url, "/"), local.worker_origin) +} + +# --- Generate database password --- + +resource "random_password" "db_password" { + length = 32 + special = true + # Avoid characters that cause issues in connection strings + override_special = "!#$%&*()-_=+[]{}|:,.<>?" +} + +# --- Supabase project --- + +resource "supabase_project" "this" { + organization_id = local.supabase_org_id + name = local.project_name + database_password = random_password.db_password.result + region = local.supabase_region +} + +# --- Outputs --- +# +# Credentials leave this module ONLY through the outputs component.yaml's +# `secretOutputs` names, which the runner lease-publishes onto the project's +# environment rung after the apply (never argv, never a log). The project's +# three database credentials below are published for the owner and for any +# later step that migrates the database; the app reads the `wiring` document +# further down. No Secrets Manager. + +output "project_ref" { + description = "Supabase project reference ID" + value = supabase_project.this.id +} + +output "project_name" { + description = "Supabase project name" + value = supabase_project.this.name +} + +output "project_url" { + description = "Supabase project URL" + value = "https://${supabase_project.this.id}.supabase.co" +} + +output "database_password" { + description = "Generated database password (sensitive; wired to orun secrets)" + value = random_password.db_password.result + sensitive = true +} + +output "connection_uri" { + description = "Direct Postgres connection URI (sensitive; wired to orun secrets)" + value = "postgresql://postgres:${random_password.db_password.result}@db.${supabase_project.this.id}.supabase.co:5432/postgres" + sensitive = true +} + +# --- The project, up --- +# +# The provider returns from a create as soon as the Management API accepts it, +# and a project takes minutes to come up. Its API keys and its Auth +# configuration are read and written below; both wait here until the project +# reports ACTIVE_HEALTHY (ten minutes at most). On an adopted or existing +# project this answers at once. Same tools as adopt.tf: bash, curl, jq and the +# brokered SUPABASE_ACCESS_TOKEN in the environment. + +resource "terraform_data" "project_ready" { + triggers_replace = [supabase_project.this.id] + + provisioner "local-exec" { + interpreter = ["bash", "-c"] + environment = { + PROJECT_REF = supabase_project.this.id + } + command = <<-EOT + set -uo pipefail + for _ in $(seq 1 60); do + status="$(curl -fsS --retry 2 -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ + "https://api.supabase.com/v1/projects/$PROJECT_REF" | jq -r '.status // empty')" + [ "$status" = ACTIVE_HEALTHY ] && { echo "supabase: $PROJECT_REF is $status"; exit 0; } + echo "supabase: $PROJECT_REF is $${status:-not answering yet}; waiting" + sleep 10 + done + echo "supabase: $PROJECT_REF did not report ACTIVE_HEALTHY within ten minutes" >&2 + exit 1 + EOT + } +} + +# --- API keys --- +# +# The app talks to Supabase from the browser and from the Worker with the +# project URL and the publishable (anon) key; Row Level Security is what +# protects the data, the key is public by design. Both leave this module in +# ONE wiring document, WIRING_SUPABASE, which the app's deploy renders into +# its wrangler config and inlines into its build. The service-role key is read +# out too, for the CRM's admin functions (inviting a user, resetting a +# password, deleting attachments, inbound email — upstream's edge functions, +# now the Worker's routes): it bypasses Row Level Security, so it leaves this +# module as its own Orun secret, SUPABASE_SERVICE_ROLE_KEY, which only the +# Worker's deploy reads and stores as a Worker secret — never a var, never a +# bundle, never the wiring document the browser build reads. + +data "supabase_apikeys" "this" { + project_ref = supabase_project.this.id + depends_on = [terraform_data.project_ready] +} + +output "service_role_key" { + description = "The project's service-role key (pushed to orun secrets as SUPABASE_SERVICE_ROLE_KEY; the Worker's deploy stores it as a Worker secret)" + value = data.supabase_apikeys.this.service_role_key + sensitive = true +} + +output "wiring" { + description = "Wiring document for the app's deploy-time configuration (pushed to orun secrets as WIRING_SUPABASE)" + value = jsonencode({ + supabase_url = "https://${supabase_project.this.id}.supabase.co" + supabase_anon_key = data.supabase_apikeys.this.anon_key + }) + sensitive = true +} + +# --- Auth --- +# +# A fresh project's Auth sends its links to http://localhost:3000 and asks +# every new user to confirm an email address it can only deliver to the +# organization's own members. So the app's Worker is the Site URL and the one +# allowed redirect origin, and sign-up signs the user straight in unless +# `authEmailConfirmation` is on. Only these three keys are managed; every +# other Auth setting stays the project's own, and the dashboard can change it. + +resource "supabase_settings" "this" { + project_ref = supabase_project.this.id + + auth = jsonencode({ + site_url = local.app_origin + uri_allow_list = "${local.app_origin}/**" + mailer_autoconfirm = !var.authEmailConfirmation + }) + + depends_on = [terraform_data.project_ready] +} diff --git a/packages/db/component.yaml b/packages/db/component.yaml new file mode 100644 index 0000000..41bbe7f --- /dev/null +++ b/packages/db/component.yaml @@ -0,0 +1,31 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db + description: The database migrations and their runner (built by the db-migrate component before it plans or applies) +spec: + type: turbo-package + lifecycle: production + owner: platform + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: data + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: data diff --git a/packages/db/docs/architecture.md b/packages/db/docs/architecture.md new file mode 100644 index 0000000..3f9b079 --- /dev/null +++ b/packages/db/docs/architecture.md @@ -0,0 +1,11 @@ +# db — architecture + +A workspace package at `packages/db`, consumed by the components that depend +on it. It has no deployed surface of its own. + +## Exports + +- `.` +- `./manifest` +- `./runner` +- `./types` diff --git a/packages/db/docs/overview.md b/packages/db/docs/overview.md new file mode 100644 index 0000000..c0097af --- /dev/null +++ b/packages/db/docs/overview.md @@ -0,0 +1,20 @@ +# db + +The database migrations and their runner (built by the db-migrate component before it plans or applies) + +A workspace package built by the turbo pipeline. It deploys nothing itself: its lane type-checks, lints, tests and builds it. + +| | | +| ------------ | --------------------------------------------------------------------- | +| Type | `turbo-package` | +| Source | `packages/db` | +| Package | `@saas/db` | +| Environments | `dev`: `quick-check` · `stage`: `quick-check` · `prod`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- **db-migrate** — Applies database migrations to stage and prod Supabase instances diff --git a/packages/db/docs/runbook.md b/packages/db/docs/runbook.md new file mode 100644 index 0000000..3fa7445 --- /dev/null +++ b/packages/db/docs/runbook.md @@ -0,0 +1,25 @@ +# db — runbook + +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @saas/db build +pnpm --filter @saas/db typecheck +pnpm --filter @saas/db lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. diff --git a/packages/db/eslint.config.js b/packages/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..d8e3772 --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,30 @@ +{ + "name": "@saas/db", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "The database migrations and their runner (the db-migrate composition builds this package and runs dist/runner/cli.js plan|apply)", + "exports": { + ".": "./src/index.ts", + "./manifest": "./src/manifest.ts", + "./types": "./src/types.ts", + "./runner": "./src/runner/index.ts" + }, + "bin": { + "db-migrate": "./dist/runner/cli.js" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json && cp -r src/migrations dist/", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "manifest:check": "node ../../tooling/migrations/manifest.mjs check", + "manifest:fix": "node ../../tooling/migrations/manifest.mjs fix", + "migrate:plan": "node dist/runner/cli.js plan" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@types/node": "25.3.5", + "typescript": "^5.8.3" + } +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..9b5ee07 --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,3 @@ +export { manifest } from "./manifest.js"; +export type { MigrationEntry, MigrationManifest, BoundedContext } from "./types.js"; +export { BOUNDED_CONTEXTS } from "./types.js"; diff --git a/packages/db/src/manifest.ts b/packages/db/src/manifest.ts new file mode 100644 index 0000000..7de4cb4 --- /dev/null +++ b/packages/db/src/manifest.ts @@ -0,0 +1,312 @@ +import type { MigrationManifest } from "./types.js"; + +// Every migration the runner applies, in order, with the sha256 of its file: +// the control migration, upstream's supabase/migrations in their order (the +// history `supabase db push` applies; three carry a recorded edit, each marked +// "Port:" in the file), upstream's seed, then the port's own. +// `pnpm --filter @saas/db run manifest:check` verifies the checksums; +// `manifest:fix` rewrites them after a migration file changes (only ever +// before that migration has been applied anywhere — an applied migration's +// checksum is immutable). +export const manifest: MigrationManifest = { + version: 1, + migrations: [ + { + id: "000_control_baseline", + context: "control", + path: "000_control/up.sql", + checksum: + "2a5d7f30684c99e3ff441ca8a2c38038dedd1bab4db4a40e92cd36bb22be297f", + description: + "Baseline control migration — creates the migration tracking schema", + }, + { + id: "20240730075029_init_db", + context: "app", + path: "20240730075029_init_db/up.sql", + checksum: + "98e91400b620d803f91880a858e379354736ec0cd5fe65eeb73fad9174794bee", + description: + "Upstream's migration 20240730075029_init_db (init db)", + }, + { + id: "20240730075425_init_triggers", + context: "app", + path: "20240730075425_init_triggers/up.sql", + checksum: + "dd91da42a8f9eff0f2c30a9d88c383409ad94f4f9401b1e81b81562ad208b913", + description: + "Upstream's migration 20240730075425_init_triggers (init triggers)", + }, + { + id: "20240806124555_task_sales_id", + context: "app", + path: "20240806124555_task_sales_id/up.sql", + checksum: + "1057601d37adc00bb2810fcf11bc38c3a6ba9fdd8ae2a7b160ce4049ab64b389", + description: + "Upstream's migration 20240806124555_task_sales_id (task sales id)", + }, + { + id: "20240807082449_remove-aquisition", + context: "app", + path: "20240807082449_remove-aquisition/up.sql", + checksum: + "4b10d44c974dbdb7a5fa09eade9b9a7144af56a1bb2002f45e4410d8a3120a60", + description: + "Upstream's migration 20240807082449_remove-aquisition (remove aquisition)", + }, + { + id: "20240808141826_init_state_configure", + context: "app", + path: "20240808141826_init_state_configure/up.sql", + checksum: + "2298da7dd67e2425bb28c7ebd090cb53b470c6f212669fdaa8f38d5ddf71bfa8", + description: + "Upstream's migration 20240808141826_init_state_configure (init state configure)", + }, + { + id: "20240813084010_tags_policy", + context: "app", + path: "20240813084010_tags_policy/up.sql", + checksum: + "6b4b0ae79f6b88f5d46332970d28ab484786d3b392dc4df3be7a10cccc29c9d5", + description: + "Upstream's migration 20240813084010_tags_policy (tags policy)", + }, + { + id: "20241104153231_sales_policies", + context: "app", + path: "20241104153231_sales_policies/up.sql", + checksum: + "3e2fb0e0a110259385001cc394513d8aa0f6ab28b35eaf9ec6a415634b155565", + description: + "Upstream's migration 20241104153231_sales_policies (sales policies)", + }, + { + id: "20250109152531_email_jsonb", + context: "app", + path: "20250109152531_email_jsonb/up.sql", + checksum: + "746c6fd6dbb0e3824d2be00de3015d6ad036ea633cf192bea75a4442dc3aa345", + description: + "Upstream's migration 20250109152531_email_jsonb (email jsonb)", + }, + { + id: "20250113132531_phone_jsonb", + context: "app", + path: "20250113132531_phone_jsonb/up.sql", + checksum: + "af00450cbf61252238f7bbcdb195274e236ae35f3cc14ffd093937aead457597", + description: + "Upstream's migration 20250113132531_phone_jsonb (phone jsonb)", + }, + { + id: "20251204172855_merge_contacts_function", + context: "app", + path: "20251204172855_merge_contacts_function/up.sql", + checksum: + "36fab4bf40f02d61789e885dc7e6affedcdf513e48f35ac1baaa59b56775ce7e", + description: + "Upstream's migration 20251204172855_merge_contacts_function (merge contacts function)", + }, + { + id: "20251204201317_drop_merge_contacts_function", + context: "app", + path: "20251204201317_drop_merge_contacts_function/up.sql", + checksum: + "d6a747c8cfe31e54cd4dcd95ae78dccd77a6da4f9d0958e581b6f5fb6cc8da74", + description: + "Upstream's migration 20251204201317_drop_merge_contacts_function (drop merge contacts function)", + }, + { + id: "20260108160722_task_default_sales", + context: "app", + path: "20260108160722_task_default_sales/up.sql", + checksum: + "8d4bd685983ebbe54d8fa1f0e29a259591109ee39c17088607dea4f43ec0006d", + description: + "Upstream's migration 20260108160722_task_default_sales (task default sales)", + }, + { + id: "20260115150819_snake_case_renaming", + context: "app", + path: "20260115150819_snake_case_renaming/up.sql", + checksum: + "69dc488502bad36dad3d4af0b56a0edd53224e48ddb1ea8585a78f663c54d2f1", + description: + "Upstream's migration 20260115150819_snake_case_renaming (snake case renaming)", + }, + { + id: "20260127140209_imports", + context: "app", + path: "20260127140209_imports/up.sql", + checksum: + "4edb2bcb44d822a42dfcc3047d700db3a9b4383ecb5726bfb7cc4adc4f16e627", + description: + "Upstream's migration 20260127140209_imports (imports) — with the port's one recorded edit (see the file's Port: comment)", + }, + { + id: "20260128165057_sso_handling", + context: "app", + path: "20260128165057_sso_handling/up.sql", + checksum: + "3e26fa9bda48a6b244d6ac107cc1d90af1a4099c2cbf5967fe0bac9d98a2aad2", + description: + "Upstream's migration 20260128165057_sso_handling (sso handling) — with the port's one recorded edit (see the file's Port: comment)", + }, + { + id: "20260211194545_app_configuration", + context: "app", + path: "20260211194545_app_configuration/up.sql", + checksum: + "6bcf97a0d046deb31029905b7c47116fb29338964621498b16d34230e06dbbe5", + description: + "Upstream's migration 20260211194545_app_configuration (app configuration)", + }, + { + id: "20260226163952_deals_expected_closing_date_date_only", + context: "app", + path: "20260226163952_deals_expected_closing_date_date_only/up.sql", + checksum: + "010d673c16338eff3bfdb0e469e99a003f60ad34f7822c37f3a47365816da0b5", + description: + "Upstream's migration 20260226163952_deals_expected_closing_date_date_only (deals expected closing date date only)", + }, + { + id: "20260304104600_note_attachments_trigger", + context: "app", + path: "20260304104600_note_attachments_trigger/up.sql", + checksum: + "4139e23e7f63bd6ee2c11f9e021b5e7143a617b2af30b52ee0fcd2e5a3e4a36d", + description: + "Upstream's migration 20260304104600_note_attachments_trigger (note attachments trigger) — with the port's one recorded edit (see the file's Port: comment)", + }, + { + id: "20260307120000_nb_tasks_pending_only", + context: "app", + path: "20260307120000_nb_tasks_pending_only/up.sql", + checksum: + "e28665cc2f0d91ff57f69bf0ff2b5d1ba2f5f9cd9814f7e1b46d981fb7bc38ea", + description: + "Upstream's migration 20260307120000_nb_tasks_pending_only (nb tasks pending only)", + }, + { + id: "20260309112831_fix_security_warnings", + context: "app", + path: "20260309112831_fix_security_warnings/up.sql", + checksum: + "a4f875c6d4bec41bdfc70cc1933d7789899eff8902733c33463574d44977ce5a", + description: + "Upstream's migration 20260309112831_fix_security_warnings (fix security warnings) — with the port's one recorded edit (see the file's Port: comment)", + }, + { + id: "20260314120000_activity_log_view", + context: "app", + path: "20260314120000_activity_log_view/up.sql", + checksum: + "2464e05372774e35f44aeded0f102a5ecd61319d8faac8f9d9c74f6d2eeba552", + description: + "Upstream's migration 20260314120000_activity_log_view (activity log view)", + }, + { + id: "20260320120000_lowercase_email_website", + context: "app", + path: "20260320120000_lowercase_email_website/up.sql", + checksum: + "c9f2889d6426b0e8bccfbab379ec3289ec98390fd5f1c4ebb0d07351295acefc", + description: + "Upstream's migration 20260320120000_lowercase_email_website (lowercase email website)", + }, + { + id: "20260601120000_grant_init_state_to_api_roles", + context: "app", + path: "20260601120000_grant_init_state_to_api_roles/up.sql", + checksum: + "a05670a1c8e60b2bb5910daf1dbeb879ed574e9eca7924076fc295a0eece551f", + description: + "Upstream's migration 20260601120000_grant_init_state_to_api_roles (grant init state to api roles)", + }, + { + id: "20260811131131_sales_secondary_emails", + context: "app", + path: "20260811131131_sales_secondary_emails/up.sql", + checksum: + "b7d125dce0e526677134d2afcae8db648f1bd2a19923bc8068e86a95c3391e06", + description: + "Upstream's migration 20260811131131_sales_secondary_emails (sales secondary emails)", + }, + { + id: "20260924120000_deals_lost_reason", + context: "app", + path: "20260924120000_deals_lost_reason/up.sql", + checksum: + "ac6c9aaad335756e88a88a9a68a7bfffdbe8bc38c4adeaaabab019b9d28eb54b", + description: + "Upstream's migration 20260924120000_deals_lost_reason (deals lost reason)", + }, + { + id: "20260928120000_drop_deals_lost_reason", + context: "app", + path: "20260928120000_drop_deals_lost_reason/up.sql", + checksum: + "d21ffb9b7633e1d79be79c67266f96c875d0382067ec85e6765aed2fc1c8d88f", + description: + "Upstream's migration 20260928120000_drop_deals_lost_reason (drop deals lost reason)", + }, + { + id: "20260929120000_remove_deleted_tag_from_contacts", + context: "app", + path: "20260929120000_remove_deleted_tag_from_contacts/up.sql", + checksum: + "36dc86b35b4fd3385a8a0032fab07e331f065ca8bd73e50d3a0d8e38fd782991", + description: + "Upstream's migration 20260929120000_remove_deleted_tag_from_contacts (remove deleted tag from contacts)", + }, + { + id: "20261010054346_global_search", + context: "app", + path: "20261010054346_global_search/up.sql", + checksum: + "113aaaf4144eae956932a66a57a8e0228fb6474f46a391fad367bb7b02ad7fa0", + description: + "Upstream's migration 20261010054346_global_search (global search)", + }, + { + id: "20261022120000_global_search_per_resource_cap", + context: "app", + path: "20261022120000_global_search_per_resource_cap/up.sql", + checksum: + "4397b3198a95eaf64e0a2bfaa5c77b695479bdf5ee04e5275e55e6f14be3000c", + description: + "Upstream's migration 20261022120000_global_search_per_resource_cap (global search per resource cap)", + }, + { + id: "20261026120000_deal_categories", + context: "app", + path: "20261026120000_deal_categories/up.sql", + checksum: + "4e7f91a41bab6880c75559bc989a2c7e1742535373331e5802af34166f299759", + description: + "Upstream's migration 20261026120000_deal_categories (deal categories)", + }, + { + id: "20261101000000_seed", + context: "app", + path: "20261101000000_seed/up.sql", + checksum: + "4df09f10f14a4c67eb444ca3a3b7ad6f606e8d82383ed995168638c435a9c049", + description: + "Upstream's seed.sql: the mail domains whose favicon is never fetched (its remote setup applies it with db push --include-seed)", + }, + { + id: "20261101000100_note_attachments_outbox", + context: "app", + path: "20261101000100_note_attachments_outbox/up.sql", + checksum: + "a35e23d09ab2f10662f41b3dfb9b15a45f829f5b9d0dcae556d3f7b04e86a230", + description: + "The port: cleanup_note_attachments() queues the note's old and new record in private.note_attachment_cleanups, which the Worker's Cron Trigger drains through the Storage API, instead of calling the edge function through pg_net", + }, + ], +}; diff --git a/packages/db/src/migrations/000_control/up.sql b/packages/db/src/migrations/000_control/up.sql new file mode 100644 index 0000000..1764562 --- /dev/null +++ b/packages/db/src/migrations/000_control/up.sql @@ -0,0 +1,16 @@ +-- Baseline control migration +-- Creates the migration tracking schema used by the migration runner. +-- Owner: control bounded context + +CREATE SCHEMA IF NOT EXISTS _migrations; + +CREATE TABLE IF NOT EXISTS _migrations.applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now(), + applied_by TEXT NOT NULL DEFAULT current_user +); + +COMMENT ON TABLE _migrations.applied IS + 'Tracks which migrations have been applied to the database.'; diff --git a/packages/db/src/migrations/20240730075029_init_db/up.sql b/packages/db/src/migrations/20240730075029_init_db/up.sql new file mode 100644 index 0000000..7779e0c --- /dev/null +++ b/packages/db/src/migrations/20240730075029_init_db/up.sql @@ -0,0 +1,600 @@ +create table "public"."companies" ( + "id" bigint generated by default as identity not null, + "created_at" timestamp with time zone not null default now(), + "name" text not null, + "sector" text, + "size" smallint, + "linkedin_url" text, + "website" text, + "phone_number" text, + "address" text, + "zipcode" text, + "city" text, + "stateAbbr" text, + "sales_id" bigint, + "context_links" json, + "country" text, + "description" text, + "revenue" text, + "tax_identifier" text, + "logo" jsonb +); + + +alter table "public"."companies" enable row level security; + +create table "public"."contactNotes" ( + "id" bigint generated by default as identity not null, + "contact_id" bigint not null, + "text" text, + "date" timestamp with time zone default now(), + "sales_id" bigint, + "status" text, + "attachments" jsonb[] +); + + +alter table "public"."contactNotes" enable row level security; + +create table "public"."contacts" ( + "id" bigint generated by default as identity not null, + "first_name" text, + "last_name" text, + "gender" text, + "title" text, + "email" text, + "phone_1_number" text, + "phone_1_type" text, + "phone_2_number" text, + "phone_2_type" text, + "background" text, + "acquisition" text, + "avatar" jsonb, + "first_seen" timestamp with time zone, + "last_seen" timestamp with time zone, + "has_newsletter" boolean, + "status" text, + "tags" bigint[], + "company_id" bigint, + "sales_id" bigint, + "linkedin_url" text +); + + +alter table "public"."contacts" enable row level security; + +create table "public"."dealNotes" ( + "id" bigint generated by default as identity not null, + "deal_id" bigint not null, + "type" text, + "text" text, + "date" timestamp with time zone default now(), + "sales_id" bigint, + "attachments" jsonb[] +); + + +alter table "public"."dealNotes" enable row level security; + +create table "public"."deals" ( + "id" bigint generated by default as identity not null, + "name" text not null, + "company_id" bigint, + "contact_ids" bigint[], + "category" text, + "stage" text not null, + "description" text, + "amount" bigint, + "created_at" timestamp with time zone not null default now(), + "updated_at" timestamp with time zone not null default now(), + "archived_at" timestamp with time zone default null, + "expected_closing_date" timestamp with time zone default null, + "sales_id" bigint, + "index" smallint +); + + +alter table "public"."deals" enable row level security; + +create table "public"."sales" ( + "id" bigint generated by default as identity not null, + "first_name" text not null, + "last_name" text not null, + "email" text not null, + "administrator" boolean not null, + "user_id" uuid not null, + "avatar" jsonb, + "disabled" boolean not null default FALSE +); + + +alter table "public"."sales" enable row level security; + +create table "public"."tags" ( + "id" bigint generated by default as identity not null, + "name" text not null, + "color" text not null +); + + +alter table "public"."tags" enable row level security; + +create table "public"."tasks" ( + "id" bigint generated by default as identity not null, + "contact_id" bigint not null, + "type" text, + "text" text, + "due_date" timestamp with time zone not null, + "done_date" timestamp with time zone +); + + +alter table "public"."tasks" enable row level security; + +CREATE UNIQUE INDEX companies_pkey ON public.companies USING btree (id); + +CREATE UNIQUE INDEX "contactNotes_pkey" ON public."contactNotes" USING btree (id); + +CREATE UNIQUE INDEX contacts_pkey ON public.contacts USING btree (id); + +CREATE UNIQUE INDEX "dealNotes_pkey" ON public."dealNotes" USING btree (id); + +CREATE UNIQUE INDEX deals_pkey ON public.deals USING btree (id); + +CREATE UNIQUE INDEX sales_pkey ON public.sales USING btree (id); + +CREATE UNIQUE INDEX tags_pkey ON public.tags USING btree (id); + +CREATE UNIQUE INDEX tasks_pkey ON public.tasks USING btree (id); + +alter table "public"."companies" add constraint "companies_pkey" PRIMARY KEY using index "companies_pkey"; + +alter table "public"."contactNotes" add constraint "contactNotes_pkey" PRIMARY KEY using index "contactNotes_pkey"; + +alter table "public"."contacts" add constraint "contacts_pkey" PRIMARY KEY using index "contacts_pkey"; + +alter table "public"."dealNotes" add constraint "dealNotes_pkey" PRIMARY KEY using index "dealNotes_pkey"; + +alter table "public"."deals" add constraint "deals_pkey" PRIMARY KEY using index "deals_pkey"; + +alter table "public"."sales" add constraint "sales_pkey" PRIMARY KEY using index "sales_pkey"; + +alter table "public"."tags" add constraint "tags_pkey" PRIMARY KEY using index "tags_pkey"; + +alter table "public"."tasks" add constraint "tasks_pkey" PRIMARY KEY using index "tasks_pkey"; + +alter table "public"."companies" add constraint "companies_sales_id_fkey" FOREIGN KEY (sales_id) REFERENCES sales(id) not valid; + +alter table "public"."companies" validate constraint "companies_sales_id_fkey"; + +alter table "public"."contactNotes" add constraint "contactNotes_contact_id_fkey" FOREIGN KEY (contact_id) REFERENCES contacts(id) ON UPDATE CASCADE ON DELETE CASCADE not valid; + +alter table "public"."contactNotes" validate constraint "contactNotes_contact_id_fkey"; + +alter table "public"."contactNotes" add constraint "contactNotes_sales_id_fkey" FOREIGN KEY (sales_id) REFERENCES sales(id) ON UPDATE CASCADE ON DELETE CASCADE not valid; + +alter table "public"."contactNotes" validate constraint "contactNotes_sales_id_fkey"; + +alter table "public"."contacts" add constraint "contacts_company_id_fkey" FOREIGN KEY (company_id) REFERENCES companies(id) ON UPDATE CASCADE ON DELETE CASCADE not valid; + +alter table "public"."contacts" validate constraint "contacts_company_id_fkey"; + +alter table "public"."contacts" add constraint "contacts_sales_id_fkey" FOREIGN KEY (sales_id) REFERENCES sales(id) not valid; + +alter table "public"."contacts" validate constraint "contacts_sales_id_fkey"; + +alter table "public"."dealNotes" add constraint "dealNotes_deal_id_fkey" FOREIGN KEY (deal_id) REFERENCES deals(id) ON UPDATE CASCADE ON DELETE CASCADE not valid; + +alter table "public"."dealNotes" validate constraint "dealNotes_deal_id_fkey"; + +alter table "public"."dealNotes" add constraint "dealNotes_sales_id_fkey" FOREIGN KEY (sales_id) REFERENCES sales(id) not valid; + +alter table "public"."dealNotes" validate constraint "dealNotes_sales_id_fkey"; + +alter table "public"."deals" add constraint "deals_company_id_fkey" FOREIGN KEY (company_id) REFERENCES companies(id) ON UPDATE CASCADE ON DELETE CASCADE not valid; + +alter table "public"."deals" validate constraint "deals_company_id_fkey"; + +alter table "public"."deals" add constraint "deals_sales_id_fkey" FOREIGN KEY (sales_id) REFERENCES sales(id) not valid; + +alter table "public"."deals" validate constraint "deals_sales_id_fkey"; + +alter table "public"."sales" add constraint "sales_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) not valid; + +alter table "public"."sales" validate constraint "sales_user_id_fkey"; + +alter table "public"."tasks" add constraint "tasks_contact_id_fkey" FOREIGN KEY (contact_id) REFERENCES contacts(id) ON UPDATE CASCADE ON DELETE CASCADE not valid; + +alter table "public"."tasks" validate constraint "tasks_contact_id_fkey"; + +set check_function_bodies = off; + +grant delete on table "public"."companies" to "authenticated"; +grant insert on table "public"."companies" to "authenticated"; +grant select on table "public"."companies" to "authenticated"; +grant update on table "public"."companies" to "authenticated"; + +grant delete on table "public"."companies" to "service_role"; +grant insert on table "public"."companies" to "service_role"; +grant references on table "public"."companies" to "service_role"; +grant select on table "public"."companies" to "service_role"; +grant trigger on table "public"."companies" to "service_role"; +grant truncate on table "public"."companies" to "service_role"; +grant update on table "public"."companies" to "service_role"; + +grant delete on table "public"."contactNotes" to "authenticated"; +grant insert on table "public"."contactNotes" to "authenticated"; +grant select on table "public"."contactNotes" to "authenticated"; +grant update on table "public"."contactNotes" to "authenticated"; + +grant delete on table "public"."contactNotes" to "service_role"; +grant insert on table "public"."contactNotes" to "service_role"; +grant references on table "public"."contactNotes" to "service_role"; +grant select on table "public"."contactNotes" to "service_role"; +grant trigger on table "public"."contactNotes" to "service_role"; +grant truncate on table "public"."contactNotes" to "service_role"; +grant update on table "public"."contactNotes" to "service_role"; + +grant delete on table "public"."contacts" to "authenticated"; +grant insert on table "public"."contacts" to "authenticated"; +grant select on table "public"."contacts" to "authenticated"; +grant update on table "public"."contacts" to "authenticated"; + +grant delete on table "public"."contacts" to "service_role"; +grant insert on table "public"."contacts" to "service_role"; +grant references on table "public"."contacts" to "service_role"; +grant select on table "public"."contacts" to "service_role"; +grant trigger on table "public"."contacts" to "service_role"; +grant truncate on table "public"."contacts" to "service_role"; +grant update on table "public"."contacts" to "service_role"; + +grant delete on table "public"."dealNotes" to "authenticated"; +grant insert on table "public"."dealNotes" to "authenticated"; +grant select on table "public"."dealNotes" to "authenticated"; +grant update on table "public"."dealNotes" to "authenticated"; + +grant delete on table "public"."dealNotes" to "service_role"; +grant insert on table "public"."dealNotes" to "service_role"; +grant references on table "public"."dealNotes" to "service_role"; +grant select on table "public"."dealNotes" to "service_role"; +grant trigger on table "public"."dealNotes" to "service_role"; +grant truncate on table "public"."dealNotes" to "service_role"; +grant update on table "public"."dealNotes" to "service_role"; + + +grant delete on table "public"."deals" to "authenticated"; +grant insert on table "public"."deals" to "authenticated"; +grant select on table "public"."deals" to "authenticated"; +grant update on table "public"."deals" to "authenticated"; + +grant delete on table "public"."deals" to "service_role"; +grant insert on table "public"."deals" to "service_role"; +grant references on table "public"."deals" to "service_role"; +grant select on table "public"."deals" to "service_role"; +grant trigger on table "public"."deals" to "service_role"; +grant truncate on table "public"."deals" to "service_role"; +grant update on table "public"."deals" to "service_role"; + +grant delete on table "public"."sales" to "authenticated"; +grant insert on table "public"."sales" to "authenticated"; +grant select on table "public"."sales" to "authenticated"; +grant update on table "public"."sales" to "authenticated"; + +grant delete on table "public"."sales" to "service_role"; +grant insert on table "public"."sales" to "service_role"; +grant references on table "public"."sales" to "service_role"; +grant select on table "public"."sales" to "service_role"; +grant trigger on table "public"."sales" to "service_role"; +grant truncate on table "public"."sales" to "service_role"; +grant update on table "public"."sales" to "service_role"; + +grant delete on table "public"."tags" to "authenticated"; +grant insert on table "public"."tags" to "authenticated"; +grant select on table "public"."tags" to "authenticated"; +grant update on table "public"."tags" to "authenticated"; + +grant delete on table "public"."tags" to "service_role"; +grant insert on table "public"."tags" to "service_role"; +grant references on table "public"."tags" to "service_role"; +grant select on table "public"."tags" to "service_role"; +grant trigger on table "public"."tags" to "service_role"; +grant truncate on table "public"."tags" to "service_role"; +grant update on table "public"."tags" to "service_role"; + +grant delete on table "public"."tasks" to "authenticated"; +grant insert on table "public"."tasks" to "authenticated"; +grant select on table "public"."tasks" to "authenticated"; +grant update on table "public"."tasks" to "authenticated"; + +grant delete on table "public"."tasks" to "service_role"; +grant insert on table "public"."tasks" to "service_role"; +grant references on table "public"."tasks" to "service_role"; +grant select on table "public"."tasks" to "service_role"; +grant trigger on table "public"."tasks" to "service_role"; +grant truncate on table "public"."tasks" to "service_role"; +grant update on table "public"."tasks" to "service_role"; + +create policy "Enable insert for authenticated users only" +on "public"."companies" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."companies" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable update for authenticated users only" +on "public"."companies" +as permissive +for update +to authenticated +using (true) +with check (true); + + +create policy "Enable insert for authenticated users only" +on "public"."contactNotes" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."contactNotes" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable insert for authenticated users only" +on "public"."contacts" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."contacts" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable update for authenticated users only" +on "public"."contacts" +as permissive +for update +to authenticated +using (true) +with check (true); + + +create policy "Enable insert for authenticated users only" +on "public"."dealNotes" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."dealNotes" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable insert for authenticated users only" +on "public"."deals" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."deals" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable update for authenticated users only" +on "public"."deals" +as permissive +for update +to authenticated +using (true) +with check (true); + + +create policy "Enable insert for authenticated users only" +on "public"."sales" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable update for authenticated users only" +on "public"."sales" +as permissive +for update +to authenticated +using (true) +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."sales" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable insert for authenticated users only" +on "public"."tags" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."tags" +as permissive +for select +to authenticated +using (true); + + +create policy "Enable insert for authenticated users only" +on "public"."tasks" +as permissive +for insert +to authenticated +with check (true); + + +create policy "Enable read access for authenticated users" +on "public"."tasks" +as permissive +for select +to authenticated +using (true); + + +create policy "Company Delete Policy" +on "public"."companies" +as permissive +for delete +to authenticated +using (true); + + +create policy "Contact Notes Delete Policy" +on "public"."contactNotes" +as permissive +for delete +to authenticated +using (true); + + +create policy "Contact Notes Update policy" +on "public"."contactNotes" +as permissive +for update +to authenticated +using (true); + + +create policy "Contact Delete Policy" +on "public"."contacts" +as permissive +for delete +to authenticated +using (true); + + +create policy "Deal Notes Delete Policy" +on "public"."dealNotes" +as permissive +for delete +to authenticated +using (true); + + +create policy "Deal Notes Update Policy" +on "public"."dealNotes" +as permissive +for update +to authenticated +using (true); + + +create policy "Deals Delete Policy" +on "public"."deals" +as permissive +for delete +to authenticated +using (true); + + +create policy "Task Delete Policy" +on "public"."tasks" +as permissive +for delete +to authenticated +using (true); + + +create policy "Task Update Policy" +on "public"."tasks" +as permissive +for update +to authenticated +using (true); + + +-- Use Postgres to create a bucket. + +insert into storage.buckets + (id, name, public) +values + ('attachments', 'attachments', true); + +CREATE POLICY "Attachments 1mt4rzk_0" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'attachments'); +CREATE POLICY "Attachments 1mt4rzk_1" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'attachments'); +CREATE POLICY "Attachments 1mt4rzk_3" ON storage.objects FOR DELETE TO authenticated USING (bucket_id = 'attachments'); + +-- Use Postgres to create views for companies. + +create view "public"."companies_summary" + with (security_invoker=on) + as +select + c.*, + count(distinct d.id) as nb_deals, + count(distinct co.id) as nb_contacts +from + "public"."companies" c +left join + "public"."deals" d on c.id = d.company_id +left join + "public"."contacts" co on c.id = co.company_id +group by + c.id; + +-- Use Postgres to create views for contacts. + +create view "public"."contacts_summary" + with (security_invoker=on) + as +select + co.*, + c.name as company_name, + count(distinct t.id) as nb_tasks +from + "public"."contacts" co +left join + "public"."tasks" t on co.id = t.contact_id +left join + "public"."companies" c on co.company_id = c.id +group by + co.id, c.name; + + diff --git a/packages/db/src/migrations/20240730075425_init_triggers/up.sql b/packages/db/src/migrations/20240730075425_init_triggers/up.sql new file mode 100644 index 0000000..9aa5dfd --- /dev/null +++ b/packages/db/src/migrations/20240730075425_init_triggers/up.sql @@ -0,0 +1,57 @@ +create function public.handle_new_user() +returns trigger +language plpgsql +security definer set search_path = '' +as $$ +declare + sales_count int; +begin + select count(id) into sales_count + from public.sales; + + insert into public.sales (first_name, last_name, email, user_id, administrator) + values ( + new.raw_user_meta_data ->> 'first_name', + new.raw_user_meta_data ->> 'last_name', + new.email, + new.id, + case when sales_count > 0 then FALSE else TRUE end + ); + return new; +end; +$$; + +create function public.handle_update_user() +returns trigger +language plpgsql +security definer set search_path = '' +as $$ +begin + update public.sales + set + first_name = new.raw_user_meta_data ->> 'first_name', + last_name = new.raw_user_meta_data ->> 'last_name', + email = new.email + where user_id = new.id; + + return new; +end; +$$; + + +create unique index "uq__sales__user_id" on public.sales (user_id); + +create trigger on_auth_user_created + after insert on auth.users + for each row execute procedure public.handle_new_user(); + +create trigger on_auth_user_updated + after update on auth.users + for each row execute procedure public.handle_update_user(); + +create view init_state + with (security_invoker=off) + as +select count(id) as is_initialized +from public.sales +limit 1; diff --git a/packages/db/src/migrations/20240806124555_task_sales_id/up.sql b/packages/db/src/migrations/20240806124555_task_sales_id/up.sql new file mode 100644 index 0000000..68f8a12 --- /dev/null +++ b/packages/db/src/migrations/20240806124555_task_sales_id/up.sql @@ -0,0 +1 @@ +alter table "public"."tasks" add column "sales_id" bigint; \ No newline at end of file diff --git a/packages/db/src/migrations/20240807082449_remove-aquisition/up.sql b/packages/db/src/migrations/20240807082449_remove-aquisition/up.sql new file mode 100644 index 0000000..0286c90 --- /dev/null +++ b/packages/db/src/migrations/20240807082449_remove-aquisition/up.sql @@ -0,0 +1,20 @@ +-- this will drop the `contacts_summary` view as well +ALTER TABLE "public"."contacts" +DROP COLUMN acquisition CASCADE; + + -- We need to recreate the view with the new schema + +create view "public"."contacts_summary" +as +select + co.*, + c.name as company_name, + count(distinct t.id) as nb_tasks +from + "public"."contacts" co +left join + "public"."tasks" t on co.id = t.contact_id +left join + "public"."companies" c on co.company_id = c.id +group by + co.id, c.name; diff --git a/packages/db/src/migrations/20240808141826_init_state_configure/up.sql b/packages/db/src/migrations/20240808141826_init_state_configure/up.sql new file mode 100644 index 0000000..42ccf12 --- /dev/null +++ b/packages/db/src/migrations/20240808141826_init_state_configure/up.sql @@ -0,0 +1,9 @@ +create or replace view init_state + with (security_invoker=off) + as +select count(id) as is_initialized +from ( + select id + from public.sales + limit 1 +) as sub; diff --git a/packages/db/src/migrations/20240813084010_tags_policy/up.sql b/packages/db/src/migrations/20240813084010_tags_policy/up.sql new file mode 100644 index 0000000..a1790fc --- /dev/null +++ b/packages/db/src/migrations/20240813084010_tags_policy/up.sql @@ -0,0 +1,18 @@ +create policy "Enable delete for authenticated users only" +on "public"."tags" +as permissive +for delete +to authenticated +using (true); + + +create policy "Enable update for authenticated users only" +on "public"."tags" +as permissive +for update +to authenticated +using (true); + + + + diff --git a/packages/db/src/migrations/20241104153231_sales_policies/up.sql b/packages/db/src/migrations/20241104153231_sales_policies/up.sql new file mode 100644 index 0000000..a17afaf --- /dev/null +++ b/packages/db/src/migrations/20241104153231_sales_policies/up.sql @@ -0,0 +1,7 @@ +create schema if not exists "private"; + +set check_function_bodies = off; + +drop policy "Enable insert for authenticated users only" on "public"."sales"; + +drop policy "Enable update for authenticated users only" on "public"."sales"; diff --git a/packages/db/src/migrations/20250109152531_email_jsonb/up.sql b/packages/db/src/migrations/20250109152531_email_jsonb/up.sql new file mode 100644 index 0000000..435bca2 --- /dev/null +++ b/packages/db/src/migrations/20250109152531_email_jsonb/up.sql @@ -0,0 +1,43 @@ +alter table contacts add column email_jsonb jsonb; + +update contacts set email_jsonb = ('[{"email": "' || email || '", "type": "Other"}]')::jsonb; + +drop view contacts_summary; + +alter table contacts drop column email; + +create view contacts_summary +as +select + co.id, + co.first_name, + co.last_name, + co.gender, + co.title, + co.email_jsonb, + jsonb_path_query_array(co.email_jsonb, '$[*].email')::text as email_fts, + co.phone_1_number, + co.phone_1_type, + co.phone_2_number, + co.phone_2_type, + co.background, + co.avatar, + co.first_seen, + co.last_seen, + co.has_newsletter, + co.status, + co.tags, + co.company_id, + co.sales_id, + co.linkedin_url, + c.name as company_name, + count(distinct t.id) as nb_tasks +from + contacts co +left join + tasks t on co.id = t.contact_id +left join + companies c on co.company_id = c.id +group by + co.id, c.name; + diff --git a/packages/db/src/migrations/20250113132531_phone_jsonb/up.sql b/packages/db/src/migrations/20250113132531_phone_jsonb/up.sql new file mode 100644 index 0000000..95a24ed --- /dev/null +++ b/packages/db/src/migrations/20250113132531_phone_jsonb/up.sql @@ -0,0 +1,67 @@ +alter table contacts add column phone_jsonb jsonb; + +update contacts set phone_jsonb = + concat( + '[', + case when phone_1_number is not null then + concat( + '{"number":"', + phone_1_number, + '","type":"', + phone_1_type, + '"}' + ) + else null end, + case when phone_2_number is not null then + concat( + ',', + '{"number":"', + phone_2_number, + '","type":"', + phone_2_type, + '"}' + ) + else null end, + ']' + )::jsonb; + +drop view contacts_summary; + +alter table contacts drop column phone_1_number; +alter table contacts drop column phone_1_type; +alter table contacts drop column phone_2_number; +alter table contacts drop column phone_2_type; + +create view contacts_summary +as +select + co.id, + co.first_name, + co.last_name, + co.gender, + co.title, + co.email_jsonb, + jsonb_path_query_array(co.email_jsonb, '$[*].email')::text as email_fts, + co.phone_jsonb, + jsonb_path_query_array(co.phone_jsonb, '$[*].number')::text as phone_fts, + co.background, + co.avatar, + co.first_seen, + co.last_seen, + co.has_newsletter, + co.status, + co.tags, + co.company_id, + co.sales_id, + co.linkedin_url, + c.name as company_name, + count(distinct t.id) as nb_tasks +from + contacts co +left join + tasks t on co.id = t.contact_id +left join + companies c on co.company_id = c.id +group by + co.id, c.name; + diff --git a/packages/db/src/migrations/20251204172855_merge_contacts_function/up.sql b/packages/db/src/migrations/20251204172855_merge_contacts_function/up.sql new file mode 100644 index 0000000..81ffd92 --- /dev/null +++ b/packages/db/src/migrations/20251204172855_merge_contacts_function/up.sql @@ -0,0 +1,153 @@ +-- Create function to merge contacts server-side with transaction support +CREATE OR REPLACE FUNCTION merge_contacts(loser_id bigint, winner_id bigint) +RETURNS bigint +LANGUAGE plpgsql +SECURITY INVOKER +AS $$ +DECLARE + winner_contact contacts%ROWTYPE; + loser_contact contacts%ROWTYPE; + deal_record RECORD; + merged_emails jsonb; + merged_phones jsonb; + merged_tags bigint[]; + winner_emails jsonb; + loser_emails jsonb; + winner_phones jsonb; + loser_phones jsonb; + email_map jsonb; + phone_map jsonb; +BEGIN + -- Fetch both contacts + SELECT * INTO winner_contact FROM contacts WHERE id = winner_id; + SELECT * INTO loser_contact FROM contacts WHERE id = loser_id; + + IF winner_contact IS NULL OR loser_contact IS NULL THEN + RAISE EXCEPTION 'Contact not found'; + END IF; + + -- 1. Reassign tasks from loser to winner + UPDATE tasks SET contact_id = winner_id WHERE contact_id = loser_id; + + -- 2. Reassign contact notes from loser to winner + UPDATE "contactNotes" SET contact_id = winner_id WHERE contact_id = loser_id; + + -- 3. Update deals - replace loser with winner in contact_ids array + FOR deal_record IN + SELECT id, contact_ids + FROM deals + WHERE contact_ids @> ARRAY[loser_id] + LOOP + UPDATE deals + SET contact_ids = ( + SELECT ARRAY( + SELECT DISTINCT unnest( + array_remove(deal_record.contact_ids, loser_id) || ARRAY[winner_id] + ) + ) + ) + WHERE id = deal_record.id; + END LOOP; + + -- 4. Merge contact data + + -- Get email arrays + winner_emails := COALESCE(winner_contact.email_jsonb, '[]'::jsonb); + loser_emails := COALESCE(loser_contact.email_jsonb, '[]'::jsonb); + + -- Merge emails with deduplication by email address + -- Build a map of email -> email object, then convert back to array + email_map := '{}'::jsonb; + + -- Add winner emails to map + IF jsonb_array_length(winner_emails) > 0 THEN + FOR i IN 0..jsonb_array_length(winner_emails)-1 LOOP + email_map := email_map || jsonb_build_object( + winner_emails->i->>'email', + winner_emails->i + ); + END LOOP; + END IF; + + -- Add loser emails to map (won't overwrite existing keys) + IF jsonb_array_length(loser_emails) > 0 THEN + FOR i IN 0..jsonb_array_length(loser_emails)-1 LOOP + IF NOT email_map ? (loser_emails->i->>'email') THEN + email_map := email_map || jsonb_build_object( + loser_emails->i->>'email', + loser_emails->i + ); + END IF; + END LOOP; + END IF; + + -- Convert map back to array + merged_emails := (SELECT jsonb_agg(value) FROM jsonb_each(email_map)); + merged_emails := COALESCE(merged_emails, '[]'::jsonb); + + -- Get phone arrays + winner_phones := COALESCE(winner_contact.phone_jsonb, '[]'::jsonb); + loser_phones := COALESCE(loser_contact.phone_jsonb, '[]'::jsonb); + + -- Merge phones with deduplication by number + phone_map := '{}'::jsonb; + + -- Add winner phones to map + IF jsonb_array_length(winner_phones) > 0 THEN + FOR i IN 0..jsonb_array_length(winner_phones)-1 LOOP + phone_map := phone_map || jsonb_build_object( + winner_phones->i->>'number', + winner_phones->i + ); + END LOOP; + END IF; + + -- Add loser phones to map (won't overwrite existing keys) + IF jsonb_array_length(loser_phones) > 0 THEN + FOR i IN 0..jsonb_array_length(loser_phones)-1 LOOP + IF NOT phone_map ? (loser_phones->i->>'number') THEN + phone_map := phone_map || jsonb_build_object( + loser_phones->i->>'number', + loser_phones->i + ); + END IF; + END LOOP; + END IF; + + -- Convert map back to array + merged_phones := (SELECT jsonb_agg(value) FROM jsonb_each(phone_map)); + merged_phones := COALESCE(merged_phones, '[]'::jsonb); + + -- Merge tags (remove duplicates) + merged_tags := ARRAY( + SELECT DISTINCT unnest( + COALESCE(winner_contact.tags, ARRAY[]::bigint[]) || + COALESCE(loser_contact.tags, ARRAY[]::bigint[]) + ) + ); + + -- 5. Update winner with merged data + UPDATE contacts SET + avatar = COALESCE(winner_contact.avatar, loser_contact.avatar), + gender = COALESCE(winner_contact.gender, loser_contact.gender), + first_name = COALESCE(winner_contact.first_name, loser_contact.first_name), + last_name = COALESCE(winner_contact.last_name, loser_contact.last_name), + title = COALESCE(winner_contact.title, loser_contact.title), + company_id = COALESCE(winner_contact.company_id, loser_contact.company_id), + email_jsonb = merged_emails, + phone_jsonb = merged_phones, + linkedin_url = COALESCE(winner_contact.linkedin_url, loser_contact.linkedin_url), + background = COALESCE(winner_contact.background, loser_contact.background), + has_newsletter = COALESCE(winner_contact.has_newsletter, loser_contact.has_newsletter), + first_seen = LEAST(COALESCE(winner_contact.first_seen, loser_contact.first_seen), COALESCE(loser_contact.first_seen, winner_contact.first_seen)), + last_seen = GREATEST(COALESCE(winner_contact.last_seen, loser_contact.last_seen), COALESCE(loser_contact.last_seen, winner_contact.last_seen)), + sales_id = COALESCE(winner_contact.sales_id, loser_contact.sales_id), + tags = merged_tags + WHERE id = winner_id; + + -- 6. Delete loser contact + DELETE FROM contacts WHERE id = loser_id; + + RETURN winner_id; +END; +$$; diff --git a/packages/db/src/migrations/20251204201317_drop_merge_contacts_function/up.sql b/packages/db/src/migrations/20251204201317_drop_merge_contacts_function/up.sql new file mode 100644 index 0000000..80da065 --- /dev/null +++ b/packages/db/src/migrations/20251204201317_drop_merge_contacts_function/up.sql @@ -0,0 +1,2 @@ +-- Drop the merge_contacts function (reverting to edge function approach) +DROP FUNCTION IF EXISTS merge_contacts(bigint, bigint); diff --git a/packages/db/src/migrations/20260108160722_task_default_sales/up.sql b/packages/db/src/migrations/20260108160722_task_default_sales/up.sql new file mode 100644 index 0000000..c63e359 --- /dev/null +++ b/packages/db/src/migrations/20260108160722_task_default_sales/up.sql @@ -0,0 +1,39 @@ +CREATE OR REPLACE FUNCTION set_sales_id_default() +RETURNS TRIGGER AS $$ +BEGIN + IF NEW.sales_id IS NULL THEN + SELECT id INTO NEW.sales_id FROM sales WHERE user_id = auth.uid(); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER set_task_sales_id_trigger +BEFORE INSERT ON tasks +FOR EACH ROW +EXECUTE FUNCTION set_sales_id_default(); + +CREATE TRIGGER set_contact_sales_id_trigger +BEFORE INSERT ON contacts +FOR EACH ROW +EXECUTE FUNCTION set_sales_id_default(); + +CREATE TRIGGER set_contact_notes_sales_id_trigger +BEFORE INSERT ON "contactNotes" +FOR EACH ROW +EXECUTE FUNCTION set_sales_id_default(); + +CREATE TRIGGER set_company_sales_id_trigger +BEFORE INSERT ON companies +FOR EACH ROW +EXECUTE FUNCTION set_sales_id_default(); + +CREATE TRIGGER set_deal_sales_id_trigger +BEFORE INSERT ON deals +FOR EACH ROW +EXECUTE FUNCTION set_sales_id_default(); + +CREATE TRIGGER set_deal_notes_sales_id_trigger +BEFORE INSERT ON "dealNotes" +FOR EACH ROW +EXECUTE FUNCTION set_sales_id_default(); \ No newline at end of file diff --git a/packages/db/src/migrations/20260115150819_snake_case_renaming/up.sql b/packages/db/src/migrations/20260115150819_snake_case_renaming/up.sql new file mode 100644 index 0000000..9d4bb3b --- /dev/null +++ b/packages/db/src/migrations/20260115150819_snake_case_renaming/up.sql @@ -0,0 +1,158 @@ +alter table "public"."companies" rename column "stateAbbr" TO "state_abbr"; +alter view "public"."companies_summary" rename column "stateAbbr" TO "state_abbr"; +alter table "public"."contactNotes" rename to "contact_notes"; +alter table "public"."dealNotes" rename to "deal_notes"; + +-- Create function to merge contacts server-side with transaction support +CREATE OR REPLACE FUNCTION merge_contacts(loser_id bigint, winner_id bigint) +RETURNS bigint +LANGUAGE plpgsql +SECURITY INVOKER +AS $$ +DECLARE + winner_contact contacts%ROWTYPE; + loser_contact contacts%ROWTYPE; + deal_record RECORD; + merged_emails jsonb; + merged_phones jsonb; + merged_tags bigint[]; + winner_emails jsonb; + loser_emails jsonb; + winner_phones jsonb; + loser_phones jsonb; + email_map jsonb; + phone_map jsonb; +BEGIN + -- Fetch both contacts + SELECT * INTO winner_contact FROM contacts WHERE id = winner_id; + SELECT * INTO loser_contact FROM contacts WHERE id = loser_id; + + IF winner_contact IS NULL OR loser_contact IS NULL THEN + RAISE EXCEPTION 'Contact not found'; + END IF; + + -- 1. Reassign tasks from loser to winner + UPDATE tasks SET contact_id = winner_id WHERE contact_id = loser_id; + + -- 2. Reassign contact notes from loser to winner + UPDATE "contact_notes" SET contact_id = winner_id WHERE contact_id = loser_id; + + -- 3. Update deals - replace loser with winner in contact_ids array + FOR deal_record IN + SELECT id, contact_ids + FROM deals + WHERE contact_ids @> ARRAY[loser_id] + LOOP + UPDATE deals + SET contact_ids = ( + SELECT ARRAY( + SELECT DISTINCT unnest( + array_remove(deal_record.contact_ids, loser_id) || ARRAY[winner_id] + ) + ) + ) + WHERE id = deal_record.id; + END LOOP; + + -- 4. Merge contact data + + -- Get email arrays + winner_emails := COALESCE(winner_contact.email_jsonb, '[]'::jsonb); + loser_emails := COALESCE(loser_contact.email_jsonb, '[]'::jsonb); + + -- Merge emails with deduplication by email address + -- Build a map of email -> email object, then convert back to array + email_map := '{}'::jsonb; + + -- Add winner emails to map + IF jsonb_array_length(winner_emails) > 0 THEN + FOR i IN 0..jsonb_array_length(winner_emails)-1 LOOP + email_map := email_map || jsonb_build_object( + winner_emails->i->>'email', + winner_emails->i + ); + END LOOP; + END IF; + + -- Add loser emails to map (won't overwrite existing keys) + IF jsonb_array_length(loser_emails) > 0 THEN + FOR i IN 0..jsonb_array_length(loser_emails)-1 LOOP + IF NOT email_map ? (loser_emails->i->>'email') THEN + email_map := email_map || jsonb_build_object( + loser_emails->i->>'email', + loser_emails->i + ); + END IF; + END LOOP; + END IF; + + -- Convert map back to array + merged_emails := (SELECT jsonb_agg(value) FROM jsonb_each(email_map)); + merged_emails := COALESCE(merged_emails, '[]'::jsonb); + + -- Get phone arrays + winner_phones := COALESCE(winner_contact.phone_jsonb, '[]'::jsonb); + loser_phones := COALESCE(loser_contact.phone_jsonb, '[]'::jsonb); + + -- Merge phones with deduplication by number + phone_map := '{}'::jsonb; + + -- Add winner phones to map + IF jsonb_array_length(winner_phones) > 0 THEN + FOR i IN 0..jsonb_array_length(winner_phones)-1 LOOP + phone_map := phone_map || jsonb_build_object( + winner_phones->i->>'number', + winner_phones->i + ); + END LOOP; + END IF; + + -- Add loser phones to map (won't overwrite existing keys) + IF jsonb_array_length(loser_phones) > 0 THEN + FOR i IN 0..jsonb_array_length(loser_phones)-1 LOOP + IF NOT phone_map ? (loser_phones->i->>'number') THEN + phone_map := phone_map || jsonb_build_object( + loser_phones->i->>'number', + loser_phones->i + ); + END IF; + END LOOP; + END IF; + + -- Convert map back to array + merged_phones := (SELECT jsonb_agg(value) FROM jsonb_each(phone_map)); + merged_phones := COALESCE(merged_phones, '[]'::jsonb); + + -- Merge tags (remove duplicates) + merged_tags := ARRAY( + SELECT DISTINCT unnest( + COALESCE(winner_contact.tags, ARRAY[]::bigint[]) || + COALESCE(loser_contact.tags, ARRAY[]::bigint[]) + ) + ); + + -- 5. Update winner with merged data + UPDATE contacts SET + avatar = COALESCE(winner_contact.avatar, loser_contact.avatar), + gender = COALESCE(winner_contact.gender, loser_contact.gender), + first_name = COALESCE(winner_contact.first_name, loser_contact.first_name), + last_name = COALESCE(winner_contact.last_name, loser_contact.last_name), + title = COALESCE(winner_contact.title, loser_contact.title), + company_id = COALESCE(winner_contact.company_id, loser_contact.company_id), + email_jsonb = merged_emails, + phone_jsonb = merged_phones, + linkedin_url = COALESCE(winner_contact.linkedin_url, loser_contact.linkedin_url), + background = COALESCE(winner_contact.background, loser_contact.background), + has_newsletter = COALESCE(winner_contact.has_newsletter, loser_contact.has_newsletter), + first_seen = LEAST(COALESCE(winner_contact.first_seen, loser_contact.first_seen), COALESCE(loser_contact.first_seen, winner_contact.first_seen)), + last_seen = GREATEST(COALESCE(winner_contact.last_seen, loser_contact.last_seen), COALESCE(loser_contact.last_seen, winner_contact.last_seen)), + sales_id = COALESCE(winner_contact.sales_id, loser_contact.sales_id), + tags = merged_tags + WHERE id = winner_id; + + -- 6. Delete loser contact + DELETE FROM contacts WHERE id = loser_id; + + RETURN winner_id; +END; +$$; diff --git a/packages/db/src/migrations/20260127140209_imports/up.sql b/packages/db/src/migrations/20260127140209_imports/up.sql new file mode 100644 index 0000000..43a65aa --- /dev/null +++ b/packages/db/src/migrations/20260127140209_imports/up.sql @@ -0,0 +1,206 @@ +-- Port: guarded — Supabase installs pgsql-http; a Postgres without it (the tests') skips it, and get_avatar_for_email() then falls back as it does on any error +DO $$ +BEGIN + create extension if not exists "http" with schema "extensions"; +EXCEPTION WHEN feature_not_supported OR undefined_file THEN + RAISE NOTICE 'skipped, not installed on this server: create extension if not exists "http" with schema "extensions"'; +END $$; + +create table "public"."favicons_excluded_domains" ( + "id" bigint generated by default as identity not null, + "domain" text not null +); + + +alter table "public"."favicons_excluded_domains" enable row level security; + +CREATE UNIQUE INDEX favicons_excluded_domains_pkey ON public.favicons_excluded_domains USING btree (id); + +alter table "public"."favicons_excluded_domains" add constraint "favicons_excluded_domains_pkey" PRIMARY KEY using index "favicons_excluded_domains_pkey"; + +alter table "public"."tasks" alter column "due_date" drop not null; + +set check_function_bodies = off; + +CREATE OR REPLACE FUNCTION public.get_avatar_for_email(email text) + RETURNS text + LANGUAGE plpgsql +AS $function$declare email_hash text; +declare gravatar_url text; +declare gravatar_status int8; +declare email_domain text; +declare favicon_url text; +declare domain_status int8; + +begin + -- Try to fetch a gravatar image + email_hash = encode(digest(email, 'sha256'), 'hex'); + gravatar_url = concat('https://www.gravatar.com/avatar/', email_hash, '?d=404'); + + select status from http_get(gravatar_url) into gravatar_status; + + if gravatar_status = 200 then + return gravatar_url; + end if; + + -- Fallback to email's domain favicon if not excluded + email_domain = split_part(email, '@', 2); + return get_domain_favicon(email_domain); +exception + when others then + return 'ERROR'; +end;$function$ +; + +CREATE OR REPLACE FUNCTION public.get_domain_favicon(domain_name text) + RETURNS text + LANGUAGE plpgsql +AS $function$declare domain_status int8; + +begin + if exists (select from favicons_excluded_domains as fav where fav.domain = domain_name) then + return null; + end if; + + return concat( + 'https://favicon.show/', + (regexp_matches(domain_name, '^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)', 'i'))[1] + ); +end;$function$ +; + +CREATE OR REPLACE FUNCTION public.handle_contact_saved() + RETURNS trigger + LANGUAGE plpgsql +AS $function$declare contact_avatar text; +declare emails_length int8; +declare item jsonb; + +begin + if new.avatar is not null then + return new; + end if; + + select coalesce(jsonb_array_length(new.email_jsonb), 0) into emails_length; + + if emails_length = 0 then + return new; + end if; + + for item in select jsonb_array_elements(new.email_jsonb) + loop + select public.get_avatar_for_email(item->>'email') into contact_avatar; + if (contact_avatar is not null) then + exit; + end if; + end loop; + + if contact_avatar is null then + return new; + end if; + + new.avatar = concat('{"src":"', contact_avatar, '"}'); + return new; +end;$function$ +; + +CREATE TRIGGER contact_saved BEFORE INSERT OR UPDATE ON public.contacts FOR EACH ROW EXECUTE FUNCTION public.handle_contact_saved(); + +grant delete on table "public"."favicons_excluded_domains" to "authenticated"; + +grant insert on table "public"."favicons_excluded_domains" to "authenticated"; + +grant references on table "public"."favicons_excluded_domains" to "authenticated"; + +grant select on table "public"."favicons_excluded_domains" to "authenticated"; + +grant trigger on table "public"."favicons_excluded_domains" to "authenticated"; + +grant truncate on table "public"."favicons_excluded_domains" to "authenticated"; + +grant update on table "public"."favicons_excluded_domains" to "authenticated"; + +grant delete on table "public"."favicons_excluded_domains" to "postgres"; + +grant insert on table "public"."favicons_excluded_domains" to "postgres"; + +grant references on table "public"."favicons_excluded_domains" to "postgres"; + +grant select on table "public"."favicons_excluded_domains" to "postgres"; + +grant trigger on table "public"."favicons_excluded_domains" to "postgres"; + +grant truncate on table "public"."favicons_excluded_domains" to "postgres"; + +grant update on table "public"."favicons_excluded_domains" to "postgres"; + +grant delete on table "public"."favicons_excluded_domains" to "service_role"; + +grant insert on table "public"."favicons_excluded_domains" to "service_role"; + +grant references on table "public"."favicons_excluded_domains" to "service_role"; + +grant select on table "public"."favicons_excluded_domains" to "service_role"; + +grant trigger on table "public"."favicons_excluded_domains" to "service_role"; + +grant truncate on table "public"."favicons_excluded_domains" to "service_role"; + +grant update on table "public"."favicons_excluded_domains" to "service_role"; + + +create policy "Enable access for authenticated users only" + on "public"."favicons_excluded_domains" + as permissive + for all + to authenticated +using (true) +with check (true); + +CREATE OR REPLACE FUNCTION public.handle_company_saved() + RETURNS trigger + LANGUAGE plpgsql +AS $function$declare company_logo text; + +begin + if new.logo is not null then + return new; + end if; + + company_logo = get_domain_favicon(new.website); + if company_logo is null then + return new; + end if; + + new.logo = concat('{"src":"', company_logo, '","title":"Company favicon"}'); + return new; +end;$function$ +; + +CREATE TRIGGER company_saved BEFORE INSERT OR UPDATE ON public.companies FOR EACH ROW EXECUTE FUNCTION public.handle_company_saved(); + +CREATE OR REPLACE FUNCTION public.handle_contact_note_created_or_updated() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO '' +AS $function$ +begin + update public.contacts set last_seen = new.date where contacts.id = new.contact_id and contacts.last_seen < new.date; + return new; +end; +$function$ +; + +CREATE TRIGGER on_public_contact_notes_created_or_updated AFTER INSERT ON public.contact_notes FOR EACH ROW EXECUTE FUNCTION public.handle_contact_note_created_or_updated(); + +CREATE OR REPLACE FUNCTION get_user_id_by_email(email TEXT) +RETURNS TABLE (id uuid) +SECURITY definer +AS $$ +BEGIN + RETURN QUERY SELECT au.id FROM auth.users au WHERE au.email = $1; +END; +$$ LANGUAGE plpgsql; + +revoke execute on function public.get_user_id_by_email from anon, authenticated, public; diff --git a/packages/db/src/migrations/20260128165057_sso_handling/up.sql b/packages/db/src/migrations/20260128165057_sso_handling/up.sql new file mode 100644 index 0000000..e4ecab0 --- /dev/null +++ b/packages/db/src/migrations/20260128165057_sso_handling/up.sql @@ -0,0 +1,52 @@ +-- Port: upstream creates pgjwt here and never uses it; Supabase's Postgres 17 +-- (every new project) no longer ships it, so it is not created. + +alter table "public"."sales" alter column "first_name" set default 'Pending'::text; + +alter table "public"."sales" alter column "last_name" set default 'Pending'::text; + +set check_function_bodies = off; + +CREATE OR REPLACE FUNCTION public.handle_new_user() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO '' +AS $function$ +declare + sales_count int; +begin + select count(id) into sales_count + from public.sales; + + insert into public.sales (first_name, last_name, email, user_id, administrator) + values ( + coalesce(new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data -> 'custom_claims' ->> 'first_name', 'Pending'), + coalesce(new.raw_user_meta_data ->> 'last_name', new.raw_user_meta_data -> 'custom_claims' ->> 'last_name', 'Pending'), + new.email, + new.id, + case when sales_count > 0 then FALSE else TRUE end + ); + return new; +end; +$function$ +; + +CREATE OR REPLACE FUNCTION public.handle_update_user() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO '' +AS $function$ +begin + update public.sales + set + first_name = coalesce(new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data -> 'custom_claims' ->> 'first_name', 'Pending'), + last_name = coalesce(new.raw_user_meta_data ->> 'last_name', new.raw_user_meta_data -> 'custom_claims' ->> 'last_name', 'Pending'), + email = new.email + where user_id = new.id; + + return new; +end; +$function$ +; diff --git a/packages/db/src/migrations/20260211194545_app_configuration/up.sql b/packages/db/src/migrations/20260211194545_app_configuration/up.sql new file mode 100644 index 0000000..fefa097 --- /dev/null +++ b/packages/db/src/migrations/20260211194545_app_configuration/up.sql @@ -0,0 +1,77 @@ +-- Singleton table storing the app configuration as a JSONB document. +-- Admins can customize branding, company sectors, deal stages/categories, +-- note statuses, and task types via the Settings page. +-- The app merges stored values with code defaults, so missing keys are safe. + +create table "public"."configuration" ( + "id" integer not null default 1, + "config" jsonb not null default '{}'::jsonb, + constraint "configuration_pkey" primary key ("id"), + constraint "configuration_singleton" check ("id" = 1) +); + +alter table "public"."configuration" enable row level security; + +-- Helper to check admin status in RLS policies +create or replace function public.is_admin() +returns boolean language plpgsql security definer set search_path = '' as $$ +begin + return exists ( + select 1 from public.sales where user_id = auth.uid() and administrator = true + ); +end; +$$; + +-- All authenticated users can read +create policy "Enable read for authenticated" on "public"."configuration" + as permissive for select to authenticated using (true); + +-- Only admins can insert/update +create policy "Enable insert for admins" on "public"."configuration" + as permissive for insert to authenticated with check (public.is_admin()); +create policy "Enable update for admins" on "public"."configuration" + as permissive for update to authenticated + using (public.is_admin()) with check (public.is_admin()); + +-- Grants +grant select, insert, update on "public"."configuration" to "authenticated"; +grant select, insert, update on "public"."configuration" to "service_role"; + +-- Seed empty config (code defaults apply) +insert into "public"."configuration" ("id", "config") values (1, '{}'::jsonb); + +-- Migrate old label-based values to slug-based values. +-- +-- Previously, companySectors, dealCategories, and taskTypes were stored as +-- plain string arrays (e.g. ["Energy", "Copywriting"]) in individual records. +-- Now they use a { value, label } format where `value` is a slug derived from +-- the label. +-- +-- This converts record fields (companies.sector, deals.category, tasks.type, +-- contact_notes.status) from display labels to slugs. + +CREATE OR REPLACE FUNCTION pg_temp.to_slug(label text) RETURNS text AS $$ +BEGIN + RETURN TRIM(BOTH '-' FROM REGEXP_REPLACE(LOWER(label), '[^a-z0-9]+', '-', 'g')); +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +UPDATE companies +SET sector = pg_temp.to_slug(sector) +WHERE sector IS NOT NULL + AND sector != pg_temp.to_slug(sector); + +UPDATE deals +SET category = pg_temp.to_slug(category) +WHERE category IS NOT NULL + AND category != pg_temp.to_slug(category); + +UPDATE tasks +SET type = pg_temp.to_slug(type) +WHERE type IS NOT NULL + AND type != pg_temp.to_slug(type); + +UPDATE contact_notes +SET status = pg_temp.to_slug(status) +WHERE status IS NOT NULL + AND status != pg_temp.to_slug(status); diff --git a/packages/db/src/migrations/20260226163952_deals_expected_closing_date_date_only/up.sql b/packages/db/src/migrations/20260226163952_deals_expected_closing_date_date_only/up.sql new file mode 100644 index 0000000..ad9f3b7 --- /dev/null +++ b/packages/db/src/migrations/20260226163952_deals_expected_closing_date_date_only/up.sql @@ -0,0 +1,3 @@ +-- Migrating from timestamp with timezone to date only for expected_closing_date as we don't need the precision +-- And by only handling the date part in the client it caused conversion issues for users in different timezones +ALTER table "public"."deals" ALTER COLUMN "expected_closing_date" TYPE date USING ("expected_closing_date" AT TIME ZONE 'UTC')::date; diff --git a/packages/db/src/migrations/20260304104600_note_attachments_trigger/up.sql b/packages/db/src/migrations/20260304104600_note_attachments_trigger/up.sql new file mode 100644 index 0000000..e2d1b48 --- /dev/null +++ b/packages/db/src/migrations/20260304104600_note_attachments_trigger/up.sql @@ -0,0 +1,124 @@ +-- Deletes attachment files from storage when note attachments are removed, +-- either by deleting a note or by updating a note attachments list. +-- Port: guarded — Supabase installs pg_net; cleanup_note_attachments() no longer calls it (the outbox migration), so a Postgres without it skips it +DO $$ +BEGIN + CREATE EXTENSION IF NOT EXISTS pg_net; +EXCEPTION WHEN feature_not_supported OR undefined_file THEN + RAISE NOTICE 'skipped, not installed on this server: CREATE EXTENSION IF NOT EXISTS pg_net'; +END $$; + +DO $migration$ +BEGIN + EXECUTE $url_sql$ + -- SQL triggers cannot read Edge Function env vars directly. Resolve the + -- function URL from request context, and keep a local Docker fallback. + CREATE OR REPLACE FUNCTION public.get_note_attachments_function_url() + RETURNS text + LANGUAGE plpgsql + AS $function$ + DECLARE + issuer text; + function_url text; + BEGIN + issuer := coalesce( + nullif(current_setting('request.jwt.claim.iss', true), ''), + ( + coalesce( + nullif(current_setting('request.jwt.claims', true), ''), + '{}' + )::jsonb ->> 'iss' + ) + ); + issuer := nullif(issuer, ''); + IF issuer IS NOT NULL THEN + issuer := rtrim(issuer, '/'); + IF right(issuer, 8) = '/auth/v1' THEN + function_url := + left(issuer, length(issuer) - 8) || '/functions/v1/delete_note_attachments'; + + IF function_url LIKE 'http://127.0.0.1:%' THEN + RETURN replace( + function_url, + 'http://127.0.0.1:', + 'http://host.docker.internal:' + ); + END IF; + + IF function_url LIKE 'http://localhost:%' THEN + RETURN replace( + function_url, + 'http://localhost:', + 'http://host.docker.internal:' + ); + END IF; + + RETURN function_url; + END IF; + END IF; + + RETURN 'http://host.docker.internal:54321/functions/v1/delete_note_attachments'; + END; + $function$; + $url_sql$; + + EXECUTE $cleanup_sql$ + CREATE OR REPLACE FUNCTION public.cleanup_note_attachments() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO '' + AS $function$ + DECLARE + payload jsonb; + request_headers jsonb; + auth_header text; + BEGIN + request_headers := coalesce( + nullif(current_setting('request.headers', true), '')::jsonb, + '{}'::jsonb + ); + auth_header := request_headers ->> 'authorization'; + + IF auth_header IS NULL OR auth_header = '' THEN + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + + RETURN NEW; + END IF; + + payload := jsonb_build_object( + 'old_record', OLD, + 'record', NEW, + 'type', TG_OP + ); + + PERFORM net.http_post( + url := public.get_note_attachments_function_url(), + body := payload, + params := '{}'::jsonb, + headers := jsonb_build_object( + 'Content-Type', + 'application/json', + 'Authorization', + auth_header + ), + timeout_milliseconds := 10000 + ); + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + + RETURN NEW; + END; + $function$; + $cleanup_sql$; + + EXECUTE 'CREATE TRIGGER on_contact_notes_deleted_delete_note_attachments AFTER DELETE ON public.contact_notes FOR EACH ROW EXECUTE FUNCTION public.cleanup_note_attachments()'; + EXECUTE 'CREATE TRIGGER on_deal_notes_deleted_delete_note_attachments AFTER DELETE ON public.deal_notes FOR EACH ROW EXECUTE FUNCTION public.cleanup_note_attachments()'; + EXECUTE 'CREATE TRIGGER on_contact_notes_attachments_updated_delete_note_attachments AFTER UPDATE ON public.contact_notes FOR EACH ROW WHEN (OLD.attachments IS DISTINCT FROM NEW.attachments) EXECUTE FUNCTION public.cleanup_note_attachments()'; + EXECUTE 'CREATE TRIGGER on_deal_notes_attachments_updated_delete_note_attachments AFTER UPDATE ON public.deal_notes FOR EACH ROW WHEN (OLD.attachments IS DISTINCT FROM NEW.attachments) EXECUTE FUNCTION public.cleanup_note_attachments()'; +END; +$migration$; diff --git a/packages/db/src/migrations/20260307120000_nb_tasks_pending_only/up.sql b/packages/db/src/migrations/20260307120000_nb_tasks_pending_only/up.sql new file mode 100644 index 0000000..7119b9c --- /dev/null +++ b/packages/db/src/migrations/20260307120000_nb_tasks_pending_only/up.sql @@ -0,0 +1,18 @@ +drop view if exists contacts_summary; + +create view contacts_summary +as +select + co.*, + jsonb_path_query_array(co.email_jsonb, '$[*].email')::text as email_fts, + jsonb_path_query_array(co.phone_jsonb, '$[*].number')::text as phone_fts, + c.name as company_name, + count(distinct t.id) filter (where t.done_date is null) as nb_tasks +from + contacts co +left join + tasks t on co.id = t.contact_id +left join + companies c on co.company_id = c.id +group by + co.id, c.name; diff --git a/packages/db/src/migrations/20260309112831_fix_security_warnings/up.sql b/packages/db/src/migrations/20260309112831_fix_security_warnings/up.sql new file mode 100644 index 0000000..682175d --- /dev/null +++ b/packages/db/src/migrations/20260309112831_fix_security_warnings/up.sql @@ -0,0 +1,350 @@ +-- This migration allows to resolve several security warnings raised by the Supabase Advisor: +-- * Security Definer View +-- * Function Search Path Mutable +-- * Extension in Public + +-- Recreate the contacts_summary view with security_invoker enabled +drop view contacts_summary; + +create view contacts_summary +with (security_invoker=on) +as +select + co.*, + jsonb_path_query_array(co.email_jsonb, '$[*].email')::text as email_fts, + jsonb_path_query_array(co.phone_jsonb, '$[*].number')::text as phone_fts, + c.name as company_name, + count(distinct t.id) filter (where t.done_date is null) as nb_tasks +from + contacts co +left join + tasks t on co.id = t.contact_id +left join + companies c on co.company_id = c.id +group by + co.id, c.name; + +-- Ensure all functions have search_path set to prevent search path injection attacks + +-- Functions that already use qualified names can be simply altered to use public search_path + +ALTER FUNCTION public.get_note_attachments_function_url() +SET search_path TO 'public'; + +ALTER FUNCTION public.get_user_id_by_email(text) +SET search_path TO 'public'; + +ALTER FUNCTION public.handle_contact_saved() +SET search_path TO 'public'; + +-- get_avatar_for_email: set search_path='public' and qualify extension calls +-- (http_get -> extensions.http_get, digest -> extensions.digest) +DROP FUNCTION IF EXISTS public.get_avatar_for_email(text); + +CREATE FUNCTION public.get_avatar_for_email(email text) +RETURNS text +LANGUAGE plpgsql +SET search_path TO 'public' +AS $function$ +declare email_hash text; +declare gravatar_url text; +declare gravatar_status int8; +declare email_domain text; +declare favicon_url text; +declare domain_status int8; + +begin + -- Try to fetch a gravatar image + email_hash = encode(extensions.digest(email, 'sha256'), 'hex'); + gravatar_url = concat('https://www.gravatar.com/avatar/', email_hash, '?d=404'); + + select status from extensions.http_get(gravatar_url) into gravatar_status; + + if gravatar_status = 200 then + return gravatar_url; + end if; + + -- Fallback to email's domain favicon if not excluded + email_domain = split_part(email, '@', 2); + return get_domain_favicon(email_domain); +exception + when others then + return 'ERROR'; +end; +$function$; + +-- get_domain_favicon: set search_path='public' (no changes to table references needed) +DROP FUNCTION IF EXISTS public.get_domain_favicon(text); + +CREATE FUNCTION public.get_domain_favicon(domain_name text) +RETURNS text +LANGUAGE plpgsql +SET search_path TO 'public' +AS $function$ +declare domain_status int8; + +begin + if exists (select from favicons_excluded_domains as fav where fav.domain = domain_name) then + return null; + end if; + + return concat( + 'https://favicon.show/', + (regexp_matches(domain_name, '^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)', 'i'))[1] + ); +end; +$function$; + +-- handle_company_saved: set search_path='public' (no changes to function calls needed) +-- Drop the trigger first, then the function +DROP TRIGGER IF EXISTS company_saved ON public.companies; +DROP FUNCTION IF EXISTS public.handle_company_saved(); + +CREATE FUNCTION public.handle_company_saved() +RETURNS trigger +LANGUAGE plpgsql +SET search_path TO 'public' +AS $function$ +declare company_logo text; + +begin + if new.logo is not null then + return new; + end if; + + company_logo = get_domain_favicon(new.website); + if company_logo is null then + return new; + end if; + + new.logo = concat('{"src":"', company_logo, '","title":"Company favicon"}'); + return new; +end; +$function$; + +-- Recreate the trigger +CREATE TRIGGER company_saved BEFORE INSERT OR UPDATE ON public.companies FOR EACH ROW EXECUTE FUNCTION public.handle_company_saved(); + +-- set_sales_id_default: set search_path='public' (no changes to table references needed) +-- Drop all triggers that depend on this function first +DROP TRIGGER IF EXISTS set_task_sales_id_trigger ON public.tasks; +DROP TRIGGER IF EXISTS set_contact_sales_id_trigger ON public.contacts; +DROP TRIGGER IF EXISTS set_contact_notes_sales_id_trigger ON public.contact_notes; +DROP TRIGGER IF EXISTS set_company_sales_id_trigger ON public.companies; +DROP TRIGGER IF EXISTS set_deal_sales_id_trigger ON public.deals; +DROP TRIGGER IF EXISTS set_deal_notes_sales_id_trigger ON public.deal_notes; + +DROP FUNCTION IF EXISTS public.set_sales_id_default(); + +CREATE FUNCTION public.set_sales_id_default() +RETURNS TRIGGER +LANGUAGE plpgsql +SET search_path TO 'public' +AS $$ +BEGIN + IF NEW.sales_id IS NULL THEN + SELECT id INTO NEW.sales_id FROM sales WHERE user_id = auth.uid(); + END IF; + RETURN NEW; +END; +$$; + +-- Recreate all triggers +CREATE TRIGGER set_task_sales_id_trigger +BEFORE INSERT ON public.tasks +FOR EACH ROW +EXECUTE FUNCTION public.set_sales_id_default(); + +CREATE TRIGGER set_contact_sales_id_trigger +BEFORE INSERT ON public.contacts +FOR EACH ROW +EXECUTE FUNCTION public.set_sales_id_default(); + +CREATE TRIGGER set_contact_notes_sales_id_trigger +BEFORE INSERT ON public.contact_notes +FOR EACH ROW +EXECUTE FUNCTION public.set_sales_id_default(); + +CREATE TRIGGER set_company_sales_id_trigger +BEFORE INSERT ON public.companies +FOR EACH ROW +EXECUTE FUNCTION public.set_sales_id_default(); + +CREATE TRIGGER set_deal_sales_id_trigger +BEFORE INSERT ON public.deals +FOR EACH ROW +EXECUTE FUNCTION public.set_sales_id_default(); + +CREATE TRIGGER set_deal_notes_sales_id_trigger +BEFORE INSERT ON public.deal_notes +FOR EACH ROW +EXECUTE FUNCTION public.set_sales_id_default(); + +-- merge_contacts: set search_path='public' (no changes to table references needed) +DROP FUNCTION IF EXISTS public.merge_contacts(bigint, bigint); + +CREATE FUNCTION public.merge_contacts(loser_id bigint, winner_id bigint) +RETURNS bigint +LANGUAGE plpgsql +SECURITY INVOKER +SET search_path TO 'public' +AS $$ +DECLARE + winner_contact contacts%ROWTYPE; + loser_contact contacts%ROWTYPE; + deal_record RECORD; + merged_emails jsonb; + merged_phones jsonb; + merged_tags bigint[]; + winner_emails jsonb; + loser_emails jsonb; + winner_phones jsonb; + loser_phones jsonb; + email_map jsonb; + phone_map jsonb; +BEGIN + -- Fetch both contacts + SELECT * INTO winner_contact FROM contacts WHERE id = winner_id; + SELECT * INTO loser_contact FROM contacts WHERE id = loser_id; + + IF winner_contact IS NULL OR loser_contact IS NULL THEN + RAISE EXCEPTION 'Contact not found'; + END IF; + + -- 1. Reassign tasks from loser to winner + UPDATE tasks SET contact_id = winner_id WHERE contact_id = loser_id; + + -- 2. Reassign contact notes from loser to winner + UPDATE contact_notes SET contact_id = winner_id WHERE contact_id = loser_id; + + -- 3. Update deals - replace loser with winner in contact_ids array + FOR deal_record IN + SELECT id, contact_ids + FROM deals + WHERE contact_ids @> ARRAY[loser_id] + LOOP + UPDATE deals + SET contact_ids = ( + SELECT ARRAY( + SELECT DISTINCT unnest( + array_remove(deal_record.contact_ids, loser_id) || ARRAY[winner_id] + ) + ) + ) + WHERE id = deal_record.id; + END LOOP; + + -- 4. Merge contact data + + -- Get email arrays + winner_emails := COALESCE(winner_contact.email_jsonb, '[]'::jsonb); + loser_emails := COALESCE(loser_contact.email_jsonb, '[]'::jsonb); + + -- Merge emails with deduplication by email address + -- Build a map of email -> email object, then convert back to array + email_map := '{}'::jsonb; + + -- Add winner emails to map + IF jsonb_array_length(winner_emails) > 0 THEN + FOR i IN 0..jsonb_array_length(winner_emails)-1 LOOP + email_map := email_map || jsonb_build_object( + winner_emails->i->>'email', + winner_emails->i + ); + END LOOP; + END IF; + + -- Add loser emails to map (won't overwrite existing keys) + IF jsonb_array_length(loser_emails) > 0 THEN + FOR i IN 0..jsonb_array_length(loser_emails)-1 LOOP + IF NOT email_map ? (loser_emails->i->>'email') THEN + email_map := email_map || jsonb_build_object( + loser_emails->i->>'email', + loser_emails->i + ); + END IF; + END LOOP; + END IF; + + -- Convert map back to array + merged_emails := (SELECT jsonb_agg(value) FROM jsonb_each(email_map)); + merged_emails := COALESCE(merged_emails, '[]'::jsonb); + + -- Get phone arrays + winner_phones := COALESCE(winner_contact.phone_jsonb, '[]'::jsonb); + loser_phones := COALESCE(loser_contact.phone_jsonb, '[]'::jsonb); + + -- Merge phones with deduplication by number + phone_map := '{}'::jsonb; + + -- Add winner phones to map + IF jsonb_array_length(winner_phones) > 0 THEN + FOR i IN 0..jsonb_array_length(winner_phones)-1 LOOP + phone_map := phone_map || jsonb_build_object( + winner_phones->i->>'number', + winner_phones->i + ); + END LOOP; + END IF; + + -- Add loser phones to map (won't overwrite existing keys) + IF jsonb_array_length(loser_phones) > 0 THEN + FOR i IN 0..jsonb_array_length(loser_phones)-1 LOOP + IF NOT phone_map ? (loser_phones->i->>'number') THEN + phone_map := phone_map || jsonb_build_object( + loser_phones->i->>'number', + loser_phones->i + ); + END IF; + END LOOP; + END IF; + + -- Convert map back to array + merged_phones := (SELECT jsonb_agg(value) FROM jsonb_each(phone_map)); + merged_phones := COALESCE(merged_phones, '[]'::jsonb); + + -- Merge tags (remove duplicates) + merged_tags := ARRAY( + SELECT DISTINCT unnest( + COALESCE(winner_contact.tags, ARRAY[]::bigint[]) || + COALESCE(loser_contact.tags, ARRAY[]::bigint[]) + ) + ); + + -- 5. Update winner with merged data + UPDATE contacts SET + avatar = COALESCE(winner_contact.avatar, loser_contact.avatar), + gender = COALESCE(winner_contact.gender, loser_contact.gender), + first_name = COALESCE(winner_contact.first_name, loser_contact.first_name), + last_name = COALESCE(winner_contact.last_name, loser_contact.last_name), + title = COALESCE(winner_contact.title, loser_contact.title), + company_id = COALESCE(winner_contact.company_id, loser_contact.company_id), + email_jsonb = merged_emails, + phone_jsonb = merged_phones, + linkedin_url = COALESCE(winner_contact.linkedin_url, loser_contact.linkedin_url), + background = COALESCE(winner_contact.background, loser_contact.background), + has_newsletter = COALESCE(winner_contact.has_newsletter, loser_contact.has_newsletter), + first_seen = LEAST(COALESCE(winner_contact.first_seen, loser_contact.first_seen), COALESCE(loser_contact.first_seen, winner_contact.first_seen)), + last_seen = GREATEST(COALESCE(winner_contact.last_seen, loser_contact.last_seen), COALESCE(loser_contact.last_seen, winner_contact.last_seen)), + sales_id = COALESCE(winner_contact.sales_id, loser_contact.sales_id), + tags = merged_tags + WHERE id = winner_id; + + -- 6. Delete loser contact + DELETE FROM contacts WHERE id = loser_id; + + RETURN winner_id; +END; +$$; + +-- Move pg_net extension to extensions schema (security requirement) +-- pg_net doesn't support ALTER EXTENSION SET SCHEMA, so drop and recreate +DROP EXTENSION IF EXISTS pg_net CASCADE; +-- Port: guarded — as in 20260304104600_note_attachments_trigger +DO $$ +BEGIN + CREATE EXTENSION IF NOT EXISTS pg_net WITH SCHEMA extensions; +EXCEPTION WHEN feature_not_supported OR undefined_file THEN + RAISE NOTICE 'skipped, not installed on this server: CREATE EXTENSION IF NOT EXISTS pg_net WITH SCHEMA extensions'; +END $$; + diff --git a/packages/db/src/migrations/20260314120000_activity_log_view/up.sql b/packages/db/src/migrations/20260314120000_activity_log_view/up.sql new file mode 100644 index 0000000..a80f7ed --- /dev/null +++ b/packages/db/src/migrations/20260314120000_activity_log_view/up.sql @@ -0,0 +1,79 @@ +-- Create a view that aggregates all activity events into a single, pageable list. +-- Each row represents one event (company created, contact created, note created, etc.) +-- sorted by date so PostgREST can paginate with Range headers. + +create view "public"."activity_log" + with (security_invoker=on) + as +SELECT + 'company.' || c.id || '.created' as id, + 'company.created' as type, + c.created_at as date, + c.id as company_id, + c.sales_id, + to_json(c.*) as company, + NULL::json as contact, + NULL::json as deal, + NULL::json as contact_note, + NULL::json as deal_note +FROM companies c +UNION ALL +SELECT + 'contact.' || co.id || '.created', + 'contact.created', + co.first_seen, + co.company_id, + co.sales_id, + NULL::json, + to_json(co.*), + NULL::json, + NULL::json, + NULL::json +FROM contacts co +UNION ALL +SELECT + 'contactNote.' || cn.id || '.created', + 'contactNote.created', + cn.date, + co.company_id, + cn.sales_id, + NULL::json, + NULL::json, + NULL::json, + to_json(cn.*), + NULL::json +FROM contact_notes cn +LEFT JOIN contacts co ON co.id = cn.contact_id +UNION ALL +SELECT + 'deal.' || d.id || '.created', + 'deal.created', + d.created_at, + d.company_id, + d.sales_id, + NULL::json, + NULL::json, + to_json(d.*), + NULL::json, + NULL::json +FROM deals d +UNION ALL +SELECT + 'dealNote.' || dn.id || '.created', + 'dealNote.created', + dn.date, + d.company_id, + dn.sales_id, + NULL::json, + NULL::json, + NULL::json, + NULL::json, + to_json(dn.*) +FROM deal_notes dn +LEFT JOIN deals d ON d.id = dn.deal_id; + +-- Indexes to support filtering the view by company_id efficiently +CREATE INDEX ON contacts (company_id); +CREATE INDEX ON deals (company_id); +CREATE INDEX ON contact_notes (contact_id); +CREATE INDEX ON deal_notes (deal_id); diff --git a/packages/db/src/migrations/20260320120000_lowercase_email_website/up.sql b/packages/db/src/migrations/20260320120000_lowercase_email_website/up.sql new file mode 100644 index 0000000..9822084 --- /dev/null +++ b/packages/db/src/migrations/20260320120000_lowercase_email_website/up.sql @@ -0,0 +1,86 @@ +-- Enable citext extension for case-insensitive text columns +CREATE EXTENSION IF NOT EXISTS "citext" WITH SCHEMA "extensions"; + +-- Drop view that depends on companies.website before altering the column type +DROP VIEW IF EXISTS public.companies_summary; + +-- Change companies.website to citext for case-insensitive comparisons +ALTER TABLE companies ALTER COLUMN website TYPE extensions.citext; + +-- Recreate companies_summary view +CREATE OR REPLACE VIEW public.companies_summary WITH (security_invoker = on) AS +SELECT + c.id, + c.created_at, + c.name, + c.sector, + c.size, + c.linkedin_url, + c.website, + c.phone_number, + c.address, + c.zipcode, + c.city, + c.state_abbr, + c.sales_id, + c.context_links, + c.country, + c.description, + c.revenue, + c.tax_identifier, + c.logo, + count(distinct d.id) as nb_deals, + count(distinct co.id) as nb_contacts +FROM public.companies c + LEFT JOIN public.deals d ON c.id = d.company_id + LEFT JOIN public.contacts co ON c.id = co.company_id +GROUP BY c.id; + +-- Change sales.email to citext for case-insensitive comparisons +ALTER TABLE sales ALTER COLUMN email TYPE extensions.citext; + +-- Function to lowercase email addresses in email_jsonb +CREATE OR REPLACE FUNCTION lowercase_email_jsonb() +RETURNS TRIGGER +LANGUAGE plpgsql +SET search_path TO 'public' +AS $$ +BEGIN + IF NEW.email_jsonb IS NOT NULL THEN + NEW.email_jsonb = COALESCE(( + SELECT jsonb_agg( + jsonb_set(elem, '{email}', to_jsonb(LOWER(elem->>'email'))) + ) + FROM jsonb_array_elements(NEW.email_jsonb) AS elem + ), '[]'::jsonb); + END IF; + RETURN NEW; +END; +$$; + +-- Drop and recreate triggers to ensure proper ordering +-- Lowercase trigger for email_jsonb must run before the avatar trigger + +-- Drop existing triggers +DROP TRIGGER IF EXISTS contact_saved ON contacts; + +-- Create lowercase trigger first (so it runs before contact_saved) +CREATE TRIGGER "10_lowercase_contact_emails" + BEFORE INSERT OR UPDATE ON contacts + FOR EACH ROW + EXECUTE FUNCTION lowercase_email_jsonb(); + +-- Recreate contact_saved trigger (will run after lowercase_contact_emails) +CREATE TRIGGER "20_contact_saved" + BEFORE INSERT OR UPDATE ON contacts + FOR EACH ROW + EXECUTE FUNCTION handle_contact_saved(); + +UPDATE contacts +SET email_jsonb = COALESCE(( + SELECT jsonb_agg( + jsonb_set(elem, '{email}', to_jsonb(LOWER(elem->>'email'))) + ) + FROM jsonb_array_elements(email_jsonb) AS elem +), '[]'::jsonb) +WHERE email_jsonb IS NOT NULL; diff --git a/packages/db/src/migrations/20260601120000_grant_init_state_to_api_roles/up.sql b/packages/db/src/migrations/20260601120000_grant_init_state_to_api_roles/up.sql new file mode 100644 index 0000000..3379eed --- /dev/null +++ b/packages/db/src/migrations/20260601120000_grant_init_state_to_api_roles/up.sql @@ -0,0 +1,33 @@ +-- The CRM's public views (activity_log, companies_summary, contacts_summary +-- and init_state) are queried through the Supabase Data API by the anon and +-- authenticated roles. `init_state` in particular is read by the anon role +-- *before* login (see src/components/atomic-crm/providers/supabase/authProvider.ts) +-- to decide whether the CRM has already been initialized. +-- +-- Unlike the tables -- whose grants were captured in earlier migrations -- these +-- views never had explicit grants in a migration: they were reachable only +-- because Supabase used to grant every object in the `public` schema to the +-- anon/authenticated/service_role API roles automatically. That behavior has +-- been removed: objects are no longer exposed to the Data/GraphQL API unless +-- access is granted explicitly. +-- https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically +-- +-- These grants are already declared in supabase/schemas/06_grants.sql (the +-- source of truth) but were never applied through a migration. Re-declare them +-- explicitly so production keeps exposing the views. + +grant all on table public.activity_log to anon; +grant all on table public.activity_log to authenticated; +grant all on table public.activity_log to service_role; + +grant all on table public.companies_summary to anon; +grant all on table public.companies_summary to authenticated; +grant all on table public.companies_summary to service_role; + +grant all on table public.contacts_summary to anon; +grant all on table public.contacts_summary to authenticated; +grant all on table public.contacts_summary to service_role; + +grant all on table public.init_state to anon; +grant all on table public.init_state to authenticated; +grant all on table public.init_state to service_role; diff --git a/packages/db/src/migrations/20260811131131_sales_secondary_emails/up.sql b/packages/db/src/migrations/20260811131131_sales_secondary_emails/up.sql new file mode 100644 index 0000000..2f78a20 --- /dev/null +++ b/packages/db/src/migrations/20260811131131_sales_secondary_emails/up.sql @@ -0,0 +1,3 @@ +alter table "public"."sales" add column "secondary_emails" jsonb not null default '[]'::jsonb; + +alter table "public"."sales" add constraint "sales_secondary_emails_is_array" check (jsonb_typeof(secondary_emails) = 'array'); diff --git a/packages/db/src/migrations/20260924120000_deals_lost_reason/up.sql b/packages/db/src/migrations/20260924120000_deals_lost_reason/up.sql new file mode 100644 index 0000000..f869850 --- /dev/null +++ b/packages/db/src/migrations/20260924120000_deals_lost_reason/up.sql @@ -0,0 +1 @@ +alter table "public"."deals" add column "lost_reason" text; diff --git a/packages/db/src/migrations/20260928120000_drop_deals_lost_reason/up.sql b/packages/db/src/migrations/20260928120000_drop_deals_lost_reason/up.sql new file mode 100644 index 0000000..215c482 --- /dev/null +++ b/packages/db/src/migrations/20260928120000_drop_deals_lost_reason/up.sql @@ -0,0 +1 @@ +alter table "public"."deals" drop column "lost_reason"; diff --git a/packages/db/src/migrations/20260929120000_remove_deleted_tag_from_contacts/up.sql b/packages/db/src/migrations/20260929120000_remove_deleted_tag_from_contacts/up.sql new file mode 100644 index 0000000..97a1cd9 --- /dev/null +++ b/packages/db/src/migrations/20260929120000_remove_deleted_tag_from_contacts/up.sql @@ -0,0 +1,53 @@ +set check_function_bodies = off; + +CREATE OR REPLACE FUNCTION public.handle_tag_deleted() + RETURNS trigger + LANGUAGE plpgsql + SET search_path TO '' +AS $function$ +begin + update public.contacts set tags = array_remove(tags, old.id) where tags @> array[old.id]; + return old; +end; +$function$ +; + +CREATE TRIGGER on_tag_deleted AFTER DELETE ON public.tags FOR EACH ROW EXECUTE FUNCTION public.handle_tag_deleted(); + +CREATE OR REPLACE FUNCTION "public"."handle_contact_saved"() RETURNS "trigger" + LANGUAGE "plpgsql" + SET "search_path" TO 'public' + AS $$declare contact_avatar text; +declare emails_length int8; +declare item jsonb; + +begin + if new.avatar is not null then + return new; + end if; + + if tg_op = 'UPDATE' and new.email_jsonb is not distinct from old.email_jsonb then + return new; + end if; + + select coalesce(jsonb_array_length(new.email_jsonb), 0) into emails_length; + + if emails_length = 0 then + return new; + end if; + + for item in select jsonb_array_elements(new.email_jsonb) + loop + select public.get_avatar_for_email(item->>'email') into contact_avatar; + if (contact_avatar is not null) then + exit; + end if; + end loop; + + if contact_avatar is null then + return new; + end if; + + new.avatar = concat('{"src":"', contact_avatar, '"}'); + return new; +end;$$; diff --git a/packages/db/src/migrations/20261010054346_global_search/up.sql b/packages/db/src/migrations/20261010054346_global_search/up.sql new file mode 100644 index 0000000..52bd782 --- /dev/null +++ b/packages/db/src/migrations/20261010054346_global_search/up.sql @@ -0,0 +1,285 @@ +alter table "public"."tasks" add column "created_at" timestamp with time zone not null default now(); + +-- Existing rows have no creation time to recover, so fall back to the best +-- available proxy: when the task was completed, a due date that has already +-- passed, or the contact's first_seen. `least(..., now())` keeps the result in +-- the past -- global_search sorts on this column, and a future date would put +-- every open task above every note, contact and deal. A bare `now()` would be +-- no better: it would tie every open task at the top of that same sort. +update "public"."tasks" t +set "created_at" = least( + coalesce( + t."done_date", + case when t."due_date" < now() then t."due_date" end, + c."first_seen" + ), + now() +) +from "public"."contacts" c +where c."id" = t."contact_id"; + +create extension if not exists "unaccent" with schema "extensions"; + +-- unaccent() is only STABLE (its dictionary could change), which generated +-- columns reject. The dictionary is fixed here, so the wrapper is immutable. +create or replace function public.search_unaccent(value text) returns text + language sql immutable strict parallel safe + set search_path to '' + as $$ select extensions.unaccent('extensions.unaccent'::regdictionary, value) $$; + +-- Documents and queries are normalized the same way: unaccented, lowercased, +-- split on anything that is not a letter or a digit. So "hélène.dupont@acme.fr" +-- indexes as helene, dupont, acme, fr and any of those prefixes finds it. +create or replace function public.search_document(variadic parts text[]) returns tsvector + language sql immutable parallel safe + set search_path to '' + as $$ + select to_tsvector( + 'simple'::regconfig, + regexp_replace(public.search_unaccent(array_to_string(parts, ' ')), '[^[:alnum:]]+', ' ', 'g') + ) + $$; + +-- Every word of the query must match, each one as a prefix: "tho dup" finds +-- "Thomas Dupont". Returns null (matching nothing) for a blank query. +create or replace function public.search_query(query text) returns tsquery + language sql immutable strict parallel safe + set search_path to '' + as $$ + select to_tsquery('simple'::regconfig, string_agg(word || ':*', ' & ')) + from regexp_split_to_table(lower(public.search_unaccent(query)), '[^[:alnum:]]+') as word + where word <> '' + $$; + +create or replace function public.search_attachment_titles(attachments jsonb[]) returns text + language sql immutable parallel safe + set search_path to '' + as $$ select string_agg(attachment ->> 'title', ' ') from unnest(attachments) as attachment $$; + +alter table public.companies add column fts tsvector generated always as ( + public.search_document(name, sector, description, website::text, phone_number, zipcode, city, state_abbr) +) stored; + +alter table public.contacts add column fts tsvector generated always as ( + public.search_document( + first_name, + last_name, + title, + background, + jsonb_path_query_array(email_jsonb, '$[*]."email"')::text, + jsonb_path_query_array(phone_jsonb, '$[*]."number"')::text + ) +) stored; + +alter table public.deals add column fts tsvector generated always as ( + public.search_document(name, category, description) +) stored; + +alter table public.tasks add column fts tsvector generated always as ( + public.search_document(text, type) +) stored; + +alter table public.contact_notes add column fts tsvector generated always as ( + public.search_document(text, public.search_attachment_titles(attachments)) +) stored; + +alter table public.deal_notes add column fts tsvector generated always as ( + public.search_document(text, public.search_attachment_titles(attachments)) +) stored; + +-- Partial indexes mirror what global_search() returns: open tasks, live deals. +create index companies_fts_idx on public.companies using gin (fts); +create index contacts_fts_idx on public.contacts using gin (fts); +create index deals_fts_idx on public.deals using gin (fts) where archived_at is null; +create index tasks_fts_idx on public.tasks using gin (fts) where done_date is null; +create index contact_notes_fts_idx on public.contact_notes using gin (fts); +create index deal_notes_fts_idx on public.deal_notes using gin (fts); + +-- A word found in most rows (a common word, a 2-letter prefix) makes the GIN +-- path fetch and sort every match. Walking a date index backwards instead stops +-- at the first max_results matches. The planner picks between the two per +-- query, which needs fine-grained lexeme statistics on the large tables. +create index contacts_first_seen_idx on public.contacts using btree (first_seen desc nulls last); +create index tasks_open_created_at_idx on public.tasks using btree (created_at desc) where done_date is null; +create index contact_notes_date_idx on public.contact_notes using btree (date desc nulls last); +create index deal_notes_date_idx on public.deal_notes using btree (date desc nulls last); + +alter table public.contacts alter column fts set statistics 10000; +alter table public.tasks alter column fts set statistics 10000; +alter table public.contact_notes alter column fts set statistics 10000; +alter table public.deal_notes alter column fts set statistics 10000; + +-- Each branch takes its own newest max_results matches (at most 200), so the +-- union never holds more than 6 * max_results rows, and the lookups that build +-- display labels only run on those. `content` carries the searched fields in +-- their original form, so the client can show and highlight where the words +-- matched. The SQL is built per call with the tsquery inlined as a literal: +-- with a parameter the planner could not tell a rare word (use the GIN index) +-- from a common one (walk the date index). +create or replace function public.global_search( + query text, + resources text[] default null, + max_results integer default 50 +) returns table ( + resource text, + record_id bigint, + title text, + subtitle text, + contact_id bigint, + deal_id bigint, + date timestamp with time zone, + content text +) + language plpgsql stable security invoker + set search_path to '' + as $$ +declare + tsq tsquery := public.search_query(query); + branch_templates constant jsonb := jsonb_build_object( + 'companies', $q$ + select 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at, + concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr) + from public.companies c + where c.fts @@ %1$L::tsquery + order by c.created_at desc + limit %2$s $q$, + 'contacts', $q$ + select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name), + (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen, + concat_ws(' · ', co.title, co.background, + (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e), + (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)) + from public.contacts co + where co.fts @@ %1$L::tsquery + order by co.first_seen desc nulls last + limit %2$s $q$, + 'deals', $q$ + select 'deals', d.id, d.name, + (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at, + concat_ws(' · ', d.category, d.description) + from public.deals d + where d.archived_at is null and d.fts @@ %1$L::tsquery + order by d.created_at desc + limit %2$s $q$, + 'tasks', $q$ + select 'tasks', t.id, left(t.text, 200), + (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id), + t.contact_id, null::bigint, t.created_at, + concat_ws(' · ', t.text, t.type) + from public.tasks t + where t.done_date is null and t.fts @@ %1$L::tsquery + order by t.created_at desc + limit %2$s $q$, + 'contact_notes', $q$ + select 'contact_notes', cn.id, left(cn.text, 200), + (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id), + cn.contact_id, null::bigint, cn.date, + concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)) + from public.contact_notes cn + where cn.fts @@ %1$L::tsquery + order by cn.date desc nulls last + limit %2$s $q$, + 'deal_notes', $q$ + select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date, + concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)) + from public.deal_notes dn + join public.deals nd on nd.id = dn.deal_id + where nd.archived_at is null and dn.fts @@ %1$L::tsquery + order by dn.date desc nulls last + limit %2$s $q$ + ); + row_limit constant integer := least(coalesce(max_results, 50), 200); + branches text[]; +begin + if tsq is null or row_limit < 1 then + return; + end if; + + select array_agg(format('(%s)', format(template, tsq::text, row_limit))) + into branches + from jsonb_each_text(branch_templates) as b(name, template) + where resources is null or b.name = any(resources); + + if branches is null then + return; + end if; + + return query execute format( + 'select * from (%s) results order by 7 desc nulls last limit %s', + array_to_string(branches, ' union all '), + row_limit + ); +end +$$; + +revoke execute on function public.global_search(text, text[], integer) from public, anon; +grant execute on function public.global_search(text, text[], integer) to authenticated, service_role; + +-- The activity log serializes whole rows: keep the search vectors out of them. +create or replace view public.activity_log with (security_invoker = on) as +select + ('company.' || c.id || '.created') as id, + 'company.created' as type, + c.created_at as date, + c.id as company_id, + c.sales_id, + (to_jsonb(c.*) - 'fts')::json as company, + null::json as contact, + null::json as deal, + null::json as contact_note, + null::json as deal_note +from public.companies c +union all +select + ('contact.' || co.id || '.created') as id, + 'contact.created' as type, + co.first_seen as date, + co.company_id, + co.sales_id, + null::json as company, + (to_jsonb(co.*) - 'fts')::json as contact, + null::json as deal, + null::json as contact_note, + null::json as deal_note +from public.contacts co +union all +select + ('contactNote.' || cn.id || '.created') as id, + 'contactNote.created' as type, + cn.date, + co.company_id, + cn.sales_id, + null::json as company, + null::json as contact, + null::json as deal, + (to_jsonb(cn.*) - 'fts')::json as contact_note, + null::json as deal_note +from public.contact_notes cn + left join public.contacts co on co.id = cn.contact_id +union all +select + ('deal.' || d.id || '.created') as id, + 'deal.created' as type, + d.created_at as date, + d.company_id, + d.sales_id, + null::json as company, + null::json as contact, + (to_jsonb(d.*) - 'fts')::json as deal, + null::json as contact_note, + null::json as deal_note +from public.deals d +union all +select + ('dealNote.' || dn.id || '.created') as id, + 'dealNote.created' as type, + dn.date, + d.company_id, + dn.sales_id, + null::json as company, + null::json as contact, + null::json as deal, + null::json as contact_note, + (to_jsonb(dn.*) - 'fts')::json as deal_note +from public.deal_notes dn + left join public.deals d on d.id = dn.deal_id; diff --git a/packages/db/src/migrations/20261022120000_global_search_per_resource_cap/up.sql b/packages/db/src/migrations/20261022120000_global_search_per_resource_cap/up.sql new file mode 100644 index 0000000..d0f5100 --- /dev/null +++ b/packages/db/src/migrations/20261022120000_global_search_per_resource_cap/up.sql @@ -0,0 +1,84 @@ +-- Cap global_search results per resource instead of overall, so newer notes +-- that mention a name no longer crowd the matching contact out of the results. + +CREATE OR REPLACE FUNCTION "public"."global_search"("query" "text", "resources" "text"[] DEFAULT NULL::"text"[], "max_results" integer DEFAULT 50) RETURNS TABLE("resource" "text", "record_id" bigint, "title" "text", "subtitle" "text", "contact_id" bigint, "deal_id" bigint, "date" timestamp with time zone, "content" "text") + LANGUAGE "plpgsql" STABLE + SET "search_path" TO '' + AS $_$ +declare + tsq tsquery := public.search_query(query); + branch_templates constant jsonb := jsonb_build_object( + 'companies', $q$ + select 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at, + concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr) + from public.companies c + where c.fts @@ %1$L::tsquery + order by c.created_at desc + limit %2$s $q$, + 'contacts', $q$ + select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name), + (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen, + concat_ws(' · ', co.title, co.background, + (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e), + (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)) + from public.contacts co + where co.fts @@ %1$L::tsquery + order by co.first_seen desc nulls last + limit %2$s $q$, + 'deals', $q$ + select 'deals', d.id, d.name, + (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at, + concat_ws(' · ', d.category, d.description) + from public.deals d + where d.archived_at is null and d.fts @@ %1$L::tsquery + order by d.created_at desc + limit %2$s $q$, + 'tasks', $q$ + select 'tasks', t.id, left(t.text, 200), + (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id), + t.contact_id, null::bigint, t.created_at, + concat_ws(' · ', t.text, t.type) + from public.tasks t + where t.done_date is null and t.fts @@ %1$L::tsquery + order by t.created_at desc + limit %2$s $q$, + 'contact_notes', $q$ + select 'contact_notes', cn.id, left(cn.text, 200), + (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id), + cn.contact_id, null::bigint, cn.date, + concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)) + from public.contact_notes cn + where cn.fts @@ %1$L::tsquery + order by cn.date desc nulls last + limit %2$s $q$, + 'deal_notes', $q$ + select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date, + concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)) + from public.deal_notes dn + join public.deals nd on nd.id = dn.deal_id + where nd.archived_at is null and dn.fts @@ %1$L::tsquery + order by dn.date desc nulls last + limit %2$s $q$ + ); + row_limit constant integer := least(coalesce(max_results, 50), 200); + branches text[]; +begin + if tsq is null or row_limit < 1 then + return; + end if; + + select array_agg(format('(%s)', format(template, tsq::text, row_limit))) + into branches + from jsonb_each_text(branch_templates) as b(name, template) + where resources is null or b.name = any(resources); + + if branches is null then + return; + end if; + + return query execute format( + 'select * from (%s) results order by 7 desc nulls last', + array_to_string(branches, ' union all ') + ); +end +$_$; diff --git a/packages/db/src/migrations/20261026120000_deal_categories/up.sql b/packages/db/src/migrations/20261026120000_deal_categories/up.sql new file mode 100644 index 0000000..ca10a6c --- /dev/null +++ b/packages/db/src/migrations/20261026120000_deal_categories/up.sql @@ -0,0 +1,97 @@ +-- deals.fts is generated from category, so it is dropped before the swap and +-- rebuilt from categories, and global_search() is updated to read categories. +alter table "public"."deals" drop column "fts"; + +alter table "public"."deals" add column "categories" text[]; + +update "public"."deals" set "categories" = array["category"] where "category" is not null; + +alter table "public"."deals" drop column "category"; + +alter table public.deals add column fts tsvector generated always as ( + public.search_document(variadic array[name, description] || categories) +) stored; + +create index deals_fts_idx on public.deals using gin (fts) where archived_at is null; + +CREATE OR REPLACE FUNCTION "public"."global_search"("query" "text", "resources" "text"[] DEFAULT NULL::"text"[], "max_results" integer DEFAULT 50) RETURNS TABLE("resource" "text", "record_id" bigint, "title" "text", "subtitle" "text", "contact_id" bigint, "deal_id" bigint, "date" timestamp with time zone, "content" "text") + LANGUAGE "plpgsql" STABLE + SET "search_path" TO '' + AS $_$ +declare + tsq tsquery := public.search_query(query); + branch_templates constant jsonb := jsonb_build_object( + 'companies', $q$ + select 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at, + concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr) + from public.companies c + where c.fts @@ %1$L::tsquery + order by c.created_at desc + limit %2$s $q$, + 'contacts', $q$ + select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name), + (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen, + concat_ws(' · ', co.title, co.background, + (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e), + (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)) + from public.contacts co + where co.fts @@ %1$L::tsquery + order by co.first_seen desc nulls last + limit %2$s $q$, + 'deals', $q$ + select 'deals', d.id, d.name, + (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at, + concat_ws(' · ', variadic d.categories || d.description) + from public.deals d + where d.archived_at is null and d.fts @@ %1$L::tsquery + order by d.created_at desc + limit %2$s $q$, + 'tasks', $q$ + select 'tasks', t.id, left(t.text, 200), + (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id), + t.contact_id, null::bigint, t.created_at, + concat_ws(' · ', t.text, t.type) + from public.tasks t + where t.done_date is null and t.fts @@ %1$L::tsquery + order by t.created_at desc + limit %2$s $q$, + 'contact_notes', $q$ + select 'contact_notes', cn.id, left(cn.text, 200), + (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id), + cn.contact_id, null::bigint, cn.date, + concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)) + from public.contact_notes cn + where cn.fts @@ %1$L::tsquery + order by cn.date desc nulls last + limit %2$s $q$, + 'deal_notes', $q$ + select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date, + concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)) + from public.deal_notes dn + join public.deals nd on nd.id = dn.deal_id + where nd.archived_at is null and dn.fts @@ %1$L::tsquery + order by dn.date desc nulls last + limit %2$s $q$ + ); + row_limit constant integer := least(coalesce(max_results, 50), 200); + branches text[]; +begin + if tsq is null or row_limit < 1 then + return; + end if; + + select array_agg(format('(%s)', format(template, tsq::text, row_limit))) + into branches + from jsonb_each_text(branch_templates) as b(name, template) + where resources is null or b.name = any(resources); + + if branches is null then + return; + end if; + + return query execute format( + 'select * from (%s) results order by 7 desc nulls last', + array_to_string(branches, ' union all ') + ); +end +$_$; diff --git a/packages/db/src/migrations/20261101000000_seed/up.sql b/packages/db/src/migrations/20261101000000_seed/up.sql new file mode 100644 index 0000000..45b10ef --- /dev/null +++ b/packages/db/src/migrations/20261101000000_seed/up.sql @@ -0,0 +1,105 @@ +-- Port: upstream's supabase/seed.sql, which its remote setup applies with +-- `supabase db push --include-seed`: the mail domains that get no favicon. +INSERT INTO favicons_excluded_domains (domain) VALUES + ('gmail.com'), + ('yahoo.com'), + ('hotmail.com'), + ('aol.com'), + ('hotmail.co.uk'), + ('hotmail.fr'), + ('msn.com'), + ('yahoo.fr'), + ('wanadoo.fr'), + ('orange.fr'), + ('comcast.net'), + ('yahoo.co.uk'), + ('yahoo.com.br'), + ('yahoo.co.in'), + ('live.com'), + ('rediffmail.com'), + ('free.fr'), + ('gmx.de'), + ('web.de'), + ('yandex.ru'), + ('ymail.com'), + ('libero.it'), + ('outlook.com'), + ('uol.com.br'), + ('bol.com.br'), + ('mail.ru'), + ('cox.net'), + ('hotmail.it'), + ('sbcglobal.net'), + ('sfr.fr'), + ('live.fr'), + ('verizon.net'), + ('live.co.uk'), + ('googlemail.com'), + ('yahoo.es'), + ('ig.com.br'), + ('live.nl'), + ('bigpond.com'), + ('terra.com.br'), + ('yahoo.it'), + ('neuf.fr'), + ('yahoo.de'), + ('alice.it'), + ('rocketmail.com'), + ('att.net'), + ('laposte.net'), + ('facebook.com'), + ('bellsouth.net'), + ('yahoo.in'), + ('hotmail.es'), + ('charter.net'), + ('yahoo.ca'), + ('yahoo.com.au'), + ('rambler.ru'), + ('hotmail.de'), + ('tiscali.it'), + ('shaw.ca'), + ('yahoo.co.jp'), + ('sky.com'), + ('earthlink.net'), + ('optonline.net'), + ('freenet.de'), + ('t-online.de'), + ('aliceadsl.fr'), + ('virgilio.it'), + ('home.nl'), + ('qq.com'), + ('telenet.be'), + ('me.com'), + ('yahoo.com.ar'), + ('tiscali.co.uk'), + ('yahoo.com.mx'), + ('voila.fr'), + ('gmx.net'), + ('mail.com'), + ('planet.nl'), + ('tin.it'), + ('live.it'), + ('ntlworld.com'), + ('arcor.de'), + ('yahoo.co.id'), + ('frontiernet.net'), + ('hetnet.nl'), + ('live.com.au'), + ('yahoo.com.sg'), + ('zonnet.nl'), + ('club-internet.fr'), + ('juno.com'), + ('optusnet.com.au'), + ('blueyonder.co.uk'), + ('bluewin.ch'), + ('skynet.be'), + ('sympatico.ca'), + ('windstream.net'), + ('mac.com'), + ('centurytel.net'), + ('chello.nl'), + ('live.ca'), + ('aim.com'), + ('bigpond.net.au'), + ('online.de'), + ('apple.com'); diff --git a/packages/db/src/migrations/20261101000100_note_attachments_outbox/up.sql b/packages/db/src/migrations/20261101000100_note_attachments_outbox/up.sql new file mode 100644 index 0000000..3a5e49e --- /dev/null +++ b/packages/db/src/migrations/20261101000100_note_attachments_outbox/up.sql @@ -0,0 +1,47 @@ +-- Port: upstream's cleanup_note_attachments() posts a note's old and new +-- record to the delete_note_attachments edge function through pg_net, at a URL +-- it derives from the Supabase project's own functions endpoint. Here that +-- function is a route of the CRM's Worker, which the database has no address +-- for, so the trigger queues the same payload instead, and the Worker's Cron +-- Trigger drains the queue (apps/web/worker/cleanup.ts): the same paths, from +-- the same function's logic, removed through the same Storage API, within a +-- few minutes. Upstream skips the call when the change did not come through +-- the Data API (no Authorization header to forward); a queue needs no header, +-- so every change is cleaned up. +CREATE SCHEMA IF NOT EXISTS private; + +CREATE TABLE IF NOT EXISTS private.note_attachment_cleanups ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + payload jsonb NOT NULL, + attempts integer NOT NULL DEFAULT 0, + last_error text, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- Only the Worker (the owner, through Hyperdrive) reads it. +REVOKE ALL ON private.note_attachment_cleanups FROM anon, authenticated, service_role; + +CREATE OR REPLACE FUNCTION public.cleanup_note_attachments() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO '' + AS $$ + BEGIN + INSERT INTO private.note_attachment_cleanups (payload) + VALUES ( + jsonb_build_object( + 'old_record', to_jsonb(OLD), + 'record', to_jsonb(NEW), + 'type', TG_OP + ) + ); + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + + RETURN NEW; + END; + $$; + +-- Upstream's helper that found the edge function's URL has no caller left. +DROP FUNCTION IF EXISTS public.get_note_attachments_function_url(); diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts new file mode 100644 index 0000000..c4df1bf --- /dev/null +++ b/packages/db/src/runner/cli.ts @@ -0,0 +1,121 @@ +#!/usr/bin/env node +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "../manifest.js"; +import { runMigrations } from "./runner.js"; +import { loadSecretFromEnv } from "./secrets.js"; +import { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +import type { MigrationAdapter, RunMode } from "./types.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = resolve(__dirname, "../migrations"); + +const SUPABASE_ACCESS_TOKEN = process.env["SUPABASE_ACCESS_TOKEN"]; + +function usage(): never { + process.stderr.write( + `Usage: db-migrate --env [--connection-uri ]\n` + + `\n` + + `Modes:\n` + + ` plan — report pending migrations without mutating the database\n` + + ` apply — apply pending migrations\n` + + `\n` + + `Options:\n` + + ` --env target environment (required)\n` + + `\n` + + `Environment:\n` + + ` SUPABASE_ACCESS_TOKEN Supabase management API token (required for apply)\n` + + ` SUPABASE_PROJECT_REF Supabase project ref (required for apply; wired from orun secrets)\n`, + ); + process.exit(1); +} + +interface ParsedArgs { + mode: RunMode; + env: string; +} + +function parseArgs(argv: string[]): ParsedArgs { + const args = argv.slice(2); + + const mode = args[0] as RunMode | undefined; + if (mode !== "plan" && mode !== "apply") { + usage(); + } + + let env: string | undefined; + + for (let i = 1; i < args.length; i++) { + if (args[i] === "--env" && args[i + 1]) { + env = args[++i]; + } + } + + if (!env) { + const envFromEnv = process.env["MIGRATION_ENV"]; + if (envFromEnv) { + env = envFromEnv; + } + } + + if (!env || !["stage", "prod"].includes(env)) { + process.stderr.write("Error: --env must be 'stage' or 'prod'\n"); + process.exit(1); + } + + return { mode, env }; +} + +async function resolveAdapter( + mode: RunMode, + _env: string, +): Promise { + if (mode === "plan") { + return null; + } + + if (!SUPABASE_ACCESS_TOKEN) { + throw new Error("SUPABASE_ACCESS_TOKEN is required for apply mode"); + } + + process.stderr.write(`Loading credentials from the wired environment (orun secrets)\n`); + const secret = loadSecretFromEnv(); + + return new SupabaseApiAdapter(secret.project_ref, SUPABASE_ACCESS_TOKEN); +} + +async function main(): Promise { + const { mode, env } = parseArgs(process.argv); + + process.stderr.write(`db-migrate: mode=${mode} env=${env}\n`); + + const adapter = await resolveAdapter(mode, env); + + const result = await runMigrations(manifest, { + mode, + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + if (result.failed) { + process.stderr.write( + `FAILED: migration ${result.failed.id} — ${result.failed.error}\n`, + ); + process.exit(1); + } + + const output = { + mode, + env, + applied: result.applied, + skipped: result.skipped, + }; + + process.stdout.write(JSON.stringify(output, null, 2) + "\n"); +} + +main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`db-migrate: fatal error — ${message}\n`); + process.exit(1); +}); diff --git a/packages/db/src/runner/index.ts b/packages/db/src/runner/index.ts new file mode 100644 index 0000000..88d97fa --- /dev/null +++ b/packages/db/src/runner/index.ts @@ -0,0 +1,5 @@ +export type { MigrationAdapter, AppliedMigration, RunnerConfig, RunMode, MigrationPlan, MigrationResult } from "./types.js"; +export { runMigrations, buildPlan } from "./runner.js"; +export { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +export { loadConnectionUriFromEnv, loadSecretFromEnv } from "./secrets.js"; +export type { SupabaseSecret } from "./secrets.js"; diff --git a/packages/db/src/runner/runner.ts b/packages/db/src/runner/runner.ts new file mode 100644 index 0000000..9574ca9 --- /dev/null +++ b/packages/db/src/runner/runner.ts @@ -0,0 +1,140 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { MigrationEntry, MigrationManifest } from "../types.js"; +import type { + MigrationPlan, + MigrationResult, + RunnerConfig, +} from "./types.js"; + +const ADVISORY_LOCK_ID = 839_201_008; + +function computeChecksum(filePath: string): string { + const content = readFileSync(filePath); + return createHash("sha256").update(content).digest("hex"); +} + +export function buildPlan( + manifest: MigrationManifest, + appliedMap: Map, + migrationsDir: string, +): MigrationPlan { + const alreadyApplied: string[] = []; + const pending: MigrationEntry[] = []; + const checksumMismatches: MigrationPlan["checksumMismatches"] = []; + + for (const entry of manifest.migrations) { + const appliedChecksum = appliedMap.get(entry.id); + + if (appliedChecksum !== undefined) { + alreadyApplied.push(entry.id); + + const fileChecksum = computeChecksum( + resolve(migrationsDir, entry.path), + ); + + if (appliedChecksum !== fileChecksum || appliedChecksum !== entry.checksum) { + checksumMismatches.push({ + id: entry.id, + expected: appliedChecksum, + actual: fileChecksum, + }); + } + } else { + pending.push(entry); + } + } + + return { alreadyApplied, pending, checksumMismatches }; +} + +export async function runMigrations( + manifest: MigrationManifest, + config: RunnerConfig, +): Promise { + const { adapter, mode, migrationsDir } = config; + const result: MigrationResult = { applied: [], skipped: [], failed: null }; + + // Offline plan: verify checksums then report all migrations as pending. + if (mode === "plan" && adapter === null) { + for (const entry of manifest.migrations) { + const filePath = resolve(migrationsDir, entry.path); + const fileChecksum = computeChecksum(filePath); + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + } + result.applied = manifest.migrations.map((m) => m.id); + return result; + } + + if (!adapter) { + throw new Error("adapter is required for apply mode"); + } + + await adapter.connect(); + + try { + const locked = await adapter.acquireAdvisoryLock(ADVISORY_LOCK_ID); + if (!locked) { + throw new Error( + "Could not acquire migration advisory lock — another runner may be active", + ); + } + + try { + const appliedRows = await adapter.getAppliedMigrations(); + const appliedMap = new Map(appliedRows.map((r) => [r.id, r.checksum])); + + const plan = buildPlan(manifest, appliedMap, migrationsDir); + + if (plan.checksumMismatches.length > 0) { + const ids = plan.checksumMismatches.map((m) => m.id).join(", "); + throw new Error( + `Checksum mismatch for already-applied migrations: ${ids}`, + ); + } + + result.skipped = plan.alreadyApplied; + + if (mode === "plan") { + result.applied = plan.pending.map((m) => m.id); + return result; + } + + for (const entry of plan.pending) { + const sqlPath = resolve(migrationsDir, entry.path); + const sql = readFileSync(sqlPath, "utf-8"); + const fileChecksum = computeChecksum(sqlPath); + + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + + await adapter.beginTransaction(); + try { + await adapter.executeSql(sql); + await adapter.recordMigration(entry); + await adapter.commitTransaction(); + result.applied.push(entry.id); + } catch (err: unknown) { + await adapter.rollbackTransaction(); + const message = err instanceof Error ? err.message : String(err); + result.failed = { id: entry.id, error: message }; + return result; + } + } + } finally { + await adapter.releaseAdvisoryLock(ADVISORY_LOCK_ID); + } + } finally { + await adapter.disconnect(); + } + + return result; +} diff --git a/packages/db/src/runner/secrets.ts b/packages/db/src/runner/secrets.ts new file mode 100644 index 0000000..e575b57 --- /dev/null +++ b/packages/db/src/runner/secrets.ts @@ -0,0 +1,62 @@ +// Supabase credentials from the ENVIRONMENT (de-AWS): the supabase terraform +// component wires its outputs into the workspace's project/env secret rung +// (composition wire-secrets step), and orun resolves the keys this runner +// declares in its component secretEnv into the job env — SUPABASE_PROJECT_REF, +// SUPABASE_DB_PASSWORD, SUPABASE_DB_URL. No Secrets Manager, no AWS SDK. + +export interface SupabaseSecret { + project_ref: string; + project_url: string; + database_host: string; + database_port: string; + database_name: string; + database_user: string; + database_password: string; + connection_uri: string; +} + +function requireEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error( + `${name} is not set — declare it in the component's secretEnv (wired from the supabase component's outputs)`, + ); + } + return value; +} + +/** Assembles the credential document from the wired env vars. The derived + * fields (host/port/db/user) follow the same convention the supabase + * component's payload always used. */ +export function loadSecretFromEnv(): SupabaseSecret { + const projectRef = requireEnv("SUPABASE_PROJECT_REF"); + const password = requireEnv("SUPABASE_DB_PASSWORD"); + const host = `db.${projectRef}.supabase.co`; + const connectionUri = + process.env["SUPABASE_DB_URL"]?.trim() || + `postgresql://postgres:${encodeURIComponent(password)}@${host}:5432/postgres`; + return { + project_ref: projectRef, + project_url: `https://${projectRef}.supabase.co`, + database_host: host, + database_port: "5432", + database_name: "postgres", + database_user: "postgres", + database_password: password, + connection_uri: connectionUri, + }; +} + +/** Direct or pooler connection URI. When a pooler region is provided, use the + * Supabase session pooler to avoid IPv6 connectivity issues with the direct + * database host — the pooler has IPv4 addresses and supports session-level + * advisory locks and transactions. */ +export function loadConnectionUriFromEnv(poolerRegion?: string): string { + const secret = loadSecretFromEnv(); + if (poolerRegion) { + const poolerHost = `aws-0-${poolerRegion}.pooler.supabase.com`; + const user = `postgres.${secret.project_ref}`; + return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(secret.database_password)}@${poolerHost}:6543/${secret.database_name}`; + } + return secret.connection_uri; +} diff --git a/packages/db/src/runner/supabase-api-adapter.ts b/packages/db/src/runner/supabase-api-adapter.ts new file mode 100644 index 0000000..e7e400c --- /dev/null +++ b/packages/db/src/runner/supabase-api-adapter.ts @@ -0,0 +1,93 @@ +import type { MigrationEntry } from "../types.js"; +import type { AppliedMigration, MigrationAdapter } from "./types.js"; + +// The Management API's origin. SUPABASE_API_URL overrides it so a test can +// put a local Postgres behind a stand-in for the one endpoint used here; a +// deployment never sets it. +const SUPABASE_API_BASE = (process.env["SUPABASE_API_URL"] ?? "https://api.supabase.com").replace(/\/+$/, ""); + +export class SupabaseApiAdapter implements MigrationAdapter { + private projectRef: string; + private accessToken: string; + + constructor(projectRef: string, accessToken: string) { + this.projectRef = projectRef; + this.accessToken = accessToken; + } + + async connect(): Promise { /* stateless HTTP — no persistent connection */ } + async disconnect(): Promise { /* no-op */ } + + // Advisory locks are session-scoped and can't be held across HTTP calls. + // Idempotent ON CONFLICT DO NOTHING in recordMigration protects against + // duplicate application when concurrent runners are unlikely. + async acquireAdvisoryLock(_lockId: number): Promise { return true; } + async releaseAdvisoryLock(_lockId: number): Promise { /* no-op */ } + + async getAppliedMigrations(): Promise { + try { + const rows = await this.query( + `SELECT id, context, checksum, applied_at::text AS applied_at + FROM _migrations.applied ORDER BY id`, + ); + return rows as unknown as AppliedMigration[]; + } catch (err: unknown) { + const msg = err instanceof Error ? err.message : String(err); + // Table doesn't exist yet — first-ever run. + if (msg.includes("does not exist")) { + return []; + } + throw err; + } + } + + // Transactions: each step is sent immediately in autocommit mode. + // The migration SQL and record insertion are sent as separate calls. + // Migrations must be idempotent; the runner's ON CONFLICT DO NOTHING + // in recordMigration ensures safe re-runs. + async beginTransaction(): Promise { /* no-op */ } + async commitTransaction(): Promise { /* no-op */ } + async rollbackTransaction(): Promise { /* no-op */ } + + async executeSql(sql: string): Promise { + await this.query(sql); + } + + async recordMigration(entry: MigrationEntry): Promise { + const id = entry.id.replace(/'/g, "''"); + const context = entry.context.replace(/'/g, "''"); + const checksum = entry.checksum.replace(/'/g, "''"); + await this.query( + `INSERT INTO _migrations.applied (id, context, checksum) + VALUES ('${id}', '${context}', '${checksum}') + ON CONFLICT (id) DO NOTHING`, + ); + } + + private async query(sql: string): Promise[]> { + const url = `${SUPABASE_API_BASE}/v1/projects/${this.projectRef}/database/query`; + const response = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ query: sql }), + }); + + if (!response.ok) { + const body = await response.text(); + let message = `HTTP ${response.status}`; + try { + const parsed = JSON.parse(body) as { message?: string; error?: string }; + message = parsed.message ?? parsed.error ?? body; + } catch { + message = body || message; + } + throw new Error(message); + } + + const data = await response.json(); + return Array.isArray(data) ? data as Record[] : []; + } +} diff --git a/packages/db/src/runner/types.ts b/packages/db/src/runner/types.ts new file mode 100644 index 0000000..849d74a --- /dev/null +++ b/packages/db/src/runner/types.ts @@ -0,0 +1,41 @@ +import type { MigrationEntry } from "../types.js"; + +export interface AppliedMigration { + id: string; + context: string; + checksum: string; + applied_at: string; +} + +export interface MigrationAdapter { + connect(): Promise; + disconnect(): Promise; + acquireAdvisoryLock(lockId: number): Promise; + releaseAdvisoryLock(lockId: number): Promise; + getAppliedMigrations(): Promise; + beginTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; + executeSql(sql: string): Promise; + recordMigration(entry: MigrationEntry): Promise; +} + +export type RunMode = "plan" | "apply"; + +export interface RunnerConfig { + mode: RunMode; + migrationsDir: string; + adapter: MigrationAdapter | null; +} + +export interface MigrationPlan { + alreadyApplied: string[]; + pending: MigrationEntry[]; + checksumMismatches: Array<{ id: string; expected: string; actual: string }>; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + failed: { id: string; error: string } | null; +} diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts new file mode 100644 index 0000000..fad6973 --- /dev/null +++ b/packages/db/src/types.ts @@ -0,0 +1,20 @@ +// The migration manifest's shape. A "context" names the slice of the schema +// a migration belongs to: `control` is the runner's own tracking schema, +// `app` is the template's. Add contexts here when a port grows bounded +// contexts of its own. +export const BOUNDED_CONTEXTS = ["control", "app"] as const; + +export type BoundedContext = (typeof BOUNDED_CONTEXTS)[number]; + +export interface MigrationEntry { + id: string; + context: BoundedContext; + path: string; + checksum: string; + description: string; +} + +export interface MigrationManifest { + version: 1; + migrations: MigrationEntry[]; +} diff --git a/packages/db/tsconfig.build.json b/packages/db/tsconfig.build.json new file mode 100644 index 0000000..c6fb252 --- /dev/null +++ b/packages/db/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + } +} diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json new file mode 100644 index 0000000..5a609a8 --- /dev/null +++ b/packages/db/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 05a7901..c9733cc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -337,6 +337,48 @@ importers: specifier: ^4.151.0 version: 4.155.0(@cloudflare/workers-types@5.20261028.1)(@types/node@22.20.1) + packages/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: 25.3.5 + version: 25.3.5 + typescript: + specifier: ^5.8.3 + version: 5.8.3 + + tests/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@electric-sql/pglite': + specifier: 0.5.8 + version: 0.5.8 + '@saas/db': + specifier: workspace:* + version: link:../../packages/db + '@types/node': + specifier: 22.20.1 + version: 22.20.1 + eslint: + specifier: 9.39.4 + version: 9.39.4(jiti@2.7.0) + typescript: + specifier: 5.8.3 + version: 5.8.3 + vitest: + specifier: 5.0.5 + version: 5.0.5(@types/node@22.20.1)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(vite@8.3.5(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)) + tests/web: devDependencies: '@cloudflare/workers-types': @@ -1018,6 +1060,9 @@ packages: resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} + '@electric-sql/pglite@0.5.8': + resolution: {integrity: sha512-n9tsbUOhwx2epK1V0ZG9Ar4SHWUju04dhmzZXiSBXwBoleOvIfals33NAaWgagQVAL4Rbvx/Ptsu3P+pA09f6Q==} + '@emnapi/core@1.11.0': resolution: {integrity: sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==} @@ -3232,6 +3277,9 @@ packages: '@types/node@22.20.1': resolution: {integrity: sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==} + '@types/node@25.3.5': + resolution: {integrity: sha512-oX8xrhvpiyRCQkG1MFchB09f+cXftgIXb3a7UUa4Y3wpmZPw5tyZGTLWhlESOLq1Rq6oDlc8npVU2/9xiCuXMA==} + '@types/papaparse@5.5.2': resolution: {integrity: sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==} @@ -5448,6 +5496,9 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + undici@7.30.1: resolution: {integrity: sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==} engines: {node: '>=20.18.1'} @@ -6493,6 +6544,8 @@ snapshots: dependencies: '@jridgewell/trace-mapping': 0.3.9 + '@electric-sql/pglite@0.5.8': {} + '@emnapi/core@1.11.0': dependencies: '@emnapi/wasi-threads': 1.2.2 @@ -8533,6 +8586,10 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/node@25.3.5': + dependencies: + undici-types: 7.18.2 + '@types/papaparse@5.5.2': dependencies: '@types/node': 22.20.1 @@ -8563,7 +8620,7 @@ snapshots: '@types/ws@8.18.2': dependencies: - '@types/node': 22.20.1 + '@types/node': 25.3.5 '@typescript-eslint/eslint-plugin@8.57.2(@typescript-eslint/parser@8.57.2(eslint@9.39.4(jiti@2.7.0))(typescript@5.8.3))(eslint@9.39.4(jiti@2.7.0))(typescript@5.8.3)': dependencies: @@ -11070,6 +11127,8 @@ snapshots: undici-types@6.21.0: {} + undici-types@7.18.2: {} + undici@7.30.1: {} unenv@2.0.0-rc.24: diff --git a/specs/epics/atomic-crm/IMPLEMENTATION-STATUS.md b/specs/epics/atomic-crm/IMPLEMENTATION-STATUS.md index 2dc46b5..97b09fb 100644 --- a/specs/epics/atomic-crm/IMPLEMENTATION-STATUS.md +++ b/specs/epics/atomic-crm/IMPLEMENTATION-STATUS.md @@ -3,8 +3,8 @@ | Milestone | State | Landed | |---|---|---| | AT0 — the spec | done | AT-1 (#1) | -| AT1 — the CRM on Workers | in review | AT-2 | -| AT2 — the data plane | — | | +| AT1 — the CRM on Workers | done | AT-2 (#2) | +| AT2 — the data plane | in review | AT-3 | | AT3 — ready to instantiate | — | | | AT4 — a baseline | — | | @@ -25,6 +25,33 @@ server's Postgres) — `pnpm typecheck`, `pnpm lint`, `pnpm test` and `pnpm build` green. +## AT2 as built + +- `infra/terraform/supabase` (supabase-starter's root): one project per + environment, Auth's Site URL and redirect allow-list the Worker, sign-up + without email confirmation; publishes the database credentials, + `WIRING_SUPABASE` (URL and publishable key) and `SUPABASE_SERVICE_ROLE_KEY`. +- `infra/terraform/cloudflare-hyperdrive`: a Hyperdrive config in front of + each project's Postgres, caching off; publishes `WIRING_CLOUDFLARE_HYPERDRIVE`. +- `packages/db` (`@saas/db`): the control migration, upstream's 30 + `supabase/migrations` in their order, its seed, and the port's outbox — 33 + checksummed migrations, applied through the Management API by + `infra/db-migrate` before the Worker deploys. Upstream's declarative + `supabase/schemas` were compared with its migration history on a + Supabase-shaped Postgres 16 first: the same schema except one column's + position and a grant the declarative files still give (`get_user_id_by_email` + to `anon` and `authenticated`, which the history revokes), so the history — + what `supabase db push` applies — is what ships. +- `tests/db`: every migration by db-migrate's runner on a Supabase-shaped + PGlite, twice (the second applies nothing), then sign-up (the first user is + the administrator), contacts through the Data API's roles, the attachments + bucket and its policies, the seed, and the attachments outbox. The same + migrations apply as Supabase's non-superuser `postgres` on a real Postgres 16. +- `apps/web` deploys after `supabase`, `cloudflare-hyperdrive` and + `db-migrate` (enforced on a push to `main`), renders its config from their + wiring documents, stores the service-role key as a Worker secret, and drains + the attachments outbox on a Cron Trigger every ten minutes. + ## Departures from the upstream template | Where | Upstream | Here | Why | @@ -44,3 +71,9 @@ | Dependencies | npm, `package-lock.json` | pnpm, every direct dependency pinned to the version upstream's lockfile resolves; `@supabase/supabase-js`, `cropperjs`, `date-fns`, `react-router-dom` declared (transitive upstream) | Upstream's tests pass against its lockfile, and pnpm resolves only declared packages | | Tests | Colocated, Storybook stories as fixtures | `tests/web/src/upstream`, mirroring `src/`, with the 14 stories they render; Storybook itself is not carried | The repository's tests live in `tests/` | | Folder `src/components/atomic-crm` | — | `src/components/crm` | A product's rename rewrites the repository's slug everywhere | +| Migrations | `supabase db push` of `supabase/migrations` (+ `--include-seed`) | The same files, in order, through `@saas/db`'s runner (Management API), then the seed as a migration | Orun's db-migrate composition | +| `pgjwt` | Created in `20260128165057_sso_handling`, never used | Not created | Not shipped on Supabase's Postgres 17 | +| `http`, `pg_net` | Created unconditionally | Created where installed (every Supabase project); skipped elsewhere | The tests' Postgres has neither | +| Note-attachments clean-up | Trigger → `pg_net` → `delete_note_attachments` (only for Data API changes) | Trigger → `private.note_attachment_cleanups` → the Worker's Cron Trigger → Storage (every change) | The database has no address for the Worker's route | +| Service-role key | Supabase injects it into every edge function | The Supabase root's output, an Orun secret, stored as a Worker secret by the deploy | The functions are the Worker's | +| Hyperdrive caching | — (direct pool) | Off | A CRM's reads must see the write before them | diff --git a/tests/db/component.yaml b/tests/db/component.yaml new file mode 100644 index 0000000..cdb2bc5 --- /dev/null +++ b/tests/db/component.yaml @@ -0,0 +1,32 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-tests + description: The migrations' tests — the manifest and its checksums, then every migration applied by db-migrate's runner to a Supabase-shaped Postgres in process (PGlite), twice, and what the app does through the Data API on it — run on every pull request +spec: + type: turbo-package + lifecycle: production + owner: platform + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: tests + change: + inputs: + - packages/db/** + - pnpm-lock.yaml + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test diff --git a/tests/db/docs/architecture.md b/tests/db/docs/architecture.md new file mode 100644 index 0000000..9f56ba0 --- /dev/null +++ b/tests/db/docs/architecture.md @@ -0,0 +1,8 @@ +# db-tests — architecture + +A test package at `tests/db`. Its lane runs the suite before it builds. + +## Suites (2) + +- `migrations.test.ts` +- `schema.test.ts` diff --git a/tests/db/docs/overview.md b/tests/db/docs/overview.md new file mode 100644 index 0000000..c87f1ea --- /dev/null +++ b/tests/db/docs/overview.md @@ -0,0 +1,20 @@ +# db-tests + +The migrations' tests — the manifest and its checksums, then every migration applied by db-migrate's runner to a Supabase-shaped Postgres in process (PGlite), twice, and what the app does through the Data API on it — run on every pull request + +The test suite for **db**. It deploys nothing: its lane installs, builds and runs the tests. + +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `tests/db` | +| Package | `@app/db-tests` | +| Environments | `dev`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/db/docs/runbook.md b/tests/db/docs/runbook.md new file mode 100644 index 0000000..aa64499 --- /dev/null +++ b/tests/db/docs/runbook.md @@ -0,0 +1,26 @@ +# db-tests — runbook + +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/db-tests build +pnpm --filter @app/db-tests test +pnpm --filter @app/db-tests typecheck +pnpm --filter @app/db-tests lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. diff --git a/tests/db/eslint.config.js b/tests/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/db/package.json b/tests/db/package.json new file mode 100644 index 0000000..ce159c9 --- /dev/null +++ b/tests/db/package.json @@ -0,0 +1,22 @@ +{ + "name": "@app/db-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "lint": "eslint src" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@electric-sql/pglite": "0.5.8", + "@saas/db": "workspace:*", + "@types/node": "22.20.1", + "eslint": "9.39.4", + "typescript": "5.8.3", + "vitest": "5.0.5" + } +} diff --git a/tests/db/src/fixtures/supabase-shape.sql b/tests/db/src/fixtures/supabase-shape.sql new file mode 100644 index 0000000..36e950b --- /dev/null +++ b/tests/db/src/fixtures/supabase-shape.sql @@ -0,0 +1,121 @@ +-- What a new Supabase project already has when db-migrate first runs, as far +-- as the CRM's schema touches it — run by the tests (PGlite) and the e2e (a +-- real Postgres) as the bootstrap superuser, before the migrations: +-- +-- roles anon, authenticated, service_role (the Data API's, with +-- Supabase's default privileges on what `postgres` creates in +-- public), and the +-- owners of auth and storage; `postgres` — what the migrations +-- run as — a member of the storage owner (so it can put +-- policies on storage.objects, as Supabase lets it) and granted +-- auth.users (so it can reference it and trigger on it) +-- auth auth.users, and auth.uid() / auth.jwt() / auth.role() read +-- from the request's JWT claims as Supabase's do +-- storage storage.buckets and storage.objects, row-level security on +-- extensions the schema Supabase installs extensions into, on the search +-- path, with pgcrypto (upstream's digest()) pre-installed +-- +-- Idempotent: every statement can run against a database that has it. +DO $$ +BEGIN + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'postgres') THEN + CREATE ROLE postgres LOGIN; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anon') THEN + CREATE ROLE anon NOLOGIN NOINHERIT; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN + CREATE ROLE authenticated NOLOGIN NOINHERIT; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'service_role') THEN + CREATE ROLE service_role NOLOGIN NOINHERIT BYPASSRLS; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'supabase_auth_admin') THEN + CREATE ROLE supabase_auth_admin NOLOGIN; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'supabase_storage_admin') THEN + CREATE ROLE supabase_storage_admin NOLOGIN; + END IF; +END $$; + +GRANT anon, authenticated, service_role TO postgres; +DO $$ BEGIN EXECUTE format('GRANT CREATE ON DATABASE %I TO postgres', current_database()); END $$; +GRANT supabase_storage_admin TO postgres; +GRANT USAGE, CREATE ON SCHEMA public TO postgres; +GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role; +-- Supabase's default privileges: what `postgres` creates in public is the +-- Data API roles' to use, unless a migration narrows it. +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO anon, authenticated, service_role; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon, authenticated, service_role; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon, authenticated, service_role; + +CREATE SCHEMA IF NOT EXISTS extensions; +GRANT USAGE ON SCHEMA extensions TO postgres, anon, authenticated, service_role; +GRANT CREATE ON SCHEMA extensions TO postgres; +CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions; +-- Supabase puts `extensions` on every session's search path, so an +-- extension's operators (citext's =) resolve unqualified. +DO $$ BEGIN EXECUTE format('ALTER DATABASE %I SET search_path TO "$user", public, extensions', current_database()); END $$; +SET search_path TO "$user", public, extensions; + +CREATE SCHEMA IF NOT EXISTS auth AUTHORIZATION supabase_auth_admin; +CREATE TABLE IF NOT EXISTS auth.users ( + id uuid PRIMARY KEY, + email text, + encrypted_password text, + raw_user_meta_data jsonb DEFAULT '{}'::jsonb, + raw_app_meta_data jsonb DEFAULT '{}'::jsonb, + created_at timestamptz DEFAULT now(), + updated_at timestamptz DEFAULT now() +); +ALTER TABLE auth.users OWNER TO supabase_auth_admin; +GRANT USAGE ON SCHEMA auth TO postgres, anon, authenticated, service_role; +GRANT ALL ON auth.users TO postgres; + +CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb LANGUAGE sql STABLE AS $$ + SELECT coalesce( + nullif(current_setting('request.jwt.claim', true), ''), + nullif(current_setting('request.jwt.claims', true), '') + )::jsonb +$$; +CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE AS $$ + SELECT coalesce( + nullif(current_setting('request.jwt.claim.sub', true), ''), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub') + )::uuid +$$; +CREATE OR REPLACE FUNCTION auth.role() RETURNS text LANGUAGE sql STABLE AS $$ + SELECT coalesce( + nullif(current_setting('request.jwt.claim.role', true), ''), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role') + )::text +$$; +GRANT EXECUTE ON FUNCTION auth.jwt(), auth.uid(), auth.role() TO postgres, anon, authenticated, service_role; + +CREATE SCHEMA IF NOT EXISTS storage AUTHORIZATION supabase_storage_admin; +CREATE TABLE IF NOT EXISTS storage.buckets ( + id text PRIMARY KEY, + name text NOT NULL UNIQUE, + owner uuid, + public boolean DEFAULT false, + file_size_limit bigint, + allowed_mime_types text[], + created_at timestamptz DEFAULT now(), + updated_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS storage.objects ( + id uuid PRIMARY KEY DEFAULT extensions.gen_random_uuid(), + bucket_id text REFERENCES storage.buckets (id), + name text, + owner uuid, + metadata jsonb, + created_at timestamptz DEFAULT now(), + updated_at timestamptz DEFAULT now() +); +ALTER TABLE storage.buckets OWNER TO supabase_storage_admin; +ALTER TABLE storage.objects OWNER TO supabase_storage_admin; +ALTER TABLE storage.objects ENABLE ROW LEVEL SECURITY; +GRANT USAGE ON SCHEMA storage TO postgres, anon, authenticated, service_role; +GRANT ALL ON storage.buckets, storage.objects TO postgres, service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON storage.objects TO anon, authenticated; +GRANT SELECT ON storage.buckets TO anon, authenticated; diff --git a/tests/db/src/harness.ts b/tests/db/src/harness.ts new file mode 100644 index 0000000..e9f2adf --- /dev/null +++ b/tests/db/src/harness.ts @@ -0,0 +1,97 @@ +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { PGlite, type Transaction } from "@electric-sql/pglite"; +import { citext } from "@electric-sql/pglite/contrib/citext"; +import { pgcrypto } from "@electric-sql/pglite/contrib/pgcrypto"; +import { unaccent } from "@electric-sql/pglite/contrib/unaccent"; +import type { MigrationEntry } from "@saas/db"; +import { manifest } from "@saas/db/manifest"; +import { runMigrations, type AppliedMigration, type MigrationAdapter } from "@saas/db/runner"; + +// A Supabase-shaped Postgres in process (PGlite: Postgres compiled to WASM, +// with the contrib extensions upstream's schema creates), the migrations +// applied by the same runner db-migrate runs. +export const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); +const shape = readFileSync(path.join(__dirname, "fixtures/supabase-shape.sql"), "utf8"); + +export async function supabaseShaped(): Promise { + const db = new PGlite({ extensions: { citext, pgcrypto, unaccent } }); + await db.exec(shape); + return db; +} + +/** The runner's adapter over PGlite (the Management API's, in process). */ +export class PGliteAdapter implements MigrationAdapter { + constructor(private readonly db: PGlite) {} + async connect() {} + async disconnect() {} + async acquireAdvisoryLock() { + return true; + } + async releaseAdvisoryLock() {} + async getAppliedMigrations(): Promise { + try { + const { rows } = await this.db.query( + "select id, context, checksum, applied_at::text as applied_at from _migrations.applied order by id", + ); + return rows; + } catch (e) { + if (String(e).includes("does not exist")) return []; + throw e; + } + } + async beginTransaction() { + await this.db.exec("begin"); + } + async commitTransaction() { + await this.db.exec("commit"); + } + async rollbackTransaction() { + await this.db.exec("rollback"); + } + async executeSql(sql: string) { + await this.db.exec(sql); + } + async recordMigration(entry: MigrationEntry) { + await this.db.query( + "insert into _migrations.applied (id, context, checksum) values ($1, $2, $3) on conflict (id) do nothing", + [entry.id, entry.context, entry.checksum], + ); + } +} + +export function migrate(db: PGlite) { + return runMigrations(manifest, { mode: "apply", migrationsDir, adapter: new PGliteAdapter(db) }); +} + +export const USERS = { + first: { id: "11111111-1111-4111-8111-111111111111", email: "jane@example.com" }, + second: { id: "22222222-2222-4222-8222-222222222222", email: "john@example.com" }, +}; + +/** Sign a user up as Supabase Auth does: a row in auth.users. */ +export async function signUp(db: PGlite, user: { id: string; email: string }, first = "Jane", last = "Doe") { + await db.query("insert into auth.users (id, email, raw_user_meta_data) values ($1, $2, $3)", [ + user.id, + user.email, + JSON.stringify({ first_name: first, last_name: last }), + ]); +} + +/** + * Run `fn` as PostgREST runs a request: in a transaction, as the request's + * role, with its JWT claims set. + */ +export function as( + db: PGlite, + role: "anon" | "authenticated", + sub: string | null, + fn: (tx: Transaction) => Promise, +): Promise { + return db.transaction(async (tx) => { + const claims = sub ? { sub, role } : { role }; + await tx.query("select set_config('request.jwt.claims', $1, true)", [JSON.stringify(claims)]); + await tx.exec(`set local role ${role}`); + return fn(tx); + }); +} diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts new file mode 100644 index 0000000..eafa3ee --- /dev/null +++ b/tests/db/src/migrations.test.ts @@ -0,0 +1,56 @@ +import { createHash } from "node:crypto"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import * as path from "node:path"; +import { describe, expect, it } from "vitest"; +import { manifest } from "@saas/db/manifest"; +import { buildPlan, runMigrations } from "@saas/db/runner"; +import { migrationsDir } from "./harness"; + +describe("the migration manifest (packages/db)", () => { + it("starts with the control migration and names every file with its checksum", () => { + expect(manifest.migrations[0]?.id).toBe("000_control_baseline"); + for (const entry of manifest.migrations) { + const file = readFileSync(path.join(migrationsDir, entry.path)); + expect(createHash("sha256").update(file).digest("hex"), entry.id).toBe(entry.checksum); + } + }); + + it("lists every migration directory, once, in timestamp order after the control migration", () => { + const dirs = readdirSync(migrationsDir).sort(); + expect(manifest.migrations.map((m) => path.dirname(m.path)).sort()).toEqual(dirs); + const ids = manifest.migrations.slice(1).map((m) => m.id); + expect(ids).toEqual([...ids].sort()); + expect(new Set(manifest.migrations.map((m) => m.id)).size).toBe(manifest.migrations.length); + }); + + it("carries upstream's history, then its seed, then the port's own", () => { + const ids = manifest.migrations.map((m) => m.id); + expect(ids[1]).toBe("20240730075029_init_db"); + expect(ids.indexOf("20261026120000_deal_categories")).toBe(ids.length - 3); + expect(ids.slice(-2)).toEqual(["20261101000000_seed", "20261101000100_note_attachments_outbox"]); + }); + + it("marks every edit to an upstream migration in the file", () => { + const edited = ["20260127140209_imports", "20260128165057_sso_handling", "20260304104600_note_attachments_trigger", "20260309112831_fix_security_warnings"]; + for (const entry of manifest.migrations) { + const sql = readFileSync(path.join(migrationsDir, entry.path), "utf8"); + if (edited.includes(entry.id)) expect(sql, entry.id).toMatch(/^-- Port: /m); + expect(sql, entry.id).not.toMatch(/create extension[^;]*pgjwt/i); + } + expect(existsSync(path.join(migrationsDir, "000_control/up.sql"))).toBe(true); + }); + + it("plans every migration as pending offline", async () => { + const result = await runMigrations(manifest, { mode: "plan", migrationsDir, adapter: null }); + expect(result.failed).toBeNull(); + expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); + }); + + it("skips what the database already recorded", () => { + const applied = new Map([[manifest.migrations[0]!.id, manifest.migrations[0]!.checksum]]); + const plan = buildPlan(manifest, applied, migrationsDir); + expect(plan.alreadyApplied).toEqual([manifest.migrations[0]!.id]); + expect(plan.pending.map((m) => m.id)).toEqual(manifest.migrations.slice(1).map((m) => m.id)); + expect(plan.checksumMismatches).toEqual([]); + }); +}); diff --git a/tests/db/src/schema.test.ts b/tests/db/src/schema.test.ts new file mode 100644 index 0000000..6e0d190 --- /dev/null +++ b/tests/db/src/schema.test.ts @@ -0,0 +1,130 @@ +import type { PGlite } from "@electric-sql/pglite"; +import { beforeAll, describe, expect, it } from "vitest"; +import { manifest } from "@saas/db/manifest"; +import { as, migrate, signUp, supabaseShaped, USERS } from "./harness"; + +// Every migration db-migrate applies, by its runner, on a Supabase-shaped +// Postgres (fixtures/supabase-shape.sql): the CRM's schema as upstream's +// `supabase db push` leaves it, then what the app does through the Data API. +describe("the CRM's schema on a Supabase-shaped Postgres", () => { + let db: PGlite; + beforeAll(async () => { + db = await supabaseShaped(); + const first = await migrate(db); + expect(first.failed).toBeNull(); + expect(first.applied).toEqual(manifest.migrations.map((m) => m.id)); + }, 120_000); + + it("applies nothing the second time", async () => { + const again = await migrate(db); + expect(again.applied).toEqual([]); + expect(again.skipped).toEqual(manifest.migrations.map((m) => m.id)); + }); + + it("creates the CRM's tables and views", async () => { + const { rows } = await db.query<{ relname: string; relkind: string }>(` + select c.relname, c.relkind from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind in ('r', 'v') order by c.relname`); + const tables = rows.filter((r) => r.relkind === "r").map((r) => r.relname); + const views = rows.filter((r) => r.relkind === "v").map((r) => r.relname); + expect(tables).toEqual(expect.arrayContaining([ + "companies", "configuration", "contact_notes", "contacts", "deal_notes", "deals", + "favicons_excluded_domains", "sales", "tags", "tasks", + ])); + expect(views).toEqual(expect.arrayContaining(["activity_log", "companies_summary", "contacts_summary", "init_state"])); + }); + + it("leaves no table in public without row-level security", async () => { + const { rows } = await db.query<{ relname: string }>(` + select c.relname from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind = 'r' and not c.relrowsecurity`); + expect(rows).toEqual([]); + }); + + it("creates the public attachments bucket and its three policies", async () => { + const bucket = await db.query("select id, public from storage.buckets"); + expect(bucket.rows).toEqual([{ id: "attachments", public: true }]); + const policies = await db.query<{ cmd: string }>( + "select cmd from pg_policies where schemaname = 'storage' and tablename = 'objects' order by cmd", + ); + expect(policies.rows.map((p) => p.cmd)).toEqual(["DELETE", "INSERT", "SELECT"]); + }); + + it("seeds the mail domains whose favicon is never fetched", async () => { + const { rows } = await db.query<{ n: number }>( + "select count(*)::int as n from favicons_excluded_domains where domain in ('gmail.com', 'yahoo.com', 'hotmail.com')", + ); + expect(rows[0]!.n).toBe(3); + }); + + it("makes the first user to sign up an administrator, and the next not", async () => { + expect((await db.query<{ is_initialized: number }>("select is_initialized::int from init_state")).rows[0]).toEqual({ is_initialized: 0 }); + await signUp(db, USERS.first); + await signUp(db, USERS.second, "John", "Roe"); + const { rows } = await db.query("select email::text, first_name, last_name, administrator from sales order by id"); + expect(rows).toEqual([ + { email: "jane@example.com", first_name: "Jane", last_name: "Doe", administrator: true }, + { email: "john@example.com", first_name: "John", last_name: "Roe", administrator: false }, + ]); + expect((await db.query<{ is_initialized: number }>("select is_initialized::int from init_state")).rows[0]).toEqual({ is_initialized: 1 }); + }); + + it("lets a signed-in user work with contacts, and a signed-out caller see none", async () => { + const id = await as(db, "authenticated", USERS.first.id, async (tx) => { + const company = await tx.query<{ id: number }>("insert into companies (name, sales_id) values ('Acme', 1) returning id"); + const contact = await tx.query<{ id: number }>( + `insert into contacts (first_name, last_name, company_id, sales_id, email_jsonb) + values ('Ada', 'Lovelace', $1, 1, '[{"email": "Ada@Example.com", "type": "Work"}]') returning id`, + [company.rows[0]!.id], + ); + return contact.rows[0]!.id; + }); + const seen = await as(db, "authenticated", USERS.second.id, (tx) => + tx.query<{ first_name: string; email: string }>("select first_name, email_jsonb->0->>'email' as email from contacts where id = $1", [id]), + ); + // upstream lowercases every email on save + expect(seen.rows).toEqual([{ first_name: "Ada", email: "ada@example.com" }]); + const summary = await as(db, "authenticated", USERS.first.id, (tx) => + tx.query<{ company_name: string }>("select company_name from contacts_summary where id = $1", [id]), + ); + expect(summary.rows).toEqual([{ company_name: "Acme" }]); + const anon = await as(db, "anon", null, (tx) => tx.query("select id from contacts").then((r) => r.rows, () => "denied")); + expect(anon === "denied" || (Array.isArray(anon) && anon.length === 0)).toBe(true); + }); + + it("keeps auth.users' emails from the Data API roles", async () => { + for (const role of ["anon", "authenticated"] as const) { + await expect( + as(db, role, role === "anon" ? null : USERS.first.id, (tx) => tx.query("select * from get_user_id_by_email('jane@example.com')")), + ).rejects.toThrow(/permission denied/); + } + }); + + it("queues a note's removed attachments for the Worker to delete", async () => { + const attachment = (p: string) => JSON.stringify({ src: `https://x.supabase.co/storage/v1/object/public/attachments/${p}`, path: p, title: p }); + const noteId = await as(db, "authenticated", USERS.first.id, async (tx) => { + const contact = await tx.query<{ id: number }>("select id from contacts limit 1"); + const note = await tx.query<{ id: number }>( + "insert into contact_notes (contact_id, text, sales_id, attachments) values ($1, 'hello', 1, array[$2::jsonb, $3::jsonb]) returning id", + [contact.rows[0]!.id, attachment("a.png"), attachment("b.pdf")], + ); + await tx.query("update contact_notes set attachments = array[$2::jsonb] where id = $1", [note.rows[0]!.id, attachment("b.pdf")]); + await tx.query("delete from contact_notes where id = $1", [note.rows[0]!.id]); + return note.rows[0]!.id; + }); + const { rows } = await db.query<{ payload: { type: string; old_record: { id: number; attachments: { path: string }[] }; record: { attachments: { path: string }[] } | null } }>( + "select payload from private.note_attachment_cleanups order by id", + ); + expect(rows.map((r) => r.payload.type)).toEqual(["UPDATE", "DELETE"]); + expect(rows[0]!.payload.old_record.attachments.map((a) => a.path)).toEqual(["a.png", "b.pdf"]); + expect(rows[0]!.payload.record!.attachments.map((a) => a.path)).toEqual(["b.pdf"]); + expect(rows[1]!.payload.old_record).toMatchObject({ id: noteId }); + expect(rows[1]!.payload.record).toBeNull(); + }); + + it("keeps the cleanup queue from the Data API roles", async () => { + await expect( + as(db, "authenticated", USERS.first.id, (tx) => tx.query("select * from private.note_attachment_cleanups")), + ).rejects.toThrow(/permission denied/); + }); +}); diff --git a/tests/db/tsconfig.json b/tests/db/tsconfig.json new file mode 100644 index 0000000..47d9ecc --- /dev/null +++ b/tests/db/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/tests/db/vitest.config.ts b/tests/db/vitest.config.ts new file mode 100644 index 0000000..ce36a74 --- /dev/null +++ b/tests/db/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["src/**/*.test.ts"], + environment: "node", + }, +}); diff --git a/tests/web/docs/architecture.md b/tests/web/docs/architecture.md index 433e115..4f0860a 100644 --- a/tests/web/docs/architecture.md +++ b/tests/web/docs/architecture.md @@ -1,14 +1,50 @@ # web-tests — architecture -Two Vitest projects, as upstream's `vitest.config.ts` has: +A test package at `tests/web`. Its lane runs the suite before it builds. -- **app** — upstream's tests of the React-Admin app and the Storybook stories - they render, in `src/upstream`, mirroring `apps/web/src` (a test's - relative import of app code is an `@/` import here). They run in a real - browser: Playwright's Chromium headless shell, which `pnpm test` installs - first, as upstream's CI does. -- **worker** — in Node: upstream's edge-function tests (`src/functions`) - and the port's own (`src/worker`): the Worker's routes, the Supabase - client's fetch that sends function calls to the Worker, the build's - Supabase project, the committed wrangler render, the MCP server's - Postgres. `cloudflare:workers` is stood in for by `src/stubs`. +## Suites (44) + +- `validateSql.test.ts` +- `addNoteToContact.test.ts` +- `extractMailContactData.test.ts` +- `forwardedParser.test.ts` +- `secondaryEmails.test.ts` +- `ContactCreate.test.tsx` +- `ContactEdit.test.tsx` +- `ContactList.test.tsx` +- `ContactShow.test.tsx` +- `DashboardStepper.test.tsx` +- `DataImport.test.tsx` +- `DataImportButton.test.tsx` +- `parseCell.test.ts` +- `DealInputs.test.tsx` +- `DealList.test.tsx` +- `dealUtils.test.ts` +- `MobileRefreshButton.test.tsx` +- `PullToRefresh.test.tsx` +- `NoteInputs.test.tsx` +- `NoteInputsMobile.test.tsx` +- `NotesIteratorMobile.test.tsx` +- `getCompanyAvatar.test.ts` +- `getContactAvatar.test.ts` +- `i18nProvider.test.ts` +- `dataProvider.test.ts` +- `supabaseAdapter.test.ts` +- `transformContainsFilter.test.ts` +- `transformInFilter.test.ts` +- `transformOrFilter.test.ts` +- `searchDealCategories.test.ts` +- `salesErrorNotification.test.ts` +- `GlobalSearchButton.test.tsx` +- `searchModel.test.ts` +- `SettingsPage.test.ts` +- `TaskCreateSheet.test.tsx` +- `TasksListFilter.test.tsx` +- `tasksPredicate.test.ts` +- `oauth-consent-page.test.tsx` +- `build-env.test.ts` +- `cleanup.test.ts` +- `functions-fetch.test.ts` +- `request-postgres.test.ts` +- `routes.test.ts` +- `wrangler-config.test.ts` diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md index b31c268..4e49e37 100644 --- a/tests/web/docs/overview.md +++ b/tests/web/docs/overview.md @@ -2,14 +2,14 @@ The CRM's tests — upstream's component tests in a real browser, its edge-function tests, and the port's own (the Worker's routes, the functions' fetch, the build's project, the wrangler config) — run on every pull request -A Turborepo package: built and checked on every pull request. +The test suite for **web**. It deploys nothing: its lane installs, builds and runs the tests. -| | | -| ------------ | --------------------- | -| Type | `turbo-package` | -| Source | `tests/web` | -| Package | `@app/web-tests` | -| Environments | `dev`: `quick-check` | +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `tests/web` | +| Package | `@app/web-tests` | +| Environments | `dev`: `quick-check` | ## Depends on diff --git a/tests/web/docs/runbook.md b/tests/web/docs/runbook.md index e70419f..c687de2 100644 --- a/tests/web/docs/runbook.md +++ b/tests/web/docs/runbook.md @@ -1,7 +1,26 @@ # web-tests — runbook -| Symptom | Fix | -|---|---| -| `app` fails with "Executable doesn't exist" | `pnpm exec playwright install chromium-headless-shell` (the `test` script does this) | -| the wrangler-config test fails | `pnpm --filter @app/web run wire:fixture`, and commit `apps/web/wrangler.jsonc` | -| a function test fails after an upstream sync | compare the function with upstream's `supabase/functions/`: the port changes only the imports, the env shim and the handler export | +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web-tests build +pnpm --filter @app/web-tests test +pnpm --filter @app/web-tests typecheck +pnpm --filter @app/web-tests lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. diff --git a/tests/web/src/worker/cleanup.test.ts b/tests/web/src/worker/cleanup.test.ts new file mode 100644 index 0000000..7f58a2c --- /dev/null +++ b/tests/web/src/worker/cleanup.test.ts @@ -0,0 +1,84 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// The Cron Trigger's drain of the note-attachments queue (worker/cleanup.ts): +// upstream's getPathsToDelete picks the paths, the Storage admin API removes +// them, and the row goes — or stays, counted, when Storage refuses. +const storage = vi.hoisted(() => ({ remove: vi.fn(), bucket: "" })); +vi.mock("@worker/functions/_shared/supabaseAdmin", () => ({ + supabaseAdmin: { + storage: { + from: (bucket: string) => { + storage.bucket = bucket; + return { remove: storage.remove }; + }, + }, + }, +})); + +import { BATCH, MAX_ATTEMPTS, drainNoteAttachmentCleanups } from "@worker/cleanup"; + +const att = (path: string) => ({ src: `https://x.supabase.co/storage/v1/object/public/attachments/${path}`, path }); +function fakeClient(rows: { id: number; payload: unknown }[]) { + const queries: { text: string; params?: unknown[] }[] = []; + return { + queries, + async query(text: string, params?: unknown[]) { + queries.push({ text: text.replace(/\s+/g, " ").trim(), params }); + return { rows: /^\s*select/i.test(text) ? rows : [] }; + }, + }; +} + +describe("draining the note-attachments queue", () => { + beforeEach(() => storage.remove.mockReset()); + + it("removes what a change or a deletion left behind, then the rows", async () => { + storage.remove.mockResolvedValue({ data: [], error: null }); + const client = fakeClient([ + { id: 1, payload: { type: "UPDATE", old_record: { attachments: [att("a.png"), att("b.pdf")] }, record: { attachments: [att("b.pdf")] } } }, + { id: 2, payload: { type: "DELETE", old_record: { attachments: [att("c.txt")] }, record: null } }, + { id: 3, payload: { type: "UPDATE", old_record: { attachments: [att("d.png")] }, record: { attachments: [att("d.png")] } } }, + ]); + const result = await drainNoteAttachmentCleanups(client as never); + expect(result).toEqual({ processed: 3, removed: 2, failed: 0 }); + expect(storage.bucket).toBe("attachments"); + expect(storage.remove.mock.calls).toEqual([[["a.png"]], [["c.txt"]]]); + const texts = client.queries.map((q) => q.text); + expect(texts[0]).toBe("begin"); + expect(texts[1]).toMatch(/for update skip locked/); + expect(client.queries[1]!.params).toEqual([MAX_ATTEMPTS, BATCH]); + expect(client.queries.filter((q) => q.text.startsWith("delete")).map((q) => q.params)).toEqual([[1], [2], [3]]); + expect(texts.at(-1)).toBe("commit"); + }); + + it("keeps a row Storage refused, with the attempt and the error", async () => { + storage.remove.mockResolvedValue({ data: null, error: { message: "Bucket not found" } }); + const client = fakeClient([{ id: 7, payload: { type: "DELETE", old_record: { attachments: [att("x.png")] }, record: null } }]); + expect(await drainNoteAttachmentCleanups(client as never)).toEqual({ processed: 1, removed: 0, failed: 1 }); + const update = client.queries.find((q) => q.text.startsWith("update")); + expect(update?.params).toEqual([7, "Bucket not found"]); + expect(client.queries.some((q) => q.text.startsWith("delete"))).toBe(false); + }); + + it("rolls back when the database fails, and does nothing without the service-role key", async () => { + const broken = { + queries: [] as string[], + async query(text: string) { + this.queries.push(text.trim()); + if (/^select/i.test(text.trim())) throw new Error("connection lost"); + return { rows: [] }; + }, + }; + await expect(drainNoteAttachmentCleanups(broken as never)).rejects.toThrow("connection lost"); + expect(broken.queries.at(-1)).toBe("rollback"); + + vi.stubEnv("SUPABASE_SERVICE_ROLE_KEY", ""); + try { + const client = fakeClient([]); + expect(await drainNoteAttachmentCleanups(client as never)).toMatchObject({ processed: 0, skipped: expect.stringMatching(/SERVICE_ROLE/) }); + expect(client.queries).toEqual([]); + } finally { + vi.unstubAllEnvs(); + } + }); +}); diff --git a/tests/web/src/worker/routes.test.ts b/tests/web/src/worker/routes.test.ts index f646fcb..36c4322 100644 --- a/tests/web/src/worker/routes.test.ts +++ b/tests/web/src/worker/routes.test.ts @@ -77,6 +77,12 @@ describe("the Worker's routes", () => { }); }); + it("drains the note-attachments queue on its schedule, given a database", async () => { + const waited: Promise[] = []; + await worker.scheduled({}, env, { waitUntil: (p) => waited.push(p) }); + expect(waited).toEqual([]); + }); + it("serves everything else from the app's assets", async () => { const res = await call("/"); expect(await res.text()).toContain('
'); diff --git a/tests/web/src/worker/wrangler-config.test.ts b/tests/web/src/worker/wrangler-config.test.ts index eb463cf..ab42739 100644 --- a/tests/web/src/worker/wrangler-config.test.ts +++ b/tests/web/src/worker/wrangler-config.test.ts @@ -127,6 +127,8 @@ describe("apps/web wrangler config", () => { run_worker_first: ["/functions/*", "/api/*"], }); expect(config.hyperdrive[0].binding).toBe("HYPERDRIVE"); + // the note-attachments queue's drain (worker/cleanup.ts) + expect(config.triggers).toEqual({ crons: ["*/10 * * * *"] }); }); it("never carries a secret as a var", () => { diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py new file mode 100644 index 0000000..743782b --- /dev/null +++ b/tooling/catalog/gen-component-docs.py @@ -0,0 +1,550 @@ +#!/usr/bin/env python3 +"""Generate each component's docs (overview / architecture / runbook). + + python3 tooling/catalog/gen-component-docs.py # write + python3 tooling/catalog/gen-component-docs.py --check # fail on drift (CI) + +Every `component.yaml` attaches its `docs/` folder in `spec.docs` (overview, +architecture, runbook), which is what the Orun workspace's Docs library shows +and what the catalog's docs and runbook checks read; a folder nothing declares +is never attached (testing/coverage.test.sh holds the rule). These pages are +generated, not hand-written, because almost +everything in them is already declared somewhere CI validates: the component's +manifest (type, description, dependencies, environments, the secrets a lane +resolves, the smoke), its Worker config (bindings, triggers, the wiring the +deploy fills in), its Terraform (resources and outputs), its migrations and its +package scripts. A hand-written copy of those facts drifts the first time one +changes; a generated one cannot, because `--check` fails the pull request that +changes the fact without the page. + +What is NOT derivable (why a component exists, what a failure means for this +product in particular) belongs in the component's `description` and in the +product's own docs, not here. + +The pages ship with the component into every product built from this tree, so +they say nothing about where they came from: no factory paths, no generator +path, no provenance. Zero dependencies beyond PyYAML. +""" + +from __future__ import annotations + +import json +import pathlib +import re +import sys + +try: + import yaml +except ImportError: # pragma: no cover - the contract job installs it + sys.exit("gen-component-docs needs PyYAML (pip install pyyaml)") + +ROOT = pathlib.Path(__file__).resolve().parents[2] +ROOTS = ("apps", "packages", "infra", "tests") +SKIP_DIRS = {"node_modules", "dist", ".turbo", "docs", ".next", ".open-next", + ".wrangler", ".svelte-kit", ".nuxt", ".output", ".astro", "coverage"} + +# Paths a shipped page must never name: products are not placed with them. +FACTORY = re.compile( + r"repo-blueprint|BOOTSTRAP\.md|(? str: + """JSONC → JSON: drop comments outside strings, then trailing commas.""" + out, i, n, in_str = [], 0, len(text), False + while i < n: + c = text[i] + if in_str: + out.append(c) + if c == "\\" and i + 1 < n: + out.append(text[i + 1]) + i += 2 + continue + if c == '"': + in_str = False + i += 1 + continue + if c == '"': + in_str = True + out.append(c) + i += 1 + elif text.startswith("//", i): + j = text.find("\n", i) + i = n if j < 0 else j + elif text.startswith("/*", i): + j = text.find("*/", i + 2) + i = n if j < 0 else j + 2 + else: + out.append(c) + i += 1 + return re.sub(r",(\s*[}\]])", r"\1", "".join(out)) + + +def read_json(path: pathlib.Path) -> dict | None: + try: + return json.loads(strip_jsonc(path.read_text(encoding="utf-8"))) + except (OSError, ValueError): + return None + + +def rel(p: pathlib.Path) -> str: + return p.relative_to(ROOT).as_posix() + + +def discover() -> list[dict]: + found = [] + for root in ROOTS: + base = ROOT / root + if not base.is_dir(): + continue + stack = [base] + while stack: + d = stack.pop() + for entry in sorted(d.iterdir()): + if entry.is_dir(): + if entry.name in SKIP_DIRS or entry.name.startswith("."): + continue + if (entry / "main.tf").exists() and not (entry / "component.yaml").exists(): + continue + if len(entry.relative_to(base).parts) <= 3: + stack.append(entry) + elif entry.name == "component.yaml": + found.append(read_component(entry)) + comps = [c for c in found if c["name"] and c["type"]] + return sorted(comps, key=lambda c: c["name"]) + + +def read_component(file: pathlib.Path) -> dict: + doc = yaml.safe_load(file.read_text(encoding="utf-8")) or {} + meta, spec = doc.get("metadata") or {}, doc.get("spec") or {} + params = spec.get("parameters") or {} + deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)] + envs = [] + # Secrets may be declared for the whole component or per environment + # (`subscribe.environments[].secretEnv`); a page lists both. + req_env = set((spec.get("secretEnv") or {}).keys()) + opt_env = set((spec.get("optionalSecretEnv") or {}).keys()) + for e in ((spec.get("subscribe") or {}).get("environments") or []): + req_env |= set((e.get("secretEnv") or {}).keys()) + opt_env |= set((e.get("optionalSecretEnv") or {}).keys()) + rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef"))) + for r in (e.get("profileRules") or [])] + envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules}) + return { + "dir": file.parent, + "path": rel(file.parent), + "name": meta.get("name"), + "description": (meta.get("description") or "").strip(), + "type": spec.get("type"), + "deps": [d for d in deps if d], + "secret_env": sorted(req_env), + "optional_env": sorted(opt_env - req_env), + "envs": envs, + "params": params, + "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None, + } + + +def package_of(c: dict) -> dict | None: + return read_json(c["dir"] / "package.json") + + +def worker_config(c: dict) -> tuple[str | None, dict | None]: + """The config a deploy uses: the template when wiring renders one.""" + names = ["wrangler.template.jsonc", c["params"].get("wranglerConfig") or "", + "wrangler.jsonc", "wrangler.json"] + for name in names: + if name and (c["dir"] / name).is_file(): + return name, read_json(c["dir"] / name) + return None, None + + +WIRING = re.compile(r"@@wiring\(([^/)]+)/__ENV__:([^)]+)\)@@") + + +def wired(value) -> str | None: + m = WIRING.search(str(value)) if value is not None else None + return f"`{m.group(2)}` from `{m.group(1)}`" if m else None + + +def bindings(cfg: dict) -> list[tuple[str, str, str]]: + rows = [] + for kv in cfg.get("kv_namespaces") or []: + rows.append((kv.get("binding"), "Workers KV namespace", wired(kv.get("id")) or "declared in the config")) + for b in cfg.get("r2_buckets") or []: + rows.append((b.get("binding"), "R2 bucket", wired(b.get("bucket_name")) or f"`{b.get('bucket_name')}`")) + for d in cfg.get("d1_databases") or []: + rows.append((d.get("binding"), "D1 database", wired(d.get("database_id")) or "declared in the config")) + for h in cfg.get("hyperdrive") or []: + rows.append((h.get("binding"), "Hyperdrive (pooled Postgres)", wired(h.get("id")) or "declared in the config")) + if isinstance(cfg.get("ai"), dict) and cfg["ai"].get("binding"): + rows.append((cfg["ai"]["binding"], "Workers AI", "account-level; no resource to provision")) + for d in ((cfg.get("durable_objects") or {}).get("bindings") or []): + rows.append((d.get("name"), "Durable Object", f"class `{d.get('class_name')}`")) + for s in cfg.get("services") or []: + rows.append((s.get("binding"), "Service binding", f"Worker `{s.get('service')}`")) + for q in ((cfg.get("queues") or {}).get("producers") or []): + rows.append((q.get("binding"), "Queue producer", f"queue `{q.get('queue')}`")) + for r in cfg.get("ratelimits") or []: + simple = r.get("simple") or {} + rows.append((r.get("name"), "Rate limiter", + f"{simple.get('limit')} requests / {simple.get('period')}s per location")) + assets = cfg.get("assets") or {} + if assets.get("binding"): + rows.append((assets["binding"], "Static assets", f"`{assets.get('directory')}`")) + return [r for r in rows if r[0]] + + +def tf_facts(c: dict) -> dict: + tf_dir = c["dir"] / (c["params"].get("terraformDir") or "terraform") + resources, outputs, variables, backend = [], [], [], None + for f in sorted(tf_dir.glob("*.tf")) if tf_dir.is_dir() else []: + text = f.read_text(encoding="utf-8") + resources += [f"{t}.{n}" for t, n in re.findall(r'^resource\s+"([^"]+)"\s+"([^"]+)"', text, re.M)] + outputs += re.findall(r'^output\s+"([^"]+)"', text, re.M) + variables += re.findall(r'^variable\s+"([^"]+)"', text, re.M) + m = re.search(r'backend\s+"([^"]+)"', text) + backend = backend or (m.group(1) if m else None) + imports = (tf_dir / "adopt.tf").is_file() if tf_dir.is_dir() else False + return {"dir": rel(tf_dir) if tf_dir.is_dir() else None, "resources": resources, + "outputs": outputs, "variables": variables, "backend": backend, "adopt": imports} + + +def published(c: dict) -> list[tuple[str, str]]: + spec = c["params"].get("secretOutputs") or "" + pairs = [] + for part in str(spec).split(","): + if "=" in part: + k, v = part.split("=", 1) + pairs.append((k.strip(), v.strip())) + return pairs + + +def test_files(c: dict) -> list[str]: + out = [] + for p in sorted(c["dir"].rglob("*")): + if any(part in SKIP_DIRS for part in p.relative_to(c["dir"]).parts): + continue + if p.is_file() and re.search(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$", p.name): + out.append(p.name) + return out + + +def migrations(c: dict) -> list[str]: + path = c["migrations_path"] + if not path: + return [] + d = ROOT / path + if not d.is_dir(): + return [] + return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql") + + +# ── markdown ───────────────────────────────────────────────────────────── + +def md_table(header: list[str], rows: list[list[str]]) -> list[str]: + """A table laid out the way prettier lays it out, so a repo whose lint is + `prettier --check` accepts the page as written.""" + cols = len(header) + width = [max(3, len(header[i]), *(len(r[i]) for r in rows)) for i in range(cols)] + def line(cells): + return "| " + " | ".join(c.ljust(width[i]) for i, c in enumerate(cells)) + " |" + return [line(header), "| " + " | ".join("-" * w for w in width) + " |", *(line(r) for r in rows)] + + +# ── phrasing ───────────────────────────────────────────────────────────── + +KIND = { + "cloudflare-worker-turbo": "A Cloudflare Worker, deployed per environment by its CI lane.", + "cloudflare-workers-assets-turbo": "A Cloudflare Worker with Static Assets (server rendering plus " + "static files), deployed per environment by its CI lane.", + "terraform": "Terraform-managed infrastructure, planned and applied per environment by its CI lane.", + "db-migrate": "Applies this repository's ordered database migrations per environment: " + "plan on pull requests, apply on merge to `main`.", + "turbo-package": "A workspace package built by the turbo pipeline. It deploys nothing itself: " + "its lane type-checks, lints, tests and builds it.", +} + +TRIGGER = {"github-push-main": "a push to `main`", "github-pull-request": "a pull request"} + + +def env_line(e: dict) -> str: + s = f"`{e['name']}`: `{e['profile']}`" + for profile, ref in e["rules"]: + s += f", `{profile}` on {TRIGGER.get(ref, f'`{ref}`')}" + return s + + +def is_tests(c: dict) -> bool: + return c["name"].endswith("-tests") or c["path"].startswith("tests/") + + +def subject_of(c: dict, by_name: dict) -> str | None: + if c["name"].endswith("-tests"): + s = c["name"][: -len("-tests")] + return s if s in by_name else None + return None + + +def names_list(c: dict, keep) -> list[str]: + """Secret names a lane resolves, required first; an optional one (from + `optionalSecretEnv`) is resolved when it exists and skipped when not.""" + req = [f"- `{k}`" for k in c["secret_env"] if keep(k)] + opt = [f"- `{k}` (optional)" for k in c["optional_env"] if keep(k)] + return req + opt + + +def bullet_list(names: list[str], by_name: dict) -> list[str]: + if not names: + return ["- (none)"] + out = [] + for n in names: + d = by_name.get(n) + out.append(f"- **{n}** — {d['description']}" if d and d["description"] else f"- **{n}**") + return out + + +# ── pages ──────────────────────────────────────────────────────────────── + +def overview(c: dict, by_name: dict, dependents: list[str]) -> str: + pkg = package_of(c) + kind = KIND.get(c["type"], f"A `{c['type']}` component.") + subject = subject_of(c, by_name) + if is_tests(c): + kind = (f"The test suite for **{subject}**. " if subject else "A test suite. ") + \ + "It deploys nothing: its lane installs, builds and runs the tests." + lines = [f"# {c['name']}", ""] + if c["description"]: + lines += [c["description"], ""] + facts = [["Type", f"`{c['type']}`"], ["Source", f"`{c['path']}`"]] + if pkg and pkg.get("name"): + facts.append(["Package", f"`{pkg['name']}`"]) + if c["envs"]: + facts.append(["Environments", " · ".join(env_line(e) for e in c["envs"])]) + lines += [kind, "", *md_table(["", ""], facts)] + lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name), + "", "## Depended on by", "", *bullet_list(dependents, by_name), ""] + return "\n".join(lines) + + +def architecture(c: dict, by_name: dict) -> str: + lines = [f"# {c['name']} — architecture", ""] + t = c["type"] + + if t == "terraform": + f = tf_facts(c) + lines += [f"A `terraform` root at `{f['dir'] or c['path']}`.", ""] + if f["backend"] == "http": + lines += ["- **State** lives in the Orun Cloud HTTP state backend — no local state and", + " no state bucket to manage."] + lines += ["- **Credentials are brokered per run** from the workspace's provider", + " connections and resolved by name; none is stored in this repository."] + if f["adopt"]: + lines += ["- **Adoption** (`adopt.tf`): when state is empty but the resource already", + " exists, plan-time import adopts it instead of failing."] + lines.append("") + if f["resources"]: + lines += ["## Resources", "", *[f"- `{r}`" for r in f["resources"]], ""] + pub = published(c) + if pub: + lines += ["## Published outputs", "", + "Written as job-output secrets on each environment after an apply; deploy", + "lanes downstream resolve them by name.", "", + *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""] + elif f["outputs"]: + lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] + return "\n".join(lines) + + if t == "db-migrate": + migs = migrations(c) + lines += [f"Applies the migrations under `{c['migrations_path']}` in order, recording each one", + "it applies so a run only ever applies what is new. An already-applied migration", + "is never edited: a change is a new, later migration.", ""] + if migs: + lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] + return "\n".join(lines) + + pkg = package_of(c) + if t.startswith("cloudflare-"): + cfg_name, cfg = worker_config(c) + lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""] + if cfg: + facts = [["Worker config", f"`{c['path']}/{cfg_name}`"]] + if cfg.get("main"): + facts.append(["Entry", f"`{cfg['main']}`"]) + if cfg.get("compatibility_date"): + facts.append(["Compatibility date", f"`{cfg['compatibility_date']}`"]) + if cfg.get("compatibility_flags"): + facts.append(["Compatibility flags", ", ".join(f"`{x}`" for x in cfg["compatibility_flags"])]) + lines += [*md_table(["", ""], facts), ""] + rows = bindings(cfg) + lines += ["## Bindings", ""] + if rows: + lines += [*md_table(["Binding", "Kind", "Source"], [[f"`{b}`", k, s] for b, k, s in rows]), ""] + if any("from `" in s for _, _, s in rows): + lines += ["Identifiers marked _from_ a component are filled in at deploy time from", + "that component's published outputs for the environment being deployed.", ""] + else: + lines += ["None: the Worker binds no storage or service.", ""] + crons = (cfg.get("triggers") or {}).get("crons") or [] + if crons: + lines += ["## Scheduled triggers", "", *[f"- `{x}`" for x in crons], ""] + env_names = sorted((cfg.get("env") or {}).keys()) + var_names = sorted((cfg.get("vars") or {}).keys()) + if var_names: + lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names) + + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})." + if env_names else "."), ""] + wiring = names_list(c, lambda k: k.startswith("WIRING_")) + others = names_list(c, lambda k: not k.startswith("WIRING_")) + if wiring: + lines += ["## Wiring", "", + "Resolved at deploy time from secrets the infrastructure lanes publish (names only):", + "", *wiring, ""] + if others: + lines += ["## Secrets resolved by the lane (names only)", "", *others, ""] + return "\n".join(lines) + + # turbo-package + if is_tests(c): + files = test_files(c) + lines += [f"A test package at `{c['path']}`. Its lane runs the suite before it builds.", ""] + if files: + lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""] + return "\n".join(lines) + lines += [f"A workspace package at `{c['path']}`, consumed by the components that depend", + "on it. It has no deployed surface of its own.", ""] + if pkg and pkg.get("exports"): + ex = pkg["exports"] + keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."] + lines += ["## Exports", "", *[f"- `{k}`" for k in keys], ""] + return "\n".join(lines) + + +def runbook(c: dict, by_name: dict) -> str: + t = c["type"] + pkg = package_of(c) + lines = [f"# {c['name']} — runbook", "", "## How it runs", ""] + deploys = [e["name"] for e in c["envs"] + if any(ref == "github-push-main" for _, ref in e["rules"])] + if deploys and t in ("terraform", "db-migrate"): + lines += [f"Pull requests plan it; a merge to `main` applies it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + elif deploys: + lines += [f"Pull requests verify it; a merge to `main` deploys it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + else: + lines += ["Its lane runs on every pull request that changes it; it has no deployed surface."] + lines += ["CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;", + "the plan orders a component after everything it depends on.", ""] + + if pkg and pkg.get("scripts"): + name = pkg.get("name") + wanted = [s for s in ("dev", "build", "test", "typecheck", "lint", "preview") if s in pkg["scripts"]] + if name and wanted: + lines += ["## Local commands", "", "```bash", + *[f"pnpm --filter {name} {s}" for s in wanted], "```", ""] + + smoke = c["params"].get("smokeCommand") + if smoke and "No smoke" not in str(smoke): + lines += ["## Verify", "", "After a deploy the lane runs this smoke against the environment it", + "deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:", "", + "```bash", str(smoke).strip(), "```", ""] + + lines += ["## Rollback", "", + "Revert the commit on `main`. The next convergence applies the previous desired", + "state; nothing was changed out of band, so there is nothing else to undo.", "", + "## Common failures", ""] + if t == "terraform": + lines += ["- **Provider authentication fails**: the workspace's provider connection is", + " missing or revoked. Reconnect it in the console; credentials are brokered", + " from it per run.", + "- **\"Already exists\" on a first apply**: state is empty but the resource is", + " not." + (" `adopt.tf` imports it at plan time; if it still fails, the resource" + " was renamed outside Terraform." if tf_facts(c)["adopt"] else + " Import it, or delete the stray resource, then re-run."), ""] + elif t == "db-migrate": + lines += ["- **An applied migration's file changed**: the run stops rather than guess.", + " Restore the file and write the change as a new migration.", + "- **The database is unreachable**: the infrastructure lane it depends on has", + " not applied for this environment; that lane runs first in a convergence.", ""] + elif t.startswith("cloudflare-"): + _, cfg = worker_config(c) + takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"] + c["optional_env"]) or \ + bool(cfg and WIRING.search(json.dumps(cfg))) + if takes_wiring: + lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", + " has not applied for this environment yet. Within one convergence the plan", + " runs it first; on its own, re-run that lane."] + lines += ["- **The smoke fails right after a first deploy**: a new workers.dev route can", + " answer 4xx for a few seconds and the lane retries. A failure that persists", + " is a regression in the deployed code.", ""] + else: + lines += ["- **A dependent fails to build after a change here**: run `pnpm typecheck`", + " across the workspace before merging.", ""] + return "\n".join(lines) + + +# ── main ───────────────────────────────────────────────────────────────── + +def main() -> int: + check = "--check" in sys.argv[1:] + comps = discover() + if not comps: + print("no component.yaml found", file=sys.stderr) + return 1 + by_name = {c["name"]: c for c in comps} + dependents: dict[str, list[str]] = {c["name"]: [] for c in comps} + for c in comps: + for d in c["deps"]: + dependents.setdefault(d, []).append(c["name"]) + + drifted, written, leaks = [], 0, [] + for c in comps: + pages = { + "overview.md": overview(c, by_name, sorted(dependents.get(c["name"], []))), + "architecture.md": architecture(c, by_name), + "runbook.md": runbook(c, by_name), + } + for fname, body in pages.items(): + target = c["dir"] / "docs" / fname + for n, line in enumerate(body.splitlines(), 1): + m = FACTORY.search(line) + if m: + leaks.append(f"{rel(target)}:{n} would name {m.group(0)!r}") + current = target.read_text(encoding="utf-8") if target.exists() else None + if current == body: + continue + if check: + drifted.append(rel(target)) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(body, encoding="utf-8") + written += 1 + + if leaks: + print("✗ a generated page would name a path products do not have:", file=sys.stderr) + for l in leaks: + print(f" {l}", file=sys.stderr) + return 1 + if check: + if drifted: + print(f"✗ {len(drifted)} component doc(s) differ from what the manifests say:", file=sys.stderr) + for f in drifted: + print(f" {f}", file=sys.stderr) + print("\nRun: python3 tooling/catalog/gen-component-docs.py", file=sys.stderr) + return 1 + print(f"✓ component docs match {len(comps)} component.yaml file(s)") + return 0 + print(f"✓ wrote {written} page(s) for {len(comps)} component(s)") + return 0 + + +if __name__ == "__main__": + sys.exit(main())