ARCHIVED: This plan was not delivered. Preserved for context.
Plan: PR #524 Review Fixes — Buildings Module v2¶
Address all review comments from guilbep on PR #524 (173-task-module-buildings-v2).
Summary of Changes Required¶
| # | File | Why | How |
|---|---|---|---|
| 1 | backend/app/api/v1/carbon_report_module.py |
Archibus helpers don't belong here | Extract to own file |
| 2 | backend/app/api/v1/carbon_report_module.py |
get_archibus_rooms missing FastAPI response type |
Add response_model or -> list[...] |
| 3 | backend/app/services/data_ingestion/csv_providers/building_room_csv_provider.py |
Manual column constants duplicate what BaseCSVProvider already provides |
Use parent helpers |
| 4 | backend/app/services/data_ingestion/csv_providers/building_room_csv_provider.py |
_process_row manually maps fields one-by-one instead of using a simple dict merge |
Simplify to {**row, **room.model_dump()} |
| 5 | backend/app/utils/emission_breakdown.py |
Large structural refactor (ChartBar dataclass, BARS list) is unrelated to the buildings task and should not be in this PR |
Move to separate branch |
| 6 | frontend/src/stores/factors.ts |
Archibus room state was added to the factors store where it doesn't belong | Create dedicated useArchibusRoomStore |
| 7 | frontend/src/stores/factors.py |
Building-specific unit_id caching added to the generic factors store |
Revert to pre-PR state |
| 8 | frontend/src/composables/useEquipmentClassOptions.ts |
classOptionId/subClassOptionId fields were added to FieldConfig unnecessarily |
Roll back to original interface |
| 9 | frontend/src/components/organisms/module/ModuleInlineSelect.vue |
?? undefined added to classFieldId/subClassFieldId with no clear reason |
Revert or document the reason |
| 10 | frontend/src/components/organisms/module/ModuleForm.vue |
Dynamic options lookup uses inp.id in addition to inp.optionsId — inconsistent |
Use only optionsId |
| 11 | frontend/src/components/organisms/module/ModuleForm.vue |
Loading state check uses inp.id === kindFieldId in addition to optionsId |
Keep only optionsId check |
| 12 | frontend/src/components/organisms/module/ModuleForm.vue |
Archibus auto-fill watcher placed inline in ModuleForm.vue |
Extract to useArchibusRoomDynamicOptions.ts |
| 13 | frontend/src/components/organisms/module/ModuleForm.vue |
dynamicOptions[i.id] used in init() radio-group default — unclear why |
Investigate and remove or justify |
| 14 | frontend/src/api/factors.ts |
unit_id parameter added to getSubclassMap with no clear justification |
Investigate and remove or document |
| 15 | frontend/src/constant/module-config/buildings.ts |
room_type option values ('Office', 'Miscels', etc.) are used as factor lookup keys and must never be translated, but there is no comment warning about this |
Add a comment referencing the issue |
Detailed Changes¶
1 & 2 — Extract /archibus-rooms to its own router file¶
File: backend/app/api/v1/carbon_report_module.py
Review comments:
Line 48: "@BenBotros I'd move
_unit_institutional_idsand all related/archibus-roomsto its own file inapi/v1" Line 99: "use fastapi response type"
Why:
_unit_institutional_idsand all/archibus-roomslogic was added directly to the existingcarbon_report_modulerouter file. This mixes unrelated concerns — the module router handles data entries, while Archibus is a building-specific lookup service. Additionally, the endpoint has no return type annotation, losing FastAPI's automatic response validation and OpenAPI docs.
How:
- Create
backend/app/api/v1/archibus.pywith its ownAPIRouter. - Move
_unit_institutional_ids()helper andget_archibus_rooms()into that file. - Add a proper return type:
-> list[dict]or a typedArchibusRoomResponsePydantic model, and setresponse_model=list[ArchibusRoomResponse]on the route. - Register the new router in
backend/app/api/v1/__init__.py(or wherever routers are registered). - Remove the moved code from
carbon_report_module.py.
3 — Use BaseCSVProvider column helpers in BuildingRoomCSVProvider¶
File: backend/app/services/data_ingestion/csv_providers/building_room_csv_provider.py (lines 19–28)
Review comment:
Line 20: "@BenBotros Have a look at the base_csv_provider (that you use!) why not using
_get_expected_columns_from_handlers/_get_required_columns_from_handlerto retrieve the REQuired_columns and OPTIONAL columns?"
Why:
The three module-level constants (
BUILDING_ROOM_CSV_REQUIRED_COLUMNS,BUILDING_ROOM_CSV_OPTIONAL_COLUMNS,BUILDING_ROOM_CSV_ALL_COLUMNS) duplicate functionality that already exists inBaseCSVProvider:# Already in base_csv_provider.py def _get_expected_columns_from_handlers(handlers): # all fields from handler.create_dto def _get_required_columns_from_handler(handler): # only required fieldsKeeping custom constants means the column list can drift out of sync with the handler DTO.
How:
- Remove
BUILDING_ROOM_CSV_REQUIRED_COLUMNS,BUILDING_ROOM_CSV_OPTIONAL_COLUMNS, andBUILDING_ROOM_CSV_ALL_COLUMNSconstants. - In
_setup_and_validate(), replace the manual constants with calls to the base class helpers:expected_columns = _get_expected_columns_from_handlers([handler]) required_columns = _get_required_columns_from_handler(handler) - Pass
expected_columnsandrequired_columnsto_validate_csv_headers().
4 — Simplify _process_row row transformation¶
File: backend/app/services/data_ingestion/csv_providers/building_room_csv_provider.py (lines 271–308)
Review comment:
Line 275: "EUH @BenBotros ?
transformed_row={**row, **room.model_dump()}???"
Why:
The
_process_rowmethod manually copies each field from theArchibusRoommodel intotransformed_rowwith explicitif room.field is not Nonechecks. The reviewer suggests this is unnecessarily verbose and should simply be:transformed_row = {**row, **room.model_dump()}This merges the CSV row with all Archibus room fields at once, letting Archibus data override CSV data where both are present.
How:
- Replace the manual field-by-field construction of
transformed_row(the ~40-line block) with:transformed_row = {**row, **room.model_dump(exclude_none=True)} - Verify that
room.model_dump()keys match the handler DTO field names (they should, as theArchibusRoommodel uses the same naming). - Keep the
notefield handling if it is not part ofroom.model_dump().
5 — Move emission_breakdown.py refactor to a separate branch¶
File: backend/app/utils/emission_breakdown.py
Review comment:
Line 18: "@BenBotros keep the code! but in another branch! nothing to do in this PR"
Why:
The PR introduced a large structural refactor replacing the old dict-based
MODULE_TYPE_TO_CATEGORY/_MODULE_EMISSION_CATEGORYpattern with a newChartBardataclass andBARSlist. While this is a legitimate improvement, it is unrelated to the buildings task scope and makes the PR significantly harder to review.
How:
- Create a new branch (e.g.
refactor/emission-breakdown-chart-bars) frommain. - Cherry-pick or re-apply the
emission_breakdown.pystructural refactor onto that branch. - In this PR, revert
emission_breakdown.pyto the pre-PR version and apply only the minimal changes needed for buildings: - Add
(3, EmissionTypeEnum.energy): "Buildings energy consumption"to_MODULE_EMISSION_CATEGORY - Replace
(3, EmissionTypeEnum.grey_energy): "Buildings room"→(3, EmissionTypeEnum.combustion): "Energy combustion" - Update
MODULE_BREAKDOWN_ORDERandCATEGORY_CHART_KEYSaccordingly.
6 & 7 — Create useArchibusRoomStore and revert useFactorsStore¶
File: frontend/src/stores/factors.ts
Review comments:
Line 37: "@ create an another Store for archibusRoom," Line 59: "@BenBotros comme avant!" Line 73: "@BenBotros c'est quoi ?"
Why (line 37 — new store):
The Archibus room lookup state (buildings list, rooms list, caching by unit) was added into
useFactorsStore. Factors and Archibus rooms are completely different concerns — the factors store should only manage emission factor trees. Mixing them violates single-responsibility and makes the store harder to test.
Why (line 59 — revert):
The PR added
workspaceStore,subclassMapUnitId, and theSUBMODULE_BUILDINGS_TYPES.Building-specificrequestedUnitIdlogic into the genericensureTree()function. This makes a generic utility module-aware. The reviewer wants it reverted to the pre-PR state ("comme avant" = as it was before).
Why (line 73 — questioning getOptionsAtPath):
The
getOptionsAtPath(submodule, path)function was added as part of the refactor. The reviewer questions its necessity ("c'est quoi ?" = what is this?). If it only exists to serve the Archibus-specific dropdown path, it should live in the new dedicated store.
How:
- Revert
frontend/src/stores/factors.tsto its pre-PR state: - Restore
ensureSubclassOptionMap()function name and its originalRecord<string, Option[]>return type. - Remove
workspaceStoreimport and usage. - Remove
subclassMapUnitIdreactive state. - Remove
SUBMODULE_BUILDINGS_TYPESimport. - Remove
requestedUnitId/cachedUnitIdlogic fromensureTree/ensureSubclassOptionMap. - Remove
getOptionsAtPath()function (if it was only needed for Archibus). - Create
frontend/src/stores/archibus.tsas a new Pinia store:export const useArchibusRoomStore = defineStore("archibus", () => { // state: buildings by unitId, rooms by (unitId, buildingName) // actions: fetchBuildings(unitId), fetchRooms(unitId, buildingName) // uses src/api/archibus.ts internally // caches results keyed by unitId });
8 — Roll back useEquipmentClassOptions FieldConfig interface¶
File: frontend/src/composables/useEquipmentClassOptions.ts
Review comments:
Line 8: "Roll back comme avant?" Line 148: "@BenBotros mais non?"
Why (line 8 — roll back):
The PR added
classOptionIdandsubClassOptionIdtoFieldConfigas separate properties fromclassFieldIdandsubClassFieldId. This created a confusing split whereclassFieldIdtracks the actual entity field (used to read the value) andclassOptionIdtracks the key used to store options indynamicOptions. The reviewer asks to roll this back to the simpler original design ("comme avant" = as it was before).
Why (line 148 — "mais non?"):
Inside the
watch(submoduleType, ...)handler the code was changed from clearingdynamicOptions[classFieldId]to clearingdynamicOptions[classOptionId]. The reviewer disagrees ("mais non?" = but no?) — if options are keyed byclassFieldId, clearing by a separateclassOptionIdkey is wrong.
How:
- Remove
classOptionIdandsubClassOptionIdfromFieldConfiginterface. - Restore the
watchhandlers to clear/readdynamicOptionsusingclassFieldId/subClassFieldIddirectly (as before the PR). - Update all call sites (
ModuleForm.vue,ModuleInlineSelect.vue) to remove theclassOptionId/subClassOptionIdparams.
9 — Revert ModuleInlineSelect.vue ?? undefined change¶
File: frontend/src/components/organisms/module/ModuleInlineSelect.vue (line 79)
Review comments:
Line 79: "@BenBotros roll back comme avant?" Line 79: "peut-être que y'a une raison pour le undefined?" (maybe there's a reason for the undefined?)
Why:
The PR changed
classFieldId: kindFieldId.valuetoclassFieldId: kindFieldId.value ?? undefined. The reviewer first asks to revert ("comme avant"), then asks if there's a deliberate reason for it. The?? undefinedcoercion is a no-op whenkindFieldId.valueis alreadystring | null— passingnullvsundefinedto an optional string param is effectively the same. This change adds noise without clear intent.
How:
- Revert to
classFieldId: kindFieldId.valueandsubClassFieldId: subkindFieldId.value. - If the TypeScript types require
string | undefined(notstring | null), fix the computed return type ofkindFieldIdinstead of adding?? undefinedat every call site.
10 & 11 — Use only optionsId in ModuleForm.vue dynamic option lookup¶
File: frontend/src/components/organisms/module/ModuleForm.vue (lines 190, 415)
Review comments:
Line 415: "on garde que optionsId et on ne se base pas sur le id" (keep only
optionsId, do not base ourselves on theid) Line 190: "Keep optionsId everywhere?"
Why (line 415 — filteredOptionsMap):
The PR changed dynamic options lookup from
dynamicOptions[inp?.optionsId ?? '']todynamicOptions[inp?.id ?? ''] ?? dynamicOptions[inp?.optionsId ?? '']. Usinginp.idas a fallback creates ambiguity — if a field has nooptionsIdset, it will accidentally match options keyed by the field's rawid. The convention is thatoptionsIdis the sole key for dynamic options.
Why (line 190 — loading state):
Similarly,
:loadingwas changed to check bothinp.id === kindFieldIdandinp.optionsId === 'kind'. The reviewer asks to keepoptionsIdas the only signal — consistent with the convention above.
How:
- In
filteredOptionsMapcomputed, revert to:const dynamicOpts = dynamicOptions[inp?.optionsId ?? '']; - In the
:loadingbinding, revert to:inp.optionsId === 'kind' ? loadingClasses : inp.optionsId === 'subkind' ? loadingSubclasses : false
12 & 13 — Extract Archibus auto-fill watcher from ModuleForm.vue¶
File: frontend/src/components/organisms/module/ModuleForm.vue (lines 526–563, 605)
Review comments:
Line 533: "@BenBotros ??" (questioning the whole inline watcher block) Line 537 (two comments): "@BenBotros move in a
useArchibusRoomDynamicOptions.tsor something like that" and "put that inside a if module === building" Line 512: "@BenBotros ?" (questioningclassOptionId: kindFieldId.value ?? undefinedpassed touseEquipmentClassOptions) Line 605: "@BenBotros why ? not sure" (questioningdynamicOptions[i.id]used in radio-group init)
Why (lines 533/537 — extract to composable):
The Archibus room auto-fill watcher (watching
form['room_name']and populating kWh fields from the Archibus API) is placed inline inModuleForm.vue. This is buildings-specific logic in a generic component. The reviewer asks to move it to a dedicated composable (useArchibusRoomDynamicOptions.ts) and guard it withif module === building.
Why (line 512 — classOptionId param):
classOptionId: kindFieldId.value ?? undefinedwas added as a new param touseEquipmentClassOptions. The reviewer questions this — onceclassOptionId/subClassOptionIdare removed fromFieldConfig(Change 8), this argument disappears too.
Why (line 605 — dynamicOptions[i.id] in init()):
In the
init()function's radio-group default-value block,dynamicOptions[i.id]was added as a fallback beforei.options. The reviewer questions why — radio-group defaults should come from static config oroptionsId-keyed dynamic options, not by fieldid.
How:
- Create
frontend/src/composables/useArchibusRoomDynamicOptions.ts: - Accepts
formref,moduleType,submoduleType,unitId. - Contains the
isBuildingsRoomSubmodulecomputed. - Contains the
watch(() => form['room_name'], ...)watcher that callsgetArchibusRoomsand auto-fills fields. - Returns nothing (side-effect composable).
- In
ModuleForm.vue, import and calluseArchibusRoomDynamicOptions(form, moduleType, submoduleType, unitId)— wrapped in a guard so it only runs whenmoduleType === MODULES.Buildings. - Remove the
isBuildingsRoomSubmodulecomputed and the inline watcher fromModuleForm.vue. - In
init(), revert to using onlyi.options(notdynamicOptions[i.id]) for radio-group defaults.
14 — Investigate unit_id in getSubclassMap¶
File: frontend/src/api/factors.ts (line 14)
Review comment:
Line 14: "Find out why! doesn't make sense to me"
Why:
The
unit_idparameter was added to thegetSubclassMapAPI call and forwarded to the backend/factors/{submodule_type_id}/class-subclass-mapendpoint. For the buildings module, the class-subclass map (buildings → rooms) is unit-specific. However, the factors endpoint is generic — it is not clear whether it actually filters byunit_id, or whether this concern belongs entirely in the dedicated Archibus endpoint instead.
How:
- Check whether
GET /factors/{submodule_type_id}/class-subclass-map?unit_id=Xon the backend actually filters by unit. If not, theunit_idparam is a no-op. - If the buildings dropdown (building_name / room_name) should be sourced from the Archibus endpoint (not from the factors class-subclass map), then:
- Remove
unitIdfromgetSubclassMap. - Route buildings dropdowns through
useArchibusRoomStoreinstead. - This aligns with Copilot's separate comment that
room_nameusingoptionsId: 'subkind'(factors tree) is wrong — rooms should come from Archibus, not the factors map. - If
unit_idfiltering via factors is intentional, document it with a comment.
15 — Add comment to buildings.ts about non-translatable room_type values¶
File: frontend/src/constant/module-config/buildings.ts (line 47)
Review comment:
Line 47: "@BenBotros Add a comment linking to the issue saying that we should not translate this"
Why:
The
room_typefield's option values ('Office','Miscels','Laboratories','Archives','Libraries','Auditoriums') are the exact string keys used by the backend to look up emission factors. If these values are ever translated or changed, factor lookups will silently returnnulland no CO₂ will be calculated. The reviewer asks for an explicit warning comment with a link to the issue.
How:
// IMPORTANT: these option values are used as emission-factor lookup keys on the backend.
// They MUST NOT be translated or changed without updating the corresponding seed data.
// See: https://github.com/EPFL-ENAC/co2-calculator/issues/173
options: [
{ value: '', label: '-' },
{ value: 'Office', label: 'Office' },
...
Execution Order¶
The changes are mostly independent but the following ordering avoids conflicts:
- Step 5 (revert
emission_breakdown.py) — do first to reduce diff size and clarify scope. - Steps 1 & 2 (extract Archibus router) — backend-only, no frontend dependency.
- Steps 3 & 4 (simplify CSV provider) — backend-only.
- Step 14 (investigate
unit_id) — determines whether Steps 6/7 need adjustment before proceeding. - Steps 6 & 7 (revert
factors.ts, createarchibus.tsstore) — foundation for frontend changes. - Steps 8 & 9 (revert
useEquipmentClassOptions,ModuleInlineSelect) — depend on Step 6 being clear first. - Steps 10 & 11 (fix
ModuleForm.vueoptions lookup) — can be done alongside Step 6. - Steps 12 & 13 (extract Archibus watcher composable) — done after Steps 6/7.
- Step 15 (add comment) — trivial, do last.