fix: order nearby schools by distance, not by how alike they are

Reported from staging: a Catholic primary showed six Catholic primaries, none
of them close enough to be a real option, and omitted the community school
down the road.

Three causes, compounding. Ranking put tier before distance, so a faith match
at 2.9 miles outranked a community school at 0.3. The ENOUGH=3 stopping rule —
added so a cap of six would not drag in weak distant matches — filled the row
from the best tier before it ever widened, which is what made every card
Catholic. And a 3-mile tier-1 radius is sane for a secondary and most of a city
for a primary, whose catchments are routinely under a mile.

The premise was backwards. For a parent, distance is a constraint and intake is
a preference; a school beyond a primary catchment is not a weaker option, it is
not an option. So distance now decides the order and nothing else does. The
hard filters are untouched — they were always where the defensibility lived.
Similarity survives as chips on the card: reported, so a reader applies their
own weighting, rather than ranked, so we apply ours for them.

Reach is capped per phase (primary 2, secondary 6, post-16 10) as a sanity
bound, not a target: ordering already handles density, so the cap only decides
what happens where an area is sparse. A primary with nothing inside two miles
now renders no section, which is the honest answer.

Deleted: the tier system, the stopping rule, the tier-dependent lede, the
`tier` field, the tier-3 fallback chip and its style. select_similar also stops
taking is_secondary — it reads the phase from the subject's own row, so no
caller can hand it one that disagrees with the data.

The heading is now "Other schools nearby". The hard filters still guarantee a
comparable set, but nothing ranks on likeness, so the heading no longer says it
does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
TudorandClaude Opus 5 committed 2026-09-22 13:06:32 +01:00
1 parent 151cf4bc80
commit 5c0ccc693d
11 files changed
+343 -278

No files matched your search

