# charity-analytics

Charity-scoring site for ARK AID: a public Livewire site plus a Filament admin
over one big `charities` table populated from five national regulators
(US IRS 990, Canada CRA T3010, UK CCEW/OSCR/CCNI). Each charity is scored on
the "4R" model — R1 Revenue, R2 Religious, R3 Recipient, R4 Results — described
in `aaa-compassion.md` (business methodology, not a runbook).

## Stack

- PHP ^8.3, Laravel 13, Filament v5 (admin at `/admin`), Livewire v4
  (public pages as single-file components — see `resources/CLAUDE.md`).
- Vite 8 + Sass; entries are `resources/css/app.scss` and `resources/js/app.js`
  (vite.config.js). Tailwind 4 is wired into Vite but the public site is
  hand-written SCSS. Chart.js is the only runtime JS dependency.
- Python ≥3.10 ETL scripts at repo root (`bulk_load.py`, `load_*.py`,
  `loader_common.py`) — they, not Laravel, own the `charities` table.
- `anthropic-ai/sdk` is the only AI dependency; OpenAI and Gemini are called
  over the Http client (neither ships a first-party PHP SDK).

## Commands

```bash
composer dev            # serve + queue:listen + pail + vite, concurrently
npm run build           # vite build (required before deploy; Docker does it in-image)
php artisan charities:rescore   # recompute 4R scores; ~14 min on 2.88M rows — screen/tmux
php artisan imports:recover     # mark stuck ImportBatch rows failed (--dry-run first)
composer test           # artisan test — NOTE: tests/ does not exist; finds zero tests
docker compose up       # nginx :8080 + php-fpm app + mysql 8 + queue worker
```

Three recurring tasks have step-by-step skills — use them instead of
improvising: `.claude/skills/load-charity-data/` (imports),
`.claude/skills/deploy-cpanel/` (production deploy), and
`.claude/skills/add-charity-column/` (schema changes to `charities`).

## Architecture facts you can't infer from one file

- **The `charities` table has no Laravel migration.** `load_to_mysql.py`
  (IRS loader) creates it; Laravel migrations only ALTER it behind
  `Schema::hasColumn()` guards. `php artisan migrate` on a fresh DB gives you
  the framework tables but no charities.
- **A "charity" is many rows**: one per `(country_code, registration_number,
  tax_year)` (the upsert unique key), with `is_latest` marking the current
  year. Shared fields (featured, logo, description) are fanned out to sibling
  rows on save; `is_latest` is recomputed only after imports and wizard saves —
  direct DB inserts leave it stale.
- **Import flow**: Filament "Data Import" page → `App\Jobs\ProcessImportBatch`
  (timeout 0, queue `database`) → shells out to `bulk_load.py` with creds from
  `config('irs.*')` (config/irs.php, env `IRS_DB_*` / `IRS_PYTHON_BIN`).
- **Scoring lives in `app/Services/CharityScoreCalculator.php`** (see
  `app/CLAUDE.md`). Loader behavior differs per source and is easy to get
  wrong: the IRS loader computes preliminary scores for new rows and
  *preserves* existing scores on re-import (`score_composite = score_composite`
  in its upsert, load_to_mysql.py:1398), but the CRA/CCEW/OSCR/CCNI loaders
  upsert score columns from `loader_common.py` with NULL — **re-importing a
  non-US source wipes scores (including manually edited `score_religious`) on
  every row it touches**. Always run `charities:rescore` after any import.
- **Live customizer** (`/admin/customizer`): the public site in an iframe plus
  an editing panel. Two halves that must stay in sync — `resources/js/
  customizer.js` runs *inside the preview* and is the only thing that can
  answer "which CSS custom property painted this element" (it indexes the
  CSSOM and matches the click target and its ancestors against every rule
  whose value contains `var(--…)`); the panel
  (`resources/views/filament/pages/customizer.blade.php`) keeps the unsaved
  working copy in Alpine and pushes it over postMessage, so nothing hits the
  server until Publish. The runtime is only injected when
  `App\Support\Customizer::isActive()` — `?customizer=1` **and** an admin
  session — so it never ships to visitors, and it is a separate Vite entry.
