Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
480ac4b9a9 | ||
|
|
93f17211b1 | ||
|
|
dfa4928641 | ||
|
|
e6babe21f5 | ||
|
|
358705bf39 | ||
|
|
3be902e98f | ||
|
|
12c52244ee | ||
|
|
e1373fb6df | ||
|
|
ccfa44389e | ||
|
|
423b27140c | ||
|
|
1c62e8247d | ||
|
|
da5d63593f | ||
|
|
ef4a2ccccb | ||
|
|
392ec29fdb | ||
|
|
03e44cf154 | ||
|
|
59ea8a4bdd | ||
|
|
c931d1078c | ||
|
|
807133c305 | ||
|
|
41d3f3b971 | ||
|
|
c013265cb4 | ||
|
|
ad9d3b67f7 | ||
|
|
ca47d08186 | ||
|
|
62a6bfaf0c | ||
|
|
e344298440 | ||
|
|
8020191832 | ||
|
|
5f9caad7f4 | ||
|
|
e65c93b68e | ||
|
|
e3f21a5bc7 | ||
|
|
dea435a906 | ||
|
|
dd5b48e612 | ||
|
|
a88139a539 | ||
|
|
9b765125ad | ||
|
|
ccf0892a0e | ||
|
|
0450f8ecd6 | ||
|
|
27d83f9bd0 | ||
|
|
19c574edb0 | ||
|
|
e78ec14e2e | ||
|
|
fb3ef7d2b9 |
No files matched your search
+52
-18
@@ -40,14 +40,14 @@ from .data_loader import (
|
||||
from .data_loader import get_data_info as get_db_info
|
||||
from . import flags
|
||||
from .places import build_place_index, build_place_registry, places_for_urn
|
||||
from .schemas import METRIC_DEFINITIONS, PHASE_GROUPS, RANKING_COLUMNS, SCHOOL_COLUMNS
|
||||
from .schemas import METRIC_DEFINITIONS, PHASE_GROUPS, PHASE_ORDER, RANKING_COLUMNS, SCHOOL_COLUMNS
|
||||
from .school_groups import (
|
||||
FAITH_GROUPS,
|
||||
FAITH_KEYS,
|
||||
TYPE_GROUP_KEYS,
|
||||
TYPE_GROUPS,
|
||||
faith_groups_for,
|
||||
type_group_for,
|
||||
type_group_key,
|
||||
)
|
||||
from .nearby_schools import select_nearby
|
||||
from .utils import clean_for_json, convert_to_native
|
||||
@@ -381,6 +381,12 @@ def clean_filter_values(series: pd.Series) -> list[str]:
|
||||
)
|
||||
|
||||
|
||||
def order_phases(phases: list[str]) -> list[str]:
|
||||
"""Phases in the order a child meets them; any GIAS adds later follow, A-Z."""
|
||||
rank = {p: i for i, p in enumerate(PHASE_ORDER)}
|
||||
return sorted(phases, key=lambda p: (rank.get(p.lower(), len(rank)), p))
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# SECURITY MIDDLEWARE & HELPERS
|
||||
# =============================================================================
|
||||
@@ -615,6 +621,31 @@ def verify_admin_api_key(x_api_key: str = Header(None)) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _with_whole_school_pupils(rows: pd.DataFrame, source: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Set total_pupils to the size of the school.
|
||||
|
||||
fact_performance's total_pupils is the cohort a year's results were
|
||||
measured on. For a secondary that is the GCSE year group alone (Burntwood:
|
||||
245 against 1,462 on roll). Cards, map popups and place rows label it
|
||||
"pupils", so they take the register's whole-school count instead, and
|
||||
nothing when the register has none.
|
||||
"""
|
||||
whole = source["gias_total_pupils"] if "gias_total_pupils" in source.columns else None
|
||||
return rows.assign(total_pupils=whole)
|
||||
|
||||
|
||||
def _with_type_group(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Name each row's search-filter type group, or None for a type in no group.
|
||||
|
||||
The school page and the search rows print it ("State school") in place of
|
||||
the GIAS establishment type, and an independent school gets a Fee-paying
|
||||
flag from it.
|
||||
"""
|
||||
if "school_type" not in rows.columns:
|
||||
return rows
|
||||
return rows.assign(type_group=rows["school_type"].map(type_group_for))
|
||||
|
||||
|
||||
# Input validation helpers
|
||||
def _names_in_group(names: pd.Series, in_group) -> set:
|
||||
"""The distinct names in a column that a group predicate accepts.
|
||||
@@ -853,7 +884,7 @@ async def get_schools(
|
||||
if c in df_latest.columns
|
||||
]
|
||||
# fact_performance guarantees one row per (urn, year); df_latest has one row per urn.
|
||||
schools_df = df_latest[available_cols]
|
||||
schools_df = _with_whole_school_pupils(df_latest[available_cols], df_latest)
|
||||
|
||||
# Location-based search (uses pre-geocoded data from database)
|
||||
search_coords = None
|
||||
@@ -918,17 +949,17 @@ async def get_schools(
|
||||
schools_df["local_authority"].str.lower() == local_authority.lower()
|
||||
]
|
||||
|
||||
# A type group key (backend/school_groups.py), or for an old link a raw
|
||||
# GIAS type label, matched exactly as before.
|
||||
# A type group key (backend/school_groups.py), old keys included, or for
|
||||
# an old link a raw GIAS type label, matched exactly as before.
|
||||
if school_type:
|
||||
type_key = school_type.lower()
|
||||
if type_key in TYPE_GROUP_KEYS:
|
||||
type_key = type_group_key(school_type)
|
||||
if type_key:
|
||||
column = schools_df["school_type"]
|
||||
schools_df = schools_df[
|
||||
column.isin(_names_in_group(column, lambda n: type_group_for(n) == type_key))
|
||||
]
|
||||
else:
|
||||
schools_df = schools_df[schools_df["school_type"].str.lower() == type_key]
|
||||
schools_df = schools_df[schools_df["school_type"].str.lower() == school_type.lower()]
|
||||
|
||||
# Compute result-scoped filter values (before pagination).
|
||||
# Gender and admissions are secondary-only filters — scope them to schools
|
||||
@@ -937,7 +968,7 @@ async def get_schools(
|
||||
result_filters = {
|
||||
"local_authorities": clean_filter_values(schools_df["local_authority"]) if "local_authority" in schools_df.columns else [],
|
||||
"school_types": clean_filter_values(schools_df["school_type"]) if "school_type" in schools_df.columns else [],
|
||||
"phases": clean_filter_values(schools_df["phase"]) if "phase" in schools_df.columns else [],
|
||||
"phases": order_phases(clean_filter_values(schools_df["phase"])) if "phase" in schools_df.columns else [],
|
||||
"genders": clean_filter_values(schools_df.loc[_sec_mask, "gender"]) if "gender" in schools_df.columns and _sec_mask.any() else [],
|
||||
"admissions_policies": clean_filter_values(schools_df.loc[_sec_mask, "admissions_policy"]) if "admissions_policy" in schools_df.columns and _sec_mask.any() else [],
|
||||
}
|
||||
@@ -946,7 +977,7 @@ async def get_schools(
|
||||
total = len(schools_df)
|
||||
start_idx = (page - 1) * page_size
|
||||
end_idx = start_idx + page_size
|
||||
schools_df = schools_df.iloc[start_idx:end_idx]
|
||||
schools_df = _with_type_group(schools_df.iloc[start_idx:end_idx])
|
||||
|
||||
return {
|
||||
"schools": clean_for_json(schools_df),
|
||||
@@ -1010,11 +1041,14 @@ async def get_school_details(request: Request, urn: int):
|
||||
"school_name": latest.get("school_name", ""),
|
||||
"local_authority": latest.get("local_authority", ""),
|
||||
"school_type": latest.get("school_type", ""),
|
||||
"type_group": type_group_for(latest.get("school_type")),
|
||||
"address": latest.get("address", ""),
|
||||
"religious_denomination": latest.get("religious_denomination", ""),
|
||||
"age_range": latest.get("age_range", ""),
|
||||
"has_sixth_form": latest.get("has_sixth_form"),
|
||||
"nursery_provision": latest.get("nursery_provision"),
|
||||
# The header's Selective flag reads it (lib/schoolFacts).
|
||||
"admissions_policy": latest.get("admissions_policy"),
|
||||
"status": latest.get("status"),
|
||||
"latitude": latest.get("latitude"),
|
||||
"longitude": latest.get("longitude"),
|
||||
@@ -1207,8 +1241,8 @@ async def get_filter_options(request: Request):
|
||||
"faiths": [],
|
||||
}
|
||||
|
||||
# Phases: return values from data, ordered sensibly
|
||||
phases = clean_filter_values(df["phase"]) if "phase" in df.columns else []
|
||||
# Phases: the values in the data, in the order a child meets them
|
||||
phases = order_phases(clean_filter_values(df["phase"])) if "phase" in df.columns else []
|
||||
|
||||
secondary_df = df[df["attainment_8_score"].notna()] if "attainment_8_score" in df.columns else df.iloc[0:0]
|
||||
genders = clean_filter_values(secondary_df["gender"]) if "gender" in secondary_df.columns else []
|
||||
@@ -1503,13 +1537,12 @@ async def get_place(request: Request, kind: str, slug: str,
|
||||
# warning. Ordered de-duplication keeps the column order and the warning
|
||||
# cannot come back.
|
||||
#
|
||||
# nursery_provision and parliamentary_constituency are not in
|
||||
# SCHOOL_COLUMNS and the place table shows both. The `in rows.columns`
|
||||
# guard is what keeps a mart the pipeline has not rebuilt working: those
|
||||
# two are the optional GIAS columns data_loader degrades to NULL.
|
||||
# parliamentary_constituency is not in SCHOOL_COLUMNS and the place table
|
||||
# shows it. The `in rows.columns` guard is what keeps a mart the pipeline
|
||||
# has not rebuilt working: it and nursery_provision are the optional GIAS
|
||||
# columns data_loader degrades to NULL.
|
||||
cols = [c for c in dict.fromkeys(
|
||||
SCHOOL_COLUMNS + ["latitude", "longitude", "phase",
|
||||
"nursery_provision",
|
||||
"parliamentary_constituency",
|
||||
"rwm_expected_pct", "attainment_8_score",
|
||||
"total_pupils"])
|
||||
@@ -1539,7 +1572,8 @@ async def get_place(request: Request, kind: str, slug: str,
|
||||
# variants that exist rather than 404s.
|
||||
"phases": [ph for ph in ("primary", "secondary")
|
||||
if place.publishes_phase(ph)]},
|
||||
"schools": clean_for_json(rows[cols]),
|
||||
"schools": clean_for_json(
|
||||
_with_type_group(_with_whole_school_pupils(rows[cols], rows))),
|
||||
"averages": averages,
|
||||
}
|
||||
|
||||
|
||||
@@ -544,6 +544,19 @@ PHASE_GROUPS: dict[str, set[str]] = {
|
||||
"all-through": {"all-through"},
|
||||
}
|
||||
|
||||
# GIAS phases in the order a child meets them, for the phase filter's options.
|
||||
# All-through spans the whole path, so it follows the stages. Lowercased, as
|
||||
# PHASE_GROUPS is, so a change of case in the GIAS label keeps its place.
|
||||
PHASE_ORDER: list[str] = [
|
||||
"nursery",
|
||||
"primary",
|
||||
"middle deemed primary",
|
||||
"middle deemed secondary",
|
||||
"secondary",
|
||||
"16 plus",
|
||||
"all-through",
|
||||
]
|
||||
|
||||
# School listing columns
|
||||
SCHOOL_COLUMNS = [
|
||||
"urn",
|
||||
@@ -556,6 +569,7 @@ SCHOOL_COLUMNS = [
|
||||
"religious_denomination",
|
||||
"age_range",
|
||||
"has_sixth_form",
|
||||
"nursery_provision",
|
||||
"status",
|
||||
"gender",
|
||||
"admissions_policy",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
The 34 GIAS establishment types describe governance and funding, which for a
|
||||
mainstream state school barely changes what a parent experiences. The search
|
||||
filter offers six groups a parent recognises instead, and a faith filter in
|
||||
filter offers five groups a parent recognises instead, and a faith filter in
|
||||
place of the faith signal that "Voluntary aided" and "Voluntary controlled"
|
||||
only half carry. See
|
||||
docs/superpowers/specs/2026-10-02-school-type-groups-and-faith-filter-design.md.
|
||||
@@ -21,12 +21,16 @@ from .gias_codes import RELIGIOUS_CHARACTER, SCHOOL_TYPE
|
||||
|
||||
# (key, label, GIAS TypeOfEstablishment codes), in the order shown.
|
||||
TYPE_GROUPS: tuple[tuple[str, str, frozenset[int]], ...] = (
|
||||
# Academy sponsor led, Academy converter, Free schools, University technical
|
||||
# college, Studio schools, City technology college. UTCs and studio schools
|
||||
# are legally academies, and a family considering one searches by name.
|
||||
("academy", "State school: academy or free school", frozenset({28, 34, 35, 40, 41, 6})),
|
||||
# Community, Voluntary aided, Voluntary controlled, Foundation, LA nursery.
|
||||
("council", "State school: council-run", frozenset({1, 2, 3, 5, 15})),
|
||||
# Every mainstream state school, academy or council-run: Academy sponsor
|
||||
# led, Academy converter, Free schools, University technical college,
|
||||
# Studio schools, City technology college, Community, Voluntary aided,
|
||||
# Voluntary controlled, Foundation, LA nursery. Academy against council-run
|
||||
# was two near-halves of one pool, and did not follow the difference a
|
||||
# parent feels most, admissions: voluntary aided and foundation schools
|
||||
# set their own, as academies do. Faith, which voluntary aided mostly
|
||||
# meant, has its own filter.
|
||||
("state", "State school (free)",
|
||||
frozenset({28, 34, 35, 40, 41, 6, 1, 2, 3, 5, 15})),
|
||||
("independent", "Independent (fee-paying)", frozenset({11})),
|
||||
# Every special type, independent ones included (usually funded by the
|
||||
# council through an EHCP, so SEND provision to a parent, not private
|
||||
@@ -64,6 +68,10 @@ FAITH_GROUPS: tuple[tuple[str, str, frozenset[int]], ...] = (
|
||||
)
|
||||
|
||||
TYPE_GROUP_KEYS: frozenset[str] = frozenset(k for k, _, _ in TYPE_GROUPS)
|
||||
|
||||
# Keys a group was offered under before, so their links keep working: "state"
|
||||
# was "academy" and "council" until 2026-10-02.
|
||||
TYPE_GROUP_ALIASES: dict[str, str] = {"academy": "state", "council": "state"}
|
||||
FAITH_KEYS: frozenset[str] = frozenset(k for k, _, _ in FAITH_GROUPS)
|
||||
|
||||
|
||||
@@ -86,6 +94,14 @@ for _faith, _, _codes in FAITH_GROUPS:
|
||||
_FAITHS_BY_NAME[_name] = _FAITHS_BY_NAME.get(_name, ()) + (_faith,)
|
||||
|
||||
|
||||
def type_group_key(value: str) -> Optional[str]:
|
||||
"""The type group a school_type URL value names, old keys included, or
|
||||
None when it names no group (an old link's raw GIAS type)."""
|
||||
v = value.strip().lower()
|
||||
v = TYPE_GROUP_ALIASES.get(v, v)
|
||||
return v if v in TYPE_GROUP_KEYS else None
|
||||
|
||||
|
||||
def type_group_for(name: object) -> Optional[str]:
|
||||
"""The type group of a GIAS establishment type name, or None."""
|
||||
if not isinstance(name, str):
|
||||
|
||||
@@ -82,3 +82,25 @@ def test_grouped_phases_still_take_in_their_related_phases(client):
|
||||
|
||||
def test_an_unknown_phase_returns_nothing_rather_than_everything(client):
|
||||
assert _urns(client, "kindergarten") == []
|
||||
|
||||
|
||||
def test_filters_lists_phases_in_the_order_a_child_meets_them(client):
|
||||
# Alphabetical put "16 plus" and "All-through" first and Nursery fifth.
|
||||
# All-through spans the whole path, so it comes after the stages.
|
||||
assert client.get("/api/filters").json()["phases"] == [
|
||||
"Nursery",
|
||||
"Primary",
|
||||
"Middle deemed primary",
|
||||
"Middle deemed secondary",
|
||||
"Secondary",
|
||||
"16 plus",
|
||||
"All-through",
|
||||
]
|
||||
|
||||
|
||||
def test_an_unknown_phase_follows_the_known_ones():
|
||||
from backend.app import order_phases
|
||||
|
||||
assert order_phases(["Secondary", "Zeta", "Alpha", "Nursery"]) == [
|
||||
"Nursery", "Secondary", "Alpha", "Zeta",
|
||||
]
|
||||
@@ -17,6 +17,7 @@ from backend.school_groups import (
|
||||
UNOFFERED_TYPE_CODES,
|
||||
faith_groups_for,
|
||||
type_group_for,
|
||||
type_group_key,
|
||||
)
|
||||
|
||||
DBT_PROJECT = Path(__file__).resolve().parents[2] / "pipeline" / "transform" / "dbt_project.yml"
|
||||
@@ -40,7 +41,7 @@ def test_every_religion_code_has_a_faith():
|
||||
|
||||
def test_type_groups_in_display_order():
|
||||
assert [k for k, _, _ in TYPE_GROUPS] == [
|
||||
"academy", "council", "independent", "special", "post16", "alternative"]
|
||||
"state", "independent", "special", "post16", "alternative"]
|
||||
|
||||
|
||||
def test_faiths_in_display_order():
|
||||
@@ -50,21 +51,34 @@ def test_faiths_in_display_order():
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, group", [
|
||||
("Academy converter", "academy"),
|
||||
("University technical college", "academy"),
|
||||
("Voluntary aided school", "council"),
|
||||
("Local authority nursery school", "council"),
|
||||
("Academy converter", "state"),
|
||||
("University technical college", "state"),
|
||||
("Voluntary aided school", "state"),
|
||||
("Local authority nursery school", "state"),
|
||||
("Other independent school", "independent"),
|
||||
("Other independent special school", "special"),
|
||||
("Special post 16 institution", "special"),
|
||||
("Further education", "post16"),
|
||||
("Pupil referral unit", "alternative"),
|
||||
("academy CONVERTER", "academy"),
|
||||
("academy CONVERTER", "state"),
|
||||
])
|
||||
def test_type_group_by_name(name, group):
|
||||
assert type_group_for(name) == group
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value, key", [
|
||||
("state", "state"),
|
||||
("Special", "special"),
|
||||
# The two state groups that preceded "state", kept so their links still work.
|
||||
("academy", "state"),
|
||||
("Council", "state"),
|
||||
("Community school", None),
|
||||
("", None),
|
||||
])
|
||||
def test_type_group_key_resolves_keys_and_old_keys(value, key):
|
||||
assert type_group_key(value) == key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", [
|
||||
"Higher education institutions", "Miscellaneous", "Unknown (9999)", "Academy", "", None, np.nan,
|
||||
])
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""The school page's header flags (nextjs-app/lib/schoolFacts.ts) read seven
|
||||
school_info fields, so the detail payload must carry every one.
|
||||
|
||||
It lacked admissions_policy, so no school page could flag Selective while its
|
||||
search row did: Tiffin and The Grammar School at Leeds showed the tag in
|
||||
search and nothing on their own pages.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
# The fields schoolFlags() picks from School (FlagFields in lib/schoolFacts.ts).
|
||||
FLAG_FIELDS = (
|
||||
"type_group", "admissions_policy", "gender", "religious_denomination",
|
||||
"nursery_provision", "has_sixth_form", "phase",
|
||||
)
|
||||
|
||||
|
||||
def _school_df() -> pd.DataFrame:
|
||||
return pd.DataFrame([{
|
||||
"urn": 136910, "school_name": "Tiffin School", "phase": "Secondary",
|
||||
"school_type": "Academy converter", "admissions_policy": "Selective",
|
||||
"gender": "Boys", "religious_denomination": "Christian",
|
||||
"nursery_provision": "Not applicable", "has_sixth_form": True,
|
||||
"age_range": "11-18", "local_authority": "Kingston upon Thames",
|
||||
"address": "Queen Elizabeth Road, Kingston upon Thames, KT2 6RL",
|
||||
"postcode": "KT2 6RL", "latitude": 51.41, "longitude": -0.30,
|
||||
"year": 202425, "attainment_8_score": 75.0, "total_pupils": 200,
|
||||
"gias_total_pupils": 1478, "ofsted_grade": np.nan,
|
||||
}])
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
from backend import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "load_school_data", _school_df)
|
||||
monkeypatch.setattr(app_module, "load_latest_school_data", _school_df)
|
||||
monkeypatch.setattr(app_module, "get_supplementary_data", lambda db, urn: {})
|
||||
monkeypatch.setattr(app_module, "_place_registry", None)
|
||||
return TestClient(app_module.app, raise_server_exceptions=False)
|
||||
|
||||
|
||||
def test_the_school_page_carries_every_field_its_flags_read(client):
|
||||
resp = client.get("/api/schools/136910")
|
||||
assert resp.status_code == 200, resp.text
|
||||
info = resp.json()["school_info"]
|
||||
assert [f for f in FLAG_FIELDS if f not in info] == []
|
||||
|
||||
|
||||
def test_the_school_page_says_a_selective_school_is_selective(client):
|
||||
info = client.get("/api/schools/136910").json()["school_info"]
|
||||
assert info["admissions_policy"] == "Selective"
|
||||
@@ -49,8 +49,9 @@ def _urns(client, **params):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, urns", [
|
||||
("council", [100001, 100002]),
|
||||
("academy", [100003]),
|
||||
("state", [100001, 100002, 100003]),
|
||||
("academy", [100001, 100002, 100003]),
|
||||
("council", [100001, 100002, 100003]),
|
||||
("special", [100004, 100005]),
|
||||
("independent", [100006]),
|
||||
("Special", [100004, 100005]),
|
||||
@@ -85,8 +86,7 @@ def test_type_and_faith_combine(client):
|
||||
def test_filters_lists_only_groups_present_in_order(client):
|
||||
body = client.get("/api/filters").json()
|
||||
assert body["school_type_groups"] == [
|
||||
{"value": "academy", "label": "State school: academy or free school"},
|
||||
{"value": "council", "label": "State school: council-run"},
|
||||
{"value": "state", "label": "State school (free)"},
|
||||
{"value": "independent", "label": "Independent (fee-paying)"},
|
||||
{"value": "special", "label": "Special school (SEND)"},
|
||||
]
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Payloads name each school's type group.
|
||||
|
||||
The school page and the search rows say "State school" or "Independent
|
||||
school" in the search filter's own terms, not GIAS's 34 establishment types,
|
||||
and an independent school gets a Fee-paying flag. A type in no group keeps a
|
||||
null group, and the page prints the register's own name for it. Search rows
|
||||
also carry nursery_provision, for their "Nursery class" flag.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def _schools_df() -> pd.DataFrame:
|
||||
base = {
|
||||
"local_authority": "Essex", "phase": "Primary", "year": 202425,
|
||||
"ofsted_grade": 2.0, "ofsted_date": None, "attainment_8_score": np.nan,
|
||||
"town": "Brentwood", "postcode": "CM13 1AA", "status": "Open",
|
||||
"address": "1 Test Street", "latitude": 51.6, "longitude": 0.3,
|
||||
"rwm_expected_pct": 60.0, "nursery_provision": "No Nursery Classes",
|
||||
}
|
||||
rows = [
|
||||
{**base, "urn": 100001, "school_name": "Alpha Academy",
|
||||
"school_type": "Academy converter", "nursery_provision": "Has Nursery Classes"},
|
||||
{**base, "urn": 100002, "school_name": "Beta Prep",
|
||||
"school_type": "Other independent school"},
|
||||
{**base, "urn": 100003, "school_name": "Gamma Unit",
|
||||
"school_type": "Secure units"},
|
||||
]
|
||||
# Enough schools in one town for it to have a place page.
|
||||
rows += [
|
||||
{**base, "urn": 100010 + i, "school_name": f"Delta Primary {i}",
|
||||
"school_type": "Community school"}
|
||||
for i in range(3)
|
||||
]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
from backend import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "load_latest_school_data", _schools_df)
|
||||
monkeypatch.setattr(app_module, "load_school_data", _schools_df)
|
||||
monkeypatch.setattr(app_module, "get_supplementary_data", lambda db, urn: {})
|
||||
monkeypatch.setattr(app_module, "_place_registry", None)
|
||||
return TestClient(app_module.app, raise_server_exceptions=False)
|
||||
|
||||
|
||||
def _by_urn(schools: list[dict]) -> dict[int, dict]:
|
||||
return {s["urn"]: s for s in schools}
|
||||
|
||||
|
||||
def test_the_list_names_each_type_group(client):
|
||||
resp = client.get("/api/schools?page_size=50")
|
||||
assert resp.status_code == 200, resp.text
|
||||
schools = _by_urn(resp.json()["schools"])
|
||||
assert schools[100001]["type_group"] == "state"
|
||||
assert schools[100002]["type_group"] == "independent"
|
||||
assert schools[100003]["type_group"] is None
|
||||
|
||||
|
||||
def test_the_list_carries_nursery_provision(client):
|
||||
schools = _by_urn(client.get("/api/schools?page_size=50").json()["schools"])
|
||||
assert schools[100001]["nursery_provision"] == "Has Nursery Classes"
|
||||
|
||||
|
||||
def test_the_school_page_names_its_type_group(client):
|
||||
resp = client.get("/api/schools/100002")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["school_info"]["type_group"] == "independent"
|
||||
|
||||
|
||||
def test_a_place_page_names_each_type_group(client):
|
||||
resp = client.get("/api/places/town/brentwood")
|
||||
assert resp.status_code == 200, resp.text
|
||||
schools = _by_urn(resp.json()["schools"])
|
||||
assert schools[100001]["type_group"] == "state"
|
||||
assert schools[100003]["type_group"] is None
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Cards, map popups and place rows label total_pupils "pupils".
|
||||
|
||||
fact_performance's total_pupils is the cohort a year's results were measured
|
||||
on. For a secondary that is the GCSE year group alone: Burntwood showed 245 in
|
||||
search against 1,462 on roll. The list and place payloads therefore carry the
|
||||
register's whole-school count, and nothing when the register has none.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def _schools_df() -> pd.DataFrame:
|
||||
base = {
|
||||
"local_authority": "Essex", "school_type": "Academy converter",
|
||||
"year": 202425, "ofsted_grade": 2.0, "ofsted_date": None,
|
||||
"town": "Brentwood", "postcode": "CM13 1AA", "status": "Open",
|
||||
"address": "1 Test Street", "latitude": 51.6, "longitude": 0.3,
|
||||
"gender": "Mixed", "rwm_expected_pct": np.nan, "attainment_8_score": 50.0,
|
||||
}
|
||||
rows = [
|
||||
# Secondary: results cohort 245, register 1,462.
|
||||
{**base, "urn": 100001, "school_name": "Alpha High", "phase": "Secondary",
|
||||
"total_pupils": 245, "gias_total_pupils": 1462},
|
||||
# Register count missing: no count, never the cohort.
|
||||
{**base, "urn": 100002, "school_name": "Beta High", "phase": "Secondary",
|
||||
"total_pupils": 180, "gias_total_pupils": np.nan},
|
||||
]
|
||||
# Enough schools in one town for it to have a place page.
|
||||
rows += [
|
||||
{**base, "urn": 100010 + i, "school_name": f"Gamma High {i}", "phase": "Secondary",
|
||||
"total_pupils": 200, "gias_total_pupils": 1000 + i}
|
||||
for i in range(5)
|
||||
]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
from backend import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "load_latest_school_data", _schools_df)
|
||||
monkeypatch.setattr(app_module, "load_school_data", _schools_df)
|
||||
monkeypatch.setattr(app_module, "_place_registry", None)
|
||||
return TestClient(app_module.app, raise_server_exceptions=False)
|
||||
|
||||
|
||||
def _pupils(schools: list[dict]) -> dict[int, object]:
|
||||
return {s["urn"]: s.get("total_pupils") for s in schools}
|
||||
|
||||
|
||||
def test_the_list_carries_the_whole_school_count(client):
|
||||
resp = client.get("/api/schools?page_size=50")
|
||||
assert resp.status_code == 200, resp.text
|
||||
pupils = _pupils(resp.json()["schools"])
|
||||
assert pupils[100001] == 1462
|
||||
assert pupils[100002] is None
|
||||
|
||||
|
||||
def test_a_place_page_carries_the_whole_school_count(client):
|
||||
resp = client.get("/api/places/town/brentwood")
|
||||
assert resp.status_code == 200, resp.text
|
||||
pupils = _pupils(resp.json()["schools"])
|
||||
assert pupils[100001] == 1462
|
||||
assert pupils[100002] is None
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,14 +1,24 @@
|
||||
# School Type Groups and a Faith Filter — Design
|
||||
|
||||
**Date:** 2026-10-02
|
||||
**Status:** approved in conversation, awaiting spec review
|
||||
**Status:** shipped in PR #170; revised 2026-10-02 (one state group)
|
||||
**Scope:** search filters (`/` results toolbar and phone filter sheet), `/api/schools`, `/api/filters`
|
||||
|
||||
## Goal
|
||||
|
||||
Replace the School type filter's 34 GIAS establishment types with six groups a
|
||||
Replace the School type filter's 34 GIAS establishment types with five groups a
|
||||
parent recognises, and add a Faith filter.
|
||||
|
||||
> **Revision, 2026-10-02.** PR #170 shipped six groups, with state schools
|
||||
> split into "academy or free school" and "council-run". They are now one,
|
||||
> "State school (free)". The split was two near-halves of the same pool, so it
|
||||
> rarely narrowed anything, and it did not follow the difference a parent feels
|
||||
> most, admissions: voluntary aided and foundation schools set their own
|
||||
> admissions, as academies do, while community and voluntary controlled
|
||||
> schools have theirs set by the council. Faith, which voluntary aided mostly
|
||||
> meant, has its own filter. The old keys `academy` and `council` resolve to
|
||||
> `state`, so their links keep working.
|
||||
|
||||
Since PR #169 the School type select offers the full GIAS list rather than the
|
||||
types in the results. That fixed the trap where choosing a type left only that
|
||||
type on offer, but it exposed the list itself: "Academy converter", "Academy
|
||||
@@ -44,8 +54,7 @@ Order is the order shown. Codes are GIAS `TypeOfEstablishment` codes
|
||||
|
||||
| Key | Label | GIAS codes | Schools |
|
||||
|---|---|---|---|
|
||||
| `academy` | State school: academy or free school | 28 Academy sponsor led, 34 Academy converter, 35 Free schools, 40 University technical college, 41 Studio schools, 6 City technology college | 11,186 |
|
||||
| `council` | State school: council-run | 1 Community school, 2 Voluntary aided school, 3 Voluntary controlled school, 5 Foundation school, 15 Local authority nursery school | 9,316 |
|
||||
| `state` | State school (free) | 28 Academy sponsor led, 34 Academy converter, 35 Free schools, 40 University technical college, 41 Studio schools, 6 City technology college, 1 Community school, 2 Voluntary aided school, 3 Voluntary controlled school, 5 Foundation school, 15 Local authority nursery school | 20,502 |
|
||||
| `independent` | Independent (fee-paying) | 11 Other independent school | 1,585 |
|
||||
| `special` | Special school (SEND) | 7 Community special, 12 Foundation special, 44 Academy special converter, 33 Academy special sponsor led, 36 Free schools special, 8 Non-maintained special, 10 Other independent special, 32 Special post 16 institution | 2,227 |
|
||||
| `post16` | Sixth form or college | 18 Further education, 31 Sixth form centres, 45 Academy 16-19 converter, 46 Academy 16 to 19 sponsor led, 39 Free schools 16 to 19 | 302 |
|
||||
@@ -64,9 +73,11 @@ department. 238 schools.
|
||||
- **Independent special schools are Special, not Independent.** They are
|
||||
usually funded by the local authority through a child's EHCP; to a parent
|
||||
they are SEND provision, not private school.
|
||||
- **UTCs, studio schools and city technology colleges are academies.** They are
|
||||
legally academies, they are few (66 together), and a family considering one
|
||||
searches for it by name.
|
||||
- **UTCs, studio schools and city technology colleges are state schools.** They
|
||||
are legally academies, they are few (66 together), and a family considering
|
||||
one searches for it by name.
|
||||
- **Academies and council-run schools are one group.** See the revision note
|
||||
under Goal.
|
||||
- **Special post 16 institutions are Special, not Sixth form or college.** The
|
||||
defining fact for a parent is the SEND provision.
|
||||
- **Alternative provision is last.** Parents do not apply to it; the local
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
# Ofsted Current Status — Design
|
||||
|
||||
**Date:** 2026-10-05
|
||||
**Status:** approved design, not yet implemented
|
||||
**Scope:** `pipeline/transform` Ofsted models, `backend/data_loader.py`, list and
|
||||
detail API Ofsted fields, search and map badges, school-page Ofsted section,
|
||||
compare Ofsted rows, Typesense rating, sitemap
|
||||
**Fixes:** audit findings C1, M1 and (as a side effect) M2 and part of H3,
|
||||
from the 3 Oct 2026 accuracy audit
|
||||
|
||||
## Goal
|
||||
|
||||
Never show an Ofsted grade under a date it was not awarded or confirmed on, and
|
||||
always date "Inspected" by the school's latest visit.
|
||||
|
||||
## The problem
|
||||
|
||||
Ofsted's management information gives each school at most three inspections:
|
||||
the latest graded inspection (date G, an overall grade or "Not judged", area
|
||||
grades), the latest ungraded inspection (date U, an outcome sentence) and the
|
||||
latest report card (date RC).
|
||||
|
||||
The site derives a grade and a date from these with two independent rules:
|
||||
|
||||
- grade = the graded inspection's overall grade, or else the grade parsed from
|
||||
the ungraded outcome ("School remains Good" → 2);
|
||||
- date = G, or else U.
|
||||
|
||||
The two rules can pick different inspections. Every inspection from
|
||||
September 2024 to November 2025 was graded with "Not judged" overall, so the
|
||||
grade falls back to an older ungraded visit while the date stays the new one.
|
||||
|
||||
- **C1.** Rabbsfarm Primary School (102408) shows "Good · 2025". Ofsted's
|
||||
17 June 2025 inspection gave no overall grade and rated quality of education,
|
||||
behaviour and leadership Requires Improvement. The "Good" comes from an
|
||||
ungraded visit on 6 February 2020. Site-wide, 932 badges pair a
|
||||
carried-forward grade with a newer inspection's year, and 147 of them say Good
|
||||
or Outstanding while that inspection rated an area Requires Improvement or
|
||||
Inadequate. Acre Wood Academy (151783) reads "Good · 2024" though the
|
||||
October 2024 inspection rated all four areas Inadequate.
|
||||
- **M1.** When a newer ungraded visit exists, the page shows the older graded
|
||||
date. Washwood Heath Academy (139888) reads "Inspected 3 Mar 2020 · 4+ years
|
||||
ago"; Ofsted visited on 21 May 2025. 667 schools.
|
||||
|
||||
Ofsted's own provider page for Rabbsfarm leads with the 2025 area judgements and
|
||||
"From September 2024, Ofsted no longer makes an overall effectiveness
|
||||
judgement". It shows no overall grade.
|
||||
|
||||
The rule is also implemented four times: `dim_school.ofsted_grade` (feeds
|
||||
Typesense), the list SQL in `data_loader.py`, `_ofsted_block`, and two separate
|
||||
"latest row" picks over `marts.fact_ofsted_inspection` by `inspection_date`,
|
||||
which tie arbitrarily on duplicate monthly rows.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Predecessor inspections (audit M10): a grade Ofsted attributes to a previous
|
||||
URN stays unlabelled.
|
||||
- Post-16 and ISI-inspected schools (H4) and the "Not yet inspected" label.
|
||||
- The compare page's broken Ofsted link (M4).
|
||||
- Report-card display, which is unchanged.
|
||||
|
||||
## The rule
|
||||
|
||||
Computed once per URN in `int_ofsted_latest`.
|
||||
|
||||
**Latest visit:** the newest of RC, G and U.
|
||||
|
||||
- `latest_visit_date`
|
||||
- `latest_visit_kind`: `report_card`, `graded` or `ungraded`
|
||||
- `latest_visit_outcome`: the ungraded outcome text when the kind is `ungraded`,
|
||||
otherwise null
|
||||
|
||||
**Current grade:** the overall grade still in force, if any.
|
||||
|
||||
| Situation | `current_grade` | `current_grade_date` | `current_grade_basis` |
|
||||
|---|---|---|---|
|
||||
| A report card exists | null | null | null |
|
||||
| Latest is graded, overall 1–4 | that grade | G | `graded` |
|
||||
| Latest is graded, "Not judged" | null | null | null |
|
||||
| Latest is ungraded, outcome "School remains X…" (any qualifier) | X | U | `confirmed` |
|
||||
| Latest is ungraded, any other outcome ("Standards maintained", "Improved significantly", "Some aspects not as strong") | the graded inspection's overall grade if it is 1–4, else null | G when a grade is kept | `graded` when a grade is kept |
|
||||
| No inspection | null | null | null |
|
||||
|
||||
A report card replaced overall grades, so no legacy grade stays in force beside
|
||||
one. The latest visit is read from the dates, not assumed: report cards began in
|
||||
November 2025, after the last legacy graded and ungraded inspections, and in
|
||||
Ofsted's 31 Aug 2026 data no school has a legacy visit newer than its report
|
||||
card, but the rule does not depend on that. Ties between G, U and RC on the same
|
||||
date resolve in the order report card, graded, ungraded.
|
||||
|
||||
Invariants: `current_grade` is null or 1–4; `current_grade_date <=
|
||||
latest_visit_date`; `current_grade_basis` is null exactly when `current_grade`
|
||||
is null.
|
||||
|
||||
### Expected results (Ofsted MI as at 31 Aug 2026)
|
||||
|
||||
| URN | School | Ofsted data | Latest visit | Current grade |
|
||||
|---|---|---|---|---|
|
||||
| 102408 | Rabbsfarm Primary School | G 17 Jun 2025 Not judged; U 6 Feb 2020 remains Good | graded, 17 Jun 2025 | none |
|
||||
| 151783 | Acre Wood Academy | G 1 Oct 2024 Not judged; U 14 Mar 2023 remains Good (Concerns) | graded, 1 Oct 2024 | none |
|
||||
| 139888 | Washwood Heath Academy | G 3 Mar 2020 Good; U 21 May 2025 Standards maintained | ungraded, 21 May 2025, "Standards maintained" | Good, 3 Mar 2020, graded |
|
||||
| 104762 | Robins Lane Community Primary | G 7 Jan 2020 Good; U 18 Jul 2024 School remains Good | ungraded, 18 Jul 2024 | Good, 18 Jul 2024, confirmed |
|
||||
| 100094 | Royal Free Hospital Children's School | G 9 Oct 2019 Outstanding; U 5 Feb 2025 Some aspects not as strong | ungraded, 5 Feb 2025 | Outstanding, 9 Oct 2019, graded |
|
||||
| 136454 | Oakgrove School | U 13 Nov 2024 Standards maintained only | ungraded, 13 Nov 2024 | none |
|
||||
| 137086 | Bishop Stopford School | G 1 Apr 2025 Not judged | graded, 1 Apr 2025 | none |
|
||||
| 110048 | The Willink School | U 5 Oct 2023 remains Good; RC 6 May 2026 | report card, 6 May 2026 | none (report card shown) |
|
||||
| 149612 | St Michael's Catholic School | RC 10 Feb 2026 only | report card, 10 Feb 2026 | none (report card shown) |
|
||||
|
||||
## What each page shows
|
||||
|
||||
**Search and map badge** (`buildOfstedListBadge`), first match wins:
|
||||
|
||||
1. Report card: "Report Card · *RC year*" (unchanged)
|
||||
2. Current grade: "*Grade* · *year of `current_grade_date`*"
|
||||
3. Latest visit: "Inspected · *year of `latest_visit_date`*"
|
||||
4. "Not yet inspected" (unchanged)
|
||||
|
||||
**School page** (`OfstedSection`, both phases):
|
||||
|
||||
- Title date: "Inspected *latest visit date*".
|
||||
- Headline: the report card; or the current grade with a source line
|
||||
("Graded inspection, 6 July 2016" or "Confirmed at an ungraded inspection,
|
||||
14 March 2023"); or "No overall grade" with "Ofsted stopped giving overall
|
||||
grades in September 2024".
|
||||
- "Latest visit" line when the latest visit is not the grade's source, e.g.
|
||||
"Ungraded inspection, 13 Nov 2024: Standards maintained".
|
||||
- The area grid shows the graded inspection's judgements through
|
||||
`ofstedLegacyAreas()`, dated by that inspection when it is not the latest
|
||||
visit. The primary and secondary no-grade branches merge into one; the
|
||||
secondary branch's four hard-coded areas (audit M2) go with it.
|
||||
|
||||
**Compare:** `ofstedDisplay` returns `report_card`, `graded`, `confirmed`,
|
||||
`no_overall_grade` or `none`. The "Latest Ofsted inspection", "Result" and
|
||||
"Inspected" rows use the same fields as the school page.
|
||||
|
||||
## Delivery
|
||||
|
||||
Two pull requests. The mart columns exist before anything reads them, so
|
||||
neither needs compatibility code.
|
||||
|
||||
### PR 1: pipeline (additive)
|
||||
|
||||
- `stg_ofsted_inspections`: keep `graded_inspection_date`,
|
||||
`ungraded_inspection_date` and `rc_inspection_date` as separate typed
|
||||
columns, with the report-card date's existing guard. Keep `inspection_date`
|
||||
(graded, else ungraded) for the current backend. Keep a row when any of the
|
||||
three dates is present, so report-card-only schools are no longer dropped
|
||||
(part of H3: 123 schools).
|
||||
- `int_ofsted_latest`: pick one row per URN by `latest_visit_date` descending,
|
||||
then `rc_inspection_date`, `ungraded_inspection_date` and
|
||||
`graded_inspection_date` descending (nulls last). A duplicate monthly row that
|
||||
carries a newer report card therefore always wins. Add the five status
|
||||
columns.
|
||||
- New mart `marts.fact_ofsted_latest`: one row per URN from `int_ofsted_latest`
|
||||
with every column the pages need (status, area grades, report-card grades,
|
||||
ungraded outcome, report URL). It does not join `dim_school`, so only the
|
||||
monthly Ofsted DAG builds it.
|
||||
- `dim_school` is not changed in PR 1: the daily DAG does not rebuild
|
||||
`int_ofsted_latest`, and reading a column that the monthly DAG has not yet
|
||||
built would fail the daily run.
|
||||
- Visible effect: report-card-only schools gain their report card, because the
|
||||
backend's existing reads of `fact_ofsted_inspection` now see their rows.
|
||||
Nothing else changes.
|
||||
|
||||
### PR 2: backend and UI (after the Ofsted DAG has run on PR 1)
|
||||
|
||||
- `data_loader.py`: the list query and the batch query read
|
||||
`marts.fact_ofsted_latest` instead of picking the latest row of
|
||||
`fact_ofsted_inspection`. `_ofsted_block` reads the status columns and loses
|
||||
its fallback to `ungraded_grade`.
|
||||
- List rows: `ofsted_grade` becomes `current_grade`; `ofsted_date` becomes
|
||||
`latest_visit_date`; new `ofsted_grade_date`. `ofsted_rc_date` stays.
|
||||
- `ofsted` block: `overall_effectiveness` and `inspection_date` are the graded
|
||||
inspection's own result and date (they label the area grid); new
|
||||
`current_grade` `{grade, date, basis}` (or null) and `latest_visit`
|
||||
`{date, kind, outcome}`; `grade_source` is removed. Report-card fields are
|
||||
unchanged.
|
||||
- `dim_school.ofsted_grade` becomes `current_grade` (Typesense's rating follows
|
||||
at the next sync); `ofsted_date` becomes `latest_visit_date`.
|
||||
- Sitemap: `lastmod` from `latest_visit_date`; `_PUBLISHABLE_FIELDS` also counts
|
||||
a latest visit, so schools that lose a carried grade keep their sitemap entry.
|
||||
- Front end: `lib/types.ts`, `buildOfstedListBadge`, `OfstedSection`,
|
||||
`PrimarySchoolSections`, `SecondarySchoolSections`, `compareLogic.ofstedDisplay`,
|
||||
`CompareAtAGlance`, `CompareOfsted`. Place-page counts need no change.
|
||||
- Delete `buildOfstedHeroChip` and `buildSchoolSummary` in their own commit:
|
||||
nothing renders them and they encode the old rule.
|
||||
|
||||
## Testing
|
||||
|
||||
**PR 1**
|
||||
|
||||
- dbt unit tests on `int_ofsted_latest`, one per table row above plus
|
||||
"report-card only" and "duplicate rows, newer report card wins".
|
||||
- Schema tests on `fact_ofsted_latest`: unique, not-null `urn`; accepted values
|
||||
for `latest_visit_kind` and `current_grade_basis`; `current_grade` null or
|
||||
1–4; `current_grade_date <= latest_visit_date`.
|
||||
- Run locally against a throwaway Postgres from `pgserver` (no Docker here). If
|
||||
that fails, they still run in the Ofsted DAG's `dbt build`, which fails on any
|
||||
broken case.
|
||||
- `pipeline/tests/test_dag_selectors.py` (PR #181) keeps passing.
|
||||
|
||||
**PR 2**
|
||||
|
||||
- pytest: contract test for the list and `ofsted` fields (style of
|
||||
`test_school_page_flag_fields.py`); `_ofsted_block` from a
|
||||
`fact_ofsted_latest` row; sitemap publishability.
|
||||
- Jest: a badge case per table row; `OfstedSection` for graded, confirmed, no
|
||||
grade, the latest-visit line and a sixth-form area; `ofstedDisplay` kinds.
|
||||
Rewrite tests that assert `carried_forward`.
|
||||
- E2E (same PR): Rabbsfarm's search row says "Inspected · 2025" and its page
|
||||
says "No overall grade" with quality of education Requires Improvement; a
|
||||
confirmed school says "Confirmed at an ungraded inspection". The existing
|
||||
report-card journey stays.
|
||||
|
||||
## Rollout and verification
|
||||
|
||||
1. Merge PR 1. On staging, run `school_data_monthly_ofsted`, then:
|
||||
|
||||
```sql
|
||||
-- one row per school
|
||||
select count(*) = count(distinct urn) from marts.fact_ofsted_latest;
|
||||
-- the examples above
|
||||
select urn, latest_visit_date, latest_visit_kind, latest_visit_outcome,
|
||||
current_grade, current_grade_date, current_grade_basis
|
||||
from marts.fact_ofsted_latest
|
||||
where urn in (102408, 151783, 139888, 104762, 100094, 136454, 137086, 110048, 149612);
|
||||
-- C1: a grade in force although the latest inspection gave none (expect 0)
|
||||
select count(*) from marts.fact_ofsted_latest
|
||||
where current_grade is not null and latest_visit_kind = 'graded'
|
||||
and overall_effectiveness is null;
|
||||
-- invariant (expect 0)
|
||||
select count(*) from marts.fact_ofsted_latest where current_grade_date > latest_visit_date;
|
||||
```
|
||||
|
||||
Check through the API that St Michael's Catholic School (149612) shows its
|
||||
report card.
|
||||
2. Promote PR 1 to production; run the Ofsted DAG there; repeat the checks.
|
||||
3. Merge PR 2. Let the daily DAG run (or trigger it) so `dim_school` and
|
||||
Typesense pick up the change; run the E2E journeys; re-run the audit's C1,
|
||||
M1 and M2 checks against staging: expect 0.
|
||||
4. Promote PR 2; repeat the audit checks on production.
|
||||
|
||||
## Expected visible change
|
||||
|
||||
About 932 schools change from a grade badge dated by a no-grade inspection
|
||||
("Good · 2025") to "Inspected · 2025". Counts of Good and Outstanding schools
|
||||
on place pages fall by the same schools, and Typesense's rating changes for
|
||||
them. Dates beside a grade can move earlier (to the inspection that awarded
|
||||
it); "Inspected" dates move later (to the latest visit).
|
||||
|
||||
## Risks
|
||||
|
||||
- Ofsted changes its MI columns most months. Unknown grade text parses to null
|
||||
(`safe_numeric`), which degrades to "Inspected · year", never to a wrong grade.
|
||||
- PR 2 depends on the Ofsted DAG having run on the target environment after PR
|
||||
1. If PR 2 is promoted first, the backend reads a missing table: promote in
|
||||
order.
|
||||
+199
-12
@@ -53,7 +53,7 @@ async function settledScrollLeft(scroller: Locator): Promise<number> {
|
||||
* whatever primaries the environment holds.
|
||||
*/
|
||||
async function twoPrimaryUrns(page: Page): Promise<[string, string]> {
|
||||
const res = await page.request.get('/api/schools?search=primary&per_page=50');
|
||||
const res = await page.request.get('/api/schools?search=primary&page_size=50');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const body = await res.json();
|
||||
const urns: string[] = (body.schools ?? [])
|
||||
@@ -66,7 +66,7 @@ async function twoPrimaryUrns(page: Page): Promise<[string, string]> {
|
||||
}
|
||||
|
||||
async function twoSecondaryUrns(page: Page): Promise<[string, string]> {
|
||||
const res = await page.request.get('/api/schools?search=school&per_page=100');
|
||||
const res = await page.request.get('/api/schools?search=school&page_size=100');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const body = await res.json();
|
||||
const urns: string[] = (body.schools ?? [])
|
||||
@@ -286,6 +286,19 @@ test('the phase filter switches straight from secondary to primary', async ({ pa
|
||||
await expect(phase).toHaveValue('primary');
|
||||
});
|
||||
|
||||
test('the phase filter lists phases in the order a child meets them', async ({ page }) => {
|
||||
// They were alphabetical, so "16 plus" and "All-through" came before Nursery.
|
||||
const childPath = ['Nursery', 'Primary', 'Middle deemed primary',
|
||||
'Middle deemed secondary', 'Secondary', '16 plus', 'All-through'];
|
||||
await page.goto('/?search=school');
|
||||
const phase = page.getByRole('combobox', { name: 'Phase' });
|
||||
await expect(phase).toBeVisible({ timeout: 15_000 });
|
||||
const offered = (await phase.locator('option').allTextContents())
|
||||
.filter((o) => childPath.includes(o));
|
||||
expect(offered, 'no phase on offer').toContain('Primary');
|
||||
expect(offered).toEqual(childPath.filter((p) => offered.includes(p)));
|
||||
});
|
||||
|
||||
test('school type and gender switch straight to another value', async ({ page }) => {
|
||||
// Their options came from the result set, which the filter had already
|
||||
// narrowed, so with one value chosen it was the only one on offer.
|
||||
@@ -309,6 +322,19 @@ test('school type and gender switch straight to another value', async ({ page })
|
||||
* School type offers six groups a parent recognises, and Faith sits beside it.
|
||||
* Data-invariant: asserts what every returned school is, never how many.
|
||||
*/
|
||||
// Clear all once dropped the search with the filters, which sent desktop back
|
||||
// to the home page instead of to the unfiltered results.
|
||||
test('Clear all removes the filters and keeps the search', async ({ page }) => {
|
||||
await page.goto('/?search=school&phase=primary');
|
||||
const row = page.getByRole('group', { name: 'Filters', exact: true });
|
||||
await expect(schoolLinks(page).first()).toBeVisible({ timeout: 15_000 });
|
||||
await row.getByRole('button', { name: 'Clear all', exact: true }).click();
|
||||
await expect(page).not.toHaveURL(/[?&]phase=/);
|
||||
await expect(page).toHaveURL(/[?&]search=school(&|$)/);
|
||||
await expect(schoolLinks(page).first()).toBeVisible();
|
||||
await expect(row.getByRole('button', { name: 'Clear all', exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('school type groups and the faith filter narrow to what they name', async ({ page }) => {
|
||||
await page.goto('/?search=school');
|
||||
const type = page.getByRole('combobox', { name: 'School type', exact: true });
|
||||
@@ -329,6 +355,84 @@ test('school type groups and the faith filter narrow to what they name', async (
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Search rows printed tags the register does not hold. Every non-selective
|
||||
* secondary was "Selective" ("non-selective" contains "selective"), and a
|
||||
* school with no religious character got "Faith priority" or a bare "None"
|
||||
* chip, because only "Does not apply" was excluded. Data-invariant: each test
|
||||
* picks its school from the API and reads only that school's row.
|
||||
*/
|
||||
async function rowTags(page: Page, school: { urn: number; school_name: string }) {
|
||||
await searchByName(page, school.school_name);
|
||||
const link = page.locator(`a[href^="/school/${school.urn}-"]`).first();
|
||||
await expect(link).toBeVisible({ timeout: 15_000 });
|
||||
return link.locator('xpath=ancestor::div[contains(@class, "__rowContent")][1]')
|
||||
.locator('[class*="__line2"]');
|
||||
}
|
||||
|
||||
test('a non-selective secondary is not tagged Selective in search', async ({ page }) => {
|
||||
const res = await page.request.get(
|
||||
'/api/schools?search=school&phase=secondary&admissions_policy=non-selective&page_size=1');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const [school] = (await res.json()).schools ?? [];
|
||||
test.skip(!school, 'no non-selective secondary in this environment');
|
||||
expect(school.admissions_policy, 'the admissions filter was ignored').toBe('Non-selective');
|
||||
|
||||
const tags = await rowTags(page, school);
|
||||
await expect(tags).toBeVisible();
|
||||
await expect(tags.getByText('Selective', { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('a school with no religious character carries no faith tag in search', async ({ page }) => {
|
||||
const res = await page.request.get('/api/schools?search=school&faith=none&page_size=100');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
// Not a selective school: the Selective tag would win and hide the bug.
|
||||
const school = ((await res.json()).schools ?? []).find(
|
||||
(s: { religious_denomination?: string; admissions_policy?: string }) =>
|
||||
s.religious_denomination === 'None' && !/selective/i.test(s.admissions_policy ?? ''));
|
||||
test.skip(!school, 'no school recorded with religious character "None" here');
|
||||
|
||||
const tags = await rowTags(page, school);
|
||||
await expect(tags).toBeVisible();
|
||||
await expect(tags.getByText('Faith priority', { exact: true })).toHaveCount(0);
|
||||
await expect(tags.getByText('None', { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('search and the school page agree on how many pupils a secondary has', async ({ page }) => {
|
||||
// Search showed the GCSE year group as "pupils": Burntwood had 245 in
|
||||
// search and 1,462 on its page. Both now carry the register's count.
|
||||
const res = await page.request.get('/api/schools?search=school&phase=secondary&page_size=20');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const school = ((await res.json()).schools ?? []).find(
|
||||
(s: { total_pupils?: number | null }) => s.total_pupils != null);
|
||||
test.skip(!school, 'no secondary with a pupil count in this environment');
|
||||
const detail = await (await page.request.get(`/api/schools/${school.urn}`)).json();
|
||||
expect(school.total_pupils).toBe(detail.school_info.total_pupils);
|
||||
});
|
||||
|
||||
test('a secondary search row compares its Attainment 8 with the LA average', async ({ page }) => {
|
||||
// The comparison vanished unnoticed: the averages were fetched with
|
||||
// force-cache, so one stored failure hid it in that browser for good.
|
||||
// Playwright disables the HTTP cache when it intercepts requests, so this
|
||||
// guards the comparison itself; the unit test pins the cache mode.
|
||||
const la = await (await page.request.get('/api/la-averages')).json();
|
||||
const averages: Record<string, number> = la.secondary?.attainment_8_by_la ?? {};
|
||||
const res = await page.request.get('/api/schools?search=school&phase=secondary&page_size=50');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const school = ((await res.json()).schools ?? []).find(
|
||||
(s: { attainment_8_score?: number | null; local_authority?: string; school_type?: string }) =>
|
||||
s.attainment_8_score != null && s.local_authority != null && averages[s.local_authority] != null
|
||||
&& !/special|pupil referral|alternative provision/i.test(s.school_type ?? ''));
|
||||
test.skip(!school, 'no mainstream secondary with an LA average here');
|
||||
|
||||
await searchByName(page, school.school_name);
|
||||
const link = page.locator(`a[href^="/school/${school.urn}-"]`).first();
|
||||
await expect(link).toBeVisible({ timeout: 15_000 });
|
||||
const stats = link.locator('xpath=ancestor::div[contains(@class, "__rowContent")][1]')
|
||||
.locator('[class*="__line3"]');
|
||||
await expect(stats.getByText(/vs LA avg/)).toBeVisible();
|
||||
});
|
||||
|
||||
test('a phase outside primary/secondary filters to that phase, not to everything', async ({ page }) => {
|
||||
// The search page offers every GIAS phase, but the API only knew the grouped
|
||||
// ones and silently dropped the rest — so "Nursery" returned primaries.
|
||||
@@ -406,9 +510,10 @@ test('school detail page shows GIAS identity/contact details and drops the unwir
|
||||
if (info.telephone) {
|
||||
await expect(page.locator('a[href^="tel:"]').first()).toBeVisible();
|
||||
}
|
||||
if (info.parliamentary_constituency) {
|
||||
await expect(page.getByText('Constituency:').first()).toBeVisible();
|
||||
}
|
||||
// Constituency and county left the header in the facts-and-flags redesign:
|
||||
// neither helps a parent decide. The place pages keep both.
|
||||
await expect(page.getByText('Constituency:')).toHaveCount(0);
|
||||
await expect(page.getByText('County:')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('header details collapse behind a "Show all details" toggle on mobile', async ({ page }) => {
|
||||
@@ -518,7 +623,7 @@ test('school with no performance data still gets a working detail page', async (
|
||||
const candidates: number[] = [];
|
||||
for (const q of ['post 16', 'specialist college', 'sixth form']) {
|
||||
const resp = await page.request.get(
|
||||
`/api/schools?search=${encodeURIComponent(q)}&per_page=20`
|
||||
`/api/schools?search=${encodeURIComponent(q)}&page_size=20`
|
||||
);
|
||||
if (!resp.ok()) continue;
|
||||
const body = await resp.json();
|
||||
@@ -1097,7 +1202,7 @@ test('compare metric-help popover stays within the mobile viewport', async ({ pa
|
||||
test('admissions year/trend toggle still switches views after the server/client split', async ({ page }) => {
|
||||
// Find a school with at least two years carrying an offer rate — the toggle
|
||||
// only appears then. Data-invariant: uses whatever the environment holds.
|
||||
const res = await page.request.get('/api/schools?search=primary&per_page=50');
|
||||
const res = await page.request.get('/api/schools?search=primary&page_size=50');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const candidates: number[] = ((await res.json()).schools ?? []).map((s: { urn: number }) => s.urn);
|
||||
|
||||
@@ -2057,7 +2162,7 @@ test('English schools with Welsh postcodes are kept', async ({ page }) => {
|
||||
test('a Welsh school URL 404s while an English one still resolves', async ({ page }) => {
|
||||
// Paired on purpose: the Welsh assertion alone would also pass if the whole
|
||||
// site were down, which is the failure this test most needs to distinguish.
|
||||
const english = await page.request.get('/api/schools?search=primary&per_page=1');
|
||||
const english = await page.request.get('/api/schools?search=primary&page_size=1');
|
||||
expect(english.ok()).toBeTruthy();
|
||||
const [first] = (await english.json()).schools ?? [];
|
||||
expect(first, 'no English school available to compare against').toBeTruthy();
|
||||
@@ -2167,7 +2272,7 @@ test('a filtered homepage still canonicalises to the bare root', async ({ page }
|
||||
});
|
||||
|
||||
test('a school page canonicalises to its own slug on the www host', async ({ page }) => {
|
||||
const res = await page.request.get('/api/schools?search=primary&per_page=1');
|
||||
const res = await page.request.get('/api/schools?search=primary&page_size=1');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const [first] = (await res.json()).schools ?? [];
|
||||
expect(first, 'no school available').toBeTruthy();
|
||||
@@ -2242,7 +2347,7 @@ function blocksEverything(robots: string, agent: string): boolean {
|
||||
}
|
||||
|
||||
test('a school page on staging is noindexed too, not just the homepage', async ({ page }) => {
|
||||
const list = await page.request.get('/api/schools?search=primary&per_page=1');
|
||||
const list = await page.request.get('/api/schools?search=primary&page_size=1');
|
||||
const [first] = (await list.json()).schools ?? [];
|
||||
expect(first, 'no school available').toBeTruthy();
|
||||
|
||||
@@ -2853,7 +2958,7 @@ test('with autosuggest off, the search box is a plain input', async ({ page }) =
|
||||
async function secondaryWithDestinations(page: Page): Promise<{
|
||||
urn: string; destinations: any;
|
||||
}> {
|
||||
const res = await page.request.get('/api/schools?search=school&per_page=100');
|
||||
const res = await page.request.get('/api/schools?search=school&page_size=100');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const body = await res.json();
|
||||
const urns: string[] = (body.schools ?? [])
|
||||
@@ -2949,7 +3054,7 @@ test('switching to disadvantaged pupils never reveals a withheld figure', async
|
||||
});
|
||||
|
||||
test('a school with no sixth form has no post-16 destinations section', async ({ page }) => {
|
||||
const res = await page.request.get('/api/schools?search=school&per_page=100');
|
||||
const res = await page.request.get('/api/schools?search=school&page_size=100');
|
||||
const body = await res.json();
|
||||
const noSixthForm = (body.schools ?? [])
|
||||
.filter((s: { phase?: string; has_sixth_form?: boolean }) =>
|
||||
@@ -3260,3 +3365,85 @@ for (const width of [360, 390, 430]) {
|
||||
expect(failing).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
* The header's facts row read GIAS text as booleans: "Not applicable" put a
|
||||
* "Nursery" chip on secondaries aged 11–18, and "Girls" became "Girls's
|
||||
* school". Data-invariant: the chip follows whatever the API says.
|
||||
*/
|
||||
test('a girls\' secondary header names it properly and shows Nursery only when it has one', async ({ page }) => {
|
||||
const res = await page.request.get('/api/schools?search=school&phase=secondary&gender=girls&page_size=1');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const [school] = (await res.json()).schools ?? [];
|
||||
test.skip(!school, 'no girls\' secondary in this environment');
|
||||
expect(school.gender, 'the gender filter was ignored').toBe('Girls');
|
||||
const detail = await (await page.request.get(`/api/schools/${school.urn}`)).json();
|
||||
// Without the field, the Nursery assertion below would pass vacuously.
|
||||
expect(detail.school_info).toHaveProperty('nursery_provision');
|
||||
|
||||
await page.goto(`/school/${school.urn}`);
|
||||
const header = page.locator('header', { has: page.getByRole('heading', { level: 1 }) });
|
||||
await expect(header.getByText("Girls' school", { exact: true })).toBeVisible({ timeout: 15_000 });
|
||||
await expect(header.getByText(/'s school/)).toHaveCount(0);
|
||||
await expect(header.getByText('Nursery class', { exact: true }))
|
||||
.toHaveCount(detail.school_info.nursery_provision === 'Has Nursery Classes' ? 1 : 0);
|
||||
});
|
||||
|
||||
/*
|
||||
* The header states facts in fixed slots and flags only what applies: a
|
||||
* selective school is flagged Selective, and its type reads in the search
|
||||
* filter's words, not as a GIAS establishment type. The search row carries
|
||||
* the same flag. Data-invariant: the school comes from the API.
|
||||
*/
|
||||
const TYPE_GROUP_LABELS: Record<string, string> = {
|
||||
state: 'State school', independent: 'Independent school', special: 'Special school (SEND)',
|
||||
post16: 'Sixth form or college', alternative: 'Alternative provision',
|
||||
};
|
||||
|
||||
test('a selective school is flagged Selective, on its page and in search', async ({ page }) => {
|
||||
const res = await page.request.get(
|
||||
'/api/schools?search=school&phase=secondary&admissions_policy=selective&page_size=1');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const [school] = (await res.json()).schools ?? [];
|
||||
test.skip(!school, 'no selective secondary in this environment');
|
||||
expect(school.admissions_policy, 'the admissions filter was ignored').toBe('Selective');
|
||||
expect(school, 'the list must name the type group').toHaveProperty('type_group');
|
||||
|
||||
await page.goto(`/school/${school.urn}`);
|
||||
const header = page.locator('header', { has: page.getByRole('heading', { level: 1 }) });
|
||||
const flags = header.getByRole('list', { name: 'Admission and provision' });
|
||||
await expect(flags.getByText('Selective', { exact: true })).toBeVisible({ timeout: 15_000 });
|
||||
const typeLabel = TYPE_GROUP_LABELS[school.type_group] ?? school.school_type;
|
||||
await expect(header.getByText(typeLabel, { exact: true })).toBeVisible();
|
||||
|
||||
const tags = await rowTags(page, school);
|
||||
await expect(tags.getByText('Selective', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
/*
|
||||
* The Admissions section repeated the search rows' old tag logic: "selective"
|
||||
* matched inside "Non-selective", and "None" counted as a faith, so Burntwood
|
||||
* read "this school has a faith-based admissions priority (None)". The
|
||||
* Selective half stayed hidden only because the school page's API did not
|
||||
* send admissions_policy. Data-invariant: the school comes from the API, and
|
||||
* must have an Admissions section to read.
|
||||
*/
|
||||
test('a non-selective school with no faith makes neither claim in its Admissions section', async ({ page }) => {
|
||||
const res = await page.request.get(
|
||||
'/api/schools?search=school&phase=secondary&faith=none&admissions_policy=non-selective&page_size=20');
|
||||
expect(res.ok()).toBeTruthy();
|
||||
let urn: number | null = null;
|
||||
for (const s of ((await res.json()).schools ?? []).slice(0, 8)) {
|
||||
if (s.religious_denomination !== 'None') continue;
|
||||
const detail = await (await page.request.get(`/api/schools/${s.urn}`)).json();
|
||||
if (detail.admissions) { urn = s.urn; break; }
|
||||
}
|
||||
test.skip(urn == null, 'no non-selective, no-faith secondary with admissions data here');
|
||||
|
||||
await page.goto(`/school/${urn}`);
|
||||
const admissions = page.locator('section#admissions');
|
||||
await expect(admissions).toBeVisible({ timeout: 15_000 });
|
||||
await expect(admissions.getByText('Selective:', { exact: true })).toHaveCount(0);
|
||||
await expect(admissions.getByText('Faith priority:', { exact: true })).toHaveCount(0);
|
||||
await expect(admissions.getByText(/\(None\)/)).toHaveCount(0);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { HomeView } from '@/components/HomeView';
|
||||
import { fetchSchools } from '@/lib/api';
|
||||
import { fetchLAaverages, fetchSchools } from '@/lib/api';
|
||||
import { primaryFixture } from '../support/schoolFixtures';
|
||||
import type { SchoolsResponse, School } from '@/lib/types';
|
||||
|
||||
@@ -84,3 +84,23 @@ test('failed map requests can be retried by reopening the map', async () => {
|
||||
expect(fetchSchools).toHaveBeenCalledTimes(2);
|
||||
expect(screen.getByTestId('map')).toHaveTextContent('Retry result');
|
||||
});
|
||||
|
||||
test('LA averages are not fetched with force-cache, so one failure is not replayed for good', async () => {
|
||||
// force-cache serves any stored response, however old, without asking the
|
||||
// server. A request that failed once (a staging deploy restart, the July
|
||||
// proxy outage) was stored and replayed on every later visit, and the
|
||||
// "vs LA avg" delta vanished from every secondary row in that browser.
|
||||
// The default mode honours the API's Cache-Control and never reuses an
|
||||
// error.
|
||||
params = new URLSearchParams('search=high');
|
||||
const secondary: SchoolsResponse = {
|
||||
...response('Alpha High'),
|
||||
schools: [{ ...primaryFixture.schoolInfo, school_name: 'Alpha High', phase: 'Secondary', attainment_8_score: 50 }],
|
||||
};
|
||||
render(<HomeView initialSchools={secondary} filters={filters} />);
|
||||
await act(async () => {});
|
||||
expect(fetchLAaverages).toHaveBeenCalled();
|
||||
for (const [options] of jest.mocked(fetchLAaverages).mock.calls) {
|
||||
expect(options?.cache).not.toBe('force-cache');
|
||||
}
|
||||
});
|
||||
@@ -8,7 +8,6 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
import {
|
||||
nearbyNoun,
|
||||
NearbySchoolsSection,
|
||||
shouldRenderNearby,
|
||||
} from '@/components/school/NearbySchoolsSection';
|
||||
@@ -43,13 +42,7 @@ function school(overrides: Partial<NearbySchool> = {}): NearbySchool {
|
||||
|
||||
function renderSection(nearby: NearbySchool[]) {
|
||||
return render(
|
||||
<NearbySchoolsSection
|
||||
urn={100001}
|
||||
schoolName="Meadowbrook Primary School"
|
||||
phase="Primary"
|
||||
thisMetricValue={72}
|
||||
nearby={nearby}
|
||||
/>,
|
||||
<NearbySchoolsSection urn={100001} thisMetricValue={72} nearby={nearby} />,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,15 +83,10 @@ describe('what the section claims', () => {
|
||||
});
|
||||
|
||||
it('shows no chips at all when nothing is shared, rather than inventing one', () => {
|
||||
const { container } = render(
|
||||
<NearbySchoolsSection
|
||||
urn={100001}
|
||||
schoolName="Meadowbrook Primary School"
|
||||
phase="Primary"
|
||||
thisMetricValue={72}
|
||||
nearby={[school({ shared: [] }), school({ urn: 100003, shared: [] })]}
|
||||
/>,
|
||||
);
|
||||
const { container } = renderSection([
|
||||
school({ shared: [] }),
|
||||
school({ urn: 100003, shared: [] }),
|
||||
]);
|
||||
// The card still carries its distance, name, type and figure — just no
|
||||
// claim of likeness.
|
||||
expect(container.querySelectorAll('li ul').length).toBe(0);
|
||||
@@ -106,37 +94,6 @@ describe('what the section claims', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('what the lede calls the set', () => {
|
||||
it.each([
|
||||
['Primary', 'primary schools'],
|
||||
['Middle deemed primary', 'primary schools'],
|
||||
['Secondary', 'secondary schools'],
|
||||
['Middle deemed secondary', 'secondary schools'],
|
||||
['All-through', 'all-through schools'],
|
||||
// GIAS phase 6. Its candidates span the whole secondary group, so no
|
||||
// single noun fits and it takes the honest general one.
|
||||
['16 plus', 'schools and colleges'],
|
||||
['', 'schools'],
|
||||
[null, 'schools'],
|
||||
])('calls a %s school\'s neighbours "%s"', (phase, expected) => {
|
||||
expect(nearbyNoun(phase)).toBe(expected);
|
||||
});
|
||||
|
||||
it('never calls a sixth form college\'s neighbours primary schools', () => {
|
||||
render(
|
||||
<NearbySchoolsSection
|
||||
urn={100001}
|
||||
schoolName="Barnet Sixth Form College"
|
||||
phase="16 plus"
|
||||
thisMetricValue={null}
|
||||
nearby={[school(), school({ urn: 100003 })]}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText(/Other schools and colleges near Barnet Sixth Form College/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/primary schools/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('cards', () => {
|
||||
it('links each school to its canonical slug', () => {
|
||||
renderSection([school(), school({ urn: 100003, school_name: 'Oakfield Primary School' })]);
|
||||
|
||||
@@ -361,12 +361,12 @@ describe('PlaceView school attributes', () => {
|
||||
{ urn: 1, school_name: 'Alpha Primary', phase: 'Primary',
|
||||
rwm_expected_pct: 82, attainment_8_score: null,
|
||||
age_range: '4-11', religious_denomination: 'Church of England',
|
||||
nursery_provision: true,
|
||||
nursery_provision: 'Has Nursery Classes',
|
||||
parliamentary_constituency: 'Chelmsford' } as never,
|
||||
{ urn: 2, school_name: 'Beta High', phase: 'Secondary',
|
||||
rwm_expected_pct: null, attainment_8_score: 47,
|
||||
age_range: '11-16', religious_denomination: 'Does not apply',
|
||||
nursery_provision: false,
|
||||
nursery_provision: 'No Nursery Classes',
|
||||
parliamentary_constituency: 'Witham' } as never,
|
||||
],
|
||||
averages: { rwm_expected_pct: 63, attainment_8_score: 45 },
|
||||
@@ -459,6 +459,18 @@ describe('PlaceView school attributes', () => {
|
||||
expect(cells.slice(2)).toEqual(['—', '—', '—', '—']);
|
||||
});
|
||||
|
||||
it('reads "Not applicable" as no nursery, not as a yes', () => {
|
||||
// GIAS sends text. Tested for truthiness, every value was a "Yes".
|
||||
const notApplicable: PlaceDetail = {
|
||||
...withAttributes,
|
||||
schools: [{ urn: 5, school_name: 'Epsilon Primary', phase: 'Primary',
|
||||
rwm_expected_pct: 70, nursery_provision: 'Not applicable' } as never],
|
||||
};
|
||||
const { container } = render(<PlaceView detail={notApplicable} phase="primary"
|
||||
englandAverage={61} neighbours={[]} />);
|
||||
expect(container.querySelector('tbody')!.textContent).not.toContain('Yes');
|
||||
});
|
||||
|
||||
it('gives an all-through school its nursery under primary only', () => {
|
||||
// All-through schools render in both groups. Nursery belongs to the
|
||||
// primary reading of the same school, not the secondary one.
|
||||
@@ -467,7 +479,7 @@ describe('PlaceView school attributes', () => {
|
||||
schools: [{ urn: 4, school_name: 'Delta Academy', phase: 'All-through',
|
||||
rwm_expected_pct: 66, attainment_8_score: 51,
|
||||
age_range: '4-18', religious_denomination: 'None',
|
||||
nursery_provision: true,
|
||||
nursery_provision: 'Has Nursery Classes',
|
||||
parliamentary_constituency: 'Chelmsford' } as never],
|
||||
};
|
||||
const { container } = render(<PlaceView detail={allThrough}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { HomeView } from '@/components/HomeView';
|
||||
import { FilterBar } from '@/components/FilterBar';
|
||||
import { fetchSchools } from '@/lib/api';
|
||||
@@ -175,3 +175,24 @@ describe('the results list', () => {
|
||||
expect(screen.queryByText('Search: southmead')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the desktop Clear all', () => {
|
||||
const row = () => screen.getByRole('group', { name: 'Filters' });
|
||||
|
||||
it('removes the filters and keeps the search, rather than going home', () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=3&phase=primary&school_type=council&local_authority=Wandsworth');
|
||||
render(<FilterBar filters={filters} />);
|
||||
fireEvent.click(within(row()).getByRole('button', { name: 'Clear all' }));
|
||||
const pushed = push.mock.calls.at(-1)![0] as string;
|
||||
const next = new URLSearchParams(pushed.split('?')[1]);
|
||||
expect(next.get('postcode')).toBe('SW196AR');
|
||||
expect(next.get('radius')).toBe('3');
|
||||
for (const key of ['phase', 'school_type', 'local_authority']) expect(next.get(key)).toBeNull();
|
||||
});
|
||||
|
||||
it('is not offered when only a search is applied', () => {
|
||||
params = new URLSearchParams('search=southmead');
|
||||
render(<FilterBar filters={filters} />);
|
||||
expect(within(row()).queryByRole('button', { name: /^Clear/ })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* SchoolRow (primary search results): line 2 prints the religious character
|
||||
* only when the school has one. The register's "None" was printed as a chip.
|
||||
*/
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { SchoolRow } from '@/components/SchoolRow';
|
||||
import type { School } from '@/lib/types';
|
||||
|
||||
const base = {
|
||||
urn: 100001,
|
||||
school_name: 'Alpha Primary School',
|
||||
local_authority: 'Testshire',
|
||||
school_type: 'Free schools',
|
||||
phase: 'Primary',
|
||||
gender: 'Mixed',
|
||||
age_range: '4-11',
|
||||
rwm_expected_pct: 70,
|
||||
} as unknown as School;
|
||||
|
||||
describe('SchoolRow religious character', () => {
|
||||
it.each(['None', 'Does not apply', ''])(
|
||||
'prints nothing when the register says %p',
|
||||
(religious_denomination) => {
|
||||
render(<SchoolRow school={{ ...base, religious_denomination }} />);
|
||||
expect(screen.queryByText('None')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Does not apply')).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('prints a religious character the school has', () => {
|
||||
render(<SchoolRow school={{ ...base, religious_denomination: 'Church of England' }} />);
|
||||
expect(screen.getByText('Church of England')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SchoolRow shares the school page flags', () => {
|
||||
it("prints the type in the search filter's terms", () => {
|
||||
render(<SchoolRow school={{ ...base, type_group: 'state' }} />);
|
||||
expect(screen.getByText('State school')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Free schools')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('flags a nursery class', () => {
|
||||
render(<SchoolRow school={{ ...base, nursery_provision: 'Has Nursery Classes' }} />);
|
||||
expect(screen.getByText('Nursery class')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("flags a boys' school", () => {
|
||||
render(<SchoolRow school={{ ...base, gender: 'Boys' }} />);
|
||||
expect(screen.getByText("Boys' school")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -65,3 +65,54 @@ describe('SecondarySchoolRow proposed-to-close tag', () => {
|
||||
expect(screen.queryByText(/Proposed to close/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SecondarySchoolRow admissions tag', () => {
|
||||
it('tags a selective school', () => {
|
||||
render(<SecondarySchoolRow school={{ ...base, admissions_policy: 'Selective' }} />);
|
||||
expect(screen.getByText('Selective')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not tag a non-selective school as selective', () => {
|
||||
// "Non-selective" contains "selective": a substring test tagged every
|
||||
// comprehensive (Burntwood, Graveney) as Selective.
|
||||
render(<SecondarySchoolRow school={{ ...base, admissions_policy: 'Non-selective' }} />);
|
||||
expect(screen.queryByText('Selective')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(['None', 'Does not apply'])(
|
||||
'gives no faith tag when the religious character is %p',
|
||||
(religious_denomination) => {
|
||||
render(
|
||||
<SecondarySchoolRow
|
||||
school={{ ...base, admissions_policy: 'Not applicable', religious_denomination }}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByText(religious_denomination)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Faith priority')).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('tags the religious character the register records, not "Faith priority"', () => {
|
||||
render(
|
||||
<SecondarySchoolRow
|
||||
school={{ ...base, admissions_policy: 'Not applicable', religious_denomination: 'Church of England' }}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('Church of England')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Faith priority')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SecondarySchoolRow shares the school page flags', () => {
|
||||
it("prints the type in the search filter's terms", () => {
|
||||
render(<SecondarySchoolRow school={{ ...base, type_group: 'state' }} />);
|
||||
expect(screen.getByText('State school')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Academy')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("flags a girls' school and fees", () => {
|
||||
render(<SecondarySchoolRow school={{ ...base, type_group: 'independent', gender: 'Girls' }} />);
|
||||
expect(screen.getByText("Girls' school")).toBeInTheDocument();
|
||||
expect(screen.getByText('Fee-paying')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* The school header: one fact line (phase, ages, type, pupils), then flags
|
||||
* only for what applies, then the address and the details.
|
||||
*
|
||||
* nursery_provision is GIAS text, not a boolean: "Has Nursery Classes",
|
||||
* "No Nursery Classes" or "Not applicable". Tested for truthiness, every one
|
||||
* of those read as a nursery, so secondaries aged 11–18 showed "Nursery".
|
||||
*/
|
||||
|
||||
import { screen, within } from '@testing-library/react';
|
||||
import type { School } from '@/lib/types';
|
||||
import { primaryFixture, secondaryFixture } from '../support/schoolFixtures';
|
||||
import { renderSchoolDetail, renderSecondarySchoolDetail } from '../support/renderSchoolDetail';
|
||||
|
||||
jest.mock('@/lib/analytics', () => ({
|
||||
track: jest.fn(),
|
||||
getNavigationSource: () => 'direct',
|
||||
}));
|
||||
jest.mock('@/components/PerformanceChart', () => ({
|
||||
PerformanceChart: () => <div data-testid="performance-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/SatsChart', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="sats-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/AdmissionsTrendChart', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="admissions-trend-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/SchoolHeroMap', () => ({
|
||||
SchoolHeroMap: () => <div data-testid="hero-map" />,
|
||||
__esModule: true,
|
||||
}));
|
||||
|
||||
function withSchool<T extends { schoolInfo: School }>(fixture: T, info: Partial<School>): T {
|
||||
return { ...fixture, schoolInfo: { ...fixture.schoolInfo, ...info } };
|
||||
}
|
||||
|
||||
const flagList = () => screen.queryByRole('list', { name: 'Admission and provision' });
|
||||
const flagLabels = () => within(flagList()!).getAllByRole('listitem').map((li) => li.textContent);
|
||||
|
||||
describe('school header fact line', () => {
|
||||
it('states phase, ages, type and pupils, in that order', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { type_group: 'state' }));
|
||||
const line = screen.getByText('Ages 4–11').parentElement!;
|
||||
expect(line).toHaveTextContent(/^PrimaryAges 4–11State school420 pupils$/);
|
||||
});
|
||||
|
||||
it("prints the register's type name for a type in no group", () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { type_group: null, school_type: 'Secure units' }));
|
||||
expect(screen.getByText('Secure units')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('no longer prints the GIAS establishment type', () => {
|
||||
renderSecondarySchoolDetail(withSchool(secondaryFixture, { type_group: 'state' }));
|
||||
expect(screen.queryByText('Academy converter')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('school header flags', () => {
|
||||
it('shows no flag list for a school with nothing to flag', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { type_group: 'state' }));
|
||||
expect(flagList()).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('lists who-can-apply flags, then what the school offers', () => {
|
||||
renderSecondarySchoolDetail(withSchool(secondaryFixture, {
|
||||
type_group: 'independent', admissions_policy: 'Selective', gender: 'Girls',
|
||||
religious_denomination: 'Church of England', has_sixth_form: true,
|
||||
}));
|
||||
expect(flagLabels()).toEqual(['Fee-paying', 'Selective', "Girls' school", 'Church of England', 'Sixth form']);
|
||||
});
|
||||
|
||||
it('shows Nursery class when GIAS says the school has nursery classes', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { nursery_provision: 'Has Nursery Classes' }));
|
||||
expect(flagLabels()).toEqual(['Nursery class']);
|
||||
});
|
||||
|
||||
it.each(['No Nursery Classes', 'Not applicable', null])(
|
||||
'shows no nursery flag when GIAS says %p',
|
||||
(value) => {
|
||||
renderSecondarySchoolDetail(withSchool(secondaryFixture, { nursery_provision: value }));
|
||||
expect(screen.queryByText(/^Nursery/)).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([['Girls', "Girls' school"], ['Boys', "Boys' school"]])(
|
||||
'labels a %s school with a plural possessive',
|
||||
(gender, label) => {
|
||||
renderSecondarySchoolDetail(withSchool(secondaryFixture, { gender }));
|
||||
expect(screen.getByText(label)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/'s school/)).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('says nothing for a mixed school', () => {
|
||||
renderSecondarySchoolDetail(withSchool(secondaryFixture, { gender: 'Mixed' }));
|
||||
expect(screen.queryByText(/^(Girls|Boys|Mixed)'s? school$/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('school header address', () => {
|
||||
it('names the council after the postcode', () => {
|
||||
renderSchoolDetail(primaryFixture);
|
||||
expect(screen.getByText(/TE1 1ST · Westshire/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('leaves the council out when the address already names it', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { local_authority: 'Testville' }));
|
||||
expect(screen.queryByText(/· Testville/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('school header details', () => {
|
||||
const detailed = {
|
||||
headteacher_name: 'Mrs A Head', capacity: 426, county: 'Surrey',
|
||||
parliamentary_constituency: 'Putney', religious_denomination: 'Church of England',
|
||||
};
|
||||
|
||||
it('drops county, constituency and religious character', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, detailed));
|
||||
expect(screen.queryByText('County:')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Constituency:')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Religious character:')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the capacity', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, detailed));
|
||||
expect(screen.getByText('Capacity:').parentElement).toHaveTextContent('Capacity: 426');
|
||||
});
|
||||
|
||||
it('names an academy trust', () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { trust_name: 'BURNTWOOD TRUST' }));
|
||||
expect(screen.getByText('Academy trust:').parentElement).toHaveTextContent('BURNTWOOD TRUST');
|
||||
});
|
||||
|
||||
it("hides a trust that has the school's own name", () => {
|
||||
renderSchoolDetail(withSchool(primaryFixture, { trust_name: 'TEST PRIMARY SCHOOL' }));
|
||||
expect(screen.queryByText('Academy trust:')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* "Pupils" on a school page is the size of the school.
|
||||
*
|
||||
* A year's results row carries the cohort its figures were measured on. For a
|
||||
* secondary that is the GCSE year group alone (Burntwood: 245, against 1,462
|
||||
* on roll), so it must never stand in for the whole-school count.
|
||||
*/
|
||||
|
||||
import { screen } from '@testing-library/react';
|
||||
import { secondaryFixture } from '../support/schoolFixtures';
|
||||
import { renderSecondarySchoolDetail } from '../support/renderSchoolDetail';
|
||||
|
||||
jest.mock('@/lib/analytics', () => ({
|
||||
track: jest.fn(),
|
||||
getNavigationSource: () => 'direct',
|
||||
}));
|
||||
jest.mock('@/components/PerformanceChart', () => ({
|
||||
PerformanceChart: () => <div data-testid="performance-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/SatsChart', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="sats-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/AdmissionsTrendChart', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="admissions-trend-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/SchoolHeroMap', () => ({
|
||||
SchoolHeroMap: () => <div data-testid="hero-map" />,
|
||||
__esModule: true,
|
||||
}));
|
||||
|
||||
function withoutCensus(schoolTotal: number | null) {
|
||||
const yearlyData = secondaryFixture.yearlyData.map((r) => ({ ...r, total_pupils: 245 }));
|
||||
return {
|
||||
...secondaryFixture,
|
||||
census: null,
|
||||
yearlyData,
|
||||
schoolInfo: { ...secondaryFixture.schoolInfo, total_pupils: schoolTotal },
|
||||
};
|
||||
}
|
||||
|
||||
describe('pupil count without a census record', () => {
|
||||
it('uses the register count in the header, not the results cohort', () => {
|
||||
renderSecondarySchoolDetail(withoutCensus(1462));
|
||||
expect(screen.getByText('1,462 pupils')).toBeInTheDocument();
|
||||
expect(screen.queryByText('245 pupils')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows no count rather than the results cohort when the register has none', () => {
|
||||
renderSecondarySchoolDetail(withoutCensus(null));
|
||||
expect(screen.queryByText(/^[\d,]+ pupils$/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Total pupils')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* The Admissions section's Selective and faith notes.
|
||||
*
|
||||
* It tested the policy with includes('selective'), which "Non-selective"
|
||||
* passes, and excluded only "Does not apply" from the religious character, so
|
||||
* Burntwood (no religious character, recorded as "None") read "this school
|
||||
* has a faith-based admissions priority (None)". The Selective half never
|
||||
* fired only because the school page's API did not send admissions_policy.
|
||||
*/
|
||||
|
||||
import { screen, within } from '@testing-library/react';
|
||||
import type { School } from '@/lib/types';
|
||||
import { secondaryFixture } from '../support/schoolFixtures';
|
||||
import { renderSecondarySchoolDetail } from '../support/renderSchoolDetail';
|
||||
|
||||
jest.mock('@/lib/analytics', () => ({
|
||||
track: jest.fn(),
|
||||
getNavigationSource: () => 'direct',
|
||||
}));
|
||||
jest.mock('@/components/PerformanceChart', () => ({
|
||||
PerformanceChart: () => <div data-testid="performance-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/AdmissionsTrendChart', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="admissions-trend-chart" />,
|
||||
}));
|
||||
jest.mock('@/components/SchoolHeroMap', () => ({
|
||||
SchoolHeroMap: () => <div data-testid="hero-map" />,
|
||||
__esModule: true,
|
||||
}));
|
||||
|
||||
function admissionsOf(info: Partial<School>) {
|
||||
renderSecondarySchoolDetail({ ...secondaryFixture, schoolInfo: { ...secondaryFixture.schoolInfo, ...info } });
|
||||
return within(screen.getByRole('heading', { name: 'Admissions' }).closest('section')!);
|
||||
}
|
||||
|
||||
describe('Admissions section notes', () => {
|
||||
it('notes the entrance test for a selective school', () => {
|
||||
const section = admissionsOf({ admissions_policy: 'Selective', religious_denomination: 'None' });
|
||||
expect(section.getByText('Selective:')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not call a non-selective school selective', () => {
|
||||
const section = admissionsOf({ admissions_policy: 'Non-selective', religious_denomination: 'None' });
|
||||
expect(section.queryByText('Selective:')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(['None', 'Does not apply'])('claims no faith priority when the register says %p', (religious_denomination) => {
|
||||
// Not "Non-selective": a misread Selective would win and hide this case.
|
||||
const section = admissionsOf({ admissions_policy: 'Not applicable', religious_denomination });
|
||||
expect(section.queryByText('Faith priority:')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('notes the religious character of a faith school', () => {
|
||||
const section = admissionsOf({ admissions_policy: 'Non-selective', religious_denomination: 'Church of England' });
|
||||
expect(section.getByText('Faith priority:')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -157,6 +157,13 @@ describe('compareToCutoff', () => {
|
||||
});
|
||||
|
||||
describe('describeCutoffAbsence', () => {
|
||||
it('does not read "Non-selective" as selective', () => {
|
||||
// A substring test matched "selective" inside "Non-selective".
|
||||
const s = describeCutoffAbsence({ localAuthority: 'Wandsworth', admissionsPolicy: 'Non-selective' });
|
||||
expect(s).not.toMatch(/entrance test/);
|
||||
expect(s).toMatch(/^Wandsworth has not published/);
|
||||
});
|
||||
|
||||
it('explains a selective school by how it admits, not as missing data', () => {
|
||||
const s = describeCutoffAbsence({ localAuthority: 'Kent', admissionsPolicy: 'Selective' });
|
||||
expect(s).toContain('entrance test');
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* The facts the school header and the search rows print: a type in the search
|
||||
* filter's terms, and flags only for what applies.
|
||||
*/
|
||||
|
||||
import { schoolFlags, schoolTypeLabel } from '@/lib/schoolFacts';
|
||||
import type { School } from '@/lib/types';
|
||||
|
||||
const school = (over: Partial<School>): School =>
|
||||
({ urn: 1, school_name: 'Test School', ...over }) as School;
|
||||
|
||||
const labels = (over: Partial<School>) => schoolFlags(school(over)).map((f) => f.label);
|
||||
|
||||
describe('schoolTypeLabel', () => {
|
||||
it.each([
|
||||
['state', 'State school'],
|
||||
['independent', 'Independent school'],
|
||||
['special', 'Special school (SEND)'],
|
||||
['post16', 'Sixth form or college'],
|
||||
['alternative', 'Alternative provision'],
|
||||
])("names the %s group in the search filter's terms", (type_group, label) => {
|
||||
expect(schoolTypeLabel(school({ type_group, school_type: 'Academy converter' }))).toBe(label);
|
||||
});
|
||||
|
||||
it("prints the register's own name for a type in no group", () => {
|
||||
expect(schoolTypeLabel(school({ type_group: null, school_type: 'Secure units' }))).toBe('Secure units');
|
||||
});
|
||||
|
||||
it('returns null when there is no type at all', () => {
|
||||
expect(schoolTypeLabel(school({}))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('schoolFlags', () => {
|
||||
it('flags nothing for a mixed, non-faith, non-selective state school', () => {
|
||||
expect(labels({
|
||||
type_group: 'state', gender: 'Mixed', admissions_policy: 'Non-selective',
|
||||
religious_denomination: 'None', nursery_provision: 'No Nursery Classes',
|
||||
has_sixth_form: false, phase: 'Secondary',
|
||||
})).toEqual([]);
|
||||
});
|
||||
|
||||
it('lists who-can-apply flags first, then what the school offers, in a fixed order', () => {
|
||||
expect(labels({
|
||||
type_group: 'independent', admissions_policy: 'Selective', gender: 'Boys',
|
||||
religious_denomination: 'Christian', nursery_provision: 'Has Nursery Classes',
|
||||
has_sixth_form: true, phase: 'All-through',
|
||||
})).toEqual(['Fee-paying', 'Selective', "Boys' school", 'Christian', 'Nursery class', 'Sixth form']);
|
||||
});
|
||||
|
||||
it('marks who-can-apply flags as conditions and offers as provision', () => {
|
||||
const kinds = Object.fromEntries(
|
||||
schoolFlags(school({ admissions_policy: 'Selective', has_sixth_form: true, phase: 'Secondary' }))
|
||||
.map((f) => [f.label, f.kind]),
|
||||
);
|
||||
expect(kinds).toEqual({ Selective: 'condition', 'Sixth form': 'provision' });
|
||||
});
|
||||
|
||||
it('never prints Non-selective, and never a no-faith value', () => {
|
||||
expect(labels({ admissions_policy: 'Non-selective', religious_denomination: 'Does not apply' })).toEqual([]);
|
||||
expect(labels({ admissions_policy: 'Not applicable', religious_denomination: 'None' })).toEqual([]);
|
||||
// PlaceView's rule: GIAS sometimes says "Not applicable" for no faith too.
|
||||
expect(labels({ religious_denomination: 'Not applicable' })).toEqual([]);
|
||||
});
|
||||
|
||||
it('prints the religious character as the register records it', () => {
|
||||
expect(labels({ religious_denomination: 'Church of England/Methodist' })).toEqual(['Church of England/Methodist']);
|
||||
});
|
||||
|
||||
it('does not flag a nursery class on a nursery school, or a sixth form on a post-16 one', () => {
|
||||
expect(labels({ phase: 'Nursery', nursery_provision: 'Has Nursery Classes' })).toEqual([]);
|
||||
expect(labels({ phase: '16 plus', has_sixth_form: true })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
computeYBounds,
|
||||
formatAgeRange,
|
||||
formatAgeSpan,
|
||||
hasNurseryClasses,
|
||||
singleSexLabel,
|
||||
} from '@/lib/utils';
|
||||
|
||||
describe('formatPercentage', () => {
|
||||
@@ -346,3 +348,32 @@ describe('formatAgeRange', () => {
|
||||
expect(formatAgeRange('4-11')).toBe('Ages 4–11');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasNurseryClasses', () => {
|
||||
it('is true only for the GIAS value that means it', () => {
|
||||
// GIAS sends text, and two of its three values mean no nursery.
|
||||
expect(hasNurseryClasses('Has Nursery Classes')).toBe(true);
|
||||
expect(hasNurseryClasses('No Nursery Classes')).toBe(false);
|
||||
expect(hasNurseryClasses('Not applicable')).toBe(false);
|
||||
expect(hasNurseryClasses(null)).toBe(false);
|
||||
expect(hasNurseryClasses(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('singleSexLabel', () => {
|
||||
it('uses the plural possessive GIAS values need', () => {
|
||||
expect(singleSexLabel('Girls')).toBe("Girls' school");
|
||||
expect(singleSexLabel('Boys')).toBe("Boys' school");
|
||||
});
|
||||
|
||||
it('ignores case, as hasNurseryClasses does', () => {
|
||||
expect(singleSexLabel(' girls ')).toBe("Girls' school");
|
||||
expect(singleSexLabel('BOYS')).toBe("Boys' school");
|
||||
});
|
||||
|
||||
it('returns null for a mixed or unknown school', () => {
|
||||
expect(singleSexLabel('Mixed')).toBeNull();
|
||||
expect(singleSexLabel(null)).toBeNull();
|
||||
expect(singleSexLabel(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,6 @@ export function renderSchoolDetail(fixture: any) {
|
||||
withProviders(
|
||||
<SchoolDetailShell
|
||||
schoolInfo={fixture.schoolInfo}
|
||||
yearlyData={fixture.yearlyData}
|
||||
census={fixture.census}
|
||||
navItems={navItems}
|
||||
>
|
||||
@@ -67,7 +66,6 @@ export function renderSecondarySchoolDetail(fixture: any) {
|
||||
withProviders(
|
||||
<SchoolDetailShell
|
||||
schoolInfo={fixture.schoolInfo}
|
||||
yearlyData={fixture.yearlyData}
|
||||
census={fixture.census}
|
||||
navItems={navItems}
|
||||
>
|
||||
|
||||
@@ -249,7 +249,6 @@ export default async function SchoolPage({ params }: SchoolPageProps) {
|
||||
{isSecondary ? (
|
||||
<SchoolDetailShell
|
||||
schoolInfo={school_info}
|
||||
yearlyData={yearly_data}
|
||||
census={census ?? null}
|
||||
navItems={secondaryNavItems}
|
||||
>
|
||||
@@ -273,7 +272,6 @@ export default async function SchoolPage({ params }: SchoolPageProps) {
|
||||
) : (
|
||||
<SchoolDetailShell
|
||||
schoolInfo={school_info}
|
||||
yearlyData={yearly_data}
|
||||
census={census ?? null}
|
||||
navItems={primaryNavItems}
|
||||
>
|
||||
|
||||
@@ -377,31 +377,13 @@ export function FilterBar({
|
||||
updateURL({ ...cleared, [key]: value });
|
||||
};
|
||||
|
||||
// Every filter at once, keeping the search and its distance: what "Clear
|
||||
// all" means beside the applied filters, where the search is not one of them.
|
||||
// Every filter at once, keeping the search and its distance. The search is
|
||||
// what the results answer, not a filter on them: clearing it too used to
|
||||
// send desktop back to the home page.
|
||||
const handleClearFilterValues = () => {
|
||||
updateURL(Object.fromEntries(FILTER_KEYS.map((k) => [k, ""])));
|
||||
};
|
||||
|
||||
const handleClearFilters = () => {
|
||||
setOmniValue("");
|
||||
pendingQueryRef.current = "";
|
||||
startTransition(() => {
|
||||
router.push(pathname);
|
||||
});
|
||||
};
|
||||
|
||||
const hasActiveFilters =
|
||||
currentSearch ||
|
||||
currentLA ||
|
||||
currentType ||
|
||||
currentFaith ||
|
||||
currentPhase ||
|
||||
currentPostcode ||
|
||||
currentGender ||
|
||||
currentAdmissionsPolicy ||
|
||||
currentHasSixthForm;
|
||||
|
||||
/*
|
||||
* A filter's options come from the full lists, not from the results: the
|
||||
* results have already been narrowed by that filter, so scoping to them
|
||||
@@ -413,7 +395,7 @@ export function FilterBar({
|
||||
*/
|
||||
const laOptions =
|
||||
resultFilters?.local_authorities ?? filters.local_authorities;
|
||||
// Six groups a parent recognises, not GIAS's 34 establishment types.
|
||||
// Five groups a parent recognises, not GIAS's 34 establishment types.
|
||||
const typeOptions = filters.school_type_groups ?? [];
|
||||
const faithOptions = filters.faiths ?? [];
|
||||
const phaseOptions = filters.phases ?? [];
|
||||
@@ -844,14 +826,14 @@ export function FilterBar({
|
||||
/>
|
||||
</button>
|
||||
|
||||
{hasActiveFilters && (
|
||||
{appliedCount > 0 && (
|
||||
<button
|
||||
onClick={handleClearFilters}
|
||||
onClick={handleClearFilterValues}
|
||||
className={`btn btn-tertiary ${styles.clearButton}`}
|
||||
type="button"
|
||||
disabled={isPending}
|
||||
>
|
||||
Clear
|
||||
Clear all
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -358,10 +358,14 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
return () => controller.abort();
|
||||
}, [resultsView, searchParams, initialSchools.schools]);
|
||||
|
||||
// Fetch LA averages when secondary or mixed schools are visible
|
||||
// Fetch LA averages when secondary or mixed schools are visible. Default
|
||||
// cache mode, never force-cache: force-cache replays any stored response
|
||||
// without asking the server, so one failed request (a deploy restart) hid
|
||||
// every "vs LA avg" delta in that browser for good. The API's Cache-Control
|
||||
// already lets the browser reuse a good answer for five minutes.
|
||||
useEffect(() => {
|
||||
if (!isSecondaryView && !isMixedView) return;
|
||||
fetchLAaverages({ cache: 'force-cache' })
|
||||
fetchLAaverages()
|
||||
.then(data => setLaAverages(data.secondary.attainment_8_by_la))
|
||||
.catch(() => {});
|
||||
}, [isSecondaryView, isMixedView]);
|
||||
|
||||
@@ -79,7 +79,11 @@
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
|
||||
/* 44px, the MOBILE.md touch-target minimum: the 24px icon and its padding
|
||||
came to 40, and the phone filter sheet journey caught it. */
|
||||
.closeButton {
|
||||
min-width: 2.75rem;
|
||||
min-height: 2.75rem;
|
||||
padding: 0.5rem;
|
||||
background: transparent;
|
||||
border: none;
|
||||
|
||||
@@ -100,6 +100,19 @@
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* Changes who can apply or what it costs. Outlined, not tinted: a fact, not
|
||||
a verdict. An inset ring keeps the box the size of its neighbours. */
|
||||
.conditionTag {
|
||||
display: inline-block;
|
||||
padding: 0.0625rem 0.4rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
border-radius: 4px;
|
||||
box-shadow: inset 0 0 0 1px rgba(var(--ink-rgb), 0.4);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* Line 3: stats */
|
||||
.line3 {
|
||||
display: flex;
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
* Four-line row for primary school search results
|
||||
*
|
||||
* Line 1: School name · Ofsted badge (framework-aware)
|
||||
* Line 2: School type · Age range · Denomination · Gender
|
||||
* Line 2: Phase · Type · Age range · the school page's flags (lib/schoolFacts)
|
||||
* Line 3: Reading, Writing & Maths % · trend arrow · vs-national delta · Pupils
|
||||
* Line 4: Local authority · Distance
|
||||
*/
|
||||
|
||||
import type { School } from '@/lib/types';
|
||||
import { formatPercentage, calculateTrend, getPhaseStyle, schoolUrl, buildOfstedListBadge, formatAgeRange, isProposedToClose, isSpecialSchool, listRwmValue } from '@/lib/utils';
|
||||
import { schoolFlags, schoolTypeLabel } from '@/lib/schoolFacts';
|
||||
import styles from './SchoolRow.module.css';
|
||||
|
||||
interface SchoolRowProps {
|
||||
@@ -33,10 +34,8 @@ export function SchoolRow({
|
||||
const phase = getPhaseStyle(school.phase);
|
||||
const ofstedBadge = buildOfstedListBadge(school);
|
||||
|
||||
const showGender = school.gender && school.gender.toLowerCase() !== 'mixed';
|
||||
const showDenomination =
|
||||
school.religious_denomination &&
|
||||
school.religious_denomination !== 'Does not apply';
|
||||
const typeLabel = schoolTypeLabel(school);
|
||||
const flags = schoolFlags(school);
|
||||
|
||||
// The school's OWN figure and its year-over-year trend are same-school
|
||||
// measures — shown whenever there's a real value (not the all-zero
|
||||
@@ -79,10 +78,16 @@ export function SchoolRow({
|
||||
{phase.label}
|
||||
</span>
|
||||
)}
|
||||
{school.school_type && <span className={styles.attr}>{school.school_type}</span>}
|
||||
{typeLabel && <span className={styles.attr}>{typeLabel}</span>}
|
||||
{school.age_range && <span className={styles.attr}>{formatAgeRange(school.age_range)}</span>}
|
||||
{showDenomination && <span className={styles.attr}>{school.religious_denomination}</span>}
|
||||
{showGender && <span className={styles.attr}>{school.gender}</span>}
|
||||
{flags.map((flag) => (
|
||||
<span
|
||||
key={flag.label}
|
||||
className={flag.kind === 'condition' ? styles.conditionTag : styles.attr}
|
||||
>
|
||||
{flag.label}
|
||||
</span>
|
||||
))}
|
||||
{isProposedToClose(school) && (
|
||||
<span className={`${styles.attr} ${styles.attrClosing}`}>⚠ Proposed to close</span>
|
||||
)}
|
||||
|
||||
@@ -183,9 +183,17 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.selectiveTag {
|
||||
background: rgba(var(--status-below-rgb), 0.1);
|
||||
color: var(--status-below);
|
||||
/* Changes who can apply or what it costs. Outlined, not tinted: a fact, not
|
||||
a verdict. An inset ring keeps the box the size of its neighbours. */
|
||||
.conditionTag {
|
||||
display: inline-block;
|
||||
padding: 0.0625rem 0.4rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
border-radius: 4px;
|
||||
box-shadow: inset 0 0 0 1px rgba(var(--ink-rgb), 0.4);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* ── Ofsted badge ────────────────────────────────────── */
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Four-line row for secondary school search results
|
||||
*
|
||||
* Line 1: School name · Ofsted badge
|
||||
* Line 2: School type · Age range · Gender · Sixth form · Admissions tag
|
||||
* Line 2: Phase · Type · Age range · the school page's flags (lib/schoolFacts)
|
||||
* Line 3: Attainment 8 (large) · ±LA avg delta · Pupils
|
||||
* Line 4: LA name · distance
|
||||
*/
|
||||
@@ -12,21 +12,9 @@
|
||||
|
||||
import type { School } from '@/lib/types';
|
||||
import { buildOfstedListBadge, getPhaseStyle, schoolUrl, formatAgeRange, isProposedToClose, isSpecialSchool } from '@/lib/utils';
|
||||
import { schoolFlags, schoolTypeLabel } from '@/lib/schoolFacts';
|
||||
import styles from './SecondarySchoolRow.module.css';
|
||||
|
||||
function detectAdmissionsTag(school: School): string | null {
|
||||
const policy = school.admissions_policy?.toLowerCase() ?? '';
|
||||
if (policy.includes('selective')) return 'Selective';
|
||||
const denom = school.religious_denomination ?? '';
|
||||
if (denom && denom !== 'Does not apply') return 'Faith priority';
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasSixthForm(school: School): boolean {
|
||||
// GIAS OfficialSixthForm flag; missing (pipeline not yet re-run) => false.
|
||||
return school.has_sixth_form ?? false;
|
||||
}
|
||||
|
||||
interface SecondarySchoolRowProps {
|
||||
school: School;
|
||||
isLocationSearch?: boolean;
|
||||
@@ -64,9 +52,8 @@ export function SecondarySchoolRow({
|
||||
? att8 - laAvgAttainment8
|
||||
: null;
|
||||
|
||||
const admissionsTag = detectAdmissionsTag(school);
|
||||
const sixthForm = hasSixthForm(school);
|
||||
const showGender = school.gender && school.gender.toLowerCase() !== 'mixed';
|
||||
const typeLabel = schoolTypeLabel(school);
|
||||
const flags = schoolFlags(school);
|
||||
|
||||
return (
|
||||
<div className={`${styles.row} ${phase.key ? styles[`phase${phase.key}`] : ''} ${isInCompare ? styles.rowInCompare : ''}`}>
|
||||
@@ -90,19 +77,16 @@ export function SecondarySchoolRow({
|
||||
{phase.label}
|
||||
</span>
|
||||
)}
|
||||
{school.school_type && <span className={styles.attr}>{school.school_type}</span>}
|
||||
{typeLabel && <span className={styles.attr}>{typeLabel}</span>}
|
||||
{school.age_range && <span className={styles.attr}>{formatAgeRange(school.age_range)}</span>}
|
||||
{showGender && (
|
||||
<span className={styles.provisionTag}>{school.gender}</span>
|
||||
)}
|
||||
{sixthForm && (
|
||||
<span className={styles.provisionTag}>Sixth form</span>
|
||||
)}
|
||||
{admissionsTag && (
|
||||
<span className={`${styles.provisionTag} ${admissionsTag === 'Selective' ? styles.selectiveTag : ''}`}>
|
||||
{admissionsTag}
|
||||
{flags.map((flag) => (
|
||||
<span
|
||||
key={flag.label}
|
||||
className={flag.kind === 'condition' ? styles.conditionTag : styles.provisionTag}
|
||||
>
|
||||
{flag.label}
|
||||
</span>
|
||||
)}
|
||||
))}
|
||||
{isProposedToClose(school) && (
|
||||
<span className={`${styles.provisionTag} ${styles.closingTag}`}>⚠ Proposed to close</span>
|
||||
)}
|
||||
|
||||
@@ -13,7 +13,7 @@ import Link from 'next/link';
|
||||
import type { PlaceDetail, PlaceSummary } from '@/lib/places';
|
||||
import { placeUrl, authoritySlug } from '@/lib/places';
|
||||
import type { School } from '@/lib/types';
|
||||
import { schoolUrl, formatAgeSpan } from '@/lib/utils';
|
||||
import { schoolUrl, formatAgeSpan, hasNurseryClasses } from '@/lib/utils';
|
||||
import { absoluteUrl } from '@/lib/site';
|
||||
import { TrackPlaceView } from './TrackPlaceView';
|
||||
import styles from './PlaceView.module.css';
|
||||
@@ -131,9 +131,10 @@ function SchoolTable({ schools, phase }: { schools: School[]; phase: PhaseKey })
|
||||
{showNursery && (
|
||||
<td className={styles.attr}>
|
||||
{/* Undefined is a mart the pipeline has not rebuilt, and
|
||||
false is a school without one. Neither is a "Yes", and
|
||||
neither is worth two different words. */}
|
||||
{s.nursery_provision ? 'Yes' : NO_VALUE}
|
||||
"No Nursery Classes" or "Not applicable" is a school
|
||||
without one. None is a "Yes", and none is worth a
|
||||
different word. */}
|
||||
{hasNurseryClasses(s.nursery_provision) ? 'Yes' : NO_VALUE}
|
||||
</td>
|
||||
)}
|
||||
<td className={styles.attrWide}>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
.heading { font-family: var(--font-display); font-size: 1.4rem; letter-spacing: -0.4px; margin: 0; }
|
||||
.lede { margin: 0.5rem 0 1.25rem; color: var(--text-secondary); max-width: 64ch; }
|
||||
.caption { margin: 1rem 0 0; font-size: 0.72rem; color: var(--text-muted); }
|
||||
|
||||
.top { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; }
|
||||
.top { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1.25rem; }
|
||||
.arrows { display: flex; gap: 0.5rem; flex: none; }
|
||||
.arrow { width: 44px; height: 44px; display: grid; place-items: center; cursor: pointer; border: 1px solid var(--border-strong); border-radius: 999px; background: var(--bg-card); color: var(--brand); }
|
||||
.arrow:hover:not(:disabled) { border-color: var(--brand); background: var(--brand-bg); }
|
||||
@@ -15,10 +14,10 @@
|
||||
.scroller { display: grid; grid-auto-flow: column; grid-auto-columns: calc((100% - 1.8rem) / 3); gap: 0.9rem; overflow-x: auto; scroll-snap-type: x mandatory; padding: 2px; margin: -2px; list-style: none; scrollbar-width: none; -ms-overflow-style: none; }
|
||||
.scroller::-webkit-scrollbar { display: none; }
|
||||
@media (max-width: 820px) { .scroller { grid-auto-columns: calc((100% - 0.9rem) / 2); } }
|
||||
/* Touch widths (MOBILE.md): the arrows would take 96px from a 328px card and
|
||||
crush the lede into four lines, for a control swiping already provides. They
|
||||
go, and the documented right-edge fade carries the affordance — lifting at
|
||||
the end of the travel, where there is nothing more to hint at. */
|
||||
/* Touch widths (MOBILE.md): the arrows would take 96px from a 328px card, for
|
||||
a control swiping already provides. They go, and the documented right-edge
|
||||
fade carries the affordance — lifting at the end of the travel, where there
|
||||
is nothing more to hint at. */
|
||||
@media (max-width: 640px) {
|
||||
.top { display: block; }
|
||||
.arrows { display: none; }
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* The scroller and its arrows.
|
||||
*
|
||||
* `children` are the server-rendered cards and `header` the server-rendered
|
||||
* heading and lede: both stay server components, passed through, so this file
|
||||
* heading: both stay server components, passed through, so this file
|
||||
* owns a DOM ref and nothing else. That is what keeps all six links in the
|
||||
* initial HTML — a carousel that mounted cards on click would put four of the
|
||||
* six beyond a crawler and beyond a reader with no JavaScript.
|
||||
|
||||
@@ -13,8 +13,10 @@
|
||||
* reached on their behalf.
|
||||
*
|
||||
* There is deliberately no "how these are chosen" panel: the method is already
|
||||
* visible in the lede, the chips and the distances. The single caption line is
|
||||
* not a method note — it is the one thing a card cannot self-correct.
|
||||
* visible in the chips and the distances. The single caption line is not a
|
||||
* method note — it is the one thing a card cannot self-correct.
|
||||
*
|
||||
* Nor is there a lede: "Other primary schools near X" only restated the heading.
|
||||
*/
|
||||
|
||||
import Link from 'next/link';
|
||||
@@ -32,28 +34,6 @@ export function shouldRenderNearby(nearby?: NearbySchool[] | null): boolean {
|
||||
return (nearby?.length ?? 0) >= MINIMUM;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the lede calls the set of schools it is showing.
|
||||
*
|
||||
* Derived from the school's own GIAS phase rather than the template it renders
|
||||
* with, because those disagree for "16 plus" (GIAS phase 6): a sixth-form
|
||||
* college renders the primary template — computeSchoolFlags tests for the
|
||||
* substring "secondary" — while the backend correctly matches it against the
|
||||
* secondary group. Taking the noun from the template would print "Other primary
|
||||
* schools near <sixth form college>" above a row of secondaries.
|
||||
*
|
||||
* A 16-plus school's candidates span the whole secondary group, so no single
|
||||
* noun fits and it gets the honest general one.
|
||||
*/
|
||||
export function nearbyNoun(phase: string | null | undefined): string {
|
||||
const text = (phase ?? '').trim().toLowerCase();
|
||||
if (text === 'all-through') return 'all-through schools';
|
||||
if (text === '16 plus') return 'schools and colleges';
|
||||
if (text.includes('secondary')) return 'secondary schools';
|
||||
if (text.includes('primary')) return 'primary schools';
|
||||
return 'schools';
|
||||
}
|
||||
|
||||
function metricLabel(key: string): string {
|
||||
return key === 'attainment_8_score' ? 'Attainment 8' : 'Reading, writing & maths';
|
||||
}
|
||||
@@ -65,25 +45,16 @@ function formatMetric(value: number | null, key: string): string {
|
||||
|
||||
export function NearbySchoolsSection({
|
||||
urn,
|
||||
schoolName,
|
||||
phase,
|
||||
thisMetricValue,
|
||||
nearby,
|
||||
}: {
|
||||
urn: number;
|
||||
schoolName: string;
|
||||
/** The school's own GIAS phase, not the template it renders with. */
|
||||
phase: string | null | undefined;
|
||||
thisMetricValue: number | null;
|
||||
nearby?: NearbySchool[] | null;
|
||||
}) {
|
||||
if (!shouldRenderNearby(nearby)) return null;
|
||||
const schools = nearby as NearbySchool[];
|
||||
|
||||
// One card matched on phase alone, so the section may not claim the set
|
||||
// shares an intake with this school.
|
||||
const metricKey = schools[0].metric_key;
|
||||
const noun = nearbyNoun(phase);
|
||||
|
||||
return (
|
||||
<Section id="nearby">
|
||||
@@ -91,12 +62,9 @@ export function NearbySchoolsSection({
|
||||
count={schools.length}
|
||||
labelledBy="nearby-schools-heading"
|
||||
header={
|
||||
<div>
|
||||
<h2 id="nearby-schools-heading" className={styles.heading}>
|
||||
Other schools nearby
|
||||
</h2>
|
||||
<p className={styles.lede}>{`Other ${noun} near ${schoolName}.`}</p>
|
||||
</div>
|
||||
<h2 id="nearby-schools-heading" className={styles.heading}>
|
||||
Other schools nearby
|
||||
</h2>
|
||||
}
|
||||
>
|
||||
{schools.map((school) => (
|
||||
|
||||
@@ -154,8 +154,6 @@ export function PrimarySchoolSections({
|
||||
{/* Last: it is where the reader goes next, not part of this school. */}
|
||||
<NearbySchoolsSection
|
||||
urn={schoolInfo.urn}
|
||||
schoolName={schoolInfo.school_name}
|
||||
phase={schoolInfo.phase}
|
||||
thisMetricValue={flags.latestResults?.rwm_expected_pct ?? null}
|
||||
nearby={nearbySchools}
|
||||
/>
|
||||
|
||||
@@ -145,20 +145,90 @@
|
||||
}
|
||||
|
||||
|
||||
.meta {
|
||||
/* Fact line: the phase pill, then plain register values joined by dots.
|
||||
The line starts 1.125rem left of the column and clips that strip, so a
|
||||
value that wraps to the start of a line loses the dot in front of it
|
||||
instead of opening the line with one. */
|
||||
.facts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
align-items: center;
|
||||
row-gap: 0.25rem;
|
||||
margin: 0 0 0.5rem -1.125rem;
|
||||
clip-path: inset(0 0 0 1.125rem);
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
|
||||
.metaItem {
|
||||
font-size: 0.8125rem;
|
||||
.facts > * {
|
||||
margin-left: 1.125rem;
|
||||
}
|
||||
|
||||
|
||||
.fact {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
|
||||
.fact::before {
|
||||
content: "·";
|
||||
position: absolute;
|
||||
left: -0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
|
||||
/* The search rows' phase pill, in the same phase colours. */
|
||||
.phasePill {
|
||||
padding: 0.0625rem 0.4rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
border-radius: 4px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.phasePillPrimary { background: var(--phase-primary-bg); color: var(--phase-primary-text); }
|
||||
.phasePillSecondary { background: var(--phase-secondary-bg); color: var(--phase-secondary-text); }
|
||||
.phasePillAllThrough { background: var(--phase-all-through-bg); color: var(--phase-all-through-text); }
|
||||
.phasePillPost16 { background: var(--phase-post16-bg); color: var(--phase-post16-text); }
|
||||
.phasePillNursery { background: var(--phase-nursery-bg); color: var(--phase-nursery-text); }
|
||||
|
||||
|
||||
/* Flags are facts, not verdicts, so they carry no hue. Outlined changes who
|
||||
can apply or what it costs; filled is what the school offers. Text may
|
||||
wrap: the longest religious character runs past a 360px line. */
|
||||
.flags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.375rem;
|
||||
margin: 0 0 0.625rem;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
|
||||
.flagCondition,
|
||||
.flagProvision {
|
||||
padding: 0.0625rem 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
|
||||
.flagCondition {
|
||||
border-color: rgba(var(--ink-rgb), 0.4);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
|
||||
.flagProvision {
|
||||
background: rgba(var(--ink-rgb), 0.07);
|
||||
color: var(--text-secondary);
|
||||
padding: 0.125rem 0.5rem;
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
|
||||
@@ -703,17 +773,8 @@
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* Pills wrap horizontally instead of stacking — short tokens like
|
||||
"Manchester" / "Voluntary aided" fit 2 per row instead of 3 full
|
||||
rows of empty horizontal space. */
|
||||
.meta {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
/* Secondary header info (headteacher, website, pupil count, trust,
|
||||
contact, area) isn't needed above the fold on phones/tablets, so it's
|
||||
/* Secondary header info (headteacher, website, phone, trust, capacity)
|
||||
isn't needed above the fold on phones/tablets, so it's
|
||||
collapsed by default and revealed on demand via the "Show all details"
|
||||
link — reclaiming the vertical space so the metrics surface sooner. */
|
||||
.detailsToggle {
|
||||
|
||||
@@ -20,8 +20,9 @@ import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useComparison } from '@/hooks/useComparison';
|
||||
import { SchoolHeroMap, type SchoolHeroMapHandle } from '../SchoolHeroMap';
|
||||
import type { School, SchoolResult, SchoolCensus } from '@/lib/types';
|
||||
import { formatAgeRange, isProposedToClose } from '@/lib/utils';
|
||||
import type { School, SchoolCensus } from '@/lib/types';
|
||||
import { formatAgeRange, getPhaseStyle, isProposedToClose } from '@/lib/utils';
|
||||
import { schoolFlags, schoolTypeLabel } from '@/lib/schoolFacts';
|
||||
import type { NavItem } from '@/lib/schoolSections';
|
||||
import { track, getNavigationSource } from '@/lib/analytics';
|
||||
import styles from './SchoolDetailShell.module.css';
|
||||
@@ -34,8 +35,6 @@ import styles from './SchoolDetailShell.module.css';
|
||||
*/
|
||||
export interface SchoolDetailShellProps {
|
||||
schoolInfo: School;
|
||||
/** Only for the header's pupil-count fallback. */
|
||||
yearlyData: SchoolResult[];
|
||||
census: SchoolCensus | null;
|
||||
/** Section list for the sticky nav, computed on the server. */
|
||||
navItems: NavItem[];
|
||||
@@ -43,8 +42,14 @@ export interface SchoolDetailShellProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** Equal ignoring case and punctuation: "TIFFIN SCHOOL" is Tiffin School. */
|
||||
function sameName(a: string, b: string): boolean {
|
||||
const key = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
return key(a) === key(b);
|
||||
}
|
||||
|
||||
export function SchoolDetailShell({
|
||||
schoolInfo, yearlyData, census, navItems, children,
|
||||
schoolInfo, census, navItems, children,
|
||||
}: SchoolDetailShellProps) {
|
||||
const router = useRouter();
|
||||
const { addSchool, removeSchool, isSelected } = useComparison();
|
||||
@@ -63,7 +68,7 @@ export function SchoolDetailShell({
|
||||
const heroMapRef = useRef<SchoolHeroMapHandle>(null);
|
||||
// "All ▾" jump menu listing every section.
|
||||
const [sectionsOpen, setSectionsOpen] = useState(false);
|
||||
// Header details (headteacher, contact, trust, area) collapse behind a
|
||||
// Header details (headteacher, contact, trust, capacity) collapse behind a
|
||||
// "Show all details" link on mobile/tablet, where they're below the fold.
|
||||
const [detailsOpen, setDetailsOpen] = useState(false);
|
||||
|
||||
@@ -122,15 +127,34 @@ export function SchoolDetailShell({
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [sectionsOpen]);
|
||||
|
||||
// The chrome needs only these four. The section-shape flags are computed
|
||||
// The chrome needs only these few. The section-shape flags are computed
|
||||
// once on the server (lib/schoolSections) and consumed by the section
|
||||
// composers; recomputing them here would duplicate that work for values
|
||||
// this component never renders.
|
||||
const latestResults = yearlyData.length > 0 ? yearlyData[yearlyData.length - 1] : null;
|
||||
const phase = schoolInfo.phase ?? '';
|
||||
const isAllThrough = phase.toLowerCase() === 'all-through';
|
||||
const hasLocation = schoolInfo.latitude != null && schoolInfo.longitude != null;
|
||||
|
||||
// Header facts: each is one register value in a fixed slot (lib/schoolFacts).
|
||||
const phasePill = getPhaseStyle(schoolInfo.phase);
|
||||
// Never latestResults.total_pupils: that is the results cohort, which for a
|
||||
// secondary is the GCSE year group alone.
|
||||
const pupils = census?.total_pupils ?? schoolInfo.total_pupils ?? null;
|
||||
const facts = [
|
||||
formatAgeRange(schoolInfo.age_range),
|
||||
schoolTypeLabel(schoolInfo),
|
||||
pupils != null ? `${pupils.toLocaleString()} pupils` : null,
|
||||
].filter((fact): fact is string => !!fact);
|
||||
const flags = schoolFlags(schoolInfo);
|
||||
// The council, unless the address already names it.
|
||||
const council = schoolInfo.local_authority
|
||||
&& !(schoolInfo.address ?? '').toLowerCase().includes(schoolInfo.local_authority.toLowerCase())
|
||||
? schoolInfo.local_authority
|
||||
: null;
|
||||
// A single-academy trust carries the school's own name, which says nothing.
|
||||
const trust = schoolInfo.trust_name && !sameName(schoolInfo.trust_name, schoolInfo.school_name)
|
||||
? schoolInfo.trust_name
|
||||
: null;
|
||||
|
||||
const handleComparisonToggle = () => {
|
||||
if (isInComparison) {
|
||||
removeSchool(schoolInfo.urn);
|
||||
@@ -204,29 +228,31 @@ export function SchoolDetailShell({
|
||||
<div className={styles.headerContent}>
|
||||
<div className={styles.titleSection}>
|
||||
<h1 className={styles.schoolName}>{schoolInfo.school_name}</h1>
|
||||
<div className={styles.meta}>
|
||||
{schoolInfo.local_authority && (
|
||||
<span className={styles.metaItem}>{schoolInfo.local_authority}</span>
|
||||
)}
|
||||
{schoolInfo.school_type && (
|
||||
<span className={styles.metaItem}>{schoolInfo.school_type}</span>
|
||||
)}
|
||||
{isAllThrough && (
|
||||
<span className={styles.metaItem}>All-through (primary & secondary)</span>
|
||||
)}
|
||||
{schoolInfo.gender && schoolInfo.gender !== 'Mixed' && (
|
||||
<span className={styles.metaItem}>{schoolInfo.gender}'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>
|
||||
{(phasePill.label || facts.length > 0) && (
|
||||
<div className={styles.facts}>
|
||||
{phasePill.label && (
|
||||
<span className={`${styles.phasePill} ${styles[`phasePill${phasePill.key}`]}`}>
|
||||
{phasePill.label}
|
||||
</span>
|
||||
)}
|
||||
{facts.map((fact) => (
|
||||
<span key={fact} className={styles.fact}>{fact}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{flags.length > 0 && (
|
||||
// role="list": list-style: none drops list semantics in Safari.
|
||||
<ul role="list" className={styles.flags} aria-label="Admission and provision">
|
||||
{flags.map((flag) => (
|
||||
<li
|
||||
key={flag.label}
|
||||
className={flag.kind === 'condition' ? styles.flagCondition : styles.flagProvision}
|
||||
>
|
||||
{flag.label}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{isProposedToClose(schoolInfo) && (
|
||||
<div className={styles.closingStrip} role="note">
|
||||
<strong>⚠ Proposed to close.</strong> Check with the local authority before
|
||||
@@ -236,6 +262,7 @@ export function SchoolDetailShell({
|
||||
{schoolInfo.address && (
|
||||
<p className={styles.address}>
|
||||
{schoolInfo.address}{schoolInfo.postcode && `, ${schoolInfo.postcode}`}
|
||||
{council && ` · ${council}`}
|
||||
{hasLocation && (
|
||||
<>
|
||||
{' · '}
|
||||
@@ -282,21 +309,6 @@ export function SchoolDetailShell({
|
||||
</a>
|
||||
</span>
|
||||
)}
|
||||
{(() => {
|
||||
const total = census?.total_pupils ?? latestResults?.total_pupils ?? null;
|
||||
if (total == null) return null;
|
||||
return (
|
||||
<span className={styles.headerDetail}>
|
||||
<strong>Pupils:</strong> {total.toLocaleString()}
|
||||
{schoolInfo.capacity != null && ` (capacity: ${schoolInfo.capacity})`}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
{schoolInfo.trust_name && (
|
||||
<span className={styles.headerDetail}>
|
||||
Part of <strong>{schoolInfo.trust_name}</strong>
|
||||
</span>
|
||||
)}
|
||||
{schoolInfo.telephone && (
|
||||
<span className={styles.headerDetail}>
|
||||
<strong>Phone:</strong>{' '}
|
||||
@@ -305,22 +317,14 @@ export function SchoolDetailShell({
|
||||
</a>
|
||||
</span>
|
||||
)}
|
||||
{schoolInfo.religious_denomination && (
|
||||
{trust && (
|
||||
<span className={styles.headerDetail}>
|
||||
<strong>Religious character:</strong>{' '}
|
||||
{['Does not apply', 'None'].includes(schoolInfo.religious_denomination)
|
||||
? 'None'
|
||||
: schoolInfo.religious_denomination}
|
||||
<strong>Academy trust:</strong> {trust}
|
||||
</span>
|
||||
)}
|
||||
{schoolInfo.county && (
|
||||
{schoolInfo.capacity != null && (
|
||||
<span className={styles.headerDetail}>
|
||||
<strong>County:</strong> {schoolInfo.county}
|
||||
</span>
|
||||
)}
|
||||
{schoolInfo.parliamentary_constituency && (
|
||||
<span className={styles.headerDetail}>
|
||||
<strong>Constituency:</strong> {schoolInfo.parliamentary_constituency}
|
||||
<strong>Capacity:</strong> {schoolInfo.capacity.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
import type { School, SchoolAdmissions, SchoolAdmissionDistance } from '@/lib/types';
|
||||
import { formatPercentage } from '@/lib/utils';
|
||||
import { formatPercentage, hasReligiousCharacter, isSelective } from '@/lib/utils';
|
||||
import { Section, sectionStyles as styles } from './sectionShared';
|
||||
import {
|
||||
describeCutoff, describeCutoffAbsence,
|
||||
@@ -33,10 +33,8 @@ export function SecondaryAdmissionsSection({
|
||||
const featureOn = admissionDistance !== undefined;
|
||||
// Moved with this section from SecondarySchoolDetailView, its only consumer.
|
||||
const admissionsTag = (() => {
|
||||
const policy = schoolInfo.admissions_policy?.toLowerCase() ?? '';
|
||||
if (policy.includes('selective')) return 'Selective';
|
||||
const denom = schoolInfo.religious_denomination ?? '';
|
||||
if (denom && denom !== 'Does not apply') return 'Faith priority';
|
||||
if (isSelective(schoolInfo.admissions_policy)) return 'Selective';
|
||||
if (hasReligiousCharacter(schoolInfo.religious_denomination)) return 'Faith priority';
|
||||
return null;
|
||||
})();
|
||||
|
||||
|
||||
@@ -148,8 +148,6 @@ export function SecondarySchoolSections({
|
||||
{/* Last: it is where the reader goes next, not part of this school. */}
|
||||
<NearbySchoolsSection
|
||||
urn={schoolInfo.urn}
|
||||
schoolName={schoolInfo.school_name}
|
||||
phase={schoolInfo.phase}
|
||||
thisMetricValue={flags.latestResults?.attainment_8_score ?? null}
|
||||
nearby={nearbySchools}
|
||||
/>
|
||||
|
||||
@@ -54,7 +54,8 @@ export function WellbeingSection({
|
||||
</div>
|
||||
)}
|
||||
{(() => {
|
||||
const total = census?.total_pupils ?? schoolInfo.total_pupils ?? latestResults?.total_pupils ?? null;
|
||||
// Not latestResults.total_pupils: that is the GCSE year group.
|
||||
const total = census?.total_pupils ?? schoolInfo.total_pupils ?? null;
|
||||
if (total == null) return null;
|
||||
const female = census?.female_pupils ?? null;
|
||||
const male = census?.male_pupils ?? null;
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
*/
|
||||
|
||||
import type { SchoolAdmissionDistance } from '@/lib/types';
|
||||
import { formatCutoffDistance, formatMiles, formatEntryYear } from '@/lib/utils';
|
||||
import { formatCutoffDistance, formatMiles, formatEntryYear, isSelective } from '@/lib/utils';
|
||||
|
||||
export interface CutoffDisplay {
|
||||
/** Headline figure, e.g. "0.31 miles". */
|
||||
@@ -193,8 +193,7 @@ export function describeCutoffAbsence({
|
||||
admissionsPolicy,
|
||||
admissionsHistory = [],
|
||||
}: AbsenceInput): string {
|
||||
const policy = (admissionsPolicy ?? '').toLowerCase();
|
||||
if (policy.includes('selective')) {
|
||||
if (isSelective(admissionsPolicy)) {
|
||||
return 'Places at this school are ranked by the entrance test rather than by '
|
||||
+ 'distance, so no cut-off distance applies.';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The facts the school header and the search rows print, so a parent reads
|
||||
* the same words in the list and on the page.
|
||||
*
|
||||
* Every value comes from one register field. Nothing is inferred or explained
|
||||
* inline, and a missing field prints nothing.
|
||||
*/
|
||||
|
||||
import type { School } from './types';
|
||||
import { hasNurseryClasses, hasReligiousCharacter, isSelective, singleSexLabel } from './utils';
|
||||
|
||||
/** The search filter's type groups (backend/school_groups.py), without its
|
||||
* parenthesised notes: fees have a flag of their own. */
|
||||
const TYPE_GROUP_LABELS: Record<string, string> = {
|
||||
state: 'State school',
|
||||
independent: 'Independent school',
|
||||
special: 'Special school (SEND)',
|
||||
post16: 'Sixth form or college',
|
||||
alternative: 'Alternative provision',
|
||||
};
|
||||
|
||||
/** The school's type in the search filter's terms, or the register's own name
|
||||
* for a type in no group (secure units, online providers). */
|
||||
export function schoolTypeLabel(school: Pick<School, 'type_group' | 'school_type'>): string | null {
|
||||
const grouped = school.type_group ? TYPE_GROUP_LABELS[school.type_group] : undefined;
|
||||
return grouped ?? (school.school_type?.trim() || null);
|
||||
}
|
||||
|
||||
/** "condition": changes who can apply or what it costs.
|
||||
* "provision": what the school offers. */
|
||||
export type SchoolFlagKind = 'condition' | 'provision';
|
||||
|
||||
export interface SchoolFlag {
|
||||
label: string;
|
||||
kind: SchoolFlagKind;
|
||||
}
|
||||
|
||||
type FlagFields = Pick<
|
||||
School,
|
||||
'type_group' | 'admissions_policy' | 'gender' | 'religious_denomination'
|
||||
| 'nursery_provision' | 'has_sixth_form' | 'phase'
|
||||
>;
|
||||
|
||||
/**
|
||||
* Flags for what applies, in a fixed order: conditions first, then provision.
|
||||
*
|
||||
* Selective needs the exact value. The register files a partly selective
|
||||
* school as "Non-selective", so that value is never printed.
|
||||
*/
|
||||
export function schoolFlags(school: FlagFields): SchoolFlag[] {
|
||||
const flags: SchoolFlag[] = [];
|
||||
const condition = (label: string) => flags.push({ label, kind: 'condition' });
|
||||
const provision = (label: string) => flags.push({ label, kind: 'provision' });
|
||||
const phase = school.phase?.trim().toLowerCase();
|
||||
|
||||
if (school.type_group === 'independent') condition('Fee-paying');
|
||||
if (isSelective(school.admissions_policy)) condition('Selective');
|
||||
const singleSex = singleSexLabel(school.gender);
|
||||
if (singleSex) condition(singleSex);
|
||||
if (hasReligiousCharacter(school.religious_denomination)) {
|
||||
condition(school.religious_denomination!.trim());
|
||||
}
|
||||
if (hasNurseryClasses(school.nursery_provision) && phase !== 'nursery') provision('Nursery class');
|
||||
if (school.has_sixth_form && phase !== '16 plus') provision('Sixth form');
|
||||
return flags;
|
||||
}
|
||||
@@ -17,10 +17,13 @@ export interface School {
|
||||
local_authority_code: number | null;
|
||||
school_type: string | null;
|
||||
school_type_code: string | null;
|
||||
/** Search-filter type group ("state", "independent"…), null for a type in none. */
|
||||
type_group?: string | null;
|
||||
religious_denomination: string | null;
|
||||
age_range: string | null;
|
||||
has_sixth_form?: boolean | null;
|
||||
nursery_provision?: boolean | null;
|
||||
/** GIAS text; read it through hasNurseryClasses(). */
|
||||
nursery_provision?: string | null;
|
||||
status?: string | null; // GIAS establishment status ("Open" / "Open, but proposed to close")
|
||||
|
||||
// Address
|
||||
|
||||
@@ -99,6 +99,26 @@ export function formatAgeRange(ageRange: string | null | undefined): string {
|
||||
return /^\d+–\d+$/.test(span) ? `Ages ${span}` : span;
|
||||
}
|
||||
|
||||
/**
|
||||
* GIAS NurseryProvision is text: "Has Nursery Classes", "No Nursery Classes"
|
||||
* or "Not applicable". Only the first means a nursery, so never test the raw
|
||||
* value for truthiness.
|
||||
*/
|
||||
export function hasNurseryClasses(value: string | null | undefined): boolean {
|
||||
return value?.trim().toLowerCase() === 'has nursery classes';
|
||||
}
|
||||
|
||||
/**
|
||||
* "Girls' school" / "Boys' school" for a single-sex school, null otherwise.
|
||||
* GIAS genders are plural, so the possessive is a bare apostrophe.
|
||||
*/
|
||||
export function singleSexLabel(gender: string | null | undefined): string | null {
|
||||
const g = gender?.trim().toLowerCase();
|
||||
if (g === 'girls') return "Girls' school";
|
||||
if (g === 'boys') return "Boys' school";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Number Formatting
|
||||
// ============================================================================
|
||||
@@ -902,6 +922,25 @@ export function isSpecialSchool(school: { school_type?: string | null }): boolea
|
||||
return /\bspecial\b/.test(t) || /pupil referral/.test(t) || /alternative provision/.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether GIAS records a religious character. "None", "Does not apply" and
|
||||
* "Not applicable" are the register's ways of saying it has none; the place
|
||||
* table (PlaceView's NO_FAITH) reads the same three.
|
||||
*/
|
||||
export function hasReligiousCharacter(value: string | null | undefined): boolean {
|
||||
const v = value?.trim().toLowerCase() ?? '';
|
||||
return v !== '' && v !== 'none' && v !== 'does not apply' && v !== 'not applicable';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether GIAS records the school as selective. Exact: "Non-selective"
|
||||
* contains "selective", so a substring test read every comprehensive as
|
||||
* selective. (The register files a partly selective school as non-selective.)
|
||||
*/
|
||||
export function isSelective(admissionsPolicy: string | null | undefined): boolean {
|
||||
return admissionsPolicy?.trim().toLowerCase() === 'selective';
|
||||
}
|
||||
|
||||
/**
|
||||
* The school's combined Reading, Writing & Maths figure, or null when there is
|
||||
* no real one to show.
|
||||
|
||||
@@ -1,18 +1,91 @@
|
||||
-- Intermediate model: Latest Ofsted inspection per URN
|
||||
-- Picks the most recent inspection for each school
|
||||
-- Intermediate model: the current Ofsted status per URN
|
||||
-- One row per school: its latest visit (report card, graded or ungraded
|
||||
-- inspection) and the overall grade still in force, if any. A grade is dated
|
||||
-- by the inspection that awarded or confirmed it, never by a later visit.
|
||||
-- Rule and examples: docs/superpowers/specs/2026-10-05-ofsted-current-status-design.md
|
||||
|
||||
with ranked as (
|
||||
with inspections as (
|
||||
select
|
||||
*,
|
||||
-- The newest of the three inspections, read from the dates. (Report
|
||||
-- cards began in Nov 2025, after the last legacy inspections, so today
|
||||
-- a report card is always the latest; nothing below relies on that.)
|
||||
greatest(rc_inspection_date, graded_inspection_date, ungraded_inspection_date)
|
||||
as latest_visit_date
|
||||
from {{ ref('stg_ofsted_inspections') }}
|
||||
),
|
||||
|
||||
ranked as (
|
||||
select
|
||||
*,
|
||||
-- Monthly loads can leave several rows per school. The newest visit
|
||||
-- wins; the tie-breaks keep the choice deterministic.
|
||||
row_number() over (
|
||||
partition by urn
|
||||
order by inspection_date desc
|
||||
order by latest_visit_date desc,
|
||||
rc_inspection_date desc nulls last,
|
||||
graded_inspection_date desc nulls last,
|
||||
ungraded_inspection_date desc nulls last
|
||||
) as rn
|
||||
from {{ ref('stg_ofsted_inspections') }}
|
||||
from inspections
|
||||
),
|
||||
|
||||
latest as (
|
||||
select
|
||||
*,
|
||||
-- Same-day ties resolve report card, then graded, then ungraded.
|
||||
case
|
||||
when rc_inspection_date = latest_visit_date then 'report_card'
|
||||
when graded_inspection_date = latest_visit_date then 'graded'
|
||||
else 'ungraded'
|
||||
end as latest_visit_kind
|
||||
from ranked
|
||||
where rn = 1
|
||||
),
|
||||
|
||||
graded as (
|
||||
select
|
||||
*,
|
||||
-- The grade still in force. A report card replaced overall grades, so
|
||||
-- none survives it. Otherwise: a graded inspection's own overall grade
|
||||
-- (1-4; "Not judged" and the sentinel 9 are no grade); else an
|
||||
-- ungraded visit's "School remains X"; else, after an ungraded visit
|
||||
-- that names no grade, the graded inspection's grade.
|
||||
case
|
||||
when rc_inspection_date is not null
|
||||
then null
|
||||
when latest_visit_kind = 'graded' and overall_effectiveness between 1 and 4
|
||||
then 'graded_latest'
|
||||
when latest_visit_kind = 'ungraded' and ungraded_grade is not null
|
||||
then 'confirmed'
|
||||
when latest_visit_kind = 'ungraded' and overall_effectiveness between 1 and 4
|
||||
then 'graded_earlier'
|
||||
end as grade_case
|
||||
from latest
|
||||
)
|
||||
|
||||
select
|
||||
urn,
|
||||
latest_visit_date,
|
||||
latest_visit_kind,
|
||||
case when latest_visit_kind = 'ungraded' then ungraded_outcome end as latest_visit_outcome,
|
||||
case grade_case
|
||||
when 'confirmed' then ungraded_grade
|
||||
when 'graded_latest' then overall_effectiveness
|
||||
when 'graded_earlier' then overall_effectiveness
|
||||
end as current_grade,
|
||||
case grade_case
|
||||
when 'confirmed' then ungraded_inspection_date
|
||||
when 'graded_latest' then graded_inspection_date
|
||||
when 'graded_earlier' then graded_inspection_date
|
||||
end as current_grade_date,
|
||||
case grade_case
|
||||
when 'confirmed' then 'confirmed'
|
||||
when 'graded_latest' then 'graded'
|
||||
when 'graded_earlier' then 'graded'
|
||||
end as current_grade_basis,
|
||||
graded_inspection_date,
|
||||
ungraded_inspection_date,
|
||||
inspection_date,
|
||||
inspection_type,
|
||||
framework,
|
||||
@@ -36,5 +109,4 @@ select
|
||||
rc_sixth_form,
|
||||
rc_inspection_date,
|
||||
report_url
|
||||
from ranked
|
||||
where rn = 1
|
||||
from graded
|
||||
@@ -0,0 +1,113 @@
|
||||
version: 2
|
||||
|
||||
unit_tests:
|
||||
- name: graded_not_judged_has_no_grade
|
||||
description: Rabbsfarm (102408). The 2025 inspection gave no overall grade, so the 2020 "remains Good" is not carried forward (audit C1).
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 102408, graded_inspection_date: '2025-06-17', ungraded_inspection_date: '2020-02-06', overall_effectiveness: null, ungraded_grade: 2, ungraded_outcome: 'School remains Good'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 102408, latest_visit_date: '2025-06-17', latest_visit_kind: graded, latest_visit_outcome: null, current_grade: null, current_grade_date: null, current_grade_basis: null}
|
||||
|
||||
- name: graded_with_overall_grade
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 1, graded_inspection_date: '2019-06-01', overall_effectiveness: 2}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 1, latest_visit_date: '2019-06-01', latest_visit_kind: graded, current_grade: 2, current_grade_date: '2019-06-01', current_grade_basis: graded}
|
||||
|
||||
- name: ungraded_remains_good_confirms_the_grade
|
||||
description: Robins Lane (104762). Graded Good 2020, "School remains Good" July 2024 — Good, dated by the confirming visit.
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 104762, graded_inspection_date: '2020-01-07', ungraded_inspection_date: '2024-07-18', overall_effectiveness: 2, ungraded_grade: 2, ungraded_outcome: 'School remains Good'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 104762, latest_visit_date: '2024-07-18', latest_visit_kind: ungraded, latest_visit_outcome: 'School remains Good', current_grade: 2, current_grade_date: '2024-07-18', current_grade_basis: confirmed}
|
||||
|
||||
- name: post_2024_ungraded_keeps_graded_grade_with_its_own_date
|
||||
description: Washwood Heath (139888). Graded Good 2020, "Standards maintained" May 2025 — Good, dated 2020; latest visit May 2025 (audit M1).
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 139888, graded_inspection_date: '2020-03-03', ungraded_inspection_date: '2025-05-21', overall_effectiveness: 2, ungraded_grade: null, ungraded_outcome: 'Standards maintained'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 139888, latest_visit_date: '2025-05-21', latest_visit_kind: ungraded, latest_visit_outcome: 'Standards maintained', current_grade: 2, current_grade_date: '2020-03-03', current_grade_basis: graded}
|
||||
|
||||
- name: ungraded_only_standards_maintained
|
||||
description: Oakgrove (136454). Only an ungraded visit, outcome names no grade.
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 136454, ungraded_inspection_date: '2024-11-13', ungraded_grade: null, ungraded_outcome: 'Standards maintained'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 136454, latest_visit_date: '2024-11-13', latest_visit_kind: ungraded, latest_visit_outcome: 'Standards maintained', current_grade: null, current_grade_date: null, current_grade_basis: null}
|
||||
|
||||
- name: report_card_wins
|
||||
description: The Willink School (110048). A report card is the latest visit and no legacy grade stays in force.
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 110048, ungraded_inspection_date: '2023-10-05', ungraded_grade: 2, ungraded_outcome: 'School remains Good', rc_inspection_date: '2026-05-06', rc_inclusion: 3}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 110048, latest_visit_date: '2026-05-06', latest_visit_kind: report_card, latest_visit_outcome: null, current_grade: null, current_grade_date: null, current_grade_basis: null}
|
||||
|
||||
- name: duplicate_rows_newer_report_card_wins
|
||||
description: Monthly loads can leave an older row beside a newer one for the same graded date; the row with the report card must win (audit H3).
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 138186, graded_inspection_date: '2023-06-13', overall_effectiveness: 3}
|
||||
- {urn: 138186, graded_inspection_date: '2023-06-13', overall_effectiveness: 3, rc_inspection_date: '2026-06-02', rc_inclusion: 3}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 138186, latest_visit_date: '2026-06-02', latest_visit_kind: report_card, current_grade: null}
|
||||
|
||||
- name: same_day_graded_wins
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 2, graded_inspection_date: '2024-03-01', ungraded_inspection_date: '2024-03-01', overall_effectiveness: 1, ungraded_grade: 2, ungraded_outcome: 'School remains Good'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 2, latest_visit_kind: graded, current_grade: 1, current_grade_basis: graded}
|
||||
|
||||
- name: overall_sentinel_is_not_a_grade
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 3, graded_inspection_date: '2018-05-01', overall_effectiveness: 9}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 3, latest_visit_kind: graded, current_grade: null}
|
||||
|
||||
- name: newer_legacy_visit_after_a_report_card
|
||||
description: >
|
||||
Not in Ofsted's data today (0 of 2,451 report-card schools in the 31 Aug
|
||||
2026 MI), but the latest visit is read from the dates, not assumed. The
|
||||
report card still leaves no legacy grade in force.
|
||||
model: int_ofsted_latest
|
||||
given:
|
||||
- input: ref('stg_ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 4, ungraded_inspection_date: '2026-03-02', ungraded_grade: 2, ungraded_outcome: 'School remains Good', rc_inspection_date: '2025-12-01', rc_inclusion: 3}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 4, latest_visit_date: '2026-03-02', latest_visit_kind: ungraded, latest_visit_outcome: 'School remains Good', current_grade: null, current_grade_date: null, current_grade_basis: null}
|
||||
@@ -125,6 +125,30 @@ models:
|
||||
- name: inspection_date
|
||||
tests: [not_null]
|
||||
|
||||
- name: fact_ofsted_latest
|
||||
description: >
|
||||
Current Ofsted status, one row per URN: the latest visit and the overall
|
||||
grade still in force. See int_ofsted_latest for the rule.
|
||||
columns:
|
||||
- name: urn
|
||||
tests: [not_null, unique]
|
||||
- name: latest_visit_date
|
||||
tests: [not_null]
|
||||
- name: latest_visit_kind
|
||||
tests:
|
||||
- not_null
|
||||
- accepted_values:
|
||||
values: ['report_card', 'graded', 'ungraded']
|
||||
- name: current_grade
|
||||
tests:
|
||||
- accepted_values:
|
||||
values: [1, 2, 3, 4]
|
||||
quote: false
|
||||
- name: current_grade_basis
|
||||
tests:
|
||||
- accepted_values:
|
||||
values: ['graded', 'confirmed']
|
||||
|
||||
- name: fact_pupil_characteristics
|
||||
description: Pupil demographics — one row per URN per year
|
||||
columns:
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
-- Mart: current Ofsted status — one row per URN
|
||||
-- The backend reads this instead of choosing the latest row of
|
||||
-- fact_ofsted_inspection itself. The rule lives in int_ofsted_latest.
|
||||
|
||||
select
|
||||
urn,
|
||||
latest_visit_date,
|
||||
latest_visit_kind,
|
||||
latest_visit_outcome,
|
||||
current_grade,
|
||||
current_grade_date,
|
||||
current_grade_basis,
|
||||
graded_inspection_date,
|
||||
ungraded_inspection_date,
|
||||
rc_inspection_date,
|
||||
inspection_type,
|
||||
framework,
|
||||
overall_effectiveness,
|
||||
quality_of_education,
|
||||
behaviour_attitudes,
|
||||
personal_development,
|
||||
leadership_management,
|
||||
early_years_provision,
|
||||
sixth_form_provision,
|
||||
ungraded_outcome,
|
||||
ungraded_grade,
|
||||
rc_safeguarding_met,
|
||||
rc_inclusion,
|
||||
rc_curriculum_teaching,
|
||||
rc_achievement,
|
||||
rc_attendance_behaviour,
|
||||
rc_personal_development,
|
||||
rc_leadership_governance,
|
||||
rc_early_years,
|
||||
rc_sixth_form,
|
||||
report_url
|
||||
from {{ ref('int_ofsted_latest') }}
|
||||
@@ -1,5 +1,10 @@
|
||||
-- Staging model: Ofsted inspection records
|
||||
-- Handles both OEIF (pre-Nov 2025) and Report Card (post-Nov 2025) frameworks
|
||||
-- Handles both OEIF (pre-Nov 2025) and Report Card (post-Nov 2025) frameworks.
|
||||
--
|
||||
-- Ofsted's MI carries up to three inspections per school: the latest graded
|
||||
-- one, the latest ungraded one and the latest report card. Their dates stay
|
||||
-- separate here so int_ofsted_latest can tell which came last and which one a
|
||||
-- grade belongs to (docs/superpowers/specs/2026-10-05-ofsted-current-status-design.md).
|
||||
|
||||
with source as (
|
||||
select * from {{ source('raw', 'ofsted_inspections') }}
|
||||
@@ -8,17 +13,12 @@ with source as (
|
||||
renamed as (
|
||||
select
|
||||
cast(urn as integer) as urn,
|
||||
-- Inspection event date: the graded inspection when present, otherwise the
|
||||
-- ungraded (Section 8) inspection so schools with only an ungraded
|
||||
-- inspection are still retained.
|
||||
coalesce(
|
||||
to_date(nullif(trim(inspection_date), 'NULL'), 'DD/MM/YYYY'),
|
||||
to_date(nullif(trim(ungraded_inspection_date), 'NULL'), 'DD/MM/YYYY')
|
||||
) as inspection_date,
|
||||
to_date(nullif(trim(inspection_date), 'NULL'), 'DD/MM/YYYY') as graded_inspection_date,
|
||||
to_date(nullif(trim(ungraded_inspection_date), 'NULL'), 'DD/MM/YYYY') as ungraded_inspection_date,
|
||||
inspection_type,
|
||||
event_type_grouping as framework,
|
||||
|
||||
-- OEIF grades (1-4 scale)
|
||||
-- OEIF grades (1-4 scale; 9 = not applicable)
|
||||
{{ safe_numeric('overall_effectiveness') }}::integer as overall_effectiveness,
|
||||
{{ safe_numeric('quality_of_education') }}::integer as quality_of_education,
|
||||
{{ safe_numeric('behaviour_and_attitudes') }}::integer as behaviour_attitudes,
|
||||
@@ -27,9 +27,9 @@ renamed as (
|
||||
{{ safe_numeric('early_years_provision') }}::integer as early_years_provision,
|
||||
{{ safe_numeric('sixth_form_provision') }}::integer as sixth_form_provision,
|
||||
|
||||
-- Ungraded (Section 8) inspection outcome — free text, plus a grade
|
||||
-- parsed from it (1/2/null) used as a last-resort fallback for schools
|
||||
-- with no graded overall effectiveness.
|
||||
-- Ungraded (Section 8) inspection outcome — free text, plus the grade
|
||||
-- it confirms ("School remains Good" → 2); null for outcomes that
|
||||
-- name no grade.
|
||||
nullif(trim(ungraded_outcome), 'NULL') as ungraded_outcome,
|
||||
{{ parse_ungraded_outcome('ungraded_outcome') }}::integer as ungraded_grade,
|
||||
|
||||
@@ -50,31 +50,36 @@ renamed as (
|
||||
{{ parse_report_card_grade('rc_sixth_form') }}::integer as rc_sixth_form,
|
||||
|
||||
-- Start date of the latest FULL inspection (the report-card
|
||||
-- inspection in the renewed framework). Guarded in the final select:
|
||||
-- only kept when the row actually carries report-card grades, because
|
||||
-- in legacy-format files this column is the legacy inspection date.
|
||||
-- inspection in the renewed framework). Only kept when the row
|
||||
-- carries report-card grades, because in legacy-format files this
|
||||
-- column is the legacy inspection date.
|
||||
to_date(nullif(trim(rc_inspection_date), 'NULL'), 'DD/MM/YYYY') as rc_inspection_date_raw,
|
||||
|
||||
nullif(trim(report_url), 'NULL') as report_url
|
||||
from source
|
||||
where urn is not null
|
||||
and (
|
||||
nullif(trim(inspection_date), 'NULL') is not null
|
||||
or nullif(trim(ungraded_inspection_date), 'NULL') is not null
|
||||
)
|
||||
),
|
||||
|
||||
dated as (
|
||||
select
|
||||
*,
|
||||
case
|
||||
when rc_safeguarding_met is not null
|
||||
or rc_inclusion is not null
|
||||
or rc_curriculum_teaching is not null
|
||||
or rc_achievement is not null
|
||||
or rc_attendance_behaviour is not null
|
||||
or rc_personal_development is not null
|
||||
or rc_leadership_governance is not null
|
||||
then rc_inspection_date_raw
|
||||
end as rc_inspection_date
|
||||
from renamed
|
||||
)
|
||||
|
||||
select
|
||||
*,
|
||||
case
|
||||
when rc_safeguarding_met is not null
|
||||
or rc_inclusion is not null
|
||||
or rc_curriculum_teaching is not null
|
||||
or rc_achievement is not null
|
||||
or rc_attendance_behaviour is not null
|
||||
or rc_personal_development is not null
|
||||
or rc_leadership_governance is not null
|
||||
then rc_inspection_date_raw
|
||||
end as rc_inspection_date
|
||||
from renamed
|
||||
where inspection_date is not null
|
||||
-- For readers that predate the separate dates (fact_ofsted_inspection and
|
||||
-- the backend until it reads fact_ofsted_latest). Never null below.
|
||||
coalesce(graded_inspection_date, ungraded_inspection_date, rc_inspection_date) as inspection_date
|
||||
from dated
|
||||
where coalesce(graded_inspection_date, ungraded_inspection_date, rc_inspection_date) is not null
|
||||
@@ -0,0 +1,25 @@
|
||||
version: 2
|
||||
|
||||
unit_tests:
|
||||
- name: stg_ofsted_keeps_the_three_dates_apart
|
||||
description: The graded and ungraded dates must stay separate so the latest visit can be found.
|
||||
model: stg_ofsted_inspections
|
||||
given:
|
||||
- input: source('raw', 'ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 102408, inspection_date: '17/06/2025', ungraded_inspection_date: '06/02/2020', overall_effectiveness: 'Not judged', ungraded_outcome: 'School remains Good', rc_inspection_date: '17/06/2025', rc_inclusion: 'NULL'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 102408, graded_inspection_date: '2025-06-17', ungraded_inspection_date: '2020-02-06', rc_inspection_date: null, inspection_date: '2025-06-17', ungraded_grade: 2}
|
||||
|
||||
- name: stg_ofsted_keeps_report_card_only_rows
|
||||
description: A school whose only inspection is a report card used to be dropped (audit H3).
|
||||
model: stg_ofsted_inspections
|
||||
given:
|
||||
- input: source('raw', 'ofsted_inspections')
|
||||
rows:
|
||||
- {urn: 149612, inspection_date: 'NULL', ungraded_inspection_date: 'NULL', rc_inspection_date: '10/02/2026', rc_inclusion: 'Expected standard', rc_safeguarding_met: 'Met'}
|
||||
- {urn: 1, inspection_date: 'NULL', ungraded_inspection_date: 'NULL', rc_inspection_date: 'NULL'}
|
||||
expect:
|
||||
rows:
|
||||
- {urn: 149612, graded_inspection_date: null, ungraded_inspection_date: null, rc_inspection_date: '2026-02-10', inspection_date: '2026-02-10', rc_inclusion: 3}
|
||||
@@ -0,0 +1,10 @@
|
||||
-- A grade is dated by the inspection that awarded or confirmed it, never
|
||||
-- after the latest visit, and has a date and a basis exactly when it exists.
|
||||
-- A report card leaves no legacy grade in force.
|
||||
|
||||
select urn
|
||||
from {{ ref('fact_ofsted_latest') }}
|
||||
where current_grade_date > latest_visit_date
|
||||
or (current_grade is null) <> (current_grade_date is null)
|
||||
or (current_grade is null) <> (current_grade_basis is null)
|
||||
or (rc_inspection_date is not null and current_grade is not null)
|
||||
Reference in new issue
Block a user