#!/usr/bin/env tsx /** * Import the public programme register from a curated seed file. * * A DRY RUN unless `--write` is given. Validates every row against * programmeSchema (a fact without its page, date and sentence is refused; a * missing fact must say why) and refuses the whole file on one bad row. * * Usage: * pnpm exec tsx scripts/programme-import.ts data/programmes/seed-2026-12-01.json * DATABASE_URL=… pnpm exec tsx scripts/programme-import.ts --write */ import * as fs from 'fs'; import { programmeSeedFileSchema } from '../src/lib/schemas/programme'; async function main() { const args = process.argv.slice(2); const write = args.includes('--write'); const file = args.find((a) => a.endsWith('.json')); if (!file || !fs.existsSync(file)) { console.error('Usage: tsx scripts/programme-import.ts [--write]'); process.exit(1); } const parsed = programmeSeedFileSchema.safeParse(JSON.parse(fs.readFileSync(file, 'utf-8'))); if (!parsed.success) { console.error(`${file} is not a valid programme list. Nothing was written.`); for (const issue of parsed.error.issues.slice(0, 20)) { console.error(` ${issue.path.join('.')}: ${issue.message}`); } process.exit(1); } const { programmes, dropped, curation } = parsed.data; const ids = new Set(); for (const p of programmes) { if (ids.has(p.id)) { console.error(`Duplicate id '${p.id}'. Nothing was written.`); process.exit(1); } ids.add(p.id); } console.log( `\n${file}\n Curation: ${curation}\n Rows: ${programmes.length} Dropped: ${dropped.length}\n`, ); for (const p of programmes) { const missing = Object.keys(p.notSourced); console.log( ` ${p.id.padEnd(52)} not sourced: ${missing.length ? missing.join(', ') : 'none'}`, ); } if (!write) { console.log('\n DRY RUN. Nothing was written. Pass --write to upsert.\n'); return; } const { sql, closeDb } = await import('./lib/db'); for (const p of programmes) { await sql` INSERT INTO fundraising_programmes (id, name, data, updated_at) VALUES (${p.id}, ${p.name}, ${JSON.stringify(p)}::jsonb, now()) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, data = EXCLUDED.data, updated_at = now() `; } await closeDb(); console.log(`\n Upserted ${programmes.length} programmes.\n`); } main().catch((err) => { console.error('Programme import failed:', err); process.exit(1); });