# app/ — scoring engine and Filament admin

## CharityScoreCalculator (Services/)

Static, pure-function engine for the 4R scores; ~1200 lines, branching per
`data_source` (IRS|CRA|CCEW|OSCR|CCNI) inside each breakdown method.

- `recompute(Charity, $preserveReligious)` is the single persistence entry
  point — used by `charities:rescore` and the admin wizard. Breakdown methods
  (`revenueBreakdown` etc.) return `['suggested','method','confidence',
  'components','irs_data']` and feed both admin and public score blades.
- Composite weights are hardcoded: Revenue 50 / Religious 20 / Recipient 15 /
  Results 15. `compositeFromNullable()` renormalizes when a sub-score is NULL.
  **`FeaturedScoresPage::recalculateComposite` duplicates this math instead of
  calling the calculator** — if you change weights, change both.
- Missing source data falls back to a neutral 25/100 (post-"Round 2" scores
  are floored, never 0/NULL). The median-income lookup tables (FIPS/ISO/
  country/region → income) used for R3 are hardcoded constants in this class.

## Charity model semantics

- `$timestamps = false`, `$guarded = []`. Identity is
  `(country_code, registration_number, tax_year)` — `ein` is US-only and
  nullable. `history()` walks sibling tax-year rows; scopes `latestPerEin()`
  / `featured()` / `forCountry()`.
- Self-entered charities (admin wizard, `HandlesSelfEnteredCharity` trait) get
  `registration_number = Str::uuid()` and `is_self_entered = true`.

## Filament traps

This is Filament **v5** — its API differs from the v3 most models remember
(schemas live in dedicated classes under `Resources/Charities/Schemas/`,
tables under `Tables/`). Copy from the existing resource classes; don't write
Filament calls from memory.

- Score sliders use `->step(0.5)`, which Filament validates as `multiple_of`
  server-side. Raw imported scores (e.g. 73.2) must be pre-rounded on fill
  (see `EditCharity::mutateFormDataBeforeFill`) or the first save fails.
- `EditCharity::afterSave()` fans `is_featured`/`logo_path`/`description` out
  to all sibling tax-year rows; editing a non-latest year is blocked. The
  `is_featured` ToggleColumn in `CharitiesTable` does the same fan-out.
- `HomepageColumnResource` and `ColumnTooltipResource` are two admin views
  over the **same** `ColumnTooltip` model (visibility/labels vs tooltip text).
  The former also creates formula columns; `Forms\Components\FormulaInput` is
  the pill editor. Two things in it are load-bearing and easy to undo by
  accident: the editor div is `wire:ignore` (the pills live only in that DOM,
  so a morph would wipe them mid-typing), and state goes through `$wire.set`
  rather than `wire:model` (the value is a DOM of tokens, not an input value).
  Two more are pure contenteditable lore, both fixing "I cannot delete
  anything": the editor is `display: block` (a flex contenteditable turns text
  nodes into anonymous flex items and the caret stops reaching the end), and
  zero-width fillers pad the ends so a value that begins or ends with a pill
  still has a caret position. They are stripped on serialize.
  Its validation rule and the live preview both compile through
  `HomepageColumns::resolver()`, so a formula referencing another column
  behaves the same when saved as when rendered.
- Charity name search — the resource table and the AI-analysis charity picker
  — goes through `Charity::scopeSearchName()`, MySQL FULLTEXT
  `MATCH…AGAINST` on `name` in boolean mode, not LIKE. It marks every term
  `+` (boolean mode ORs them otherwise, so "american bible society" matched
  47k charities and revenue-sorting buried the exact one) and drops the terms
  InnoDB's tokeniser discards first — its stopword list and anything under
  `innodb_ft_min_token_size`, both mirrored as constants on the model —
  because a required `+the*` matches nothing at all.
- `SiteColor` has a string, non-incrementing primary key (`name`).
  `Services\SiteColors` caches forever under key `site_colors` — bust the
  cache on any write (its own mutators do this; raw updates won't).

## AI appraisal (Services/Ai, Jobs/AnalyzeCharityWebsite)

`Filament\Pages\CharityAnalysisPage` queues `AnalyzeCharityWebsite`
(`timeout = 0`, one try — same shape as ProcessImportBatch) and polls the
`charity_analyses` row it created; `Services\Ai\CharityAnalysisRunner`
catches its own errors and writes `status = failed` plus the message, so the
job's `failed()` hook only fires when the worker itself dies.

- Trust is decided by `CitationVerifier`, not by who found the page. It runs
  after `validate()`: pack citations are checked against text we already hold,
  cited URLs we do not hold are fetched (bounded by `ai.verify.*`) and checked
  the same way, and a fetched source is appended to the pack with
  `origin => 'model'` so it is citable and visible in the report's source
  table. Statuses: `verified`, `quote_not_found` (the quote is absent from its
  own source — the loud one), `no_quote` (nothing substantive quoted; anything
  under 12 normalised characters lands here so "71%" cannot pass as proof),
  `unreadable`. Matching is normalise-then-contain with ellipsis-segment
  support (`quoteAppearsIn`). A citation with neither a pack ID nor a URL never
  reaches the verifier — `validate()` has already moved it to
  `unverified_claims`.
- Scores are clamped; R2's total is recomputed as identity + (integrity ??
  neutral 25), matching `EditCharity::mutateFormDataBeforeSave`, so the
  suggested composite equals what the charity gets when the reviewer applies
  it.
- R1, R3 and R4 are not scores the model returns — `LedgerCalculator` computes
  them from the `calculation` block it fills in (`revenue()` multiplies the
  C1–C7 retentions, weighted by input mix when the charity publishes figures;
  `recipient()` applies 50,000/cmed per country; `results()` sums three
  five-point components). `validateMetric()` overwrites `score` with the
  computed figure, keeps the model's own total as `score_claimed`, forces
  `confidence` to low when a row was defaulted without a source, and appends
  any arithmetic mismatch to `missing_information`. A chain row claiming
  `basis: observed` with no `source_id`/`url` is demoted to a default — an
  observed rate with nothing behind it is not observed. `recipient()` returns
  `score => null` when the methodology's two R3 rules disagree; the Apply
  modal's R3 helper text (`recipientChoiceHint`) then shows both totals.
  The report renders each ledger through
  `views/filament/charities/ai-ledger.blade.php`.
- `ContentExtractor` is the only place that turns bytes into text (HTML via
  DOM, PDF via `pdftotext -layout` over stdin — no temp files).
  `pdfAvailable()` is memoised per process; when it is false the crawler notes
  it and documents are listed unread.
- Adding a provider is one class implementing `Contracts\AnalysisProvider`
  plus an entry in `ProviderFactory::DRIVERS` and `config/ai.php`. Keep the
  return in `ProviderResponse` — the runner reads nothing vendor-specific.
- The Apply action writes to the **latest** tax-year row
  (`CharityAnalysis::targetCharity()`), not to whatever row was on screen when
  the run was queued, and saving fires the Charity model events that bust the
  list cache.

## Import pipeline (Jobs/ProcessImportBatch)

Runs `bulk_load.py` via Symfony Process with `timeout(null)`; parses
`[i/n] Processing …` stdout lines into `ImportBatch` progress columns. On
success `refreshLatestFlags()` recomputes `is_latest` with raw SQL. Read DB
creds via `config('irs.*')` only — the comment at the call site explains why
env() breaks under `config:cache`.
