Compare Years: aggregate across combined units + reword target box¶
Problem (follow-up feedback on #834)¶
Two collaborator asks before closing the issue:
- On the Results page, "Add a Unit" combines units and every
/merged/*stats endpoint respects the combined perimeter — but the Compare Years pop-up ignored it.CompareYearsDialogreceived a singleunit-idand calledGET /modules-stats/unit/{unit_id}/multi-year-report-stats, so with N units combined the dialog silently showed only the selected unit's numbers. - The target KPI box wording "Missing to reach 2040 target / 11% / target 1.3 t CO₂-eq" was unclear. Approved rewording:
- EN: "Reduction needed to reach 2040 target" / "-11%" / "2040 target: 1.3 t CO₂-eq"
- FR: "Réduction nécessaire pour atteindre l'objectif 2040" / "-11 %" / "Objectif pour 2040 : 1.3 t CO₂-eq"
Decisions¶
- Aggregation is server-side (backend is the source of truth). The
frontend sends the unit list; the backend groups every unit's report
stats by year and folds each year with the existing
merge_report_stats, thenbuild_year_comparison— the same primitives the single-unit endpoint already used for multi-project years. - The single-unit endpoint is deleted (no backward-compatibility
paths). The single-unit case is a list of one on the merged endpoint.
Its access semantics therefore shift from
require_unit_accessto the/merged/*family's allow-list check, which 404s (never 403s, to avoid the frontend's hard/unauthorizedredirect on 403). - The allow-list check is factored out of the year-scoped
_authorize_and_resolve_reportsinto_authorize_unit_ids, because the multi-year endpoint needs all years (list_by_unit), not one (get_by_unit_and_year). - No 404 when no unit has any report — the endpoint returns
{"years": []}like its predecessor; the dialog has a proper no-data state. - The minus sign on the gap percentage is presentation, hardcoded in the
template for the "missing" case only;
pctMagnitudestays a positive magnitude and the "below target" case stays unsigned. results_compare_years_gap_beaten_labelis untouched — the approved proposition only covers the "missing" case.- The
%stays glued to the number in both locales (uniform rendering); the FR-typography-11 %spacing was not adopted.
Changes¶
Backend — backend/app/api/v1/carbon_report_module_stats.py¶
- New
_authorize_unit_ids(db, current_user, unit_ids) -> list[int]: empty → 400, allow-list fromUnitService.get_user_units→ 404 for unknown units, deduped ids returned. _authorize_and_resolve_reportsnow delegates to it and keeps only the per-unitget_by_unit_and_yearloop;/merged/report-statsand/merged/results-summarybehavior unchanged.- New
GET /merged/multi-year-report-stats?unit_ids=…returning the same{"years": [...]}shape as the deletedGET /unit/{unit_id}/multi-year-report-stats.
Frontend¶
frontend/src/stores/modules.ts—getMultiYearReportStats(unitIds: number[])calls the merged endpoint with repeatedunit_idsparams (mirrorsgetMergedResultsSummary).frontend/src/components/charts/results/CompareYearsDialog.vue— propunitId→unitIds: number[]; KPI template adds the conditional minus and passesyeartoresults_compare_years_gap_target. The dialog re-fetches on every open, so changing combined units between opens is covered. Objectives need no change: year config is global andcomputeCompareYearsObjectivesbaselines on the aggregated years.frontend/src/pages/app/ResultsPage.vue—compareYearsUnitIds=mergedContext.unitIdswhen combining, else the selected report's unit.frontend/src/i18n/results.ts— rewordedresults_compare_years_gap_label,results_compare_years_gap_target(now takes{year}).frontend/scripts/openapi.snapshot.json+ generatedfrontend/src/types/api/openapi.d.tsregenerated; the snapshot was stale since #1564, so the diff also catches up on routes shipped since.
Follow-up (#2043 review): aggregate in SQL¶
The review of #1975 asked to make the endpoint generic with SQL rather than a per-unit query loop folded in Python.
CarbonReportRepository.sum_stat_buckets_by_year(unit_ids)is one grouped query overjson_each(stats->'buckets')returning(year, bucket_key, scope, total_kg);list_validated_buckets_by_yearunionsstats.validated_bucketsper year. Both use SQLAlchemy's portable JSON accessors, so the unit tests exercise them on SQLite and the same statement runs on Postgres.CarbonReportService.compare_years(unit_ids)applies the validated-only / positive-only filter and the tonnes conversion; the route only authorizes and delegates.build_year_comparisonand the route-side fold are gone.list_by_units(unit_ids, year=None)replaces the per-unitget_by_unit_and_yearloop in_authorize_and_resolve_reports, so the single-year/merged/*endpoints resolve their reports in one query too (and no longer break when a unit owns two Calculator projects in a year).- Tests moved from
tests/unit/utils/test_report_stats.pytotests/unit/services/test_compare_years.py, against the real query.