fix(scripts): harden apply-ltd-numbers/apply-name-fixes/import-employees DB resolution

Same pre-ship audit fix as apply-onboarding-pipeline.ts and migrate-onboarding-
templates.ts: replace the raw `DATABASE_URL ?? ''` read with the shared
requireDbUrlForEnv() resolver, log the resolved engine/target before mutating,
hard-fail instead of silently opening a throwaway SQLite file in production, and
close the DB handle in a finally block.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
main
Thomas Joise 1 day ago
parent 9457b0f145
commit f66bab122b

@ -5,9 +5,10 @@
// Does NOT overwrite the name's spelling/casing — only appends the number. // Does NOT overwrite the name's spelling/casing — only appends the number.
// LTD_JSON=<results.json> DATABASE_URL=postgres://… npx tsx apps/hq/scripts/apply-ltd-numbers.ts // LTD_JSON=<results.json> DATABASE_URL=postgres://… npx tsx apps/hq/scripts/apply-ltd-numbers.ts
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import { openDb } from '../src/db' import { openDb, sqliteFilePath } from '../src/db'
import { openPgDb } from '../src/db-pg' import { openPgDb, pgTargetDescription, requireDbUrlForEnv } from '../src/db-pg'
import { updateClient } from '../src/repos-clients' import { updateClient } from '../src/repos-clients'
import type { DB } from '../src/db'
interface Res { clientId: string; ltdNo: string; found: boolean } interface Res { clientId: string; ltdNo: string; found: boolean }
@ -16,9 +17,18 @@ async function main() {
if (path === undefined) throw new Error('Set LTD_JSON to the workflow result json path') if (path === undefined) throw new Error('Set LTD_JSON to the workflow result json path')
const parsed = JSON.parse(readFileSync(path, 'utf8')) as { results?: Res[] } | Res[] const parsed = JSON.parse(readFileSync(path, 'utf8')) as { results?: Res[] } | Res[]
const results = Array.isArray(parsed) ? parsed : (parsed.results ?? []) const results = Array.isArray(parsed) ? parsed : (parsed.results ?? [])
const pgUrl = process.env['DATABASE_URL'] ?? ''
const db = pgUrl !== '' ? await openPgDb(pgUrl) : openDb(process.env['HQ_DATA_DIR'])
// Pre-ship audit FIX A: the SAME resolver server.ts uses (never re-derived locally) — and,
// unlike the server, this one-off script hard-fails rather than silently falling back to a
// throwaway SQLite file when NODE_ENV=production resolves no Postgres target.
const pgUrl = requireDbUrlForEnv()
if (pgUrl !== '') {
console.log(`[db] engine: postgres ${pgTargetDescription(pgUrl)}`)
} else {
console.log(`[db] engine: sqlite at ${sqliteFilePath(process.env['HQ_DATA_DIR'])}`)
}
const db: DB = pgUrl !== '' ? await openPgDb(pgUrl) : openDb(process.env['HQ_DATA_DIR'])
try {
let applied = 0, already = 0, skipped = 0 let applied = 0, already = 0, skipped = 0
const seen = new Set<string>() const seen = new Set<string>()
for (const r of results) { for (const r of results) {
@ -37,6 +47,9 @@ async function main() {
} }
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(`LTD numbers: ${applied} appended, ${already} already present, ${skipped} skipped (not found / no number).`) console.log(`LTD numbers: ${applied} appended, ${already} already present, ${skipped} skipped (not found / no number).`)
} finally {
await db.close()
}
} }
main().catch((e) => { console.error(e); process.exit(1) }) main().catch((e) => { console.error(e); process.exit(1) })

