Files
9d0c08120d refactor(tenant): which host belongs to which customer becomes a row (#79)
`HOST_TENANTS` was a TypeScript object literal, so taking on a customer — or
removing one — meant editing, reviewing and deploying the application. A
platform that has to be rebuilt to accept a customer is not a platform, and the
map was also the last place a tenant's identity was hard-coded outside its own
row.

Host → tenant is now `org_domains`. Middleware cannot read it (Edge runtime, no
node-postgres), so it stops resolving the tenant altogether: it forwards the
normalised Host as `x-tenant-host` and `getCurrentOrgId()` does the lookup in
the Node runtime, cached per request.

THE FALLBACK IS GONE, and that is the substantive change. `getCurrentOrgId()`
ended in `?? DEFAULT_TENANT_ID`, so an unrecognised Host — a stray domain, a
probe, a not-yet-mapped customer — silently rendered the first customer's site
AND scoped every query to its data. The failure mode of tenant resolution must
not be "serve somebody". It now throws, the same choice `getTenantById` already
made for a missing row. The old test asserted the opposite ("an unknown host
must land on a real tenant, never undefined"); that reasoning was right about
the danger and wrong about the remedy, and the rewritten file says so.

Three other places named a customer to get their work done:

- The platform chrome linked to "the first tenant's live site" via a hard-coded
  id. A product page that names one customer is that customer's page, and it
  made the platform surface unrenderable without that tenant existing.
- The platform funnel loaded the REFERENCE tenant's foundations, so the product
  page described one customer's research as the platform's.
  `getRegistryFoundations()` reads the shared register with nobody's
  assessments, which is what the platform has actually done: nothing.
- Both cron jobs pinned the tenant, so the data-quality report and deadline
  reminders ran for one customer and, silently, never for anyone else. Which
  tenant is now data — the organisation that has stated a `fundraisingEmail`,
  which is the opt-in it already made. Fanning out to several still means
  looping their bodies and starting to mail customers who receive nothing
  today; `lib/tenant/reporting.ts` is the seam, and says so.

Adds the ratchet this migration is measured by. The reference tenant is named
353 times across 119 files; `no-tenant-traces.test.ts` pins each spelling's
count with an exact assertion, so a reduction must be recorded and a rise
fails the build. Down 12 in this commit.

SEQUENCING: 0016 was applied to production before this merges. The resolver
reads `org_domains` on every request, so code landing first would 500 the whole
site. Data first here — the reverse of the tagline change, and for the same
reason: whichever side is depended upon goes first.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 13:47:04 +00:00

146 lines
5.6 KiB
TypeScript

/**
* Foundation data reader for standalone pipeline scripts.
*
* Same query, filter and composition as src/lib/db/foundations-repo.ts (the
* app's read layer), but without unstable_cache — that's a Next.js server API
* and doesn't work outside a Next request/build context, which is exactly the
* environment these `tsx` scripts run in. Scripts are one-shot, so an uncached
* query per run is fine.
*
* The composition itself is NOT duplicated here; both readers call
* `composeFoundation` from src/lib/db/foundation-compose.ts. They used to hold
* separate implementations and had already drifted: this file accepted
* `archived IS NULL` where the app matched `archived = false`, so an audit
* script and the page it audited could disagree about which foundations exist.
* The WHERE clause below now mirrors the app's exactly.
*/
import { sql } from './db';
import { type Foundation } from '../../src/lib/schemas/foundation';
import { composeFoundation, type AssessmentValues } from '../../src/lib/db/foundation-compose';
interface Row {
config_data: unknown;
// NULL for every column when this organisation has not assessed the
// foundation — the LEFT JOIN's miss, not a missing foundation.
fit_score: number | null;
priority: number | null;
priority_override: boolean | null;
themes: unknown;
tagline: string | null;
research_notes: string | null;
research_date: string | null;
research_depth: string | null;
possible_partners: unknown;
}
/**
* All active, sufficiently-confident foundations as `orgId` sees them.
*
* The org id is a required parameter, deliberately. These scripts audit and
* validate foundation data, and an audit that does not state whose data it
* examined reports one tenant's numbers as though they were everyone's. Callers
* get theirs from `requireOrgId()`, which refuses to guess.
*/
export async function getAllFoundations(orgId: string): Promise<Foundation[]> {
const rows = await sql<Row>`
SELECT f.config_data,
a.fit_score, a.priority, a.priority_override, a.themes,
a.tagline, a.research_notes, a.research_date, a.research_depth,
a.possible_partners
FROM fundraising_foundations f
LEFT JOIN fundraising_foundation_assessments a
ON a.foundation_id = f.id AND a.org_id = ${orgId}
WHERE f.archived = false
AND (f.data_confidence IS NULL OR f.data_confidence != 'unverified')
`;
const valid: Foundation[] = [];
for (const row of rows) {
const composed = composeRow(row);
if (composed) valid.push(composed);
}
valid.sort((a, b) => a.slug.localeCompare(b.slug));
return valid;
}
/**
* The shared registry, with nobody's assessments.
*
* For checks about the DATA'S SHAPE rather than about a tenant's view of it.
* The config-integrity suite used to pass a real customer's id here, which made
* a structural assertion depend on that organisation having assessed enough
* foundations — and named a customer in a test that is not about customers.
*/
export async function getRegistryFoundations(): Promise<Foundation[]> {
const rows = await sql<Row>`
SELECT f.config_data,
NULL::int AS fit_score, NULL::int AS priority,
NULL::int AS priority_override, NULL::text[] AS themes,
NULL::text AS tagline, NULL::text AS research_notes,
NULL::text AS research_date, NULL::text AS research_depth,
NULL::jsonb AS possible_partners
FROM fundraising_foundations f
WHERE f.archived = false
AND (f.data_confidence IS NULL OR f.data_confidence != 'unverified')
`;
const valid: Foundation[] = [];
for (const row of rows) {
const composed = composeRow(row);
if (composed) valid.push(composed);
}
valid.sort((a, b) => a.slug.localeCompare(b.slug));
return valid;
}
/** Turn one joined row into a Foundation as this organisation sees it. */
function composeRow(row: Row): Foundation | undefined {
// A row with no fit_score is a LEFT JOIN miss: this organisation has no
// assessment, so it gets the unassessed defaults rather than the blob's
// leftover values from whoever researched the foundation first.
const assessment: AssessmentValues | null =
row.fit_score === null
? null
: {
fitScore: row.fit_score,
priority: row.priority ?? 4,
priorityOverride: row.priority_override ?? false,
themes: row.themes,
tagline: row.tagline,
researchNotes: row.research_notes,
researchDate: row.research_date,
researchDepth: row.research_depth,
possiblePartners: row.possible_partners,
};
return composeFoundation(row.config_data, assessment);
}
/**
* One foundation by id, as `orgId` sees it, with no archived or confidence
* filter applied.
*
* For write paths that read back what they just wrote. `getAllFoundations`
* deliberately hides archived and unverified rows because it answers "what is
* this organisation working with"; a script correcting a row it just inserted
* is asking a different question and must see the row regardless of how the
* list view would treat it.
*/
export async function getFoundationById(
orgId: string,
id: string,
): Promise<Foundation | undefined> {
const [row] = await sql<Row>`
SELECT f.config_data,
a.fit_score, a.priority, a.priority_override, a.themes,
a.tagline, a.research_notes, a.research_date, a.research_depth,
a.possible_partners
FROM fundraising_foundations f
LEFT JOIN fundraising_foundation_assessments a
ON a.foundation_id = f.id AND a.org_id = ${orgId}
WHERE f.id = ${id}
`;
return row ? composeRow(row) : undefined;
}