- **Text is only editable where a Blade file says so.** `<x-editable
  key="…" label="…">default copy</x-editable>` marks a zone; overrides live in
  `site_texts` and the Blade slot is the fallback, so deleting the row reverts
  to the designed copy. Typography is a closed set — the type scale is
  `SiteTexts::FONT_SIZES` and colors must name a `site_colors` entry — checked
  on save *and* on render, because the values land in a `style` attribute on a
  public page. Four other properties stay whitelisted but have no control in
  the panel yet; re-exposing one is a customizer.blade.php change only.
- The customizer's **Lenses tab** edits `column_lenses` live: column
  membership, order, visibility and which one is the default. Previewing an
  unsaved lens works by rewriting `data-lens-columns` on `.list-wrap` and
  firing `charity-list:refresh-preferences` — `charity-list-expand.js` still
  owns the show/hide, so there is one implementation of "which columns are on".
  A lens' *name* is not edited there but through its `lens:<id>` model zone,
  the same draft the element picker writes to. Creating and deleting lenses
  stays in `ColumnLensResource`.
- The customizer's **Features tab** removes parts of the public site outright,
  which is the one thing colors and copy cannot do. `Services\SiteSettings`
  holds the whole closed set in `DEFINITIONS` (label, help text, default);
  `site_settings` is seeded with nothing and a *missing row means the default*,
  so switching one back deletes the row rather than storing a value nobody can
  tell apart from a choice. Three switches today. The **Columns** menu is the
  one that defaults to *off*: it is still rendered with `hidden`, because its
  checkboxes are how `charity-list-expand.js` learns the full column set, and
  `data-column-picker` on `.list-wrap` makes the JS ignore a visitor's stored
  column choice so the lens alone decides. The visitor-facing **Bars**
  button (removed ⇒ the in-cell bars are on for everyone, and which columns
  draw one is still `ColumnTooltip.show_bar`), and the **row expander** — the
  detail panel is only rendered for rows a visitor has opened, so removing the
  button removes the whole feature and there is no preloaded markup to strip;
  `⚡homepage::toggleDetail()` refuses anyway, because a stale tab still holds
  a page with the button on it. The switches change the cached markup, so
  `CharityListCache` hashes them into its key. Previewing follows the Lenses
  tab's rule — the panel flips `data-bars-control` on `.list-wrap` (which is
  what `charity-list-expand.js` reads, not the button's presence) and hides the
  rest with a preview stylesheet, because the list is Livewire's DOM and
  removed nodes would not survive the next sort.
- Editable zones repeat: the charity list's expandable detail panel renders the
  same headings and labels once per row, so the customizer applies an edit to
  *every* element with that key, and `Services\SiteTexts`/`HomepageColumns` are
  singletons with a per-request memo — the cache store is `database`, and one
  lookup per zone per row was several hundred SELECTs a page.
- Three kinds of zone do not fit a wrapper and get helpers in
  `App\Support\Editable` instead: **attribute** zones (`::attribute()`, e.g. a
  placeholder), **image** zones (`::image()` / `::imageUrl()`, uploads land on
  the `public` disk under `site-images/`), and **model** zones (`::model()`),
  whose copy is a database column the admin already edits elsewhere —
  navigation items and column lenses write back to their own row rather than
  shadowing it in `site_texts`, so the two can never drift. All three are
  copy-only. Zones rendered by JavaScript (`Editable::JS_ZONES`) get their
  copy from a JSON blob in the layout — see `resources/js/score-overrides.js`.
