The scenario-metrics route test now imports a module chain
(route → overlay.ts) that carries `import "server-only"`, which Vite can't
resolve to a Node entry. Alias it to an empty stub so the guard stays in app
code while Node-env tests load. Full suite: 600 passing.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- CONTEXT.md: add the Scenario overlay glossary term under Reporting.
- ADR-0015: the Scenario overlay is one read model behind both metrics endpoints.
- ADR-0016: the SAP↔EPC band threshold ladder has a single owner (@/lib/epc).
- ADR-0017: Likely downgrade is band-movement only; the SAP-05 signal is retired.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Money formatters: model.ts owns the single formatMoneyCompact + moneyFull;
components/primitives re-exports them (moneyCompact = formatMoneyCompact) and
the PDF's local money() is gone.
- ReportView: viewState.ts is the single definition; ScenarioCombobox re-exports
it instead of re-declaring.
- EPC_BANDS: the reporting API routes import the canonical @/lib/epc/bands
rather than the scenarios-model copy.
- compare/page uses countBelowBand(toBandCounts(...), "C") instead of a
hardcoded ["D","E","F","G"] reduce.
Typecheck + 95 reporting/epc tests green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Likely downgrade had two live definitions over near-disjoint populations: the
confidence strip used the legacy SAP-05 point comparison (legacy homes only),
while the data-quality page and drill-down used band movement (which yields 0
for legacy homes, whose lodged and effective band are the same column). So the
two surfaces could disagree for the same portfolio.
CONTEXT.md already calls the point-level signal "retired". This makes band
movement the single definition (lodged band vs effective band; real
certificates only):
- New shared SQL fragments likelyDowngradeSql / likelyUpgradeSql in
epcSources.ts — the SQL twin of model.classifyBandMovement.
- server.getLikelyDowngrades now counts band movement (was SAP-05, legacy-only),
so the confidence strip agrees with the data-quality page.
- getDataQualityMetrics and the drill-down route use the shared fragments.
Legacy portfolios now report likely-downgrades via band movement (0 where lodged
== effective), consistent everywhere. Typecheck + 86 reporting tests green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The block turning a ScenarioOverlay + current-stock totals into the ledger view
(carbonSaved, billSavings, cost-per-SAP, cost-per-carbon) was hand-written three
times — ReportingClientArea, the PDF page, and (partially) the Compare table —
where the ratios could silently disagree.
- model.ts gains deriveLedgerView() plus the atomic helpers amountSaved,
capitalOutlay, costPerSapPoint, costPerCarbonSaved. LedgerView moves here too
(re-exported from InvestmentLedger for existing imports).
- ReportingClientArea and pdf/page now call deriveLedgerView; their overlay
fetches are typed as ScenarioOverlay (candidate 3 wiring).
- Compare reuses the atomic helpers, keeping its null-for-"—" rendering.
- model.test.ts covers the derivation and its divide-by-zero guards.
Typecheck + 38 model tests green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The "After scenario" aggregate — the back half of Current → After — was
written twice: scenario/[scenarioId]/metrics (488 lines) and
scenario/default/metrics (316), differing only in plan scope. They drifted
independently (band thresholds, compliance-window predicate, ledger wiring all
duplicated) and sat outside the reporting folder.
Candidate 1+3+4 from the architecture review:
- New @/lib/reporting/overlay.ts owns all overlay SQL + shaping behind one
getScenarioOverlay(portfolioId, scope, filters, tags). The default
(recommended-plans) view is the scenario view with an inert filter set and no
EPC target, so it flows through the same code. Joins are now conditional on
what the active filters read, so an unfiltered overlay never joins the
lodged-certificate / legacy tables — strictly leaner than before. Dropped the
plans-only avg_*/total_* columns that were computed but never read.
- Both metrics routes are now thin adapters: parse+validate the request, call
the read model, return it (or 404).
- ScenarioOverlay is a single typed contract in ./model (client-safe), replacing
the untyped JSON re-typed across consumers. Dropped dead ScenarioOverlayMetrics
and MetricKey.
- Reporting reads leave the Next.js route folder for @/lib/reporting, matching
the repo's src/lib/<domain>/server.ts convention: databaseFunctions.ts +
measuresQuery.ts → server.ts; types.ts → types.ts; reportingScenarios.ts →
moved with its test. actions.ts stays as the "use server" seam.
- Deleted the dead reporting/utils.ts.
Behaviour-preserving (getLikelyDowngrades kept on the SAP-05 path here; retired
in the next commit). Typecheck + 89 reporting/epc tests green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The 92/81/69/55/39/21 band floors were defined in five places across TS and
SQL — @/app/utils.sapToEpc, a hand-copied sapToEpcLetter in actions, the
EPC_TO_SAP_MIN/MAX ranges, and the BAND_BUCKETS_SQL/EPC_MIN_SAP in both
scenario-metrics routes. "What SAP score is band C" now lives once in
@/lib/epc/thresholds (BAND_MIN_SAP), with a SQL twin in thresholdsSql.
- lib/epc/thresholds.ts: BAND_MIN_SAP, sapToBand, EPC_TO_SAP_MIN/MAX (derived)
- lib/epc/thresholdsSql.ts: sapBandBucketsSql() built from the same ladder
- @/app/utils.sapToEpc + @/app/utils/epc now delegate to the canonical ladder
- deleted the hand-copied sapToEpcLetter in actions/recommendations.ts
- both metrics routes use sapBandBucketsSql / BAND_MIN_SAP
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The left column (EPC distribution + About box) and the right column
(Investment ledger) ended at slightly different heights. Make the two
report columns equal height (items-stretch) and let each column's bottom
box grow to fill — the About/Recommended brief and the ledger card both
flex-1 — so their bottom edges always align regardless of content length.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Two requests in one: describe the scenario, and fill the blank space
under the EPC distribution (the left column was shorter than the ledger).
Both are solved by an "About this scenario" brief stacked beneath the EPC
distribution in the left column.
- New getScenarioConfig() reads the scenario's immutable config
(goal/target, housing type, budget, measure exclusions, fabric-first;
exclusions parsed from the `{a, b}` text column).
- The brief: a plain-language sentence ("what it takes to reach EPC C
across the portfolio's social homes…") plus a spec list (Goal, Stock,
Budget, Fabric-first, Excluded measures with human labels).
- Recommended plans gets a matching "About recommended plans" note.
- Tightened spacing so the fuller page still fits one A4 sheet.
Verified all three views (scenario / current stock / recommended) render
as one clean page.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The exported PDF split awkwardly — page 1 half-empty, the EPC + ledger
block pushed wholesale to page 2 — and rendered too wide. Cause: the
print CSS used `@page { margin: 0 }` plus a `transform: scale(0.94);
width: 106.4%` hack on .print-root, which renders wider than the sheet
and paginates badly (a scaled/oversized root can't break cleanly).
- Print CSS: real `@page { size: A4 portrait; margin: 12mm }`, drop the
transform-scale and width hack. (These classes are used only by the
report, so no other page is affected.)
- Constrain the report to A4 content width (max-w-190mm, centred) so it
can never render landscape/oversized, with on-screen padding that
collapses in print.
Result: cover + headline + KPI tiles + EPC distribution and Investment
ledger (side by side) + footer all fit one portrait page; current-stock
likewise. Verified by generating the real PDFs.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The report PDF was effectively broken/unfinished: it crashed locally
(self-fetch to a hardcoded :3000), only worked for a numeric scenario
("No scenario selected" from Current stock / Recommended), ignored the
new URL-driven tag + scenario filters, and printed bare because @media
print stripped background colours — so it "looked rubbish".
Rebuild it as the true print register of the reporting screen:
- Carries the full view state (view + filters + tags) from the Download
report link, so the pack matches exactly what's on screen.
- Supports every view: Current stock (baseline-only), Recommended plans
(default segment) and any scenario; filters/tags threaded through.
- Polished, print-safe layout: branded cover with the portfolio name,
headline, KPI tiles, EPC distribution (div bars, not the button-based
ladder that print hides), and the restyled Investment ledger reused
verbatim. A "Filtered view" note when filters/tags are active.
- Fix colour printing (print-color-adjust: exact on .print-root) and
drop the app chrome (portfolio-name banner + copyright footer) in print.
- Robust base URL (respects PORT in dev).
Also fixes a real bug the Recommended report surfaced: the default
metrics route omitted gross_cost (→ "£NaN gross" in the ledger) and
computed net as construction−funding with a contingency-less per-home.
It now uses computeLedger like the [scenarioId] route — fixing the
on-screen Recommended ledger too.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The modelling engine emits costed plans for homes already at a scenario's
target EPC band (e.g. ~£300–600 of low-energy lighting / system tune-ups
on effective-C homes in a "Reach EPC C" scenario). Counting them inflated
"Homes upgraded" and its costs, and stopped the KPI reconciling with the
below-target band distribution (portfolio 796 / scenario 1268: 9492
upgraded vs 9039 homes below C).
Add an interim guard to the scenario metrics upgrade aggregate (count +
cost): for Increasing-EPC scenarios, drop any home whose effective band
already meets the target (effective band <= goal_value; lexical, A best).
Unknown/NULL effective band is kept. Verified against the DB: scenario
1268 goes 9492 → 8871 upgraded, −£282k of works on compliant homes.
This is a reporting-only band-aid; the root cause is in the engine —
tracked in Hestia-Homes/Model#1652. The default/recommended view has no
single target band, so the guard doesn't apply there.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Apply the new structured tooltip treatment to the scenario filters, so
their descriptions read like the cost figures': a summary line plus a
subtle footnote, in the same larger, rounded ⓘ card.
- Extract the tooltip body into a shared `tipContent.tsx` (TipBody +
TipSpec); costHelp now consumes it instead of its own copy.
- FilterChips: the two toggle chips use the shared `InfoDot`; the
"skip already-compliant" popover reuses the same structured copy.
Filter help now lives in one `FILTER_HELP` map.
Copy/present only — no filter behaviour changed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The production build's `react/jsx-key` lint failed on the HelpBody
elements built inside COST_HELP's Object.fromEntries map. Add a key —
they're constructed in an array literal even though they're stored in an
object, so the rule applies.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The cost explanations were one dense paragraph in a small (0.75rem)
tooltip. Restructure them: a one-line definition followed by scannable
Includes (green ✓) and Excludes (grey −) lists, with a subtle noted
footnote where useful. Bump the tooltip text to 0.82rem, widen and
re-pad it, and give it a softer rounded card look.
costHelp.ts → costHelp.tsx: entries are now structured specs
(summary / includes / excludes / note) rendered to tooltip bodies;
InfoDot and KpiBand's `tip` accept ReactNode. No copy meaning changed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Users couldn't tell what the cost values include or exclude — e.g. does
"gross per home" cover contingency, is the principal contractor's price
in there. Add plain-language "what's included / excluded" disclosure
across the scenario overlay, sourced from one canonical copy module
(costHelp.ts) so every surface says it the same way and matches the
domain glossary.
- New shared `InfoDot` primitive (the one ⓘ affordance).
- Investment ledger: ⓘ on Net cost, gross/home, Construction works,
Project delivery, Contingency, Bill savings, Carbon saved, and the two
value-for-money ratios — each stating what it does/doesn't cover
(e.g. construction = the principal contractor's works, excludes
delivery + contingency; gross = works + delivery + contingency).
- KPI band gains an optional `tip`; the "Gross cost /home" KPI uses it.
- "Where the money goes" now notes it's construction works only, so it
reconciles to the Construction works line, not gross cost.
Copy only — no figures or queries changed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The scenario Investment ledger was a flat monochrome list. Give it a
visual hierarchy while keeping the reporting design vocabulary (quiet
navy-on-white, semantic green for benefits):
- lead with a Net cost hero block — the headline figure a board commits
to — with gross/home and the gross · funding breakdown beneath it;
- turn the cost lines into a colour-keyed composition bar (navy → gold →
grey, echoing the data-quality evidence bar) with matching dots;
- give annual benefits green icon-chip rows (they're recurring savings)
and value-for-money its own iconography;
- add section and header icons throughout.
Purely presentational — same LedgerView data, no behaviour change.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Follow-up to the layout tidy: the inset only applied to the issues table,
so it sat narrower than the cards above and below it. Constrain the whole
data-quality page at the container level (max-w-7xl) instead, so the
header and all three sections share the same edges, and dial the gutter
back from the earlier too-narrow max-w-6xl.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Three small visual fixes to the data-quality page:
- vertically centre the rows of the top issues table (was top-aligned, so
the count/impact/link hugged the top of each tall row);
- inset that table (max-w-6xl, centred) so it isn't stretched full-width
for its sparse content;
- replace the button-like "Template coming soon" box with a subtle muted
"Coming soon" status pill (clock icon), so it no longer reads as a
broken/disabled button.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The whole reporting view (scenario `view`, the scenario filters, and the
tag filter) now lives in the URL, so it survives refresh and browser
back/forward. `ReportingClientArea` reads the full `ReportingViewState`
from `useSearchParams` as the single source of truth, replacing the
`useState` for view/filters.
A single `applyViewState` writer routes each change by what it affects:
- a changed tag filter re-renders the server baseline → `router.replace`
(a brief metrics Suspense skeleton is correct; the data changes);
- a `view` or scenario-`filter` change only touches the client-fetched
overlay → History API (`pushState` for a scenario switch so Back has an
entry, `replaceState` for rapid filter toggles), so the baseline
Suspense never re-flashes.
Adds a pure `tagFiltersEqual` (order-insensitive; `includeMode` only
counts with 2+ includes) to decide the server-vs-client route.
Verified in a headless browser on portfolio 796: view+filters persist
across refresh and back/forward; view/filter changes make zero server
round-trips (no baseline re-flash) while a tag change makes exactly one.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds a view-wide tag filter to the reporting page. A "Tags" control in the
header lists the portfolio's tags; each can be Included (home must carry it) or
Excluded (home must not) — mutually exclusive per tag — with an Any/All switch
once two or more are included.
The filter is URL-driven (?includeTags=…&excludeTags=…&includeMode=all): the
server reads it and renders the baseline (current-stock figures) filtered, so it
survives refresh and back/forward. Changing it navigates and streams the
filtered figures back in via the Suspense boundaries. The scenario overlay,
measure allocation and drill-down all send the same tag params (in their
react-query keys), so the whole view stays consistent with the headline counts.
Scenario selection + scenario filters remain client state for now (instant, no
round-trip) — migrating those into the URL too is the documented next step.
Verified in a headless browser on #796: including the tag drops the homes count
31,398 → 607 (its exact membership) and writes ?includeTags=13 to the URL.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Threads the tag filter through every reporting query so the whole view reflects
the tagged subset: baseline aggregate, age-band + property-type counts, likely
downgrades, both scenario-metrics routes (all three property scans each), the
drill-down list, and the measures allocation. Each query ANDs
tagFilterCondition() into its WHERE; routes parse the filter from the URL via
the shared parseReportingViewState so they read exactly what the client wrote.
Defaults to the empty (no-op) filter, so existing callers/tests are unchanged.
Verified on #796/scenario 1292: include tag → n_units = the tag's membership
(607), exclude → the complement (30705), and the two EPC distributions
reconcile to the full portfolio total.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Foundation for filtering the reporting view by tags, URL-driven so the whole
view survives refresh and back/forward.
- viewState.ts: the reporting view as URL-serialisable state — scenario `view`,
the scenario filters, and the tag filter {include, exclude, includeMode}.
parse ⇄ serialize, defensively sanitised (numeric tag ids, dedupe,
include/exclude overlap → exclude wins, defaults omitted for clean URLs).
- tagFilterSql.ts: tagFilterCondition() → a SQL WHERE fragment. include=any
(EXISTS), include=all (COUNT DISTINCT = size), exclude (NOT EXISTS), empty =
TRUE (never filters everything out). Verified on real data (#796, #824):
include = membership count, exclude = complement, ANY = union, ALL =
intersection.
27 unit tests. No wiring yet — next: thread through the reporting queries + UI.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Switching from Current stock into a scenario has no previous overlay to keep,
so the scenario KPIs were momentarily empty — an empty-bar flash before the
figures loaded. That's the "no data yet" case, so it now shows the same
KpiBandSkeleton the initial page load uses (extracted + shared), and drops the
now-redundant "Loading scenario…" line there.
The dim + "Updating figures…" path is unchanged and stays for the cases where
data is already on screen (scenario→scenario switch, filter changes), where the
previous figures are deliberately kept via keepPreviousData. Net: skeleton = no
data yet; dim = refreshing existing data — one consistent convention.
Verified in a headless browser on #796: first entry shows the KPI skeleton +
aria-busy and no empty flash; a filter toggle still dims the figures with
"Updating figures…".
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The scenario overlay uses keepPreviousData, so switching scenario or changing
a filter left the previous figures on screen with nothing signalling they were
being recalculated. Now:
- The picker row shows a small spinner + "Updating…" beside the filter chips
while the overlay refetches — immediate feedback right at the controls. It
reads react-query's useIsFetching(["scenario-report"]) so the query stays
owned by MetricsBody (no lifting).
- The figures (KPI band + EPC distribution + ledger) dim (opacity-50, aria-busy)
while refetching with stale data on screen, and show a spinner + "Updating
figures…" / "Loading scenario…" line above them.
Verified end-to-end with a headless browser on portfolio 796: switching to an
"Increasing EPC" scenario and toggling a filter both surface the spinner,
"Updating…"/"Loading…" text, aria-busy and the dimmed figures.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The page previously awaited a Promise.all of every query in the server
component, so nothing painted until the slowest query returned. Now the page
kicks the queries off without awaiting and hands the promises to the client
area, which unwraps them with use() inside Suspense boundaries.
Result: the header + "Download report" paint on first byte; the scenario
picker streams in as soon as the (fast) scenarios query lands; the metrics
body (KPI band, EPC distribution, stock breakdown, confidence strip) streams
in when the baseline aggregate lands — each behind a skeleton fallback. The
current-stock "N homes" count sits in its own inner boundary so it never
holds back the picker.
All existing logic (KPIs, ledger, goal callout, drill-down, scenario overlay
via react-query, measure allocation) is preserved verbatim — just relocated
into the streamed MetricsBody. Verified end-to-end against portfolio 796
(authenticated, HTTP 200): shell + skeletons emit first, sections stream in.
Uses the same use(promise) pattern already shipping elsewhere in the app
(property pages unwrap params/searchParams the same way).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The overlay's dominant cost was a full sequential scan of property_details_epc
(the being-phased-out legacy table — ~600k rows, ~330ms warm, ~2.5s cold from
disk) on every query, because the LEFT JOIN was keyed on property_id alone.
property_details_epc has a (property_id, portfolio_id) composite index, so
adding `AND e.portfolio_id = <pid>` to the join turns the seq scan into an
index lookup. For migrated portfolios the legacy table holds ~0 rows, so the
join becomes near-free; for un-migrated ones it returns the same rows via the
index. EXPLAIN confirms 0 rows dropped and the exact (numeric) aggregates are
unchanged — only order-dependent ::float SUM accumulation jitters, which the
UI rounds away.
Applied to the scenario overlay (both [scenarioId] and default routes) and the
initial-load baseline aggregate. On portfolio #796: overlay handler ~1.6s →
~0.74s (warm; larger win cold), baseline query 790ms → 330ms.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Reporting was slow on large portfolios (e.g. #796) because every metric
re-scanned property ⋈ property_details_epc ⋈ newApproachJoins, and the
scenario overlay ran five queries strictly serially.
Baseline (initial load): the six queries that were the identical scan —
total, averages, totals, EPC-band distribution, estimated/actual split and
expired count — collapse into one conditional-aggregation pass. Age bands
(correlated subqueries) and likely downgrades (legacy-only join) stay
separate and run in parallel. 8 queries → 3; ~1945ms → ~787ms on #796,
results byte-identical.
Scenario overlay: Query 2 (portfolio-after aggregates) and Query 3 (EPC
distribution) were near-identical per-property LATERAL scans, and Q3
shipped one row per property to Node just to bucket bands in JS. Merged
into a single scan that buckets bands in SQL (thresholds matched to
sapToEpc exactly), and the three data queries now run in one Promise.all
wave instead of serially. Applied to both the [scenarioId] and default
routes. Verified identical aggregates + band counts on #796's ~31k-home
scenario.
All ADR-0002 / ADR-0010 semantics (effective baselines, compliance window,
lodged toggle) preserved unchanged.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
AnalyticsView.tsx imported and rendered QueriesReviewPanel, but that
component file was never added in any commit -- the import has been
dangling since it was introduced, breaking the production build with
"Module not found: Can't resolve './QueriesReviewPanel'".
Removes the import and its render block. The Queries/Review-with-Landlord
row can be reintroduced once the component actually exists.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Postcode searches can return ~100 addresses. Add a client-side filter
above the results that narrows the list live by address substring, so a
user can jump to a house number or street name without scrolling.
- Filter box only appears when a postcode returns more than 8 addresses
- Header count reflects the filtered subset (e.g. "12 of 97 addresses")
- Empty state when nothing matches; clear button and new searches reset it
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Postcode searches can return ~100 addresses. Add a client-side filter
above the results that narrows the list live by address substring, so a
user can jump to a house number or street name without scrolling.
- Filter box only appears when a postcode returns more than 8 addresses
- Header count reflects the filtered subset (e.g. "12 of 97 addresses")
- Empty state when nothing matches; clear button and new searches reset it
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The card rendered a blank value and "NaN%": Postgres returns column names
verbatim, so `AS without_epc` came back as `without_epc` while the code read
`withoutEpc` — undefined, and `undefined / total * 100` is NaN.
`db.execute<T>()` asserts the row shape rather than checking it, so tsc, lint and
the full suite all passed on the broken query. The previous field names (`estimated`,
`actual`) were single words and happened to survive the round trip; renaming to
camelCase did not. Quoted aliases are the existing convention (see utils.ts).
Verified against portfolio 839: keys come back as [withoutEpc, withEpc], and the
card renders 29 / "0.5% have no EPC on record".
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Impeccable critique (P1): the escalation was a bare blue text-link on the bar's
pale-blue tint, no persistent underline — invisible next to the navy primary,
and it's the exact action users hunt for. Promote it to a secondary button
(white fill + brand-navy border + check icon, fills on hover) so it stands out
without competing with "Choose a tag"; demote "Clear selection" to a legible
neutral underlined link (was blue-on-blue).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
"Homes Without an EPC" and "Expired EPCs" were both derived from estimatedSql,
which asks "was this picture gap-filled?". That conflates two different questions:
provenance (was it modelled?) and coverage (does a certificate exist?).
They used to agree, because a gap-fill implied no certificate. Model ADR-0054 ends
that: the gov EPC API only serves certs registered since 2012, so a pre-2012
dwelling is gap-filled even though a real, stale certificate exists — and gets the
new source='expired'. On portfolio 824, 375 of the 403 "without an EPC" homes have
exactly that: a real certificate, just an out-of-date one. A different, and far more
actionable, problem than never having been certified.
Two defects fell out of the same conflation:
- Every query matched source='predicted' literally, and `source` is plain text
with no enum or CHECK. An 'expired' row matches neither the lodged nor the
predicted alias, so the home would have read as having a VALID CURRENT cert —
silently gone from both cards, no Estimated badge, nothing to catch it.
- isExpiredSql read epl.registration_date alone, but 714 of 824's 4,873 lodged
certs carry only inspection_date. All 714 counted as current; 170 are in fact
>10 years old. lodgementDateSql already coalesced the two; expiry didn't.
The cards now partition on coverage: withoutEpcSql = no lodged AND no historical
record; isExpiredSql = a cert of either kind, out of date. estimatedSql keeps its
own meaning and spans the whole predicted slot, so an expired home is estimated AND
has an EPC — both true. The `AND estimated = false` guard is gone from the Expired
card: an expired home IS estimated, so it excluded the very homes being counted.
Legacy portfolios are untouched (632: 8/1662 before and after). 824 moves to
913 → 1,083 expired immediately (the inspection_date fix), then to 25 / 1,461 once
Model writes expired rows. Safe to deploy BEFORE Model — the predicates just find
none. The reverse was not safe, which is why this goes first.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
With a 7-row page size, the header "select all" (toggleAllPageRowsSelected)
only selected the visible 7 — so it never reached "all loaded", the condition
that reveals the "Select all N matching" escalation. It now selects every loaded
row (toggleAllRowsSelected):
- when everything matching is already loaded, that IS the whole set (tag via ids);
- when more match than are loaded (e.g. 250 loaded of 10,000), the escalation
appears and routes through mode:"filter" — the server resolves and tags the
entire matching set (getFilteredPropertyIds, chunked), so memory is never the
ceiling and no huge id list is sent from the client.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The header checkbox only selects loaded rows, so bulk-tagging a portfolio with
more properties than are loaded (250-row window) silently tagged just the page.
Bulk mode is now explicit (Gmail pattern): nothing selected = no target (Choose
a tag is disabled), so a tag can't be applied to everything by accident. Tick
rows to target them; once every loaded row is ticked and more match, a "Select
all N matching" escalation switches the target to the whole matching set,
resolved server-side via the existing assignments filter mode (no backend
change). Any manual checkbox change drops the escalation back to the explicit
selection; changing filters / leaving the mode clears it.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Surface Design Constraints, Planning Comments, Planning Status, and
Planning Suggested Approach in the Live Reporting properties table,
following the same read-path wiring as the previous planning columns
(query mapping, HubspotDeal type, column defs, hidden-by-default toggle,
CSV export, test fixtures). DB columns already exist via migration 0267.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Surface the four planning columns from hubspot_deal_data — Planning
Authority, Designated Area, Article 4 PD Rights, Listed Building — as
optional columns in the Live Reporting properties table.
The DB columns already exist (migration 0267); this wires them through
the read path only: query mapping, HubspotDeal type, column defs, the
column-visibility toggle (hidden by default), and CSV export. Rendered
as plain text since they are text columns in HubSpot.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The not-modelled banner and the toolbar both rendered a navy "Run modelling"
CTA whenever a portfolio had properties but no plans — two identical buttons.
The banner owns the action in that state, so the toolbar's Run modelling is now
hidden while the banner is up (it returns once everything is modelled or the
banner is dismissed). One primary CTA at a time, as intended.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>