project-nomad/admin/tests/unit/drug_ingest_status.spec.ts
caweis 762a4a12ad
Add offline FDA drug reference (labels, interaction view, conditions, remedies) (#1040)
* feat(drug-reference): offline FDA drug labels, conditions, and remedies

Adds an offline medical-reference feature with three coupled layers:

- Drug Reference: full-text search over openFDA drug-label indications,
  a detail page per label, and a side-by-side single-drug comparison view.
  A two-phase background pipeline downloads the openFDA label parts to the
  storage volume (resumable) and ingests them into the search table.
- Conditions ("When to use what"): a curated spine of first-aid situations
  that maps each situation to matching OTC drugs, each linking back to its
  Drug Reference detail page.
- Curated remedies: hand-authored natural and home-remedy entries drawn from
  US-government public-domain sources (NCCIH, CDC, MedlinePlus, FDA), shown
  with their source links and the same safety disclaimers as the rest of the
  feature.

The drug-reference and conditions layers are intentionally coupled: the drug
detail page shows the situations a drug treats, and the conditions controller
reads the same drug_labels table.

Safety surfaces ship as written. The amber SafetyBanner ("informational only,
not medical advice, not an FDA endorsement, not a drug-interaction checker, in
an emergency call emergency services") renders on the condition pages and the
search page; the detail and comparison pages carry their own "not a cross-drug
interaction checker" callout; and every page carries the openFDA CC0 source
citation and no-FDA-affiliation footer.

Wiring on this branch:
- start/routes.ts: the /drug-reference and /conditions page GETs plus their
  /api/* groups.
- commands/queue/work.ts: the drug-download and drug-ingest queues, both at
  concurrency 1. The two drug queues get a per-queue stall override
  (lockDuration 1_800_000, maxStalledCount 3) because each part is one long
  stream; every other queue keeps the existing 300000 default.
- inertia/pages/home.tsx: Drug Reference and "When to use what" tiles. The
  icon and display_order are a starting point, open to change.
- types/kv_store.ts: the two drugReference.* keys the pipeline reads and writes.
- package.json: yauzl and stream-json (plus their @types), used by the ingest
  job to stream the label JSON out of the downloaded zips.

The app reads the conditions and remedy data from the compiled TS constants in
app/data/; the repo-root collections/*.json files are the browseable mirrors.
The natural-remedies standalone test reads collections/natural_remedies.json to
assert the two stay in sync, so that file is also a test fixture.

The four standalone tests pass (drug_interactions, drug_ingest_status,
conditions, natural_remedies). tsc reports no errors in the feature code.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(drug-reference): drop a fork-internal comment reference

* fix(drug-reference): address review — defer FULLTEXT, fallback remedies prop, strip fork refs

- migration: wrap the FULLTEXT ALTER in this.defer so it runs after the
  deferred createTable (was silently swallowed, index never created)
- controller: add remedies:[] to the index() error fallback (required prop)
- strip fork-internal issue/spec references from ported comments
- tsconfig: exclude tests/standalone (node --experimental-strip-types only)
- correct the varchar(768) byte-math comment; extend remedy-spine test

* fix(drug-reference): make the interaction comparison readable at five drugs

The comparison view laid its columns out on an equal-fraction CSS grid
(repeat(N, minmax(0, 1fr))), so each added drug shrank every column; at the
five-drug maximum the FDA interaction text was squeezed into unreadable slivers.

Lay the columns out with flex instead: full-width and stacked on phones, then
fixed-width columns that scroll sideways from the sm: breakpoint up, so they
never shrink below a readable width. Theme the columns with the same palette as
the rest of the page (they were on stock gray), and give the headers a fixed
min-height so columns line up when drug names wrap.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(collections): route a 'dataset' tier resource to the drug pipeline

Add an optional `type` discriminator to SpecResource ('zim' | 'dataset',
absent == 'zim'), so the tier installer can carry a DB-ingested resource
alongside ZIM files. ZimService.downloadCategoryTier branches on it: a
'dataset' resource dispatches the existing FDA download+ingest pipeline
instead of RunDownloadJob, guarded against duplicate dispatch by the drug
ingest status. Every existing manifest entry has no `type` and keeps the
exact ZIM path.

Widen InstalledResource.resource_type to include 'dataset' and exclude
dataset rows from the ZIM/map catalog-update scan (datasets aren't
filename-versioned; their freshness path is separate). No dataset rows are
written yet: the InstalledResource 'dataset' row on ingest-ready, the
manifest entry, install-gating, and the downloads-aggregator integration
are follow-up commits.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(drug-reference): rework into an opt-in medicine-standard tier dataset

Reshapes the offline FDA drug reference from a built-in feature into curated
content installed by selecting the Medicine / Standard tier, per maintainer
direction.

- install-state: the ingest writes an installed_resources 'dataset' row on
  ready (version = the openFDA export_date), threaded installer to download to
  ingest; the tier-status math and the home-tile gate read it. Manual ingests
  write no row, so install-state stays tied to the curated path.
- manifest: declare the dataset in the medicine-standard tier (runtime fetches
  the remote manifest, so this also needs to land upstream).
- install-gating: the drug-reference home tiles render only when installed.
- uninstall: DrugReferenceService.uninstall() stops the two drug queues, deletes
  the on-disk parts, truncates drug_labels (schema kept), clears the KV markers,
  and drops the install row. Best-effort, logged, scoped to drug data only.
- downloads: the download phase reports the canonical {percent, downloadedBytes,
  totalBytes} shape as one drug-data card in the Active Downloads aggregator with
  cancel/remove; the heavy ingest stays in the IngestStatus surface with an
  Indexing handoff on the card.
- auto-update: a daily DrugAutoUpdateJob compares the manifest export_date and
  re-downloads when newer, gated on installed + no active job.

typecheck clean; the drug standalone suites pass. Three points are flagged in
code for the maintainer: the InstalledResource 'dataset' approach, the tier
home, and the export_date string format.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(downloads): keep the drug download card live across all parts

The Active Downloads card filtered to the deterministic jobId, but the
download's continuations run under auto-generated jobIds (only part 0 uses the
deterministic one). So the card tracked part 0 and then vanished while parts
2..N kept downloading. The queue is concurrency 1, so collapse to whichever
single part is in flight and report the deterministic jobId: one card tracks
aggregate progress through the whole download and cancel/remove still routes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(drug-reference): co-locate a persistent safety note with affirmative remedy guidance

Add RemedySafetyNote at the head of every natural-remedy section — the two on
Drug Reference and the one on "When to use what" — so the "informational only,
not medical advice, seek real medical care in an emergency" framing appears with
the guidance itself, not only in the page-top banner. Replaces the terse
per-section caveat with the same amber alert language as SafetyBanner.

Addresses the upstream #1040 review request that the disclaimer be unmistakable
and present wherever affirmative self-care guidance appears, not a one-time banner.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(drug-reference): fold dataset freshness into the content-auto-update path

The drug dataset auto-updated on its own daily cron that ignored the
contentAutoUpdate.* master switch, so it would refresh even with content
auto-update turned off, and it didn't ride the content-update path the way
ZIMs and maps do.

Move the export_date freshness/apply orchestration onto
DrugReferenceService.attemptAutoUpdate(), add
ContentAutoUpdateService.attemptDrugDataset() gated on the same enabled +
window config, and have the hourly ContentAutoUpdateJob drive both. Retire
the standalone DrugAutoUpdateJob. The ZIM/map attempt() path is unchanged.

Addresses the upstream #1040 request to wire the openFDA export_date check
into the content updater so the dataset updates alongside ZIMs and maps.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(drug-reference): strengthen the remedy note to consult a clinician before combining with meds

Widen the affirmative-remedy safety note from "talk to a clinician before use"
to explicitly cover using a remedy AND combining one with a medication the user
already takes — the interaction case is the higher-risk path for an off-grid
user self-treating.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(drug-reference): gate affirmative remedy content behind an off-by-default flag

Add drugReference.remediesEnabled (default off), independent of the tier
install. When off, the server emits no remedy data at any boundary — the
drug-reference page prop, conditions show, and the /api/conditions/drugs
situation search — and the "Natural" filter is hidden, so installing the
medicine-standard tier lights up the verbatim FDA label search and the
condition-to-OTC matching but not the hand-authored self-care and herbal
sections. No user-facing toggle: it is flipped on after a clinician content-pass.

Implements the upstream #1040 split-by-risk request: the regulated label content
ships with the tier; the authored remedy guidance stays gated until sign-off.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Jake Turner <52841588+jakeaturner@users.noreply.github.com>
2026-08-04 03:38:33 +00:00

205 lines
7.9 KiB
TypeScript

import { test } from '@japa/runner'
import {
partZipPath,
parseDownloadState,
deriveIngestPhase,
resolveExpectedTotal,
} from '../../util/drug_labels.js'
import type {
DrugLabelPartition,
DrugDownloadStatus,
DrugIngestPhaseStatus,
} from '../../types/drug_reference.js'
// ─── partZipPath ──────────────────────────────────────────────────────────────
test.group('partZipPath', () => {
test('joins the storage base with the basename of the file URL', ({ assert }) => {
const partition: DrugLabelPartition = {
display_name: 'part 1',
file: 'https://download.open.fda.gov/drug/label/drug-label-0001-of-0013.json.zip',
size_mb: '128',
records: 20000,
}
assert.equal(
partZipPath('/app/storage/drug-data', partition),
'/app/storage/drug-data/drug-label-0001-of-0013.json.zip'
)
})
test('round-trips a recorded on-disk path (marker rebuild path)', ({ assert }) => {
// resolvePartSource feeds the recorded path back in as `file`; partZipPath
// must resolve to the same on-disk location.
const recorded = '/app/storage/drug-data/drug-label-0007-of-0013.json.zip'
const partition: DrugLabelPartition = {
display_name: 'part 7',
file: recorded,
size_mb: '0',
records: 0,
}
assert.equal(partZipPath('/app/storage/drug-data', partition), recorded)
})
})
// ─── parseDownloadState ───────────────────────────────────────────────────────
test.group('parseDownloadState', () => {
test('parses a valid marker JSON string', ({ assert }) => {
const raw = JSON.stringify({
export_date: '2026-06-06',
totalParts: 2,
totalRecords: 258914,
parts: [
{ index: 0, name: 'part 1', path: '/app/storage/drug-data/p1.zip', bytes: 100 },
{ index: 1, name: 'part 2', path: '/app/storage/drug-data/p2.zip', bytes: 200 },
],
completedAtMs: 1717718400000,
})
const marker = parseDownloadState(raw)
assert.isNotNull(marker)
assert.equal(marker!.export_date, '2026-06-06')
assert.equal(marker!.totalParts, 2)
assert.equal(marker!.totalRecords, 258914)
assert.lengthOf(marker!.parts, 2)
assert.equal(marker!.parts[1].path, '/app/storage/drug-data/p2.zip')
assert.equal(marker!.completedAtMs, 1717718400000)
})
test('defaults totalRecords to 0 for an older marker that predates the field', ({
assert,
}) => {
const raw = JSON.stringify({
export_date: '2026-06-06',
totalParts: 1,
parts: [{ index: 0, name: 'part 1', path: '/app/storage/drug-data/p1.zip', bytes: 100 }],
})
const marker = parseDownloadState(raw)
assert.isNotNull(marker)
assert.equal(marker!.totalRecords, 0)
})
test('returns null for a never-set (null) value', ({ assert }) => {
assert.isNull(parseDownloadState(null))
})
test('returns null for malformed JSON', ({ assert }) => {
assert.isNull(parseDownloadState('{not json'))
})
test('returns null when parts is empty', ({ assert }) => {
const raw = JSON.stringify({ export_date: '2026-06-06', totalParts: 0, parts: [] })
assert.isNull(parseDownloadState(raw))
})
test('returns null when a part is missing its path', ({ assert }) => {
const raw = JSON.stringify({
export_date: '2026-06-06',
totalParts: 1,
parts: [{ index: 0, name: 'part 1', bytes: 100 }],
})
assert.isNull(parseDownloadState(raw))
})
test('defaults index/name/bytes when absent on an otherwise-valid part', ({ assert }) => {
const raw = JSON.stringify({
export_date: '2026-06-06',
totalParts: 1,
parts: [{ path: '/app/storage/drug-data/p1.zip' }],
})
const marker = parseDownloadState(raw)
assert.isNotNull(marker)
assert.equal(marker!.parts[0].index, 0)
assert.equal(marker!.parts[0].name, '')
assert.equal(marker!.parts[0].bytes, 0)
})
})
// ─── deriveIngestPhase ────────────────────────────────────────────────────────
function dl(state: DrugDownloadStatus['state']): DrugDownloadStatus {
return { state, partsDone: 0, totalParts: 13, currentPartName: null }
}
function ing(state: DrugIngestPhaseStatus['state']): DrugIngestPhaseStatus {
return { state, records: 0, expectedTotal: 0, partsDone: 0, totalParts: 13, currentPartName: null }
}
test.group('deriveIngestPhase', () => {
test('idle when nothing has run and no rows exist', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('idle'), ing('idle'), 0), 'idle')
})
test('downloading when the download phase is running', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('running'), ing('idle'), 0), 'downloading')
})
test('downloaded when the download completed and ingest has not started', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('completed'), ing('idle'), 0), 'downloaded')
})
test('ingesting when the ingest phase is running', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('completed'), ing('running'), 0), 'ingesting')
})
test('ready when the ingest phase completed', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('completed'), ing('completed'), 250000), 'ready')
})
test('ready when idle but rows already exist from a past run', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('idle'), ing('idle'), 250000), 'ready')
})
test('failed when the ingest phase failed', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('completed'), ing('failed'), 0), 'failed')
})
test('failed when the download phase failed', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('failed'), ing('idle'), 0), 'failed')
})
// A failed download does NOT force ingest to fail: if ingest is running off
// already-downloaded parts, the running phase wins.
test('a running ingest outranks a sibling download failure', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('failed'), ing('running'), 0), 'ingesting')
})
// A failed ingest does NOT force download to fail: a running download wins.
test('a running download outranks a sibling ingest failure', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('running'), ing('failed'), 0), 'downloading')
})
// A completed download + failed ingest surfaces 'failed' (ingest is terminal,
// download isn't running) — the manual re-ingest path applies.
test('completed download with a failed ingest reports failed', ({ assert }) => {
assert.equal(deriveIngestPhase(dl('completed'), ing('failed'), 0), 'failed')
})
})
// ─── resolveExpectedTotal ─────────────────────────────────────────────────────
test.group('resolveExpectedTotal', () => {
test('prefers the real manifest total when known', ({ assert }) => {
assert.equal(resolveExpectedTotal(258914, 13, 5000), 258914)
})
// The regression: total_records 0 must NOT win via `?? fallback` (0 is not
// nullish). 0 means unknown → fall through to the parts-based estimate.
test('treats a manifest total of 0 as unknown and uses the parts estimate', ({ assert }) => {
assert.equal(resolveExpectedTotal(0, 13, 5000), 13 * 20000)
})
test('treats an undefined manifest total as unknown and uses the parts estimate', ({
assert,
}) => {
assert.equal(resolveExpectedTotal(undefined, 13, 5000), 13 * 20000)
})
test('falls back to the live row count when parts is also unknown', ({ assert }) => {
assert.equal(resolveExpectedTotal(0, 0, 5000), 5000)
assert.equal(resolveExpectedTotal(undefined, undefined, 5000), 5000)
})
test('honors a custom per-part estimate', ({ assert }) => {
assert.equal(resolveExpectedTotal(0, 4, 0, 25000), 4 * 25000)
})
})