- **Homepage columns are rows, not code.** `column_tooltips` carries an
  `expression` (what the column *is* — a formula over charity fields) and a
  `renderer` (how it is drawn: `name`, `figure`, `text`, `link`, `score`,
  `composite`, `stars`, one Blade partial each in
  `views/components/columns/`). Adding a column is an admin action;
  `charity-list-row.blade.php` has no per-column cases left.
  `Services\HomepageColumns` compiles every visible column's formula once
  (cached under `ColumnTooltip::CACHE_KEY`, busted by the model's own events)
  and adds it to the charity query as `fx_<key>`, which is also what sorting
  orders by.
- **Where a charity can be found is five columns and one closed set.**
  `website_url` plus one per platform on `charities`, admin-entered and fanned
  out across tax years like `logo_path`; `App\Support\SocialLinks::PLATFORMS`
  is the only place that knows which platforms exist, what a valid address for
  one looks like (host match plus a reject list — a `sharer.php` link is a
  share button, not a profile) and what the header chip says. Adding one is an
  entry there, a column, and one `@case` in
  `views/components/social-icon.blade.php`. `Services\SocialLinkScraper` fills
  the fields from the charity's own site rather than any platform API: it
  reads the home page — anchors *and* raw markup, because half of them are in
  a JSON-LD `sameAs` — and follows the contact/about page only while a
  Facebook, Instagram or X link is still missing. Wikipedia is taken when a
  page happens to link it and never chased. Fetching is `SafeUrlFetcher`, on a
  tighter budget than the AI crawler because an admin is waiting on it.
- **A charity's own reports are links, not figures.** `charity_documents`
  rows hang off `(country_code, registration_number)` — not off a charity row,
  because a charity is one row per tax year and a report is a fact about the
  organisation, so there is nothing to fan out on save. Admins add them under
  "Reports & documents" on the charity, optionally picking them off the last
  AI run's source pack ("Add from AI analysis" reads `charity_analyses.sources`
  where `kind = document` and guesses the kind and the year — a guess a human
  then corrects). The public charity page lists all of them; the
  `link` column renderer shows exactly one, the newest of its
  `document_type`, as an icon-and-year button. That column is the one whose
  value is not an expression: `HomepageColumns::compileLink()` emits a
  correlated subquery returning a `JSON_OBJECT` of the address, year, title
  and where the file is held, under the same `fx_<key>` alias, so a page of links costs no extra query, and the
  `ColumnTooltip` saving hook clears `expression`/`show_bar`/`is_sortable` —
  there is no order to put charities in by a document.
- **A document row does not have to point at someone else's server.** Three
  shapes, and `CharityDocument::publicUrl()` is the only place that tells them
  apart: a plain link; a link with "Keep a copy on this site", where
  `Services\DocumentMirror` downloads the file once into the `public` disk and
  visitors get *our* copy while `url` keeps the address it came from (so
  unticking the toggle hands them straight back, and the charity redesigning
  its site cannot dead-link us); and `source = upload`, a file an admin holds
  that the charity never published, so `url` is nullable. The copy is taken in
  the model's own `saved` hook — after the insert, because the file is named
  after the row's id — and is *allowed to fail*: the reason lands in
  `mirror_error` and is shown under the row, the link still works, and saving
  again retries. Only PDF/Word/Excel are stored, because the file is then
  served from our origin and a mirrored HTML page would be stored XSS. The
  fetch goes through `Support\SafeUrlFetcher` like every other admin-supplied
  address.
- **A description can refer to a document without anyone pasting a URL into
  the prose.** `Charity::setUpRichContent()` registers two merge tags per
  document — `document:<id>` (inline chip) and `document-button:<id>` (a
  call-to-action for its own line): `mergeTagLabels()` names them for the
  picker via `CharityDocument::referenceLabel()`, which always carries the
  year because that is what one document is chosen by, and `mergeTags()`
  supplies the closures that draw `views/partials/documents/`. The tag stores
  an id and nothing else, so the reference follows the row: fixing the
  address, or ticking the mirror toggle, changes what the prose opens with no
  edit to the text. Those partials use masked spans, not `<svg>` — the editor
  sanitises its own output with Symfony's `allowSafeElements()`, which drops
  svg and keeps `class`.
- The same feature wearing Filament's clothes is confusing, so two overrides
  dress it as what it is. A partial vendor lang file
  (`lang/vendor/filament-forms/`, merged by `array_replace_recursive`) renames
  "Merge tags" to **Add document** on the toolbar button, the panel heading
  and the no-results message; `views/filament/forms/document-tag-assets.blade
  .php`, a HEAD_END render hook next to the formula editor's, draws the tag in
  the editor as a pill with a document glyph instead of Filament's
  `{{ braced text }}`. Both are app-wide for any rich editor — this is the
  only one with merge tags, and a second use would make the wording a lie.
  Injected at HEAD_END rather than compiled into a theme because it has to
  land after the panel stylesheet it overrides.
