Compare commits

...
Author SHA1 Message Date
TudorandClaude Opus 4.8 ed8c396eb9 feat(detail): move religious character into header details + mobile reveal
Religious character now sits with the other labelled header details (near
County / Constituency) as "Religious character: <denomination>" ("None" for
Does not apply / None), instead of as an identity chip.

On mobile/tablet (≤768px) the header details block was hidden outright; it's
now collapsed behind a "Show all details" toggle that reveals the full block
(headteacher, website, pupils, trust, phone, religious character, county,
constituency). Applied to both the primary and secondary detail views for
parity. Extends the e2e journey with the mobile toggle behaviour.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 12:18:12 +01:00
TudorandClaude Opus 4.8 a102508ef1 fix(data): strip any table alias in missing-column matcher, not just s.
PR Checks / Frontend Typecheck + Tests (pull_request) Successful in 1m1s
PR Checks / Backend Smoke (pull_request) Successful in 7s
PR Checks / Build Backend (no push) (pull_request) Successful in 17s
PR Checks / Build Frontend (no push) (pull_request) Successful in 42s
PR Checks / Build Pipeline (no push) (pull_request) Successful in 9s
PR Checks / AI Code Review (Claude) (pull_request) Successful in 2m49s
The graceful-degradation fallback keys off the column named in a Postgres
UndefinedColumn error, but the matcher only stripped an `s.` alias. The two
new dim_location columns (county, parliamentary_constituency) are selected
via the `l.` alias and Postgres reports them unquoted as
"column l.county does not exist" — which the old regex failed to match at
all, returning None.

If dim_school is rebuilt (telephone/nursery present) but dim_location is not
yet (county/parliamentary_constituency missing) — plausible since they are
independently-rebuilt dbt models — the fallback branch never matched and
load_school_data_as_dataframe() returned an empty DataFrame, showing zero
schools sitewide instead of degrading those columns to NULL.

Generalise the alias prefix to `\w+\.` and cover the l.-qualified case in
tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 09:58:27 +01:00
TudorandClaude Opus 4.8 684da611ff feat(detail): always show religious character, "None" for no religious character
PR Checks / Frontend Typecheck + Tests (pull_request) Successful in 1m1s
PR Checks / Backend Smoke (pull_request) Successful in 7s
PR Checks / Build Backend (no push) (pull_request) Successful in 22s
PR Checks / Build Frontend (no push) (pull_request) Successful in 43s
PR Checks / Build Pipeline (no push) (pull_request) Successful in 10s
PR Checks / AI Code Review (Claude) (pull_request) Failing after 2m56s
Previously the chip was hidden for "Does not apply"/"None". Show it in all
cases, rendering "None" for those two sentinel values.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 09:24:27 +01:00
TudorandClaude Opus 4.8 0186227ced feat(detail): surface GIAS identity/contact details, drop unwired sections
PR Checks / Frontend Typecheck + Tests (pull_request) Canceled after 58s
PR Checks / Backend Smoke (pull_request) Canceled after 0s
PR Checks / Build Backend (no push) (pull_request) Canceled after 0s
PR Checks / Build Frontend (no push) (pull_request) Canceled after 0s
PR Checks / Build Pipeline (no push) (pull_request) Canceled after 0s
PR Checks / AI Code Review (Claude) (pull_request) Canceled after 0s
Add seven school-identity fields to the detail header (both primary and
secondary views): age range, religious character, nursery and sixth-form
indicators as chips; telephone (tel: link), county and parliamentary
constituency as header details. religious_denomination, age_range and
has_sixth_form were already served; telephone, nursery_provision, county
and parliamentary_constituency are newly wired through the marts query
(with a NULL fallback for un-rebuilt marts, mirroring has_sixth_form) and
the school_info API response.

Remove three UI sections the backend never populated (always null): Year 1
Phonics, the SEN "types of additional needs" breakdown, and the average
class-size card — along with their now-dead props, route plumbing, and the
SenDetail/Phonics types + class_size_avg field.