@@ -1,8 +1,8 @@
/**
* The section's job is to be honest about what it matched. These tests pin the
* ways it could lie: rendering below the minimum, claiming a similar intake at
* tier 3, showing a missing figure as a number, or hiding a card behind an
* arrow where a crawler cannot reach it.
* The section's job is to be honest about what it is showing. These tests pin
* the ways it could mislead: rendering below the minimum, claiming a likeness
* it does not rank on, showing a missing figure as a number, or hiding a card
* behind an arrow where a crawler cannot reach it.
*/
import { render, screen } from '@testing-library/react';
@@ -34,7 +34,6 @@ function school(overrides: Partial<SimilarSchool> = {}): SimilarSchool {
school_type: 'Community school',
age_range: '4-11',
shared: ['Mixed', 'No religious character'],
tier: 1,
metric_value: 74,
metric_key: 'rwm_expected_pct',
metric_year: 202425,
@@ -74,15 +73,36 @@ describe('render gates', () => {
});
});
describe('the claim the lede makes', () => {
it('claims a similar intake when every card is tier 1 or 2', () => {
renderSection([school({ tier: 1 }), school({ urn: 100003, tier: 2 })]);
expect(screen.getByText(/with a similar intake/i)).toBeInTheDocument();
describe('what the section claims', () => {
it('never claims a similar intake, because it does not rank on one', () => {
renderSection([school(), school({ urn: 100003, shared: [] })]);
expect(screen.queryByText(/similar intake/i)).not.toBeInTheDocument();
});
it('drops the claim when any card is tier 3', () => {
renderSection([school({ tier: 1 }), school({ urn: 100003, tier: 3, shared: ['Primary school'] })]);
expect(screen.queryByText(/with a similar intake/i)).not.toBeInTheDocument();
it('is headed "Other schools nearby", not "similar"', () => {
renderSection([school(), school({ urn: 100003 })]);
expect(screen.getByRole('heading', { name: 'Other schools nearby' })).toBeInTheDocument();
});
it('shows chips for what is shared', () => {
renderSection([school({ shared: ['Mixed', 'Roman Catholic'] }), school({ urn: 100003 })]);
expect(screen.getAllByText('Roman Catholic').length).toBe(1);
});
it('shows no chips at all when nothing is shared, rather than inventing one', () => {
const { container } = render(
<SimilarSchoolsSection
urn={100001}
schoolName="Meadowbrook Primary School"
phase="Primary"
thisMetricValue={72}
similar={[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);
expect(screen.getAllByText(/miles away/).length).toBe(2);
});
});
+10 -10
View File
@@ -173,7 +173,7 @@ describe('buildSecondaryNavItems', () => {
});
});
describe('the similar-schools nav item', () => {
describe('the nearby-schools nav item', () => {
const navInput = {
ofsted: null, admissions: null, admissionDistance: null,
hasLocation: true, yearlyDataLength: 1,
@@ -182,29 +182,29 @@ describe('the similar-schools nav item', () => {
it('appears on both templates when the section renders', () => {
const primary = computeSchoolFlags(primaryFixture);
const secondary = computeSecondaryFlags(secondaryFixture);
const input = { ...navInput, hasSimilarSchools: true };
const input = { ...navInput, hasNearbySchools: true };
expect(buildNavItems(primary, input).map((i) => i.id)).toContain('similar');
expect(buildSecondaryNavItems(secondary, input).map((i) => i.id)).toContain('similar');
expect(buildNavItems(primary, input).map((i) => i.id)).toContain('nearby');
expect(buildSecondaryNavItems(secondary, input).map((i) => i.id)).toContain('nearby');
});
it('is absent when the section does not render', () => {
const primary = computeSchoolFlags(primaryFixture);
const secondary = computeSecondaryFlags(secondaryFixture);
const input = { ...navInput, hasSimilarSchools: false };
const input = { ...navInput, hasNearbySchools: false };
expect(buildNavItems(primary, input).map((i) => i.id)).not.toContain('similar');
expect(buildSecondaryNavItems(secondary, input).map((i) => i.id)).not.toContain('similar');
expect(buildNavItems(primary, input).map((i) => i.id)).not.toContain('nearby');
expect(buildSecondaryNavItems(secondary, input).map((i) => i.id)).not.toContain('nearby');
});
it('is absent when nothing says either way', () => {
const primary = computeSchoolFlags(primaryFixture);
expect(buildNavItems(primary, navInput).map((i) => i.id)).not.toContain('similar');
expect(buildNavItems(primary, navInput).map((i) => i.id)).not.toContain('nearby');
});
it('comes last, because the section renders last', () => {
const primary = computeSchoolFlags(primaryFixture);
const ids = buildNavItems(primary, { ...navInput, hasSimilarSchools: true }).map((i) => i.id);
expect(ids[ids.length - 1]).toBe('similar');
const ids = buildNavItems(primary, { ...navInput, hasNearbySchools: true }).map((i) => i.id);
expect(ids[ids.length - 1]).toBe('nearby');
});
});
@@ -189,7 +189,7 @@ export default async function SchoolPage({ params }: SchoolPageProps) {
admissions: admissions ?? null,
admissionDistance: admission_distance ?? null,
hasLocation: school_info.latitude != null && school_info.longitude != null,
hasSimilarSchools: shouldRenderSimilar(similarSchools),
hasNearbySchools: shouldRenderSimilar(similarSchools),
yearlyDataLength: yearly_data.length,
};
const primaryNavItems = buildNavItems(primaryFlags, navInput);
@@ -39,7 +39,6 @@
.shared { display: flex; flex-wrap: wrap; gap: 0.35rem; list-style: none; margin: 0 0 0.85rem; padding: 0; }
.chip { font-size: 0.72rem; line-height: 1.4; padding: 0.25rem 0.5rem; border-radius: 999px; background: var(--brand-bg); color: var(--brand); border: 1px solid transparent; }
.chipLoose { font-size: 0.72rem; line-height: 1.4; padding: 0.25rem 0.5rem; border-radius: 999px; background: transparent; color: var(--text-muted); border: 1px solid var(--border); }
.metric { margin-top: auto; padding-top: 0.8rem; border-top: 1px solid var(--border); }
/* No valence colour here, deliberately: green and terracotta mean "against the
@@ -1,12 +1,16 @@
/**
* SimilarSchoolsSection — nearby schools of the same phase and a comparable
* intake. Server component; only the carousel, the compare bar and the
* add-to-compare button are client-side.
* NearbySchoolsSection — the nearest eligible schools, closest first. Server
* component; only the carousel, the compare bar and the add-to-compare button
* are client-side.
*
* The section is allowed to say exactly what the backend matched and no more.
* The lede only claims a similar intake when no card came from tier 3, and a
* card's chips list what that school actually shares rather than a match it
* did not earn.
* "Other schools nearby", not "similar" ones: the order is distance and only
* distance. The hard filters upstream still guarantee the set is comparable —
* same phase, same selectivity, mainstream never beside special — but nothing
* here ranks by how alike two schools are, so the heading does not say it does.
*
* The chips report what a school shares, and may be absent entirely. That is
* information for the reader to weigh, not a verdict this section has already
* 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
@@ -78,25 +82,20 @@ export function SimilarSchoolsSection({
// One card matched on phase alone, so the section may not claim the set
// shares an intake with this school.
const loosest = Math.max(...schools.map((s) => s.tier));
const metricKey = schools[0].metric_key;
const noun = nearbyNoun(phase);
return (
<Section id="similar">
<Section id="nearby">
<SimilarSchoolsCarousel
count={schools.length}
labelledBy="similar-schools-heading"
labelledBy="nearby-schools-heading"
header={
<div>
<h2 id="similar-schools-heading" className={styles.heading}>
Similar schools nearby
<h2 id="nearby-schools-heading" className={styles.heading}>
Other schools nearby
</h2>
<p className={styles.lede}>
{loosest >= 3
? `Other ${noun} near ${schoolName}.`
: `Other ${noun} near ${schoolName}, with a similar intake.`}
</p>
<p className={styles.lede}>{`Other ${noun} near ${schoolName}.`}</p>
</div>
}
>
@@ -113,13 +112,13 @@ export function SimilarSchoolsSection({
.filter(Boolean)
.join(' · ')}
</p>
<ul className={styles.shared}>
{school.shared.map((label) => (
<li key={label} className={school.tier >= 3 ? styles.chipLoose : styles.chip}>
{label}
</li>
))}
</ul>
{school.shared.length > 0 && (
<ul className={styles.shared}>
{school.shared.map((label) => (
<li key={label} className={styles.chip}>{label}</li>
))}
</ul>
)}
<div className={styles.metric}>
<p
className={
+6 -6
View File
@@ -128,10 +128,10 @@ export interface NavItemsInput {
* measure a postcode, so the nav must gate on them too or it will link to an
* anchor that was never rendered. */
hasLocation?: boolean;
/** Whether the similar-schools section will render. Optional for the same
/** Whether the nearby-schools section will render. Optional for the same
* reason hasLocation is: the nav must never link to an anchor that was not
* rendered, and absent has to mean "no section". */
hasSimilarSchools?: boolean;
hasNearbySchools?: boolean;
yearlyDataLength: number;
}
@@ -148,7 +148,7 @@ export function buildNavItems(
flags: SchoolFlags,
{
ofsted, admissions, admissionDistance, hasLocation,
hasSimilarSchools, yearlyDataLength,
hasNearbySchools, yearlyDataLength,
}: NavItemsInput,
): NavItem[] {
const navItems: NavItem[] = [];
@@ -169,7 +169,7 @@ export function buildNavItems(
if (flags.hasDeprivation) navItems.push({ id: 'local-area', label: 'Local Area' });
if (flags.hasFinance) navItems.push({ id: 'finances', label: 'Finances' });
// Last, because the section renders last — the scroll-spy reads this order.
if (hasSimilarSchools) navItems.push({ id: 'similar', label: 'Similar schools' });
if (hasNearbySchools) navItems.push({ id: 'nearby', label: 'Nearby schools' });
return navItems;
}
@@ -250,7 +250,7 @@ export function buildSecondaryNavItems(
flags: SecondaryFlags,
{
ofsted, admissions, admissionDistance, hasLocation,
hasSimilarSchools, yearlyDataLength,
hasNearbySchools, yearlyDataLength,
}: NavItemsInput,
): NavItem[] {
const navItems: NavItem[] = [];
@@ -270,6 +270,6 @@ export function buildSecondaryNavItems(
if (flags.hasWellbeing) navItems.push({ id: 'wellbeing', label: 'Wellbeing' });
if (flags.hasFinance) navItems.push({ id: 'finances', label: 'Finances' });
// Last, because the section renders last — the scroll-spy reads this order.
if (hasSimilarSchools) navItems.push({ id: 'similar', label: 'Similar schools' });
if (hasNearbySchools) navItems.push({ id: 'nearby', label: 'Nearby schools' });
return navItems;
}
+6 -7
View File
@@ -347,12 +347,12 @@ export interface SchoolsResponse {
}
/**
* A nearby school of the same phase and a comparable intake.
* A nearby school, from the nearest-first set the detail page shows.
*
* `tier` is carried explicitly rather than inferred from `shared`, because it
* drives two separate decisions — whether the lede may claim a similar intake,
* and whether a chip renders as a fill or a muted outline — and inferring it
* from chip count would couple those decisions to the copy.
* `shared` is what this school genuinely has in common with the one being
* viewed, and may be empty. It is reported, never ranked on: an earlier
* version ordered by it and buried the school down the road under faith
* matches three times further away.
*/
export interface SimilarSchool {
urn: number;
@@ -361,7 +361,6 @@ export interface SimilarSchool {
school_type: string | null;
age_range: string | null;
shared: string[];
tier: number;
metric_value: number | null;
metric_key: string;
metric_year: number | null;
@@ -379,7 +378,7 @@ export interface SchoolDetailsResponse {
*/
places?: SchoolPlace[];
/**
* Up to six nearby schools of a comparable intake, nearest first.
* Up to six nearby eligible schools, nearest first.
*
* Optional for the same reason as `places`: a frontend deployed ahead of the
* API that serves this must render without it. Absent and empty mean the