- A column's `renderer` also decides *which language* its `expression` is in.
  `text` makes it a template — literal wording with `{field}` holes, compiled
  by `Services\Formula\TemplateCompiler` into `CONCAT_WS` with the literals as
  bound parameters. `CONCAT_WS`, not `CONCAT`: the latter returns NULL if any
  argument is, so one unfiled figure would blank the whole line. A template may
  quote a formula column but not another template, which keeps the two
  compilers from calling into each other.
- **Formulas are compiled, never interpolated.** `Services\Formula\
  FormulaCompiler` parses with symfony/expression-language and re-emits SQL
  from the AST: only the whitelisted node types and functions produce output,
  identifiers are checked against `FieldRegistry` (which reads the live
  schema), and literals leave as bound parameters. `min`/`max` map to
  LEAST/GREATEST — MySQL's own MIN/MAX are aggregates, and `avg` is likewise
  *across arguments, not rows*: it sums the ones that are non-NULL and divides
  by how many there were, so a missing year lowers the divisor instead of
  averaging against a zero, and all-NULL is NULL. Division auto-wraps in
  NULLIF. `FormulaLanguage` exists so `constant()` and `enum()` are never even
  registered. A formula that fails to compile is logged and its column renders
  N/A; it does not take the homepage down.
- **Not every formula field is a column.** `FieldRegistry::sql()` — the one
  place that turns a field name into SQL, for both compilers — resolves
  `total_revenue_ly` and `total_revenue_py2` to a correlated subquery on the
  sibling tax-year row (`uniq_country_reg_year`, so no extra query per page),
  because "what did they raise two years ago" is a fact about the organisation
  and nobody files it: the IRS 990 carries one prior year
  (`total_revenue_py`, still offered as "as filed") and the CRA/CCEW/OSCR/CCNI
  loaders carry none, so a formula reaching for `total_revenue_py` alone is
  blank for every non-US charity. The schema wins on a name collision, so a
  loader that ever adds a real column of that name displaces the stand-in.
  This is what makes the `size` column the three-year average it is.
  Two more stand-ins: `latest_tax_year` (the `is_latest` sibling's year —
  `tax_year` is a VARCHAR, so the numeric schema scan never offers it) and
  `country` (`country_code` spelled out via `CharityWizard::COUNTRIES`), plus
  `country_code` itself. The two country fields are **text**: offered and
  accepted in `text` templates only, and the formula compiler rejects it with a pointer to the Text renderer.
- Generated columns are **not** an option for formulas, however tempting:
  `load_to_mysql.py` owns the `charities` schema and upserts into it, and a
  STORED column breaks those writes.
- **The rendered charity list is cached** (`Services\CharityListCache`). It was
  21.5 ms of a 39 ms request and produces identical bytes for every visitor.
  The key covers everything the markup depends on: `Support\ListVersion` (a
  token bumped by Charity model events, `charities:rescore` and
  ProcessImportBatch — the three places charity data changes), hashes of the
  column, lens and text-zone arrays those services already hold in memory, and
  the request state (sort, search, page size, open panels). A search term is
  rendered fresh rather than filling the store. 5-minute TTL as a backstop for
  a loader run outside the job.