@ -2,9 +2,10 @@
// client-name corrections from name-review.json via the audited updateClient path. // client-name corrections from name-review.json via the audited updateClient path.
// REVIEW_JSON=<path> DATABASE_URL=postgres://… npx tsx apps/hq/scripts/apply-name-fixes.ts // REVIEW_JSON=<path> DATABASE_URL=postgres://… npx tsx apps/hq/scripts/apply-name-fixes.ts
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import { openDb } from '../src/db' import { openDb, sqliteFilePath } from '../src/db'
import { openPgDb } from '../src/db-pg' import { openPgDb, pgTargetDescription, requireDbUrlForEnv } from '../src/db-pg'
import { updateClient } from '../src/repos-clients' import { updateClient } from '../src/repos-clients'
import type { DB } from '../src/db'
interface Row { id: string; current: string; suggested: string; changed: boolean } interface Row { id: string; current: string; suggested: string; changed: boolean }
@ -12,9 +13,18 @@ async function main() {
const path = process.env['REVIEW_JSON'] const path = process.env['REVIEW_JSON']
if (path === undefined) throw new Error('Set REVIEW_JSON to the name-review.json path') if (path === undefined) throw new Error('Set REVIEW_JSON to the name-review.json path')
const rows = JSON.parse(readFileSync(path, 'utf8')) as Row[] const rows = JSON.parse(readFileSync(path, 'utf8')) as Row[]
const pgUrl = process.env['DATABASE_URL'] ?? ''
const db = pgUrl !== '' ? await openPgDb(pgUrl) : openDb(process.env['HQ_DATA_DIR'])
// Pre-ship audit FIX A: the SAME resolver server.ts uses (never re-derived locally) — and,
// unlike the server, this one-off script hard-fails rather than silently falling back to a
// throwaway SQLite file when NODE_ENV=production resolves no Postgres target.
const pgUrl = requireDbUrlForEnv()
if (pgUrl !== '') {
console.log(`[db] engine: postgres ${pgTargetDescription(pgUrl)}`)
} else {
console.log(`[db] engine: sqlite at ${sqliteFilePath(process.env['HQ_DATA_DIR'])}`)
}
const db: DB = pgUrl !== '' ? await openPgDb(pgUrl) : openDb(process.env['HQ_DATA_DIR'])
try {
let applied = 0, skipped = 0 let applied = 0, skipped = 0
for (const r of rows) { for (const r of rows) {
if (!r.changed || r.suggested === r.current) continue if (!r.changed || r.suggested === r.current) continue
@ -32,6 +42,9 @@ async function main() {
} }
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(`Name corrections: ${applied} applied, ${skipped} skipped.`) console.log(`Name corrections: ${applied} applied, ${skipped} skipped.`)
} finally {
await db.close()
}
} }
main().catch((e) => { console.error(e); process.exit(1) }) main().catch((e) => { console.error(e); process.exit(1) })

@ -3,9 +3,10 @@
// and must_change_password=1 (they change it on first login). Active per ACTIVE_STAT. // and must_change_password=1 (they change it on first login). Active per ACTIVE_STAT.
// Idempotent: skips a username/email that already exists. // Idempotent: skips a username/email that already exists.
// DATABASE_URL=postgres://… npx tsx apps/hq/scripts/import-employees.ts // DATABASE_URL=postgres://… npx tsx apps/hq/scripts/import-employees.ts
import { openDb } from '../src/db' import { openDb, sqliteFilePath } from '../src/db'
import { openPgDb } from '../src/db-pg' import { openPgDb, pgTargetDescription, requireDbUrlForEnv } from '../src/db-pg'
import { createEmployee } from '../src/repos-employees' import { createEmployee } from '../src/repos-employees'
import type { DB } from '../src/db'
// From empmaster.xlsx (EMPNAME + ACTIVE_STAT + DESIGNATION code). Emails/phones were blank. // From empmaster.xlsx (EMPNAME + ACTIVE_STAT + DESIGNATION code). Emails/phones were blank.
const EMPLOYEES: { name: string; active: boolean; title?: string }[] = [ const EMPLOYEES: { name: string; active: boolean; title?: string }[] = [
@ -28,9 +29,17 @@ function slug(name: string): string {
} }
async function main() { async function main() {
// Same engine selection as the server: DATABASE_URL → Postgres, else SQLite at HQ_DATA_DIR. // Pre-ship audit FIX A: the SAME resolver server.ts uses (never re-derived locally) — and,
const pgUrl = process.env['DATABASE_URL'] ?? '' // unlike the server, this one-off script hard-fails rather than silently falling back to a
const db = pgUrl !== '' ? await openPgDb(pgUrl) : openDb(process.env['HQ_DATA_DIR']) // throwaway SQLite file when NODE_ENV=production resolves no Postgres target.
const pgUrl = requireDbUrlForEnv()
if (pgUrl !== '') {
console.log(`[db] engine: postgres ${pgTargetDescription(pgUrl)}`)
} else {
console.log(`[db] engine: sqlite at ${sqliteFilePath(process.env['HQ_DATA_DIR'])}`)
}
const db: DB = pgUrl !== '' ? await openPgDb(pgUrl) : openDb(process.env['HQ_DATA_DIR'])
try {
let added = 0, skipped = 0 let added = 0, skipped = 0
const summary: string[] = [] const summary: string[] = []
for (const e of EMPLOYEES) { for (const e of EMPLOYEES) {
@ -53,6 +62,9 @@ async function main() {
} }
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(`Employee import: ${added} added, ${skipped} skipped.\n${summary.join('\n')}`) console.log(`Employee import: ${added} added, ${skipped} skipped.\n${summary.join('\n')}`)
} finally {
await db.close()
}
} }
main().catch((e) => { console.error(e); process.exit(1) }) main().catch((e) => { console.error(e); process.exit(1) })

Loading…
Cancel
Save