Extend the e2e detail journey to assert the Phonics section is gone and the
new header fields render when the record carries them.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 09:23:08 +01:00
tudor d02a323cdc Merge pull request 'fix(detail): give Results Over Time chart more height on desktop' (#78) from fix/detail-trend-chart-taller into main
Stage (build -> staging -> E2E gate) / Build Backend (FastAPI) (push) Successful in 14s
Stage (build -> staging -> E2E gate) / Build Frontend (Next.js) (push) Successful in 58s
Stage (build -> staging -> E2E gate) / Build Pipeline (Meltano + dbt + Airflow) (push) Successful in 14s
Stage (build -> staging -> E2E gate) / Deploy to Staging (push) Successful in 1s
Stage (build -> staging -> E2E gate) / E2E Journeys against Staging (push) Successful in 1m13s
Reviewed-on: #78
2026-07-21 21:08:34 +00:00
TudorandClaude Opus 4.8 32f8a02862 fix(detail): give Results Over Time chart more height on desktop
PR Checks / Frontend Typecheck + Tests (pull_request) Successful in 1m6s
PR Checks / Backend Smoke (pull_request) Successful in 7s
PR Checks / Build Backend (no push) (pull_request) Successful in 11s
PR Checks / Build Frontend (no push) (pull_request) Successful in 47s
PR Checks / Build Pipeline (no push) (pull_request) Successful in 11s
PR Checks / AI Code Review (Claude) (pull_request) Successful in 13s
The trend chart was capped at 280px tall on desktop, squishing the
lines together and making them hard to read. Raise the base
.chartContainer height to 380px in both the primary and secondary
detail views.

Mobile is unaffected: the base value is already overridden to
height:auto by the existing max-width:768px query, where
PerformanceChart's own .chartWrapper carries the canvas height.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0146VHeLAWjDVE2B5uU67jCB
2026-07-21 22:05:10 +01:00
tudor 7e3096c881 Merge pull request 'feat(analytics): load Umami heatmap recorder' (#77) from feat/umami-heatmap-recorder into main
Stage (build -> staging -> E2E gate) / Build Backend (FastAPI) (push) Successful in 15s
Stage (build -> staging -> E2E gate) / Build Frontend (Next.js) (push) Successful in 54s
Stage (build -> staging -> E2E gate) / Build Pipeline (Meltano + dbt + Airflow) (push) Successful in 13s
Stage (build -> staging -> E2E gate) / Deploy to Staging (push) Successful in 1s
Stage (build -> staging -> E2E gate) / E2E Journeys against Staging (push) Successful in 47s
Reviewed-on: #77
2026-07-21 15:06:04 +00:00
TudorandClaude Opus 4.8 1f80571b1f feat(analytics): load Umami heatmap recorder
PR Checks / Frontend Typecheck + Tests (pull_request) Successful in 1m4s
PR Checks / Backend Smoke (pull_request) Successful in 7s
PR Checks / Build Backend (no push) (pull_request) Successful in 11s
PR Checks / Build Frontend (no push) (pull_request) Successful in 47s
PR Checks / Build Pipeline (no push) (pull_request) Successful in 10s
PR Checks / AI Code Review (Claude) (pull_request) Failing after 42s
Adds the Umami session recorder (recorder.js) that powers heatmaps,
alongside the existing analytics tracker. Loaded via next/script with
the same data-domains guard as the main tracker so it only fires on the
production hostnames — staging runs the same image under a different
host and must not feed the heatmap.

Cookieless: recorder.js uses Umami's server-side session model (no
cookie or local storage on the device), so it adds no new PECR
consent trigger.

Verified with tsc --noEmit and next build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0146VHeLAWjDVE2B5uU67jCB
2026-07-21 16:03:18 +01:00
tudor 3132f07af2 Merge pull request 'fix(detail): compare each SATs bar to its own national benchmark' (#76) from fix/sats-per-level-national into main
Stage (build -> staging -> E2E gate) / Build Backend (FastAPI) (push) Successful in 20s
Stage (build -> staging -> E2E gate) / Build Frontend (Next.js) (push) Successful in 51s
Stage (build -> staging -> E2E gate) / Build Pipeline (Meltano + dbt + Airflow) (push) Successful in 14s
Stage (build -> staging -> E2E gate) / Deploy to Staging (push) Successful in 1s
Stage (build -> staging -> E2E gate) / E2E Journeys against Staging (push) Successful in 44s
Reviewed-on: #76
2026-07-21 13:56:55 +00:00
TudorandClaude Opus 4.8 8a9ba30cc2 fix(detail): compare each SATs bar to its own national benchmark
PR Checks / Frontend Typecheck + Tests (pull_request) Successful in 1m2s
PR Checks / Backend Smoke (pull_request) Successful in 7s
PR Checks / Build Backend (no push) (pull_request) Successful in 18s
PR Checks / Build Frontend (no push) (pull_request) Successful in 45s
PR Checks / Build Pipeline (no push) (pull_request) Successful in 10s
PR Checks / AI Code Review (Claude) (pull_request) Successful in 9s
The KS2 SATs chart drew a single national-average line spanning the
full height of each subject's chart area, positioned at the national
*expected* value. But the area stacks two bars — Expected and Exceeding
— and the higher-standard/greater-depth national is a very different,
much lower figure (e.g. reading higher standard ~29% vs expected ~75%).
So the line crossed the Exceeding bar at the wrong place, making every
school's exceeding result look far below national when it wasn't.

The per-subject higher-standard nationals were already computed in the
fact_ks2_national_averages mart; they just weren't serialized. Fix:

- backend: add reading_high_pct, writing_gd_pct (writing = greater
  depth) and maths_high_pct to the national-averages payload.
- SchoolDetailView: pass a nationalExceedingPct per subject, mapping
  writing to the greater-depth figure.
- SatsChart: replace the single full-height line with a national marker
  on each bar's own track (coral tick + "nat X%" in the bar header), so
  Expected and Exceeding each sit against the correct benchmark.

KS2 only; the secondary Attainment 8 chart already uses one line for
one measure and is untouched.

Verified: tsc --noEmit, next build, and backend pytest (national
averages marts, incl. a new test guarding the per-subject nationals).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0146VHeLAWjDVE2B5uU67jCB
2026-07-21 14:55:43 +01:00
14 changed files with 404 additions and 153 deletions
+8
View File
@@ -606,17 +606,21 @@ async def get_school_details(request: Request, urn: int):
"religious_denomination": latest.get("religious_denomination", ""), "religious_denomination": latest.get("religious_denomination", ""),
"age_range": latest.get("age_range", ""), "age_range": latest.get("age_range", ""),
"has_sixth_form": latest.get("has_sixth_form"), "has_sixth_form": latest.get("has_sixth_form"),
"nursery_provision": latest.get("nursery_provision"),
"status": latest.get("status"), "status": latest.get("status"),
"latitude": latest.get("latitude"), "latitude": latest.get("latitude"),
"longitude": latest.get("longitude"), "longitude": latest.get("longitude"),
"phase": latest.get("phase"), "phase": latest.get("phase"),
# GIAS fields # GIAS fields
"website": latest.get("website"), "website": latest.get("website"),
"telephone": latest.get("telephone"),
"headteacher_name": latest.get("headteacher_name"), "headteacher_name": latest.get("headteacher_name"),
"capacity": latest.get("capacity"), "capacity": latest.get("capacity"),
"total_pupils": latest.get("gias_total_pupils"), "total_pupils": latest.get("gias_total_pupils"),
"trust_name": latest.get("trust_name"), "trust_name": latest.get("trust_name"),
"gender": latest.get("gender"), "gender": latest.get("gender"),
"county": latest.get("county"),
"parliamentary_constituency": latest.get("parliamentary_constituency"),
}.items() }.items()
} }
@@ -807,6 +811,10 @@ async def get_la_averages(request: Request):
_KS2_NATIONAL_METRICS = [ _KS2_NATIONAL_METRICS = [
"rwm_expected_pct", "rwm_high_pct", "rwm_expected_pct", "rwm_high_pct",
"reading_expected_pct", "writing_expected_pct", "maths_expected_pct", "reading_expected_pct", "writing_expected_pct", "maths_expected_pct",
# Per-subject higher-standard nationals: reading/maths reach the "higher
# standard" in the tests; writing is teacher-assessed at "greater depth"
# (writing_gd_pct). Needed so each SATs bar compares to its own benchmark.
"reading_high_pct", "writing_gd_pct", "maths_high_pct",
"gps_expected_pct", "gps_high_pct", "science_expected_pct", "gps_expected_pct", "gps_high_pct", "science_expected_pct",
"reading_avg_score", "maths_avg_score", "gps_avg_score", "reading_avg_score", "maths_avg_score", "gps_avg_score",
"reading_progress", "writing_progress", "maths_progress", "reading_progress", "writing_progress", "maths_progress",
+47 -1
View File
@@ -169,6 +169,8 @@ _MAIN_QUERY = text("""
s.total_pupils AS gias_total_pupils, s.total_pupils AS gias_total_pupils,
s.headteacher_name, s.headteacher_name,
s.website, s.website,
s.telephone,
s.nursery_provision,
foi.ofsted_grade, foi.ofsted_grade,
foi.ofsted_date, foi.ofsted_date,
foi.ofsted_framework, foi.ofsted_framework,
@@ -178,6 +180,8 @@ _MAIN_QUERY = text("""
l.address_line1 AS address1, l.address_line1 AS address1,
l.address_line2 AS address2, l.address_line2 AS address2,
l.town, l.town,
l.county,
l.parliamentary_constituency,
l.postcode, l.postcode,
l.latitude, l.latitude,
l.longitude, l.longitude,
@@ -301,6 +305,32 @@ for _old, _new in _LEGACY_NAME_REPLACEMENTS:
_MAIN_QUERY_LEGACY_NAMES = _MAIN_QUERY_LEGACY_NAMES.replace(_old, _new) _MAIN_QUERY_LEGACY_NAMES = _MAIN_QUERY_LEGACY_NAMES.replace(_old, _new)
_MAIN_QUERY_LEGACY_NAMES = text(_MAIN_QUERY_LEGACY_NAMES) _MAIN_QUERY_LEGACY_NAMES = text(_MAIN_QUERY_LEGACY_NAMES)
# Fallback used when marts predate the optional GIAS/location detail columns
# (telephone, nursery provision, county, parliamentary constituency) — i.e. the
# nightly dbt pipeline hasn't rebuilt the mart yet on this DB. Keeps each column
# present as NULL so the whole data load degrades gracefully instead of failing.
_EXTRA_OPTIONAL_COLUMNS = (
"telephone",
"nursery_provision",
"county",
"parliamentary_constituency",
)
_MAIN_QUERY_NO_EXTRA_COLS = str(_MAIN_QUERY)
for _col, _tbl in (
("telephone", "s"),
("nursery_provision", "s"),
("county", "l"),
("parliamentary_constituency", "l"),
):
_src = f"{_tbl}.{_col},"
assert _src in _MAIN_QUERY_NO_EXTRA_COLS, (
f"expected {_src!r} to be present in _MAIN_QUERY before replacement"
)
_MAIN_QUERY_NO_EXTRA_COLS = _MAIN_QUERY_NO_EXTRA_COLS.replace(
_src, f"NULL AS {_col},"
)
_MAIN_QUERY_NO_EXTRA_COLS = text(_MAIN_QUERY_NO_EXTRA_COLS)
_GIAS_CODE_COLUMN_NAMES = ( _GIAS_CODE_COLUMN_NAMES = (
"phase_code", "phase_code",
"school_type_code", "school_type_code",
@@ -309,7 +339,11 @@ _GIAS_CODE_COLUMN_NAMES = (
"admissions_policy_code", "admissions_policy_code",
) )
_MISSING_COLUMN_RE = re.compile(r'column "?(?:s\.)?(\w+)"? does not exist') # Strip any single table alias prefix (s., l., p., foi., …) — Postgres reports
# an undefined *qualified* column unquoted as "column l.county does not exist",
# so matching only the s. alias would miss dim_location columns (county,
# parliamentary_constituency) and defeat the graceful-degradation fallback.
_MISSING_COLUMN_RE = re.compile(r'column "?(?:\w+\.)?(\w+)"? does not exist')
def _missing_column_name(exc: Exception) -> Optional[str]: def _missing_column_name(exc: Exception) -> Optional[str]:
@@ -352,6 +386,18 @@ def load_school_data_as_dataframe() -> pd.DataFrame:
except Exception as exc2: except Exception as exc2:
print(f"Warning: Could not load school data from marts: {exc2}") print(f"Warning: Could not load school data from marts: {exc2}")
return pd.DataFrame() return pd.DataFrame()
elif missing in _EXTRA_OPTIONAL_COLUMNS:
logging.getLogger(__name__).warning(
"marts.dim_school/dim_location is missing %s (pipeline hasn't "
"rebuilt the mart yet on this DB) — retrying without the "
"optional detail columns: %s",
missing, exc,
)
try:
df = pd.read_sql(_MAIN_QUERY_NO_EXTRA_COLS, engine)
except Exception as exc2:
print(f"Warning: Could not load school data from marts: {exc2}")
return pd.DataFrame()
else: else:
print(f"Warning: Could not load school data from marts: {exc}") print(f"Warning: Could not load school data from marts: {exc}")
return pd.DataFrame() return pd.DataFrame()
+18
View File
@@ -73,6 +73,24 @@ def test_missing_column_name_table_prefixed():
) )
def test_missing_column_name_location_alias_prefixed():
# dim_location columns are selected via the `l.` alias; Postgres reports a
# missing qualified column unquoted (e.g. "column l.county does not exist").
# The matcher must strip any alias, not just `s.`, or the county /
# parliamentary_constituency fallback never triggers and the whole data
# load degrades to an empty DataFrame (zero schools) instead of NULLs.
assert (
_missing_column_name(_fake_exc("column l.county does not exist"))
== "county"
)
assert (
_missing_column_name(
_fake_exc("column l.parliamentary_constituency does not exist")
)
== "parliamentary_constituency"
)
def test_missing_column_name_no_match_returns_none(): def test_missing_column_name_no_match_returns_none():
assert _missing_column_name(_fake_exc("relation \"marts.dim_school\" does not exist")) is None assert _missing_column_name(_fake_exc("relation \"marts.dim_school\" does not exist")) is None
@@ -25,6 +25,11 @@ class _Ks2Row:
year = LATEST year = LATEST
rwm_expected_pct = 62.1 rwm_expected_pct = 62.1
gps_expected_pct = 72.0 gps_expected_pct = 72.0
# Per-subject higher-standard nationals — reading/maths reach the higher
# standard, writing is teacher-assessed at greater depth (writing_gd_pct).
reading_high_pct = 29.0
writing_gd_pct = 13.0
maths_high_pct = 24.0
class _Ks4Row: class _Ks4Row:
@@ -84,6 +89,16 @@ def test_ks4_averages_come_from_the_mart_not_the_dataframe(payload):
assert body["by_year"][-1]["secondary"]["progress_8_score"] == -0.02 assert body["by_year"][-1]["secondary"]["progress_8_score"] == -0.02
def test_per_subject_higher_standard_nationals_are_surfaced(payload):
# The SATs chart compares each bar to its own benchmark, so the per-subject
# higher-standard / greater-depth nationals must reach the payload — not
# only the combined rwm_high_pct.
body = payload(_StubSession)
assert body["primary"]["reading_high_pct"] == 29.0
assert body["primary"]["writing_gd_pct"] == 13.0
assert body["primary"]["maths_high_pct"] == 24.0
def test_ks4_secondary_empty_when_mart_missing(payload): def test_ks4_secondary_empty_when_mart_missing(payload):
# No computed stand-in: the UI labels national figures as official DfE # No computed stand-in: the UI labels national figures as official DfE
# data, so an empty mart must yield an empty secondary series. # data, so an empty mart must yield an empty secondary series.
+45
View File
@@ -121,6 +121,51 @@ test('school detail page renders name and performance data', async ({ page }) =>
await expect(page.locator('canvas:visible').first()).toBeVisible({ timeout: 15_000 }); await expect(page.locator('canvas:visible').first()).toBeVisible({ timeout: 15_000 });
}); });
test('school detail page shows GIAS identity/contact details and drops the unwired Phonics section', async ({ page }) => {
const [urn] = await twoPrimaryUrns(page);
const res = await page.request.get(`/api/schools/${urn}`);
expect(res.ok()).toBeTruthy();
const info = (await res.json()).school_info;
await page.goto(`/school/${urn}`);
await expect(page.locator('h1').first()).toBeVisible({ timeout: 15_000 });
// Phonics, SEN-type breakdown and average class size were never populated by
// the backend — the sections have been removed, so the Phonics section (its
// own #phonics anchor) must no longer exist.
await expect(page.locator('#phonics')).toHaveCount(0);
// Newly surfaced GIAS/location fields render when the record carries them.
const ageMatch = String(info.age_range ?? '').match(/^\s*(\d+)\s*[-]\s*(\d+)\s*$/);
if (ageMatch) {
await expect(page.getByText(`Ages ${ageMatch[1]}${ageMatch[2]}`).first()).toBeVisible();
}
if (info.telephone) {
await expect(page.locator('a[href^="tel:"]').first()).toBeVisible();
}
if (info.parliamentary_constituency) {
await expect(page.getByText('Constituency:').first()).toBeVisible();
}
});
test('header details collapse behind a "Show all details" toggle on mobile', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const [urn] = await twoPrimaryUrns(page);
await page.goto(`/school/${urn}`);
await expect(page.locator('h1').first()).toBeVisible({ timeout: 15_000 });
// Collapsed by default on mobile/tablet …
const details = page.locator('#school-header-details');
await expect(details).toBeHidden();
const toggle = page.getByRole('button', { name: /show all details/i });
await expect(toggle).toBeVisible();
// … and the link reveals them (label flips to "Hide details").
await toggle.click();
await expect(details).toBeVisible();
await expect(page.getByRole('button', { name: /hide details/i })).toBeVisible();
});
test('a report-card school shows its report card, dated to the report-card inspection', async ({ page }) => { test('a report-card school shows its report card, dated to the report-card inspection', async ({ page }) => {
// Detail views detected report cards via `framework`, which the API never // Detail views detected report cards via `framework`, which the API never
// sets to "ReportCard" — so report-card schools rendered as legacy ratings // sets to "ReportCard" — so report-card schools rendered as legacy ratings
+8
View File
@@ -85,6 +85,14 @@ export default function RootLayout({
data-performance="true" data-performance="true"
strategy="afterInteractive" strategy="afterInteractive"
/> />
{/* Heatmap / session recorder — same data-domains guard so staging
(same image, different host) never feeds the heatmap. */}
<Script
src="https://analytics.schoolcompare.co.uk/recorder.js"
data-website-id="d7fb0c95-bb6c-4336-8209-bd10077e50dd"
data-domains="schoolcompare.co.uk,www.schoolcompare.co.uk"
strategy="afterInteractive"
/>
</head> </head>
<body className={`${dmSans.variable} ${playfairDisplay.variable}`}> <body className={`${dmSans.variable} ${playfairDisplay.variable}`}>
<div className="noise-overlay" /> <div className="noise-overlay" />
+1 -5
View File
@@ -133,7 +133,7 @@ export default async function SchoolPage({ params }: SchoolPageProps) {
notFound(); notFound();
} }
const { school_info, yearly_data, absence_data, ofsted, census, admissions, admissions_history, sen_detail, phonics, deprivation, finance } = data; const { school_info, yearly_data, absence_data, ofsted, census, admissions, admissions_history, deprivation, finance } = data;
// Redirect bare URN to canonical slug URL // Redirect bare URN to canonical slug URL
const canonicalSlug = schoolUrl(urn, school_info.school_name).replace('/school/', ''); const canonicalSlug = schoolUrl(urn, school_info.school_name).replace('/school/', '');
@@ -191,8 +191,6 @@ export default async function SchoolPage({ params }: SchoolPageProps) {
ofsted={ofsted ?? null} ofsted={ofsted ?? null}
census={census ?? null} census={census ?? null}
admissions={admissions ?? null} admissions={admissions ?? null}
senDetail={sen_detail ?? null}
phonics={phonics ?? null}
deprivation={deprivation ?? null} deprivation={deprivation ?? null}
finance={finance ?? null} finance={finance ?? null}
/> />
@@ -205,8 +203,6 @@ export default async function SchoolPage({ params }: SchoolPageProps) {
census={census ?? null} census={census ?? null}
admissions={admissions ?? null} admissions={admissions ?? null}
admissionsHistory={admissions_history ?? []} admissionsHistory={admissions_history ?? []}
senDetail={sen_detail ?? null}
phonics={phonics ?? null}
deprivation={deprivation ?? null} deprivation={deprivation ?? null}
finance={finance ?? null} finance={finance ?? null}
/> />
+31 -15
View File
@@ -44,30 +44,46 @@
background: var(--bg-secondary, #f3ede4); background: var(--bg-secondary, #f3ede4);
} }
/* ── National average marker ── */ /* ── Per-bar national average marker ──
.natLine { Each bar compares against its own benchmark (expected vs higher standard /
greater depth), so the marker sits on the individual bar's track rather than
as one line spanning both bars. */
.natTick {
position: absolute; position: absolute;
top: 0; top: -3px;
height: calc(100% - 20px); bottom: -3px;
width: 1.5px; width: 2px;
background: rgba(224, 114, 86, 0.35); /* --accent-coral at 35% */ transform: translateX(-50%);
z-index: 2; background: var(--accent-coral, #e07256);
border-radius: 2px;
z-index: 4;
pointer-events: none; pointer-events: none;
} }
.natPill { .natTick::before {
content: '';
position: absolute; position: absolute;
top: -10px; top: -3px;
left: 50%;
transform: translateX(-50%); transform: translateX(-50%);
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--accent-coral, #e07256); background: var(--accent-coral, #e07256);
color: #fff; }
.barHeaderRight {
display: flex;
align-items: baseline;
gap: 0.4rem;
}
.natLabel {
font-size: 0.55rem; font-size: 0.55rem;
font-weight: 700; font-weight: 700;
padding: 0.1rem 0.35rem; color: var(--accent-coral-dark, #b04a2e);
border-radius: 4px; text-transform: uppercase;
white-space: nowrap; letter-spacing: 0.03em;
z-index: 3;
letter-spacing: 0.02em;
} }
/* ── Bar rows ── */ /* ── Bar rows ── */
+54 -36
View File
@@ -8,6 +8,9 @@ interface SubjectData {
expectedPct: number | null; expectedPct: number | null;
exceedingPct: number | null; exceedingPct: number | null;
nationalExpectedPct: number | null; nationalExpectedPct: number | null;
/** National higher-standard / greater-depth benchmark for the exceeding
* bar — a different figure from the expected national. */
nationalExceedingPct: number | null;
} }
interface SatsChartProps { interface SatsChartProps {
@@ -17,11 +20,45 @@ interface SatsChartProps {
const RULER_TICKS = [0, 25, 50, 75, 100]; const RULER_TICKS = [0, 25, 50, 75, 100];
const GRIDLINE_POSITIONS = [25, 50, 75]; const GRIDLINE_POSITIONS = [25, 50, 75];
/** One results bar with a national marker positioned on its own track, so the
* expected and exceeding bars each compare against their own benchmark. */
function BarRow({
label,
value,
national,
barRef,
barClass,
}: {
label: string;
value: number;
national: number | null;
barRef: React.RefObject<HTMLDivElement | null>;
barClass: string;
}) {
return (
<div className={styles.barRow}>
<div className={styles.barHeader}>
<span className={styles.barLabelSuffix}>{label}</span>
<span className={styles.barHeaderRight}>
{national != null && <span className={styles.natLabel}>nat {national.toFixed(0)}%</span>}
<span className={styles.barLabel}>{value.toFixed(0)}%</span>
</span>
</div>
<div className={styles.barTrack}>
<div ref={barRef} className={`${styles.bar} ${barClass}`} data-width={value} />
{national != null && (
<div className={styles.natTick} style={{ left: `${national}%` }} aria-hidden="true" />
)}
</div>
</div>
);
}
function SubjectColumn({ subject }: { subject: SubjectData }) { function SubjectColumn({ subject }: { subject: SubjectData }) {
const expectedRef = useRef<HTMLDivElement>(null); const expectedRef = useRef<HTMLDivElement>(null);
const exceedingRef = useRef<HTMLDivElement>(null); const exceedingRef = useRef<HTMLDivElement>(null);
const { name, expectedPct, exceedingPct, nationalExpectedPct } = subject; const { name, expectedPct, exceedingPct, nationalExpectedPct, nationalExceedingPct } = subject;
// Animate bars on mount // Animate bars on mount
useEffect(() => { useEffect(() => {
@@ -51,44 +88,25 @@ function SubjectColumn({ subject }: { subject: SubjectData }) {
))} ))}
</div> </div>
{/* National average marker */} {/* Bars — each carries its own national marker */}
{nationalExpectedPct != null && (
<div className={styles.natLine} style={{ left: `${nationalExpectedPct}%` }}>
<div className={styles.natPill}>{nationalExpectedPct.toFixed(0)}%</div>
</div>
)}
{/* Bars */}
<div className={styles.barGroup}> <div className={styles.barGroup}>
{expectedPct != null && ( {expectedPct != null && (
<div className={styles.barRow}> <BarRow
<div className={styles.barHeader}> label="Expected"
<span className={styles.barLabelSuffix}>Expected</span> value={expectedPct}
<span className={styles.barLabel}>{expectedPct.toFixed(0)}%</span> national={nationalExpectedPct}
</div> barRef={expectedRef}
<div className={styles.barTrack}> barClass={styles.barExpected}
<div />
ref={expectedRef}
className={`${styles.bar} ${styles.barExpected}`}
data-width={expectedPct}
/>
</div>
</div>
)} )}
{exceedingPct != null && ( {exceedingPct != null && (
<div className={styles.barRow}> <BarRow
<div className={styles.barHeader}> label="Exceeding"
<span className={styles.barLabelSuffix}>Exceeding</span> value={exceedingPct}
<span className={styles.barLabel}>{exceedingPct.toFixed(0)}%</span> national={nationalExceedingPct}
</div> barRef={exceedingRef}
<div className={styles.barTrack}> barClass={styles.barExceeding}
<div />
ref={exceedingRef}
className={`${styles.bar} ${styles.barExceeding}`}
data-width={exceedingPct}
/>
</div>
</div>
)} )}
</div> </div>
@@ -135,7 +153,7 @@ export default function SatsChart({ subjects }: SatsChartProps) {
Exceeding / high score Exceeding / high score
</div> </div>
<div className={styles.legendItem}> <div className={styles.legendItem}>
<div className={styles.legendSwatch} style={{ background: 'var(--accent-coral, #e07256)', borderRadius: '50%' }} /> <div className={styles.legendSwatch} style={{ background: 'var(--accent-coral, #e07256)', width: '3px', height: '12px', borderRadius: '2px' }} />
National average National average
</div> </div>
</div> </div>
@@ -197,6 +197,22 @@
text-decoration: underline; text-decoration: underline;
} }
/* "Show all details" reveal — only rendered on mobile/tablet, where the
header details block is collapsed below the fold. Hidden on desktop. */
.detailsToggle {
display: none;
align-items: center;
gap: 0.25rem;
margin-top: 0.5rem;
padding: 0;
background: none;
border: none;
font-size: 0.8125rem;
font-weight: 600;
color: var(--accent-teal, #2d7d7d);
cursor: pointer;
}
/* Gender split card — sits in the Pupils & Inclusion heroStatGrid */ /* Gender split card — sits in the Pupils & Inclusion heroStatGrid */
.genderSplitValue { .genderSplitValue {
display: flex; display: flex;
@@ -855,7 +871,10 @@
/* Charts Section */ /* Charts Section */
.chartContainer { .chartContainer {
width: 100%; width: 100%;
height: 280px; /* Taller on desktop so the trend lines have vertical room to separate
and read clearly. Mobile overrides this to height:auto below (the
max-width:768px query), so this only affects desktop. */
height: 380px;
position: relative; position: relative;
} }
@@ -1202,14 +1221,24 @@
gap: 0.375rem; gap: 0.375rem;
} }
/* Secondary header info (headteacher, website, pupil count, trust) /* Secondary header info (headteacher, website, pupil count, trust,
isn't needed above the fold on phones — pupil count lives in the contact, area) isn't needed above the fold on phones/tablets, so it's
Pupils & Inclusion section, website is one scroll away. Reclaim collapsed by default and revealed on demand via the "Show all details"
the ~3 vertical lines so the actual metrics surface sooner. */ link — reclaiming the vertical space so the metrics surface sooner. */
.detailsToggle {
display: inline-flex;
}
.headerDetails { .headerDetails {
display: none; display: none;
} }
.headerDetailsOpen {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.metricsGrid { .metricsGrid {
grid-template-columns: repeat(2, 1fr); grid-template-columns: repeat(2, 1fr);
} }
+61 -66
View File
@@ -14,11 +14,11 @@ import { MetricTooltip } from './MetricTooltip';
import type { import type {
School, SchoolResult, AbsenceData, School, SchoolResult, AbsenceData,
OfstedInspection, SchoolCensus, OfstedInspection, SchoolCensus,
SchoolAdmissions, SenDetail, Phonics, SchoolAdmissions,
SchoolDeprivation, SchoolFinance, NationalAverages, SchoolDeprivation, SchoolFinance, NationalAverages,
} from '@/lib/types'; } from '@/lib/types';
import { import {
formatPercentage, formatProgress, formatAcademicYear, isProposedToClose, ofstedLegacyAreas, isSpecialSchool, formatPercentage, formatProgress, formatAcademicYear, formatAgeRange, isProposedToClose, ofstedLegacyAreas, isSpecialSchool,
} from '@/lib/utils'; } from '@/lib/utils';
import { DeltaChip } from './DeltaChip'; import { DeltaChip } from './DeltaChip';
import { SpecialSchoolNote } from './SpecialSchoolNote'; import { SpecialSchoolNote } from './SpecialSchoolNote';
@@ -68,15 +68,13 @@ interface SchoolDetailViewProps {
census: SchoolCensus | null; census: SchoolCensus | null;
admissions: SchoolAdmissions | null; admissions: SchoolAdmissions | null;
admissionsHistory: SchoolAdmissions[]; admissionsHistory: SchoolAdmissions[];
senDetail: SenDetail | null;
phonics: Phonics | null;
deprivation: SchoolDeprivation | null; deprivation: SchoolDeprivation | null;
finance: SchoolFinance | null; finance: SchoolFinance | null;
} }
export function SchoolDetailView({ export function SchoolDetailView({
schoolInfo, yearlyData, absenceData, schoolInfo, yearlyData, absenceData,
ofsted, census, admissions, admissionsHistory, senDetail, phonics, deprivation, finance, ofsted, census, admissions, admissionsHistory, deprivation, finance,
}: SchoolDetailViewProps) { }: SchoolDetailViewProps) {
const router = useRouter(); const router = useRouter();
const { addSchool, removeSchool, isSelected } = useComparison(); const { addSchool, removeSchool, isSelected } = useComparison();
@@ -101,6 +99,9 @@ export function SchoolDetailView({
const heroMapRef = useRef<SchoolHeroMapHandle>(null); const heroMapRef = useRef<SchoolHeroMapHandle>(null);
// "All ▾" jump menu listing every section. // "All ▾" jump menu listing every section.
const [sectionsOpen, setSectionsOpen] = useState(false); const [sectionsOpen, setSectionsOpen] = useState(false);
// Header details (headteacher, contact, trust, area) collapse behind a
// "Show all details" link on mobile/tablet, where they're below the fold.
const [detailsOpen, setDetailsOpen] = useState(false);
// Back returns to wherever the user came from; deep-links (no in-app history) // Back returns to wherever the user came from; deep-links (no in-app history)
// fall back to search so the button never dead-ends or leaves the site. // fall back to search so the button never dead-ends or leaves the site.
@@ -161,14 +162,12 @@ export function SchoolDetailView({
// Phase detection. All-through schools cover BOTH key stages, so they are // Phase detection. All-through schools cover BOTH key stages, so they are
// neither "pure primary" nor "pure secondary": isSecondary stays true (they // neither "pure primary" nor "pure secondary": isSecondary stays true (they
// have KS4 data) but isAllThrough gates the primary-only content (phonics, // have KS4 data) but isAllThrough gates the primary-only content (KS2 SATs,
// KS2 trend) back on and switches phase-specific copy to an all-ages framing. // KS2 trend) back on and switches phase-specific copy to an all-ages framing.
const phase = schoolInfo.phase ?? ''; const phase = schoolInfo.phase ?? '';
const isAllThrough = phase.toLowerCase() === 'all-through'; const isAllThrough = phase.toLowerCase() === 'all-through';
const isSecondary = phase.toLowerCase().includes('secondary') || isAllThrough; const isSecondary = phase.toLowerCase().includes('secondary') || isAllThrough;
const isPrimary = !isSecondary; const isPrimary = !isSecondary;
// Primary-stage content shows for pure-primary AND all-through schools.
const showPrimaryContent = isPrimary || isAllThrough;
// National averages (fetched dynamically so they stay current) // National averages (fetched dynamically so they stay current)
const [nationalAvg, setNationalAvg] = useState<NationalAverages | null>(null); const [nationalAvg, setNationalAvg] = useState<NationalAverages | null>(null);
@@ -220,11 +219,9 @@ export function SchoolDetailView({
const hasInclusionData = (latestResults?.disadvantaged_pct != null) const hasInclusionData = (latestResults?.disadvantaged_pct != null)
|| (latestResults?.eal_pct != null) || (latestResults?.eal_pct != null)
|| (latestResults?.sen_support_pct != null) || (latestResults?.sen_support_pct != null)
|| senDetail != null
|| hasGenderSplit; || hasGenderSplit;
const hasSchoolLife = absenceData != null || census?.class_size_avg != null; const hasSchoolLife = absenceData != null;
const hasPhonics = phonics != null && phonics.year1_phonics_pct != null;
const hasDeprivation = deprivation != null && deprivation.idaci_decile != null; const hasDeprivation = deprivation != null && deprivation.idaci_decile != null;
const hasFinance = finance != null && finance.per_pupil_spend != null; const hasFinance = finance != null && finance.per_pupil_spend != null;
const hasLocation = schoolInfo.latitude != null && schoolInfo.longitude != null; const hasLocation = schoolInfo.latitude != null && schoolInfo.longitude != null;
@@ -265,7 +262,6 @@ export function SchoolDetailView({
if (admissions) navItems.push({ id: 'admissions', label: 'Admissions' }); if (admissions) navItems.push({ id: 'admissions', label: 'Admissions' });
if (hasInclusionData) navItems.push({ id: 'inclusion', label: 'Pupils' }); if (hasInclusionData) navItems.push({ id: 'inclusion', label: 'Pupils' });
if (yearlyData.length > 0) navItems.push({ id: 'history', label: 'History' }); if (yearlyData.length > 0) navItems.push({ id: 'history', label: 'History' });
if (hasPhonics && showPrimaryContent) navItems.push({ id: 'phonics', label: 'Phonics' });
if (hasSchoolLife) navItems.push({ id: 'school-life', label: 'School Life' }); if (hasSchoolLife) navItems.push({ id: 'school-life', label: 'School Life' });
if (hasDeprivation) navItems.push({ id: 'local-area', label: 'Local Area' }); if (hasDeprivation) navItems.push({ id: 'local-area', label: 'Local Area' });
if (hasFinance) navItems.push({ id: 'finances', label: 'Finances' }); if (hasFinance) navItems.push({ id: 'finances', label: 'Finances' });
@@ -358,6 +354,15 @@ export function SchoolDetailView({
{schoolInfo.gender && schoolInfo.gender !== 'Mixed' && ( {schoolInfo.gender && schoolInfo.gender !== 'Mixed' && (
<span className={styles.metaItem}>{schoolInfo.gender}&apos;s school</span> <span className={styles.metaItem}>{schoolInfo.gender}&apos;s school</span>
)} )}
{schoolInfo.age_range && (
<span className={styles.metaItem}>{formatAgeRange(schoolInfo.age_range)}</span>
)}
{schoolInfo.nursery_provision && (
<span className={styles.metaItem}>Nursery</span>
)}
{schoolInfo.has_sixth_form && (
<span className={styles.metaItem}>Sixth form</span>
)}
</div> </div>
{isProposedToClose(schoolInfo) && ( {isProposedToClose(schoolInfo) && (
<div className={styles.closingStrip} role="note"> <div className={styles.closingStrip} role="note">
@@ -382,7 +387,20 @@ export function SchoolDetailView({
)} )}
</p> </p>
)} )}
<div className={styles.headerDetails}> <button
type="button"
className={styles.detailsToggle}
aria-expanded={detailsOpen}
aria-controls="school-header-details"
onClick={() => setDetailsOpen((o) => !o)}
>
{detailsOpen ? 'Hide details' : 'Show all details'}
<span aria-hidden="true">{detailsOpen ? '▴' : '▾'}</span>
</button>
<div
id="school-header-details"
className={`${styles.headerDetails}${detailsOpen ? ` ${styles.headerDetailsOpen}` : ''}`}
>
{schoolInfo.headteacher_name && ( {schoolInfo.headteacher_name && (
<span className={styles.headerDetail}> <span className={styles.headerDetail}>
<strong>Headteacher:</strong> {schoolInfo.headteacher_name} <strong>Headteacher:</strong> {schoolInfo.headteacher_name}
@@ -416,6 +434,32 @@ export function SchoolDetailView({
Part of <strong>{schoolInfo.trust_name}</strong> Part of <strong>{schoolInfo.trust_name}</strong>
</span> </span>
)} )}
{schoolInfo.telephone && (
<span className={styles.headerDetail}>
<strong>Phone:</strong>{' '}
<a href={`tel:${schoolInfo.telephone.replace(/\s+/g, '')}`}>
{schoolInfo.telephone}
</a>
</span>
)}
{schoolInfo.religious_denomination && (
<span className={styles.headerDetail}>
<strong>Religious character:</strong>{' '}
{['Does not apply', 'None'].includes(schoolInfo.religious_denomination)
? 'None'
: schoolInfo.religious_denomination}
</span>
)}
{schoolInfo.county && (
<span className={styles.headerDetail}>
<strong>County:</strong> {schoolInfo.county}
</span>
)}
{schoolInfo.parliamentary_constituency && (
<span className={styles.headerDetail}>
<strong>Constituency:</strong> {schoolInfo.parliamentary_constituency}
</span>
)}
</div> </div>
</div> </div>
<div className={styles.actions} ref={heroActionsRef}> <div className={styles.actions} ref={heroActionsRef}>
@@ -752,18 +796,22 @@ export function SchoolDetailView({
expectedPct: latestResults.reading_expected_pct, expectedPct: latestResults.reading_expected_pct,
exceedingPct: latestResults.reading_high_pct, exceedingPct: latestResults.reading_high_pct,
nationalExpectedPct: suppressKs2Comparison ? null : primaryAvg.reading_expected_pct, nationalExpectedPct: suppressKs2Comparison ? null : primaryAvg.reading_expected_pct,
nationalExceedingPct: suppressKs2Comparison ? null : primaryAvg.reading_high_pct,
}, },
{ {
name: 'Writing', name: 'Writing',
expectedPct: latestResults.writing_expected_pct, expectedPct: latestResults.writing_expected_pct,
exceedingPct: latestResults.writing_high_pct, exceedingPct: latestResults.writing_high_pct,
nationalExpectedPct: suppressKs2Comparison ? null : primaryAvg.writing_expected_pct, nationalExpectedPct: suppressKs2Comparison ? null : primaryAvg.writing_expected_pct,
// Writing's higher level is teacher-assessed "greater depth".
nationalExceedingPct: suppressKs2Comparison ? null : primaryAvg.writing_gd_pct,
}, },
{ {
name: 'Maths', name: 'Maths',
expectedPct: latestResults.maths_expected_pct, expectedPct: latestResults.maths_expected_pct,
exceedingPct: latestResults.maths_high_pct, exceedingPct: latestResults.maths_high_pct,
nationalExpectedPct: suppressKs2Comparison ? null : primaryAvg.maths_expected_pct, nationalExpectedPct: suppressKs2Comparison ? null : primaryAvg.maths_expected_pct,
nationalExceedingPct: suppressKs2Comparison ? null : primaryAvg.maths_high_pct,
}, },
]} ]}
/> />
@@ -1080,29 +1128,6 @@ export function SchoolDetailView({
); );
})()} })()}
</div> </div>
{senDetail && (
<>
<h3 className={styles.subSectionTitle}>Types of additional needs supported</h3>
<p className={styles.sectionSubtitle}>
What proportion of pupils with additional needs have each type of support need.
</p>
<div className={styles.metricsGrid}>
{[
{ label: 'Speech & Language', pct: senDetail.primary_need_speech_pct },
{ label: 'Autism (ASD)', pct: senDetail.primary_need_autism_pct },
{ label: 'Learning Difficulties', pct: senDetail.primary_need_mld_pct },
{ label: 'Specific Learning (e.g. Dyslexia)', pct: senDetail.primary_need_spld_pct },
{ label: 'Social, Emotional & Mental Health', pct: senDetail.primary_need_semh_pct },
{ label: 'Physical / Sensory', pct: senDetail.primary_need_physical_pct },
].filter(n => n.pct != null).map(({ label, pct }) => (
<div key={label} className={styles.metricCard}>
<div className={styles.metricLabel}>{label}</div>
<div className={styles.metricValue}>{pct}%</div>
</div>
))}
</div>
</>
)}
</section> </section>
)} )}
@@ -1227,41 +1252,11 @@ export function SchoolDetailView({
)} )}
</section> </section>
)} )}
{/* Year 1 Phonics — primary-stage metric (pure primary + all-through) */}
{hasPhonics && showPrimaryContent && phonics && (
<section id="phonics" className={styles.card}>
<h2 className={styles.sectionTitle}>Year 1 Phonics ({formatAcademicYear(phonics.year)})</h2>
<p className={styles.sectionSubtitle}>
Phonics is a key early reading skill. Children are tested at the end of Year 1.
</p>
<div className={styles.metricsGrid}>
<div className={styles.metricCard}>
<div className={styles.metricLabel}>Passed the phonics check</div>
<div className={styles.metricValue}>{formatPercentage(phonics.year1_phonics_pct)}</div>
<div className={styles.metricHint}>Phonics is a key early reading skill tested at end of Year 1</div>
</div>
{phonics.year2_phonics_pct != null && (
<div className={styles.metricCard}>
<div className={styles.metricLabel}>Year 2 pupils who retook and passed</div>
<div className={styles.metricValue}>{formatPercentage(phonics.year2_phonics_pct)}</div>
</div>
)}
</div>
</section>
)}
{/* School Life */} {/* School Life */}
{hasSchoolLife && ( {hasSchoolLife && (
<section id="school-life" className={styles.card}> <section id="school-life" className={styles.card}>
<h2 className={styles.sectionTitle}>School Life</h2> <h2 className={styles.sectionTitle}>School Life</h2>
<div className={styles.metricsGrid}> <div className={styles.metricsGrid}>
{census?.class_size_avg != null && (
<div className={styles.metricCard}>
<div className={styles.metricLabel}>Average class size</div>
<div className={styles.metricValue}>{census.class_size_avg.toFixed(1)}</div>
<div className={styles.metricHint}>Average number of pupils per class</div>
</div>
)}
{absenceData?.overall_absence_rate != null && ( {absenceData?.overall_absence_rate != null && (
<div className={styles.metricCard}> <div className={styles.metricCard}>
<div className={styles.metricLabel}> <div className={styles.metricLabel}>
@@ -207,6 +207,22 @@
text-decoration: underline; text-decoration: underline;
} }
/* "Show all details" reveal — only rendered on mobile/tablet, where the
header details block is collapsed below the fold. Hidden on desktop. */
.detailsToggle {
display: none;
align-items: center;
gap: 0.25rem;
margin-top: 0.5rem;
padding: 0;
background: none;
border: none;
font-size: 0.8125rem;
font-weight: 600;
color: var(--accent-teal, #2d7d7d);
cursor: pointer;
}
.actions { .actions {
display: flex; display: flex;
gap: 0.5rem; gap: 0.5rem;
@@ -490,7 +506,10 @@
/* ── Charts & Map ────────────────────────────────────── */ /* ── Charts & Map ────────────────────────────────────── */
.chartContainer { .chartContainer {
width: 100%; width: 100%;
height: 280px; /* Taller on desktop so the trend lines have vertical room to separate
and read clearly. Mobile overrides this to height:auto below (the
max-width:768px query), so this only affects desktop. */
height: 380px;
position: relative; position: relative;
} }
@@ -1063,7 +1082,18 @@
padding: 0.1rem 0.375rem; padding: 0.1rem 0.375rem;
} }
/* Collapsed below the fold on phones/tablets; revealed via "Show all
details" so the metrics surface sooner. */
.detailsToggle {
display: inline-flex;
}
.headerDetails { .headerDetails {
display: none;
}
.headerDetailsOpen {
display: flex;
flex-direction: column; flex-direction: column;
gap: 0.375rem; gap: 0.375rem;
} }
@@ -20,7 +20,7 @@ const PerformanceChart = dynamic(
import type { import type {
School, SchoolResult, AbsenceData, School, SchoolResult, AbsenceData,
OfstedInspection, SchoolCensus, OfstedInspection, SchoolCensus,
SchoolAdmissions, SenDetail, Phonics, SchoolAdmissions,
SchoolDeprivation, SchoolFinance, NationalAverages, SchoolDeprivation, SchoolFinance, NationalAverages,
} from '@/lib/types'; } from '@/lib/types';
import { formatPercentage, formatProgress, formatAcademicYear, formatAgeRange, isProposedToClose, ofstedLegacyAreas, isSpecialSchool } from '@/lib/utils'; import { formatPercentage, formatProgress, formatAcademicYear, formatAgeRange, isProposedToClose, ofstedLegacyAreas, isSpecialSchool } from '@/lib/utils';
@@ -68,15 +68,13 @@ interface SecondarySchoolDetailViewProps {
ofsted: OfstedInspection | null; ofsted: OfstedInspection | null;
census: SchoolCensus | null; census: SchoolCensus | null;
admissions: SchoolAdmissions | null; admissions: SchoolAdmissions | null;
senDetail: SenDetail | null;
phonics: Phonics | null;
deprivation: SchoolDeprivation | null; deprivation: SchoolDeprivation | null;
finance: SchoolFinance | null; finance: SchoolFinance | null;
} }
export function SecondarySchoolDetailView({ export function SecondarySchoolDetailView({
schoolInfo, yearlyData, schoolInfo, yearlyData,
ofsted, census, admissions, senDetail, deprivation, finance, absenceData, ofsted, census, admissions, deprivation, finance, absenceData,
}: SecondarySchoolDetailViewProps) { }: SecondarySchoolDetailViewProps) {
const router = useRouter(); const router = useRouter();
// Hero map — the "View on map" link opens its fullscreen view. // Hero map — the "View on map" link opens its fullscreen view.
@@ -85,6 +83,8 @@ export function SecondarySchoolDetailView({
const isInComparison = isSelected(schoolInfo.urn); const isInComparison = isSelected(schoolInfo.urn);
const [activeSection, setActiveSection] = useState<string>(''); const [activeSection, setActiveSection] = useState<string>('');
// Header details collapse behind a "Show all details" link on mobile/tablet.
const [detailsOpen, setDetailsOpen] = useState(false);
const latestResults = yearlyData.length > 0 ? yearlyData[yearlyData.length - 1] : null; const latestResults = yearlyData.length > 0 ? yearlyData[yearlyData.length - 1] : null;
@@ -248,6 +248,9 @@ export function SecondarySchoolDetailView({
{schoolInfo.age_range && ( {schoolInfo.age_range && (
<span className={styles.badge}>{formatAgeRange(schoolInfo.age_range)}</span> <span className={styles.badge}>{formatAgeRange(schoolInfo.age_range)}</span>
)} )}
{schoolInfo.nursery_provision && (
<span className={styles.badge}>Nursery</span>
)}
{hasSixthForm && ( {hasSixthForm && (
<span className={styles.badge}>Sixth form</span> <span className={styles.badge}>Sixth form</span>
)} )}
@@ -280,7 +283,20 @@ export function SecondarySchoolDetailView({
)} )}
</p> </p>
)} )}
<div className={styles.headerDetails}> <button
type="button"
className={styles.detailsToggle}
aria-expanded={detailsOpen}
aria-controls="school-header-details"
onClick={() => setDetailsOpen((o) => !o)}
>
{detailsOpen ? 'Hide details' : 'Show all details'}
<span aria-hidden="true">{detailsOpen ? '▴' : '▾'}</span>
</button>
<div
id="school-header-details"
className={`${styles.headerDetails}${detailsOpen ? ` ${styles.headerDetailsOpen}` : ''}`}
>
{schoolInfo.headteacher_name && ( {schoolInfo.headteacher_name && (
<span className={styles.headerDetail}> <span className={styles.headerDetail}>
<strong>Headteacher:</strong> {schoolInfo.headteacher_name} <strong>Headteacher:</strong> {schoolInfo.headteacher_name}
@@ -310,6 +326,32 @@ export function SecondarySchoolDetailView({
Part of <strong>{schoolInfo.trust_name}</strong> Part of <strong>{schoolInfo.trust_name}</strong>
</span> </span>
)} )}
{schoolInfo.telephone && (
<span className={styles.headerDetail}>
<strong>Phone:</strong>{' '}
<a href={`tel:${schoolInfo.telephone.replace(/\s+/g, '')}`}>
{schoolInfo.telephone}
</a>
</span>
)}
{schoolInfo.religious_denomination && (
<span className={styles.headerDetail}>
<strong>Religious character:</strong>{' '}
{['Does not apply', 'None'].includes(schoolInfo.religious_denomination)
? 'None'
: schoolInfo.religious_denomination}
</span>
)}
{schoolInfo.county && (
<span className={styles.headerDetail}>
<strong>County:</strong> {schoolInfo.county}
</span>
)}
{schoolInfo.parliamentary_constituency && (
<span className={styles.headerDetail}>
<strong>Constituency:</strong> {schoolInfo.parliamentary_constituency}
</span>
)}
</div> </div>
</div> </div>
<div className={styles.actions}> <div className={styles.actions}>
+4 -19
View File
@@ -18,6 +18,7 @@ export interface School {
religious_denomination: string | null; religious_denomination: string | null;
age_range: string | null; age_range: string | null;
has_sixth_form?: boolean | null; has_sixth_form?: boolean | null;
nursery_provision?: boolean | null;
status?: string | null; // GIAS establishment status ("Open" / "Open, but proposed to close") status?: string | null; // GIAS establishment status ("Open" / "Open, but proposed to close")
// Address // Address
@@ -60,11 +61,14 @@ export interface School {
// GIAS enrichment fields // GIAS enrichment fields
website?: string | null; website?: string | null;
telephone?: string | null;
headteacher_name?: string | null; headteacher_name?: string | null;
capacity?: number | null; capacity?: number | null;
trust_name?: string | null; trust_name?: string | null;
gender?: string | null; gender?: string | null;
admissions_policy?: string | null; admissions_policy?: string | null;
county?: string | null;
parliamentary_constituency?: string | null;
// Ofsted (for list view — summary only) // Ofsted (for list view — summary only)
ofsted_grade?: 1 | 2 | 3 | 4 | null; ofsted_grade?: 1 | 2 | 3 | 4 | null;
@@ -130,7 +134,6 @@ export interface SchoolCensus {
male_pupils: number | null; male_pupils: number | null;
fsm_pct: number | null; fsm_pct: number | null;
eal_pct: number | null; eal_pct: number | null;
class_size_avg?: number | null;
ethnicity_white_pct?: number | null; ethnicity_white_pct?: number | null;
ethnicity_asian_pct?: number | null; ethnicity_asian_pct?: number | null;
ethnicity_black_pct?: number | null; ethnicity_black_pct?: number | null;
@@ -159,22 +162,6 @@ export interface SchoolAdmissions {
cross_la_offers?: number | null; cross_la_offers?: number | null;
} }
export interface SenDetail {
year: number;
primary_need_speech_pct: number | null;
primary_need_autism_pct: number | null;
primary_need_mld_pct: number | null;
primary_need_spld_pct: number | null;
primary_need_semh_pct: number | null;
primary_need_physical_pct: number | null;
primary_need_other_pct: number | null;
}
export interface Phonics {
year: number;
year1_phonics_pct: number | null;
year2_phonics_pct: number | null;
}
export interface SchoolDeprivation { export interface SchoolDeprivation {
lsoa_code: string | null; lsoa_code: string | null;
@@ -343,8 +330,6 @@ export interface SchoolDetailsResponse {
admissions: SchoolAdmissions | null; admissions: SchoolAdmissions | null;
/** All available admissions years, oldest first. Drives the multi-year trend view. */ /** All available admissions years, oldest first. Drives the multi-year trend view. */
admissions_history: SchoolAdmissions[]; admissions_history: SchoolAdmissions[];
sen_detail: SenDetail | null;
phonics: Phonics | null;
deprivation: SchoolDeprivation | null; deprivation: SchoolDeprivation | null;
finance: SchoolFinance | null; finance: SchoolFinance | null;
} }