- **AI website appraisal** (`/admin/ai-analysis`, plus an "AI website
  analysis" button on the charity edit page) scores a charity's own site
  against the 4R model: crawl → prompt → provider → validate → verify.
  `Services\Ai\WebsiteEvidenceCollector` walks the site itself (link keywords
  → likely metric, same-domain only, budgets in config/ai.php) and reads the
  documents it finds, PDFs included, so there is always a body of text *we
  hold*; `Services\Ai\AnalysisPrompt` reads `aaa-compassion.md` at runtime,
  so editing the published methodology changes the rubric the model scores
  against, and it tells the model to search past the pack (accounts, 990s,
  regulator filings) *because* everything it cites is checked afterwards;
  `Services\Ai\CharityAnalysisRunner` clamps scores and derives the composite
  through `CharityScoreCalculator`, so an AI suggestion uses the same weights
  as everything else.
- **The AI does not write R1, R3 or R4 — it fills in a ledger and PHP does the
  arithmetic.** `Services\Ai\LedgerCalculator` is the extension of the rule
  that already governs the composite. The model returns
  `metrics.<r>.calculation`: for R1 the inputs and one row per charity-chain
  link (C1–C7) with the retention it applied, whether that came from a cited
  figure or a named default assumption, and the methodology clause quoted; for
  R3 the countries, recipient shares and median incomes; for R4 the three
  five-point components. PHP multiplies it out. Whatever total the model
  states for itself is kept as `score_claimed` and compared — a model whose
  prose total disagrees with its own ledger has told you how much to trust the
  prose. `config('ai.methodology_rates')` is a **second copy** of the rates in
  aaa-compassion.md and exists only to be disagreed with: the methodology wins
  every time and the row's own cited rate is what gets multiplied, but a
  difference is flagged on the row, which catches a model that misread the
  rubric *and* a rubric that was rewritten without anyone updating the config.
  Expect flags after editing aaa-compassion.md — that is the reminder.
- **Two R1 questions the methodology does not answer are settled in
  `LedgerCalculator`, not in the model.** Government grants: the methodology
  says "+75% of grant counted as output" but not how that meets the chain, so
  the ruling is that the grant counts in the denominator at face value and
  reaches output at 0.75 *exempt from the chain it never travelled* — worth
  ~11 points of R1 on a charity with a £600k grant against £2.4m of gifts, so
  change it in one place if the rewritten methodology says otherwise. C3 has
  two defensible rates (generic opaque fundraiser −50%, undisclosed call
  centre −25%); `also_accept` lets a link hold more than one correct rate so
  either passes the drift check and a third value still flags.
- **R3 is deliberately left unscored when the methodology contradicts itself.**
  Above $6,000 of country median income its bands table says 0% and its formula
  says 8.3%. `LedgerCalculator::recipient()` computes both; where they agree —
  every charity working only under the cap — that is the score, and where they
  diverge R3 comes back `null` with both totals shown in the report and in the
  Apply modal's helper text, for the reviewer to settle. Fixing this is a
  methodology edit, not a code change.
- **Trust in that report is quote-level, not provenance-level.**
  `Services\Ai\CitationVerifier` runs after the model answers: it fetches
  every cited URL not already in the pack and searches the source text for the
  quote — `verified`, `quote_not_found` (loud red), `no_quote`, `unreadable`.
  A page the model discovered is fetched, appended to the pack with
  `origin => 'model'` and cited like any other, because a keyword crawl loses
  to the model's own search often enough that penalising it by origin would
  throw away the better evidence. A quote that is absent from its own source is
  the thing worth flagging, and that is what the reviewer sees. Claims with
  neither a source ID nor a URL never reach the verifier — `validate()` has
  already separated them as "unverified claims".
- PDF text comes from **poppler's `pdftotext`**, shelled out like the Python
  loaders (`AI_PDFTOTEXT_BIN`, `Services\Ai\ContentExtractor`). Annual
  reports and audited accounts are PDFs and R1 lives in them; without local
  extraction the AI would be quoting a document nobody held. Missing binary =
  the run still completes, the report header says extraction was unavailable,
  and the provider's own fetch tool is the fallback.
- **The Claude provider is a cheap executor plus a strong advisor.** Reading a
  ~45k-token evidence pack and emitting a long JSON report is bulk work;
  deciding the chain and the integrity call is not. `AnthropicProvider` runs
  `claude-sonnet-5` with the beta **advisor tool** (`advisor-tool-2026-03-01`)
  pointed at `claude-opus-5`, which the executor consults mid-generation — the
  advisor must be at least as capable as the executor or the API returns 400,
  and an Opus advisor's reply is encrypted (`advisor_redacted_result`), so
  never read `.text` off it. The request is **streamed** (`max_tokens` has to
  fit a report plus three ledgers, and the SDK needs streaming at that size),
  `pause_turn` is looped rather than treated as an answer — a server-tool loop
  handing the turn back used to surface as "did not return usable JSON" — and
  a `refusal` stop reason is reported with its category instead of as a parse
  failure. The system prompt is cached at **1h**, not the default 5 minutes:
  runs are launched by hand, minutes to hours apart, so a 5-minute entry pays
  the write premium and expires unread. `usage` records cache *creation* next
  to cache reads for exactly that reason, plus web-tool request counts and the
  advisor's own tokens from `usage.iterations`.
- AI providers sit behind `Services\Ai\Contracts\AnalysisProvider` (Claude
  via the official SDK with server-side web_search/web_fetch, ChatGPT via the
  Responses API, Gemini via generateContent with google_search + url_context)
  and none of them uses a JSON-schema output mode — the contract is
  prompt-stated and enforced by the runner's tolerant parser, because the three
  vendors disagree about combining structured output with tool use. **The AI
  never writes a score.** Runs land in `charity_analyses`; "Apply scores" opens
  the suggestions as editable fields with a per-metric toggle, and only then
  does anything reach `charities`. Model IDs and keys are env-driven
  (`config/ai.php`); a provider with no key is shown disabled in the picker.
- Outbound fetches of admin-supplied addresses go through
  `Support\SafeUrlFetcher`, not Http directly: DataImport's host allow-list
  cannot work when the target is "any charity's website", so the guard is
  per-hop DNS resolution against private/reserved ranges, manual redirect
  following, and a byte cap.
- **Responses are gzipped by `App\Support\ResponseCompressor`**, called from a
  `RequestHandled` listener in AppServiceProvider — not middleware. Livewire
  injects its `<style>`/`<script>` tags from its own listener on that event,
  after the middleware pipeline has unwound, so compressing in middleware drops
  them. Public pages call `@livewireScripts` explicitly and looked fine; the
  admin panel relies on the injection and silently lost Alpine.
- MySQL-specific SQL throughout (FULLTEXT `MATCH…AGAINST` search, bulk
  `CASE WHEN` updates). Not portable to sqlite/postgres even though
  `.env.example` and phpunit.xml default to sqlite.

## Conventions

- **Laravel 13 / Livewire 4 / Filament 5 are newer than most training data.**
  Do not write Livewire or Filament API calls from memory (v3-era syntax will
  not work). Copy the pattern from an existing file in this repo: an existing
  Filament resource under `app/Filament/Resources/Charities/`, or an existing
  ⚡ page under `resources/views/pages/`.
- Runtime code reads `config('…')`, never `env('…')` — env() returns defaults
  after `config:cache`. Custom config files (config/irs.php, config/admin.php)
  exist exactly for this; follow the pattern.
- Migrations are idempotent and guard-heavy (see `database/CLAUDE.md`).
- Admin login is seeded from `ADMIN_NAME/EMAIL/PASSWORD` env by
  `AdminUserSeeder` (silent no-op if unset). The panel requires app-based 2FA —
  you cannot log in without an authenticator app.

## Gotchas

- Filenames like `resources/views/pages/⚡homepage.blade.php` are Livewire v4
  single-file-component convention — never "fix" the ⚡.
- `public/build/` is committed (force-added despite .gitignore) so shared
  hosts don't need Node. If you touch resources/css or resources/js, run
  `npm run build` and commit the result, or the deployed bundle goes stale.
- `public/css/`, `public/js/`, `public/fonts/` are Filament's published
  assets — regenerated by `php artisan filament:assets`, never hand-edited.
- `bootstrap/app.php` points at `routes/console.php`, which doesn't exist
  (Laravel tolerates this). Create it if you add scheduled tasks; the two
  console commands are auto-discovered from `app/Console/Commands/`.
- Docker: `RESCORE_ON_BOOT=true` adds ~14 min to container start. Leave false;
  rescore manually.

## Reference docs

- `DEPLOY_CPANEL.md` — full shared-hosting deploy runbook.
- `CCEW.md` / `CRA.md` — data dictionaries mapping regulator files to
  `charities` columns; read these before touching load_ccew.py / load_cra.py.
