From 883dee2683d215b8ac63b9f86ca110ecff529cc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:31:22 +0100 Subject: [PATCH 1/8] feat(gasmessung): up to 8 gases, with unit and bands from the Stammdaten MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CO-Messung becomes the Gasmessung. A new Stammdaten category, Messgase, holds up to eight gases with name, unit, direction (steigend/fallend), three optional bands and a Plausibel-bis limit; a store without it yields CO 30/200/800 as before. The first Haus of an Einsatz copies the list into the incident, which keeps its own copy. Each Wohnung holds a decimal value and a Messreihe per gas. FERTIG records every changed gas and writes one ETB entry naming them all. The tile shows the worst gas, named only when the Einsatz has more than one; the tooltip and the sidebar show every gas in its own band colour, and the PDF lists a Messwerte run per Wohnung. Migration V36 adds co_gases, co_dwellings.gas_values and the gas id and decimal value on co_readings, and moves a pre-#410 file's co_value and Messreihe onto the legacy CO gas. Sync protocol 26 replaces recordCoValue with recordGasValues and carries the gas list in the snapshot and the first addCoBuilding; the floor rises to 26. Fixes #410 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- README.md | 6 +- changelog.d/+gasmessung-messgase.added.md | 1 + docs/datenschutz-und-sicherheit.md | 8 +- docs/master-data.example.json | 7 + docs/master-data.md | 36 +- src/LageBuch.App.Shared/Theme/Styles.axaml | 17 +- .../Views/CoMessprotokollView.axaml | 138 ++++++-- .../Views/IncidentWorkspaceView.axaml | 2 +- .../Views/MasterDataEditorView.axaml | 98 ++++++ src/LageBuch.AppLogic/LocalIncidentSession.cs | 9 +- .../Services/ModuleLabels.cs | 2 +- .../ViewModels/CoMessprotokollViewModel.cs | 266 +++++++++++---- src/LageBuch.AppLogic/ViewModels/GasRow.cs | 72 ++++ .../ViewModels/GasesSection.cs | 120 +++++++ .../ViewModels/IncidentWorkspaceViewModel.cs | 2 +- .../ViewModels/MasterDataEditorViewModel.cs | 31 +- .../ViewModels/NavigationSection.cs | 2 +- .../ViewModels/PdfExportOptionsViewModel.cs | 2 +- .../Sections/CoMessprotokollSection.cs | 47 ++- .../CoMeasurement/CoMeasurementLabels.cs | 39 ++- .../CoMeasurement/CoReading.cs | 12 +- .../CoMeasurement/CoSeverity.cs | 8 +- .../CoMeasurement/CoSeverityClassifier.cs | 23 -- src/LageBuch.Domain/CoMeasurement/Dwelling.cs | 73 +++- .../CoMeasurement/GasDefinition.cs | 134 ++++++++ .../CoMeasurement/GasDirection.cs | 12 + .../CoMeasurement/GasSeverityClassifier.cs | 71 ++++ src/LageBuch.Domain/CoMeasurement/GasValue.cs | 4 + .../CoMeasurement/IncidentGas.cs | 21 ++ src/LageBuch.Domain/Formatting.cs | 14 + src/LageBuch.Domain/Incident.cs | 130 ++++++-- .../IncidentRepository.cs | 90 ++++- .../MasterData/GasDefinitionJson.cs | 93 ++++++ .../MasterData/MasterDataSet.cs | 18 + .../MasterData/MasterDataStore.cs | 55 +++ src/LageBuch.Persistence/Sqlite/Migrations.cs | 73 +++- .../Sqlite/SchemaGuard.cs | 10 + src/LageBuch.Sync/CommandApplier.cs | 28 +- src/LageBuch.Sync/IIncidentSession.cs | 7 +- src/LageBuch.Sync/IncidentSnapshot.cs | 36 +- src/LageBuch.Sync/RemoteIncidentSession.cs | 12 +- src/LageBuch.Sync/SnapshotMapper.cs | 14 +- src/LageBuch.Sync/SyncCommand.cs | 17 +- src/LageBuch.Sync/SyncProtocol.cs | 12 +- .../AutomationPropertiesTests.cs | 2 +- .../CoMessprotokollCoValueInputTests.cs | 50 ++- .../CoMessprotokollEditorCancelTests.cs | 18 +- .../CoMessprotokollEditorReachabilityTests.cs | 2 +- ...MessprotokollEditorSurvivesRefreshTests.cs | 10 +- .../CoMessprotokollMessreiheTests.cs | 2 +- .../CoMessprotokollMixedBuildingTests.cs | 2 +- .../CoMessprotokollRenderTests.cs | 12 +- .../ConfigurableRailRenderTests.cs | 2 +- .../DemoFlowRenderTests.cs | 4 +- .../GasmessungRenderTests.cs | 157 +++++++++ .../HeaderSearchAndActionPlacementTests.cs | 6 +- .../LageBuch.Acceptance.Tests.csproj | 5 + .../LayoutAlignmentTests.cs | 2 +- .../MasterDataEditorRenderTests.cs | 8 +- .../NavRailHelperTests.cs | 4 +- .../OverlayContractTests.cs | 8 +- .../OverlayKeyboardTests.cs | 6 +- .../PhoneLayoutTests.cs | 2 +- .../ReadingOrderTabTests.cs | 2 +- .../WorkspaceRenderHelper.cs | 5 +- .../CoApartmentRemovalViewModelTests.cs | 2 +- .../CoMessprotokollViewModelTests.cs | 85 ++--- .../EtbViewModelTests.cs | 2 +- .../GasesSectionTests.cs | 115 +++++++ .../GasmessungViewModelTests.cs | 205 ++++++++++++ .../LageBuch.AppLogic.Tests.csproj | 5 + .../MasterDataChecklistEditingTests.cs | 2 +- .../MasterDataEditorViewModelTests.cs | 2 +- .../MasterDataRailGroupingTests.cs | 4 +- .../WorkspaceShortcutTests.cs | 2 +- .../CoMessprotokollSectionTests.cs | 18 +- .../GasmessprotokollSectionTests.cs | 81 +++++ .../IncidentPdfTests.cs | 2 +- .../LageBuch.Documents.Tests.csproj | 4 + .../CoBuildingLabelsAtCreationTests.cs | 2 +- .../CoDwellingRemovalTests.cs | 6 +- .../CoFloorRemovalTests.cs | 2 +- .../CoMeasurementTests.cs | 48 +-- .../GasMeasurementTests.cs | 315 ++++++++++++++++++ .../LageBuch.Domain.Tests.csproj | 4 + .../CoMeasurementPersistenceTests.cs | 87 ++++- .../DemoIncidentTests.cs | 6 +- .../LageBuch.Persistence.Tests.csproj | 4 + .../MasterDataGasesTests.cs | 146 ++++++++ .../LageBuch.Sync.Hosting.Tests.csproj | 5 + .../CommandApplierTests.cs | 12 +- tests/LageBuch.Sync.Tests/GasSyncTests.cs | 189 +++++++++++ .../LageBuch.Sync.Tests.csproj | 5 + .../SnapshotRoundTripTests.cs | 6 +- .../VersionHandshakeTests.cs | 13 +- tests/Shared/CoOnlyIncidentExtensions.cs | 20 ++ tests/Shared/CoOnlySessionExtensions.cs | 11 + 97 files changed, 3171 insertions(+), 420 deletions(-) create mode 100644 changelog.d/+gasmessung-messgase.added.md create mode 100644 src/LageBuch.AppLogic/ViewModels/GasRow.cs create mode 100644 src/LageBuch.AppLogic/ViewModels/GasesSection.cs delete mode 100644 src/LageBuch.Domain/CoMeasurement/CoSeverityClassifier.cs create mode 100644 src/LageBuch.Domain/CoMeasurement/GasDefinition.cs create mode 100644 src/LageBuch.Domain/CoMeasurement/GasDirection.cs create mode 100644 src/LageBuch.Domain/CoMeasurement/GasSeverityClassifier.cs create mode 100644 src/LageBuch.Domain/CoMeasurement/GasValue.cs create mode 100644 src/LageBuch.Domain/CoMeasurement/IncidentGas.cs create mode 100644 src/LageBuch.Persistence/MasterData/GasDefinitionJson.cs create mode 100644 tests/LageBuch.Acceptance.Tests/GasmessungRenderTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/GasesSectionTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/GasmessungViewModelTests.cs create mode 100644 tests/LageBuch.Documents.Tests/GasmessprotokollSectionTests.cs create mode 100644 tests/LageBuch.Domain.Tests/GasMeasurementTests.cs create mode 100644 tests/LageBuch.Persistence.Tests/MasterDataGasesTests.cs create mode 100644 tests/LageBuch.Sync.Tests/GasSyncTests.cs create mode 100644 tests/Shared/CoOnlyIncidentExtensions.cs create mode 100644 tests/Shared/CoOnlySessionExtensions.cs diff --git a/README.md b/README.md index 29b21aff..c6cfb694 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Lagebuch ist das digitale Einsatztagebuch für den Einsatzleitwagen: eine Desktop-Anwendung, die auch ohne Netz, ohne Cloud und ohne Abo funktioniert. Ein Einsatz ist eine Datei auf dem ELW-Laptop – mit Einsatztagebuch, Kräften, -Atemschutzüberwachung, Aufgaben, CO-Messprotokoll und PDF-Bericht. +Atemschutzüberwachung, Aufgaben, Gasmessprotokoll und PDF-Bericht. **Alles auf einer Seite:** [codeforfire.github.io](https://codeforfire.github.io/) – Übersicht, Probefahrt, Download und Datenschutz, ohne GitHub-Konto und ohne @@ -70,7 +70,7 @@ Markdown. | **Ausgabeliste** | Ausgegebene Geräte (Mobilteil, Westen, AED …) aus den Stammdaten: an wen, Telefon, Organisation, mit Uhrzeit; Rückgabe mit einem Klick – was noch draußen ist, steht oben, und „Einsatz abschließen“ warnt davor; im PDF, ohne ETB-Eintrag | | **Atemschutzüberwachung** | Trupps mit Einstiegsdruck, Einsatzzeit-Countdown, Druckabfrage-Intervall, Rückzugsdruck und Rückzugsalarm – mit Sprachansage und Sirene; Sicherheitstrupp je Trupp zugeordnet und im ETB protokolliert | | **Rückmeldung an ILS** | Erinnerung nach konfigurierbarer Zeit, danach im Intervall, mit ERLEDIGT-Quittierung; überlebt Neustart und Absturz | -| **CO-Messprotokoll** | Haus, Stockwerk, Wohnung: Status (offen / durchsucht / betroffen), Messreihe je Wohnung mit Uhrzeit und ppm-Wert in Gefahrenfarbe, Bewohnername, Schlüssel vorhanden – wie die Türmarkierung vor Ort; der Verlauf steht im ETB und im PDF | +| **Gasmessprotokoll** | Haus, Stockwerk, Wohnung: Status (offen / durchsucht / betroffen), bis zu acht Gase aus den Stammdaten (CO, CO₂, H₂S, CH₄, O₂ …) mit eigener Einheit und eigenen Grenzwerten, Messreihe je Wohnung mit Uhrzeit und Wert in Gefahrenfarbe – die Kachel zeigt das schlimmste Gas, Bewohnername, Schlüssel vorhanden – wie die Türmarkierung vor Ort; der Verlauf steht im ETB und im PDF | | **Checklisten** | Beliebig viele eigene Checklisten aus den Stammdaten – benannt, in frei wählbarer Reihenfolge in der Seitenleiste, Pflichtpunkte markiert, Abschluss im ETB protokolliert | | **Dateien & Links** | Fotos und PDFs an den Einsatz hängen (landen im Bericht); Schnellzugriff auf Wetter, Karten, Hydrantenplan | | **PDF-Bericht** | Ein Klick, Abschnitte wählbar, Anhänge eingebettet – fertig für Akte und Kreisbrandinspektion | @@ -126,7 +126,7 @@ Alle Beispieldaten sind frei erfunden. ([Direktlink](https://github.com/CodeForFire/lagebuch/raw/main/docs/samples/uebung.lagebuch)), in Lagebuch **ÖFFNEN** wählen. Der Einsatz „B 3 – Zimmerbrand“ hat schon ETB-Einträge, vier Fahrzeuge, einen Angriffstrupp unter Atemschutz mit - zugeordnetem Sicherheitstrupp, Aufgaben und ein CO-Messprotokoll, in dem + zugeordnetem Sicherheitstrupp, Aufgaben und ein Gasmessprotokoll, in dem eine Wohnung schon dreimal gemessen wurde. Über **WEITER BEARBEITEN** könnt ihr selbst eingreifen. 4. **Ausprobieren** – einen ETB-Eintrag schreiben, im Tab **ATEMSCHUTZ** einen Trupp bereitstellen, einen Sicherheitstrupp zuordnen und starten, eine diff --git a/changelog.d/+gasmessung-messgase.added.md b/changelog.d/+gasmessung-messgase.added.md new file mode 100644 index 00000000..98276072 --- /dev/null +++ b/changelog.d/+gasmessung-messgase.added.md @@ -0,0 +1 @@ +Gasmessung: the former CO-Messung records up to eight gases per Wohnung, each with its own unit and bands taken from a new Messgase list in the Stammdaten and copied into the Einsatz, so CO₂, H₂S, CH₄ and a falling O₂ reach the matrix, the ETB and the PDF, the tile shows the worst gas, and an Einsatz without Messgase keeps measuring CO exactly as before (#410). diff --git a/docs/datenschutz-und-sicherheit.md b/docs/datenschutz-und-sicherheit.md index adb47544..16a3a4a1 100644 --- a/docs/datenschutz-und-sicherheit.md +++ b/docs/datenschutz-und-sicherheit.md @@ -43,7 +43,7 @@ einzelne Datei gespeichert wird. | Einsatztagebuch (ETB) | Freitext bis 4000 Zeichen, Von/An, Richtung, „erfasst von“ | Einsatzdatei | | ETB-Korrekturen | **jede überschriebene Fassung bleibt erhalten**, mit Zeitpunkt und Bearbeiter | Einsatzdatei | | Einsatzdaten | Stichwort, Einsatznummer, **Straße und Ortsteil**, „abgeschlossen von“ | Einsatzdatei | -| CO-Messprotokoll | **Name der Bewohnerin oder des Bewohners je Wohnung**, ppm-Wert, Status, Schlüssel vorhanden | Einsatzdatei | +| Gasmessprotokoll | **Name der Bewohnerin oder des Bewohners je Wohnung**, Messwerte der Gase, Status, Schlüssel vorhanden | Einsatzdatei | | Kräfte | Wache, Funkrufname, Stärke als Zahlen (ZF/GF/Mann, AGT), Status, Bemerkung – **keine Namen** | Einsatzdatei | | Aufgaben | Auftrag, Zuständiger (Freitext), „angelegt von“, „erledigt von“, Zeiten | Einsatzdatei | | Beteiligte | **Name, Telefonnummer, Notiz und Aufenthaltsort** (z. B. „im RTW …“, mit Uhrzeit) von Personen außerhalb der Feuerwehr (z. B. Eigentümer, Fahrzeughalter, Polizei), die Wohnung, in der sie angetroffen wurden, „angelegt von“ | Einsatzdatei | @@ -54,7 +54,7 @@ einzelne Datei gespeichert wird. Drei Punkte verdienen besondere Aufmerksamkeit: -**Das CO-Messprotokoll enthält Daten Dritter.** Erfasst werden hier Namen von +**Das Gasmessprotokoll enthält Daten Dritter.** Erfasst werden hier Namen von Personen, die nicht der Feuerwehr angehören und die der Erfassung nicht zugestimmt haben. Die Verarbeitung erfolgt zur Einsatzdurchführung, und genau dieser Teil der Einsatzdatei sollte bei der Festlegung von Löschfristen zuerst @@ -67,7 +67,7 @@ oder die Ansprechperson der Polizei werden mit Name, Telefonnummer und Notiz erfasst. Diese Angaben stehen bewusst nur in dieser Liste und im PDF-Bericht – das ETB erhält beim Anlegen, Ändern oder Entfernen keinen Eintrag. Ein entfernter Eintrag ist damit aus der Einsatzdatei verschwunden; für -Löschfristen gilt dasselbe wie für das CO-Messprotokoll. Für die Ausgabeliste +Löschfristen gilt dasselbe wie für das Gasmessprotokoll. Für die Ausgabeliste gilt dasselbe: Wer ein Gerät erhalten hat – etwa die Presse oder eine Nachbarwehr –, steht mit Name und Telefonnummer nur dort und im PDF-Bericht, nicht im ETB. @@ -268,7 +268,7 @@ vollständigen Stand des Einsatzes: Einsatzdaten, das gesamte ETB einschließlic der aufbewahrten Korrekturfassungen, Funktionen **mit Namen und Telefonnummern**, Kräfte, Atemschutztrupps mit den Namen der Truppmitglieder, Aufgaben, Beteiligte **mit Namen und Telefonnummern**, die Ausgabeliste -**mit Namen und Telefonnummern**, CO-Messprotokoll, Änderungsprotokoll und die +**mit Namen und Telefonnummern**, Gasmessprotokoll, Änderungsprotokoll und die Liste der Anhänge. Anhänge selbst werden nur auf Anforderung übertragen (höchstens 25 MB je Datei). diff --git a/docs/master-data.example.json b/docs/master-data.example.json index 9ab07610..71aea2d0 100644 --- a/docs/master-data.example.json +++ b/docs/master-data.example.json @@ -120,6 +120,13 @@ }, { "name": "Haus A", "street": "Hauptstraße", "houseNumber": "5", "postalCode": "12345", "place": "Musterstadt", "floors": 3, "apartmentsPerFloor": 2, "undergroundFloors": 0, "apartmentLabels": {} } ], + "gases": [ + { "name": "CO", "unit": "ppm", "direction": "steigend", "elevated": 30, "dangerous": 200, "lethal": 800, "plausibleUpTo": 2000 }, + { "name": "CO2", "unit": "Vol-%", "direction": "steigend", "elevated": 0.5, "dangerous": 4, "lethal": 8, "plausibleUpTo": 20 }, + { "name": "H2S", "unit": "ppm", "direction": "steigend", "elevated": 5, "dangerous": 10, "lethal": 100, "plausibleUpTo": 500 }, + { "name": "CH4", "unit": "%UEG", "direction": "steigend", "elevated": 10, "dangerous": 20, "lethal": 40, "plausibleUpTo": 100 }, + { "name": "O2", "unit": "Vol-%", "direction": "fallend", "elevated": 19, "dangerous": 17, "lethal": 10, "plausibleUpTo": 25 } + ], "settings": { "ilsReminderIntervalMinutes": 15, "ilsReminderFollowUpIntervalMinutes": 30, diff --git a/docs/master-data.md b/docs/master-data.md index 2adf5c2b..1aeaea1d 100644 --- a/docs/master-data.md +++ b/docs/master-data.md @@ -65,7 +65,7 @@ is plain text in the entry: changing a Textbaustein later changes no entry. Ausrückebereich whose structure is known long before the call, such as a recurring Wohnanlage. Each Objekt has a `name`, an optional address (`street`, `houseNumber`, `postalCode`, `place`) and the structure a Haus in the -CO-Messprotokoll starts with: +Gasmessprotokoll starts with: | Field | JSON | Range | Missing reads as | |---|---|---|---| @@ -81,17 +81,47 @@ gives it (`Links`/`Mitte`/`Rechts` on a floor of three, `Whg. N` otherwise). A label is cut to 60 characters, and a key that names no floor or Wohnung of the Objekt is dropped. -Typing in **BEZEICHNUNG** in the CO-Messprotokoll's **HAUS HINZUFÜGEN** dialog +Typing in **BEZEICHNUNG** in the Gasmessprotokoll's **HAUS HINZUFÜGEN** dialog suggests the Objekte. Picking one fills Geschosse, Wohnungen/Geschoss and Untergeschosse, unless one of them was already changed by hand, and the Haus is created with the Objekt's Wohnungsbezeichnungen. These values are **copied** into the Einsatz. Editing or deleting the Objekt later changes no Haus already in an Einsatzdatei. A name that matches no Objekt adds a Haus exactly as before. -The address is not copied, because a Haus in the CO-Messprotokoll has none. It +The address is not copied, because a Haus in the Gasmessprotokoll has none. It tells two Objekte apart in the list. Out-of-range numbers are clamped, rows without a name are skipped, a second Objekt of the same name (ignoring case) is dropped, and a list holds at most 500 Objekte. + +## Messgase + +`gases` is the list **Messgase**: the gases a crew reads off its multi-gas meter +in the **Gasmessung**, at most eight, in the order every Einsatz shows them. + +| Field | JSON | Meaning | +|---|---|---| +| Gas | `name` | the label on the tile, in the editor, the ETB and the PDF; at most 12 characters | +| Einheit | `unit` | free text, e.g. `ppm`, `%UEG`, `Vol-%`, `mg/m³`; at most 10 characters | +| Richtung | `direction` | `"steigend"` (higher is worse) or `"fallend"` (lower is worse, for O₂); anything else reads as steigend | +| Erhöht / Gefährlich / Lebensgefährlich | `elevated` / `dangerous` / `lethal` | the bands, each optional, ordered in the gas's direction | +| Plausibel bis | `plausibleUpTo` | optional; a reading above it gets the "bitte auf Tippfehler prüfen" hint and is still recorded | + +Numbers may carry decimals (`20.9` in the file, `20,9` on screen). A gas without +any band is recorded and shown without colour. A Stammdaten file without `gases`, +or with an empty list, measures exactly what the app always did: `CO` in `ppm`, +steigend, 30 / 200 / 800, plausible up to 2000. + +The import rejects a file whose bands are out of order for their gas, because +guessing which of them was meant would colour a Wohnung wrongly; a band that is +not a number, negative or above 100 000 rejects it too. More than eight gases are +cut at eight, an overlong name or unit is cut, and a second gas of the same name +(ignoring case) is dropped. The editor names the same problems and does not save +until they are fixed. + +The list is **copied** into an Einsatz when the Gasmessung opens its first Haus. +From then on the Einsatz keeps its own copy: editing the Messgase later changes +no Einsatzdatei, and a joined device shows the host's list. + ## Funkgruppen and the Führungstafel slot of a Funktion `talkGroups` lists the Funkgruppen a Führungsstelle works on: each has a `name`, an diff --git a/src/LageBuch.App.Shared/Theme/Styles.axaml b/src/LageBuch.App.Shared/Theme/Styles.axaml index 54c4a7d4..a253b6a9 100644 --- a/src/LageBuch.App.Shared/Theme/Styles.axaml +++ b/src/LageBuch.App.Shared/Theme/Styles.axaml @@ -2,7 +2,8 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:b="clr-namespace:LageBuch.App.Shared.Behaviors" xmlns:ctrl="clr-namespace:LageBuch.App.Shared.Controls" - xmlns:vm="clr-namespace:LageBuch.AppLogic.ViewModels;assembly=LageBuch.AppLogic"> + xmlns:vm="clr-namespace:LageBuch.AppLogic.ViewModels;assembly=LageBuch.AppLogic" + xmlns:domain="clr-namespace:LageBuch.Domain;assembly=LageBuch.Domain"> @@ -676,8 +677,8 @@ Any, no FormatString) a typed "3.5" is kept as 3.5 by the control and displayed as such, while the int-typed view-model property rounds it to 4: the number on screen is not the number written into the Einsatz record. Integer parsing refuses the fraction outright, and - FormatString pins the display to whole numbers. A future input that genuinely needs decimals - can override both locally. --> + FormatString pins the display to whole numbers. An input that genuinely needs decimals takes + the decimal class below. --> + + + + + + - + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + + + + + + + + + + + + + + + + diff --git a/src/LageBuch.App.Shared/Views/MasterDataEditorView.axaml b/src/LageBuch.App.Shared/Views/MasterDataEditorView.axaml index 50cfa77d..a2bc47ce 100644 --- a/src/LageBuch.App.Shared/Views/MasterDataEditorView.axaml +++ b/src/LageBuch.App.Shared/Views/MasterDataEditorView.axaml @@ -208,6 +208,14 @@ + + + + + + + + + + + + diff --git a/src/LageBuch.AppLogic/LocalIncidentSession.cs b/src/LageBuch.AppLogic/LocalIncidentSession.cs index 836f212e..10bd6ddc 100644 --- a/src/LageBuch.AppLogic/LocalIncidentSession.cs +++ b/src/LageBuch.AppLogic/LocalIncidentSession.cs @@ -497,8 +497,9 @@ public void AddCoBuilding( int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0, - IReadOnlyDictionary? apartmentLabels = null) => - Mutate(() => Incident.AddCoBuilding(_clock, RequireOperator(), name, floorCount, apartmentsPerFloor, undergroundFloorCount, apartmentLabels)); + IReadOnlyDictionary? apartmentLabels = null, + IReadOnlyList? gases = null) => + Mutate(() => Incident.AddCoBuilding(_clock, RequireOperator(), name, floorCount, apartmentsPerFloor, undergroundFloorCount, apartmentLabels, gases)); public void UpdateCoBuildingStructure(Guid buildingId, int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0) => Mutate(() => Incident.UpdateCoBuildingStructure(_clock, RequireOperator(), buildingId, floorCount, apartmentsPerFloor, undergroundFloorCount)); @@ -506,8 +507,8 @@ public void UpdateCoBuildingStructure(Guid buildingId, int floorCount, int apart public void RemoveCoBuilding(Guid buildingId) => Mutate(() => Incident.RemoveCoBuilding(_clock, RequireOperator(), buildingId)); - public void RecordCoValue(Guid buildingId, int floorOrdinal, int apartmentNumber, int? coValue) => - Mutate(() => Incident.RecordCoValue(_clock, RequireOperator(), buildingId, floorOrdinal, apartmentNumber, coValue)); + public void RecordCoValues(Guid buildingId, int floorOrdinal, int apartmentNumber, IReadOnlyDictionary values) => + Mutate(() => Incident.RecordCoValues(_clock, RequireOperator(), buildingId, floorOrdinal, apartmentNumber, values)); public void SetDwellingStatus(Guid buildingId, int floorOrdinal, int apartmentNumber, DwellingStatus status) => Mutate(() => Incident.SetDwellingStatus(_clock, RequireOperator(), buildingId, floorOrdinal, apartmentNumber, status)); diff --git a/src/LageBuch.AppLogic/Services/ModuleLabels.cs b/src/LageBuch.AppLogic/Services/ModuleLabels.cs index 8251f27b..9a178770 100644 --- a/src/LageBuch.AppLogic/Services/ModuleLabels.cs +++ b/src/LageBuch.AppLogic/Services/ModuleLabels.cs @@ -18,7 +18,7 @@ public static class ModuleLabels [NavModules.InvolvedParties] = "BETEILIGTE", [NavModules.IssuedItems] = "AUSGABE", [NavModules.Scba] = "ATEMSCHUTZ", - [NavModules.Co] = "CO-MESSUNG", + [NavModules.Co] = "GASMESSUNG", [NavModules.Files] = "DATEIEN", [NavModules.Links] = "LINKS", [NavModules.Contacts] = "KONTAKTE", diff --git a/src/LageBuch.AppLogic/ViewModels/CoMessprotokollViewModel.cs b/src/LageBuch.AppLogic/ViewModels/CoMessprotokollViewModel.cs index 6b9b477a..23bee13d 100644 --- a/src/LageBuch.AppLogic/ViewModels/CoMessprotokollViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/CoMessprotokollViewModel.cs @@ -28,14 +28,18 @@ public sealed partial class DwellingCellViewModel : ObservableObject { private readonly Action _onOpenEditor; + private readonly IReadOnlyList _gases; + public DwellingCellViewModel( Dwelling dwelling, Building building, bool isReadOnly, - Action onOpenEditor) + Action onOpenEditor, + IReadOnlyList? gases = null) { ArgumentNullException.ThrowIfNull(dwelling); ArgumentNullException.ThrowIfNull(building); + _gases = gases ?? []; Id = dwelling.Id; BuildingId = dwelling.BuildingId; FloorOrdinal = dwelling.FloorOrdinal; @@ -43,7 +47,7 @@ public DwellingCellViewModel( IsReadOnly = isReadOnly; _onOpenEditor = onOpenEditor; _status = dwelling.Status; - _coValue = dwelling.CoValue; + _values = dwelling.Values; _residentName = dwelling.ResidentName; _keyAvailable = dwelling.KeyAvailable; _keyNumber = dwelling.KeyNumber; @@ -65,8 +69,9 @@ public DwellingCellViewModel( [ObservableProperty] private DwellingStatus _status; + /// The current value of each gas (#410), keyed by the Einsatz's own gas id. [ObservableProperty] - private int? _coValue; + private IReadOnlyDictionary _values; [ObservableProperty] private string? _residentName; @@ -96,32 +101,54 @@ public DwellingCellViewModel( /// carries a line above. public string CoSeriesText => Readings.Count < 2 ? string.Empty - : "Messreihe: " + string.Join(" · ", Readings.Select(CoMeasurementLabels.ReadingLabel)); - - public string CoDisplay => CoValue is { } v ? $"{v} ppm" : "Kein Messwert"; - - /// The tile's ppm readout. Empty rather than "Kein Messwert" when nothing is measured: - /// unmeasured is the resting state of every unit in a fresh building, so spelling it out on each - /// tile prints the same non-information dozens of times and buries the values that do exist. - /// The status glyph already says the unit is unsearched. - public string CoCompact => CoValue is { } v ? $"{v} ppm" : string.Empty; - - // ppm severity is independent of Status (search progress): a lethal reading on an unsearched - // tile must still read as lethal. Drives Classes.elevated/dangerous/lethal on the tile's ppm + : "Messreihe: " + string.Join(" · ", Readings.Select(r => CoMeasurementLabels.ReadingLabel(r, _gases))); + + /// Every measured gas in list order, each with the band it falls in, for the tooltip + /// (#410). A CO-only Einsatz has one entry and no gas name. + public IReadOnlyList GasValueRows => CoMeasurementLabels.ValuesInOrder(_gases, Values) + .Select(v => GasValueRow.From(v, _gases.Count > 1)) + .ToList(); + + /// Every measured gas as one line, "CO 120 ppm · H2S 3 ppm", or "Kein Messwert". + public string CoDisplay => GasValueRows is { Count: > 0 } rows + ? string.Join(" · ", rows.Select(r => r.Text)) + : "Kein Messwert"; + + /// The reading that decides the tile's colour: the worst gas, a tie going to the gas + /// earlier in the list, the first measured gas while all are normal (#410). + public GasValue? Worst => GasSeverityClassifier.Worst(_gases, Values); + + /// The tile's readout: the deciding gas, named once the Einsatz measures more than one + /// ("H2S 12 ppm"), so a CO-only Einsatz reads exactly as before. Empty rather than "Kein + /// Messwert" when nothing is measured: unmeasured is the resting state of every unit in a fresh + /// building, so spelling it out on each tile prints the same non-information dozens of times and + /// buries the values that do exist. The status glyph already says the unit is unsearched. + public string CoCompact => Worst is { } w ? CoMeasurementLabels.GasValueLabel(w.Gas, w.Value, _gases.Count > 1) : string.Empty; + + // Severity is independent of Status (search progress): a lethal reading on an unsearched tile + // must still read as lethal. Drives Classes.elevated/dangerous/lethal on the tile's value // TextBlock in CoMessprotokollView.axaml, mirroring ScbaView's Classes.alarm pattern. - public bool IsCoElevated => CoSeverityClassifier.SeverityOf(CoValue) == CoSeverity.Elevated; + public bool IsCoElevated => Worst?.Severity == CoSeverity.Elevated; - public bool IsCoDangerous => CoSeverityClassifier.SeverityOf(CoValue) == CoSeverity.Dangerous; + public bool IsCoDangerous => Worst?.Severity == CoSeverity.Dangerous; - public bool IsCoLethal => CoSeverityClassifier.SeverityOf(CoValue) == CoSeverity.Lethal; + public bool IsCoLethal => Worst?.Severity == CoSeverity.Lethal; /// Detail the compact tile deliberately drops (resident, key, full status wording), - /// surfaced on hover so nothing is lost -- the tile carries identity + status + ppm only. - public string TileTooltip + /// surfaced on hover so nothing is lost -- the tile carries identity + status + the worst gas + /// only. One sentence, for a screen reader; the tooltip itself shows , + /// then each in its own colour (#410), then . + public string TileTooltip => string.Join(" · ", TooltipHead, CoDisplay, TooltipTail); + + /// "Mitte · noch nicht abgesucht". + public string TooltipHead => $"{Label} · {CoMeasurementLabels.StatusText(Status)}"; + + /// Bewohner, Schlüssel and the Messreihe, after the gas values. + public string TooltipTail { get { - var parts = new List { Label, CoMeasurementLabels.StatusText(Status), CoDisplay }; + var parts = new List(); if (!string.IsNullOrWhiteSpace(ResidentName)) { parts.Add(ResidentName!); @@ -177,14 +204,16 @@ partial void OnStatusChanged(DwellingStatus value) { StatusBrush = GetStatusBrush(value); OnPropertyChanged(nameof(StatusGlyph)); - OnPropertyChanged(nameof(TileTooltip)); + NotifyTooltip(); } - partial void OnCoValueChanged(int? value) + partial void OnValuesChanged(IReadOnlyDictionary value) { + OnPropertyChanged(nameof(Worst)); + OnPropertyChanged(nameof(GasValueRows)); OnPropertyChanged(nameof(CoDisplay)); OnPropertyChanged(nameof(CoCompact)); - OnPropertyChanged(nameof(TileTooltip)); + NotifyTooltip(); OnPropertyChanged(nameof(IsCoElevated)); OnPropertyChanged(nameof(IsCoDangerous)); OnPropertyChanged(nameof(IsCoLethal)); @@ -193,18 +222,25 @@ partial void OnCoValueChanged(int? value) partial void OnKeyAvailableChanged(KeyAvailability value) { OnPropertyChanged(nameof(KeyDisplay)); - OnPropertyChanged(nameof(TileTooltip)); + NotifyTooltip(); } partial void OnKeyNumberChanged(string? value) { OnPropertyChanged(nameof(KeyDisplay)); - OnPropertyChanged(nameof(TileTooltip)); + NotifyTooltip(); } - partial void OnResidentNameChanged(string? value) => OnPropertyChanged(nameof(TileTooltip)); + partial void OnResidentNameChanged(string? value) => NotifyTooltip(); - partial void OnLabelChanged(string value) => OnPropertyChanged(nameof(TileTooltip)); + partial void OnLabelChanged(string value) => NotifyTooltip(); + + private void NotifyTooltip() + { + OnPropertyChanged(nameof(TooltipHead)); + OnPropertyChanged(nameof(TooltipTail)); + OnPropertyChanged(nameof(TileTooltip)); + } [RelayCommand] private void OpenEditor() => _onOpenEditor(BuildingId, FloorOrdinal, ApartmentNumber); @@ -226,35 +262,118 @@ public sealed record CoReadingRow( string RecordedBy, bool IsCoElevated, bool IsCoDangerous, - bool IsCoLethal) + bool IsCoLethal, + string Gas = "") { - public static CoReadingRow From(CoReading reading) + /// A row for one reading. names the gas once the Einsatz measures + /// more than one (#410), and stays empty otherwise so a CO-only Messreihe reads as before. + public static CoReadingRow From(CoReading reading, IReadOnlyList gases) { ArgumentNullException.ThrowIfNull(reading); - var severity = CoSeverityClassifier.SeverityOf(reading.Value); + ArgumentNullException.ThrowIfNull(gases); + var gas = gases.FirstOrDefault(g => g.Id == reading.GasId); + var severity = gas is null ? CoSeverity.Normal : GasSeverityClassifier.SeverityOf(gas.Definition, reading.Value); return new( Formatting.TimeOfDay(reading.MeasuredAt), - reading.Value is { } v ? $"{v} ppm" : "gelöscht", + reading.Value is { } v ? Formatting.Measurement(v, gas?.Unit ?? string.Empty) : "gelöscht", reading.RecordedBy, severity == CoSeverity.Elevated, severity == CoSeverity.Dangerous, - severity == CoSeverity.Lethal); + severity == CoSeverity.Lethal, + gases.Count > 1 && gas is not null ? gas.Name : string.Empty); + } +} + +/// One gas's current value, pre-formatted for the tooltip and the sidebar (#410), with the +/// band that colours it. +public sealed record GasValueRow(string Text, bool IsCoElevated, bool IsCoDangerous, bool IsCoLethal) +{ + public static GasValueRow From(GasValue value, bool withName) + { + ArgumentNullException.ThrowIfNull(value); + return new( + CoMeasurementLabels.GasValueLabel(value.Gas, value.Value, withName), + value.Severity == CoSeverity.Elevated, + value.Severity == CoSeverity.Dangerous, + value.Severity == CoSeverity.Lethal); + } +} + +/// +/// One gas's input in the WOHNUNG BEARBEITEN sidebar (#410): the value as typed, against the value +/// committed, with the band and the plausibility hint recomputed live so the danger colour shows +/// before FERTIG. Like the rest of the sidebar it writes nothing; the editor reads it back on +/// commit. +/// +public sealed partial class GasInputRow : ObservableObject +{ + private readonly Action _onChanged; + + public GasInputRow(IncidentGas gas, decimal? original, Action onChanged) + { + ArgumentNullException.ThrowIfNull(gas); + Gas = gas; + Original = original; + _value = original; + _onChanged = onChanged ?? (() => { }); } + + public IncidentGas Gas { get; } + + public string Name => Gas.Name; + + public string Unit => Gas.Unit; + + /// The overline above the input: the gas's name, "CO". Its unit sits inside the field. + public string Header => Formatting.Upper(Gas.Name); + + /// What a screen reader announces for the text-less input. + public string AccessibleName => $"{Gas.Name}-Wert"; + + public decimal? Original { get; } + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasChange))] + [NotifyPropertyChangedFor(nameof(IsCoElevated))] + [NotifyPropertyChangedFor(nameof(IsCoDangerous))] + [NotifyPropertyChangedFor(nameof(IsCoLethal))] + [NotifyPropertyChangedFor(nameof(IsImplausible))] + private decimal? _value; + + /// The value FERTIG would record: rounded the way the domain stores it, so typing + /// 20,90 over 20,9 is not mistaken for a new reading. + public decimal? Committed => Value is { } v ? GasDefinition.NormalizeValue(v) ?? v : null; + + public bool HasChange => Committed != Original; + + public bool IsCoElevated => GasSeverityClassifier.SeverityOf(Gas.Definition, Value) == CoSeverity.Elevated; + + public bool IsCoDangerous => GasSeverityClassifier.SeverityOf(Gas.Definition, Value) == CoSeverity.Dangerous; + + public bool IsCoLethal => GasSeverityClassifier.SeverityOf(Gas.Definition, Value) == CoSeverity.Lethal; + + /// A caution about a likely *typo* (e.g. 9999 vs 999), distinct from severity: a real + /// fire scene can genuinely produce extreme values, so this never blocks FERTIG -- it only + /// asks the Lagebuchführer to double-check what they typed. + public bool IsImplausible => GasSeverityClassifier.IsImplausible(Gas.Definition, Value); + + partial void OnValueChanged(decimal? value) => _onChanged(); } public sealed partial class DwellingEditorViewModel : ObservableObject { - public DwellingEditorViewModel(Dwelling dwelling, Building building, IReadOnlyList? involvedPartyNames = null) + public DwellingEditorViewModel( + Dwelling dwelling, Building building, IReadOnlyList? involvedPartyNames = null, IReadOnlyList? gases = null) { ArgumentNullException.ThrowIfNull(dwelling); ArgumentNullException.ThrowIfNull(building); InvolvedPartyNames = involvedPartyNames ?? []; + var incidentGases = gases ?? []; BuildingId = dwelling.BuildingId; FloorOrdinal = dwelling.FloorOrdinal; ApartmentNumber = dwelling.ApartmentNumber; OriginalStatus = dwelling.Status; - OriginalCoValue = dwelling.CoValue; OriginalResidentName = dwelling.ResidentName; OriginalKeyAvailable = dwelling.KeyAvailable; OriginalKeyNumber = dwelling.KeyNumber; @@ -262,10 +381,12 @@ public DwellingEditorViewModel(Dwelling dwelling, Building building, IReadOnlyLi // Newest first: during an Einsatz the question is "what is it now, and was it worse?", // so the latest reading belongs at the top where the eye lands. - Readings = dwelling.Readings.Reverse().Select(CoReadingRow.From).ToList(); + Readings = dwelling.Readings.Reverse().Select(r => CoReadingRow.From(r, incidentGases)).ToList(); + + // One input per gas of the Einsatz, in list order (#410). + GasInputs = incidentGases.Select(g => new GasInputRow(g, dwelling.ValueOf(g.Id), OnGasInputChanged)).ToList(); _status = OriginalStatus; - _coValue = OriginalCoValue; _residentName = OriginalResidentName; _keyAvailable = OriginalKeyAvailable; _keyNumber = OriginalKeyNumber; @@ -289,9 +410,6 @@ public DwellingEditorViewModel(Dwelling dwelling, Building building, IReadOnlyLi [ObservableProperty] private DwellingStatus _status; - [ObservableProperty] - private int? _coValue; - [ObservableProperty] private string? _residentName; @@ -353,7 +471,8 @@ public bool IsKeyUnknown public DwellingStatus OriginalStatus { get; } - public int? OriginalCoValue { get; } + /// One input per gas of the Einsatz, in list order (#410). + public IReadOnlyList GasInputs { get; } public string? OriginalResidentName { get; } @@ -365,7 +484,7 @@ public bool IsKeyUnknown /// /// The Wohnung's committed Messreihe, newest first. Read-only on purpose: a keystroke in the - /// ppm field is not a measurement, and ABBRECHEN has to be able to discard it — a previewed + /// value field is not a measurement, and ABBRECHEN has to be able to discard it — a previewed /// row would put a reading in the list that never happened, with a timestamp that does not /// exist yet (it is minted by the clock inside RecordCoValue when FERTIG commits). /// @@ -375,7 +494,15 @@ public bool IsKeyUnknown public bool HasStatusChange => Status != OriginalStatus; - public bool HasCoValueChange => CoValue != OriginalCoValue; + public bool HasCoValueChange => GasInputs.Any(g => g.HasChange); + + /// What FERTIG records: every gas whose value changed, null where it was cleared. + public IReadOnlyDictionary ChangedValues => + GasInputs.Where(g => g.HasChange).ToDictionary(g => g.Gas.Id, g => g.Committed); + + /// The values as they stand in the sidebar, for the tile's pending preview. + public IReadOnlyDictionary PendingValues => + GasInputs.Where(g => g.Committed is not null).ToDictionary(g => g.Gas.Id, g => g.Committed.GetValueOrDefault()); // Normalized the same way Dwelling.WithDetails does, so clearing an already-empty name is not // mistaken for an edit and does not cost a save (or, on a joined device, a command POST). @@ -390,18 +517,8 @@ public bool IsKeyUnknown /// Whether ABBRECHEN would throw anything away, so it has to ask first (#652). public bool HasChanges => HasStatusChange || HasCoValueChange || HasDetailChange || HasLabelChange; - // Same severity signal as the tile (DwellingCellViewModel), shown live while typing so the - // operator sees danger coloring before committing, not only after FERTIG. - public bool IsCoElevated => CoSeverityClassifier.SeverityOf(CoValue) == CoSeverity.Elevated; - - public bool IsCoDangerous => CoSeverityClassifier.SeverityOf(CoValue) == CoSeverity.Dangerous; - - public bool IsCoLethal => CoSeverityClassifier.SeverityOf(CoValue) == CoSeverity.Lethal; - - /// A caution about a likely *typo* (e.g. 9999 vs 999), distinct from severity: a real - /// fire scene can genuinely produce extreme ppm values, so this never blocks FERTIG -- it only - /// asks the operator to double-check what they typed. - public bool IsCoImplausible => CoSeverityClassifier.IsImplausible(CoValue); + /// Whether any gas's value looks like a typo; each input carries its own hint. + public bool IsCoImplausible => GasInputs.Any(g => g.IsImplausible); private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); @@ -409,12 +526,11 @@ public bool IsKeyUnknown private static string? StoredKeyNumber(KeyAvailability keyAvailable, string? keyNumber) => keyAvailable == KeyAvailability.Available ? Normalize(keyNumber) : null; - partial void OnCoValueChanged(int? value) + // A typed value raises the editor's own change, so the tile preview (ApplyPendingEditToMatrix) + // follows the sidebar as it did for the single CO value. + private void OnGasInputChanged() { OnPropertyChanged(nameof(HasCoValueChange)); - OnPropertyChanged(nameof(IsCoElevated)); - OnPropertyChanged(nameof(IsCoDangerous)); - OnPropertyChanged(nameof(IsCoLethal)); OnPropertyChanged(nameof(IsCoImplausible)); } } @@ -620,14 +736,19 @@ public sealed partial class CoMessprotokollViewModel : ObservableObject, INarrow private readonly Action _onChanged; private readonly IReadOnlyList _premises; - // premises: the Objekte a new Haus may be picked from (#420); none when omitted. - public CoMessprotokollViewModel(IIncidentSession session, IClock clock, Action onChanged, IReadOnlyList? premises = null) + private readonly IReadOnlyList? _gases; + + // premises: the Objekte a new Haus may be picked from (#420); none when omitted. gases: the + // Stammdaten Messgase (#410), copied into the Einsatz by its first Haus; CO alone when omitted. + public CoMessprotokollViewModel( + IIncidentSession session, IClock clock, Action onChanged, IReadOnlyList? premises = null, IReadOnlyList? gases = null) { ArgumentNullException.ThrowIfNull(session); _session = session; _clock = clock; _onChanged = onChanged; _premises = premises ?? Array.Empty(); + _gases = gases; PremisesOptions = _premises.Select(p => p.Name).ToList(); IsReadOnly = session.IsReadOnly; _session.Changed += Refresh; @@ -924,7 +1045,7 @@ private void BuildMatrix() { var dwelling = dwellings.GetValueOrDefault((floor, apt)); return dwelling is not null - ? new DwellingCellViewModel(dwelling, building, IsReadOnly, OnOpenEditor) + ? new DwellingCellViewModel(dwelling, building, IsReadOnly, OnOpenEditor, _session.Incident.Gases) : null; }) .Where(c => c is not null) @@ -1015,7 +1136,7 @@ private void ApplyPendingEditToMatrix() } cell.Status = editor.Status; - cell.CoValue = editor.CoValue; + cell.Values = editor.PendingValues; cell.ResidentName = editor.ResidentName; cell.KeyAvailable = editor.KeyAvailable; cell.KeyNumber = editor.IsKeyNumberEnabled ? editor.KeyNumber : null; @@ -1096,7 +1217,7 @@ bool CarriesAnything(Dwelling d) => /// Seeds the picker: empty Wohnungen from the right first, then the rightmost units /// that do carry something, so the default selection is the least destructive one that still /// reaches the count the crew typed. - private static ApartmentRemovalViewModel BuildApartmentRemoval( + private ApartmentRemovalViewModel BuildApartmentRemoval( Building building, int floorOrdinal, int count, @@ -1134,12 +1255,14 @@ private static ApartmentRemovalViewModel BuildApartmentRemoval( return built; } - private static string DescribeContents(Dwelling dwelling) + private string DescribeContents(Dwelling dwelling) { var parts = new List(); - if (dwelling.CoValue is { } ppm) + var gases = _session.Incident.Gases; + var measured = CoMeasurementLabels.ValuesInOrder(gases, dwelling.Values); + if (measured.Count > 0) { - parts.Add($"{ppm} ppm"); + parts.AddRange(measured.Select(m => CoMeasurementLabels.GasValueLabel(m.Gas, m.Value, gases.Count > 1))); } else if (dwelling.Readings.Count > 0) { @@ -1219,7 +1342,7 @@ private void OnOpenEditor(Guid buildingId, int floorOrdinal, int apartmentNumber Editor = building is not null && dwelling is not null ? new DwellingEditorViewModel( - dwelling, building, _session.Incident.InvolvedPartiesIn(dwelling.Id).Select(p => p.Name).ToList()) + dwelling, building, _session.Incident.InvolvedPartiesIn(dwelling.Id).Select(p => p.Name).ToList(), _session.Incident.Gases) : null; } @@ -1334,8 +1457,9 @@ private void ConfirmAddBuilding() } // The labels are the Objekt's own copy (#337); Building.Create keeps only those that fit. + // The Messgase are copied the same way, by the first Haus only (#410). _session.AddCoBuilding( - NewBuildingName, NewBuildingFloors, NewBuildingApartments, NewBuildingUndergroundFloors, _pickedPremises?.ApartmentLabels); + NewBuildingName, NewBuildingFloors, NewBuildingApartments, NewBuildingUndergroundFloors, _pickedPremises?.ApartmentLabels, _gases); NewBuildingName = string.Empty; _filledFloors = _filledApartments = _filledUndergroundFloors = null; NewBuildingFloors = Premises.DefaultFloorCount; @@ -1589,7 +1713,7 @@ private void SetEditorStatus(DwellingStatus status) } /// FERTIG. The single commit point for a unit: writes only the fields that actually - /// changed, so the Einsatztagebuch gets one entry for the status and one for the ppm reading + /// changed, so the Einsatztagebuch gets one entry for the status and one for the gas readings /// rather than one per keystroke, and a joined device does not POST no-op commands. [RelayCommand] private void ConfirmEditor() @@ -1619,7 +1743,7 @@ private void ConfirmEditor() if (editor.HasCoValueChange) { - _session.RecordCoValue(editor.BuildingId, editor.FloorOrdinal, editor.ApartmentNumber, editor.CoValue); + _session.RecordCoValues(editor.BuildingId, editor.FloorOrdinal, editor.ApartmentNumber, editor.ChangedValues); wrote = true; } diff --git a/src/LageBuch.AppLogic/ViewModels/GasRow.cs b/src/LageBuch.AppLogic/ViewModels/GasRow.cs new file mode 100644 index 00000000..99c79520 --- /dev/null +++ b/src/LageBuch.AppLogic/ViewModels/GasRow.cs @@ -0,0 +1,72 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using LageBuch.Domain.CoMeasurement; + +namespace LageBuch.AppLogic.ViewModels; + +/// One editable Messgas (#410): name, unit, direction and up to three bands, plus the +/// value beyond which a reading is probably a typo. +public sealed partial class GasRow : ObservableObject +{ + private readonly Action _onChanged; + + public GasRow(GasDefinition gas, Action onChanged) + { + ArgumentNullException.ThrowIfNull(gas); + _onChanged = onChanged; + _name = gas.Name; + _unit = gas.Unit; + _direction = gas.Direction; + _elevated = gas.Elevated; + _dangerous = gas.Dangerous; + _lethal = gas.Lethal; + _plausibleUpTo = gas.PlausibleUpTo; + } + + /// steigend and fallend with their labels, built once by . + public IReadOnlyList DirectionOptions { get; } = GasesSection.DirectionChoices; + + /// What the unit field suggests; the unit itself stays free text. + public IReadOnlyList UnitSuggestions { get; } = GasDefinition.UnitSuggestions; + + public static int MaxNameLength => GasDefinition.MaxNameLength; + + public static int MaxUnitLength => GasDefinition.MaxUnitLength; + + public static decimal MaxValue => GasDefinition.MaxValue; + + [ObservableProperty] + private string _name; + [ObservableProperty] + private string _unit; + [ObservableProperty] + private GasDirection _direction; + [ObservableProperty] + private decimal? _elevated; + [ObservableProperty] + private decimal? _dangerous; + [ObservableProperty] + private decimal? _lethal; + [ObservableProperty] + private decimal? _plausibleUpTo; + + /// The row as it would be saved: name and unit trimmed, nothing else touched. + public GasDefinition ToDefinition() => + new((Name ?? string.Empty).Trim(), (Unit ?? string.Empty).Trim(), Direction, Elevated, Dangerous, Lethal, PlausibleUpTo); + + partial void OnNameChanged(string value) => _onChanged(); + + partial void OnUnitChanged(string value) => _onChanged(); + + partial void OnDirectionChanged(GasDirection value) => _onChanged(); + + partial void OnElevatedChanged(decimal? value) => _onChanged(); + + partial void OnDangerousChanged(decimal? value) => _onChanged(); + + partial void OnLethalChanged(decimal? value) => _onChanged(); + + partial void OnPlausibleUpToChanged(decimal? value) => _onChanged(); +} + +/// A paired with its label for the picker. +public readonly record struct GasDirectionOption(GasDirection Value, string Label); diff --git a/src/LageBuch.AppLogic/ViewModels/GasesSection.cs b/src/LageBuch.AppLogic/ViewModels/GasesSection.cs new file mode 100644 index 00000000..5014216e --- /dev/null +++ b/src/LageBuch.AppLogic/ViewModels/GasesSection.cs @@ -0,0 +1,120 @@ +using System.Collections.ObjectModel; +using System.Globalization; +using CommunityToolkit.Mvvm.Input; +using LageBuch.Domain.CoMeasurement; + +namespace LageBuch.AppLogic.ViewModels; + +/// +/// Editor for the Messgase Stammdaten (#410): the gases a crew measures in the Gasmessung, at most +/// , in the order every Einsatz will show them. The list never +/// goes empty -- the last row cannot be removed -- because an empty list reads back as CO alone, +/// which would make a deletion silently undo itself. Anything that would not survive the import's +/// rules (a nameless row, thresholds out of order, a name used twice) is named by +/// and blocks SPEICHERN rather than being dropped. +/// +public sealed partial class GasesSection : EditorSection +{ + private readonly Action _onChanged; + + public GasesSection(string title, IEnumerable gases, Action onChanged, Action? requestConfirm = null) + : base(title, requestConfirm) + { + _onChanged = onChanged; + Rows = new ObservableCollection(gases.Select(NewRow)); + Rows.CollectionChanged += (_, _) => + { + AddCommand.NotifyCanExecuteChanged(); + RemoveCommand.NotifyCanExecuteChanged(); + }; + } + + public ObservableCollection Rows { get; } + + internal static IReadOnlyList DirectionChoices { get; } = + [ + new(GasDirection.Rising, "steigend"), + new(GasDirection.Falling, "fallend"), + ]; + + private GasRow NewRow(GasDefinition gas) => new(gas, _onChanged); + + private bool CanAdd => Rows.Count < GasDefinition.MaxCount; + + [RelayCommand(CanExecute = nameof(CanAdd))] + private void Add() + { + var row = NewRow(new GasDefinition(string.Empty, string.Empty, GasDirection.Rising, null, null, null, null)); + Rows.Add(row); + _onChanged(); + OnRowAdded(row); + } + + private bool CanRemove(GasRow? row) => Rows.Count > 1; + + [RelayCommand(CanExecute = nameof(CanRemove))] + private void Remove(GasRow? row) + { + if (row is null || !Rows.Contains(row) || Rows.Count <= 1) + { + return; + } + + RemoveAfterConfirm(row, row.Name, AllBlank(row.Name, row.Unit) && row.Elevated is null && row.Dangerous is null && row.Lethal is null && row.PlausibleUpTo is null, () => + { + if (Rows.Remove(row)) + { + _onChanged(); + } + }); + } + + /// + /// What keeps the list from being saved, one line per kind of problem, or an empty list. The + /// rows are numbered from 1 where they have no name to go by. + /// + public IReadOnlyList Conflicts() + { + var problems = new List(); + var unnamed = Rows + .Select((row, index) => (Row: row, Number: index + 1)) + .Where(x => string.IsNullOrWhiteSpace(x.Row.Name)) + .Select(x => x.Number.ToString(CultureInfo.InvariantCulture)) + .ToList(); + if (unnamed.Count > 0) + { + problems.Add(unnamed.Count == 1 ? $"Messgas ohne Namen: Zeile {unnamed[0]}" : $"Messgas ohne Namen: Zeilen {string.Join(", ", unnamed)}"); + } + + var duplicates = Rows + .Select(r => r.Name?.Trim() ?? string.Empty) + .Where(n => n.Length > 0) + .GroupBy(n => n, StringComparer.OrdinalIgnoreCase) + .Where(g => g.Count() > 1) + .Select(g => g.Key) + .ToList(); + if (duplicates.Count > 0) + { + problems.Add($"Doppelte Messgase: {string.Join(", ", duplicates)}"); + } + + var disordered = Rows + .Where(r => !string.IsNullOrWhiteSpace(r.Name) && !r.ToDefinition().ThresholdsInOrder) + .Select(r => r.Name.Trim()) + .ToList(); + if (disordered.Count > 0) + { + problems.Add($"Schwellen nicht in Reihenfolge: {string.Join(", ", disordered)}"); + } + + return problems; + } + + /// The rows as the Stammdaten keep them: sanitised the way the import is, so a saved + /// list always passes it. Never empty. + public IReadOnlyList ToValues() + { + var gases = GasDefinition.SanitizeList(Rows.Select(r => r.ToDefinition())); + return gases.Count > 0 ? gases : [GasDefinition.DefaultCo]; + } +} diff --git a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs index 682bffc1..63a31a7b 100644 --- a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs @@ -1143,7 +1143,7 @@ private void BuildChildren() Links = new LinksViewModel(_masterData.Links, _dialogs); Contacts = new ContactsViewModel(_masterData.Personnel, _dialogs, _masterData.Vehicles); - CoMessprotokoll = new CoMessprotokollViewModel(_session, _clock, OnChanged, _masterData.Premises); + CoMessprotokoll = new CoMessprotokollViewModel(_session, _clock, OnChanged, _masterData.Premises, _masterData.Gases); Tasks = new TasksViewModel(_session, _clock, _ticker, _alarm, _masterData, OnChanged, OfferUndo); Tasks.RevealRequested += OnTasksRevealRequested; diff --git a/src/LageBuch.AppLogic/ViewModels/MasterDataEditorViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MasterDataEditorViewModel.cs index 1af33cff..535f23a8 100644 --- a/src/LageBuch.AppLogic/ViewModels/MasterDataEditorViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MasterDataEditorViewModel.cs @@ -48,6 +48,7 @@ public sealed partial class MasterDataEditorViewModel : ObservableObject, INarro private VehiclesSection _vehicles = null!; private StreetsSection _streets = null!; private TalkGroupsSection _talkGroups = null!; + private GasesSection _gases = null!; private SettingsSection _settings = null!; /// Without , the device's Kartenpakete, the editor shows no Karten section. @@ -191,10 +192,21 @@ public EditorSection? SelectedSection [NotifyCanExecuteChangedFor(nameof(SaveCommand))] private string? _personnelConflicts; + /// + /// Messgase the import would refuse or the save would drop (#410): a nameless row, a name used + /// twice, thresholds out of order. A wrong order would colour a Wohnung wrongly at the next + /// Einsatz, so it blocks saving rather than being guessed at. + /// + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(SaveCommand))] + private string? _gasConflicts; + public bool HasVehicleConflicts => VehicleConflicts is not null; public bool HasPersonnelConflicts => PersonnelConflicts is not null; + public bool HasGasConflicts => GasConflicts is not null; + [ObservableProperty] private ConfirmDialogViewModel? _pendingConfirm; @@ -267,6 +279,9 @@ private void PopulateSections(MasterDataSet set) // The derived lists still serve as typing suggestions for further rows. _vehicles = new VehiclesSection("Fahrzeuge", set.Vehicles, set.Brigades, set.RadioCallSigns, OnVehiclesChanged, RequestConfirm), _talkGroups = new TalkGroupsSection("Funkgruppen", set.TalkGroups, MarkDirty, RequestConfirm), + + // The gases the Gasmessung records (#410), copied into an Einsatz by its first Haus. + _gases = new GasesSection("Messgase", set.Gases, OnGasesChanged, RequestConfirm), }; foreach (var section in categories.OrderBy(s => s.Title, StringComparer.OrdinalIgnoreCase)) @@ -293,6 +308,19 @@ private void PopulateSections(MasterDataSet set) // answer has to be on screen before anything is touched. RefreshVehicleConflicts(); RefreshPersonnelConflicts(); + RefreshGasConflicts(); + } + + private void OnGasesChanged() + { + IsDirty = true; + RefreshGasConflicts(); + } + + private void RefreshGasConflicts() + { + var problems = _gases.Conflicts(); + GasConflicts = problems.Count == 0 ? null : string.Join("\n", problems); } private void OnVehiclesChanged() @@ -393,6 +421,7 @@ private MasterDataSet BuildSet() => _original with Personnel = _personnel.ToPeople(), Vehicles = _vehicles.ToValues(), TalkGroups = _talkGroups.ToValues(), + Gases = _gases.ToValues(), Settings = _settings.ToSettings(), }; @@ -466,7 +495,7 @@ private void Save() // Dirty alone is not enough: a duplicate Funkrufname must be resolved before the set can be // written (#76 follow-up). - private bool CanSave => IsDirty && !HasVehicleConflicts && !HasPersonnelConflicts; + private bool CanSave => IsDirty && !HasVehicleConflicts && !HasPersonnelConflicts && !HasGasConflicts; [RelayCommand(CanExecute = nameof(IsDirty))] private void Discard() => Load(); diff --git a/src/LageBuch.AppLogic/ViewModels/NavigationSection.cs b/src/LageBuch.AppLogic/ViewModels/NavigationSection.cs index f64c05e7..106aeb90 100644 --- a/src/LageBuch.AppLogic/ViewModels/NavigationSection.cs +++ b/src/LageBuch.AppLogic/ViewModels/NavigationSection.cs @@ -183,7 +183,7 @@ public static NavRow ForChecklist(ChecklistTemplateSection section, bool isVisib [NavModules.InvolvedParties] = "Beteiligte", [NavModules.IssuedItems] = "Ausgabe", [NavModules.Scba] = "Atemschutz", - [NavModules.Co] = "CO-Messung", + [NavModules.Co] = "Gasmessung", [NavModules.Files] = "Dateien", [NavModules.Links] = "Links", [NavModules.Contacts] = "Kontakte", diff --git a/src/LageBuch.AppLogic/ViewModels/PdfExportOptionsViewModel.cs b/src/LageBuch.AppLogic/ViewModels/PdfExportOptionsViewModel.cs index 7269f7f7..d5f67e1d 100644 --- a/src/LageBuch.AppLogic/ViewModels/PdfExportOptionsViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/PdfExportOptionsViewModel.cs @@ -31,7 +31,7 @@ public PdfExportOptionsViewModel(Func onExport, strin new PdfSectionOptionViewModel(IncidentPdfSections.IssuedItems, "Ausgabeliste", NotifyCanExecuteChanged), new PdfSectionOptionViewModel(IncidentPdfSections.Tasks, "Aufgaben", NotifyCanExecuteChanged), new PdfSectionOptionViewModel(IncidentPdfSections.Atemschutz, "Atemschutzüberwachung", NotifyCanExecuteChanged), - new PdfSectionOptionViewModel(IncidentPdfSections.CoMessprotokoll, "CO-Messprotokoll", NotifyCanExecuteChanged), + new PdfSectionOptionViewModel(IncidentPdfSections.CoMessprotokoll, "Gasmessprotokoll", NotifyCanExecuteChanged), new PdfSectionOptionViewModel(IncidentPdfSections.Files, "Angehängte Dateien", NotifyCanExecuteChanged), }; } diff --git a/src/LageBuch.Documents/Sections/CoMessprotokollSection.cs b/src/LageBuch.Documents/Sections/CoMessprotokollSection.cs index befa7014..384ca3c7 100644 --- a/src/LageBuch.Documents/Sections/CoMessprotokollSection.cs +++ b/src/LageBuch.Documents/Sections/CoMessprotokollSection.cs @@ -13,14 +13,16 @@ public static void Compose(IContainer container, Incident incident) container.Column(column => { column.Spacing(4); - column.Item().Text("CO-Messprotokoll").FontSize(14).SemiBold().FontColor(Colors.Blue.Darken1); + column.Item().Text("Gasmessprotokoll").FontSize(14).SemiBold().FontColor(Colors.Blue.Darken1); if (incident.Buildings.Count == 0) { - column.Item().Text("— kein CO-Messprotokoll erfasst —").Italic().FontColor(Colors.Grey.Medium); + column.Item().Text("— kein Gasmessprotokoll erfasst —").Italic().FontColor(Colors.Grey.Medium); return; } + var gases = incident.Gases; + var withName = gases.Count > 1; foreach (var building in incident.Buildings) { column.Item().PaddingTop(8).Text(t => @@ -52,21 +54,35 @@ public static void Compose(IContainer container, Incident incident) foreach (var unit in units) { var label = CoMeasurementLabels.ApartmentLabel(building, floor, unit.ApartmentNumber); - var co = unit.CoValue is { } v ? $"{v} ppm" : "kein Messwert"; var key = KeyText(unit.KeyAvailable, unit.KeyNumber); var resident = string.IsNullOrWhiteSpace(unit.ResidentName) ? null : $", {unit.ResidentName}"; + var measured = CoMeasurementLabels.ValuesInOrder(gases, unit.Values); - // ppm severity is its own span, colored independently of Status (search - // progress): a lethal reading must read as lethal in print too, matching - // the app view's Classes.elevated/dangerous/lethal on the tile. - var severityColor = GetSeverityColor(CoSeverityClassifier.SeverityOf(unit.CoValue)); + // The Messwerte (#410): every measured gas in list order, each its own + // span coloured by its own band, independently of Status (search + // progress) -- a lethal reading must read as lethal in print too, matching + // the tile. One run per Wohnung, so eight gases still fit A4 portrait. A + // single-gas Einsatz leaves the name out and reads as it always did. column.Item().Text(t => { t.Span($"• {label}{resident}: ").FontSize(8); - var coSpan = t.Span(co).FontSize(8); - if (severityColor is not null) + if (measured.Count == 0) { - coSpan.FontColor(severityColor); + t.Span("kein Messwert").FontSize(8); + } + + for (var i = 0; i < measured.Count; i++) + { + if (i > 0) + { + t.Span(" · ").FontSize(8); + } + + var valueSpan = t.Span(CoMeasurementLabels.GasValueLabel(measured[i].Gas, measured[i].Value, withName)).FontSize(8); + if (GetSeverityColor(measured[i].Severity) is { } severityColor) + { + valueSpan.FontColor(severityColor); + } } t.Span($", Schlüssel: {key}, {CoMeasurementLabels.StatusText(unit.Status)}") @@ -75,13 +91,13 @@ public static void Compose(IContainer container, Incident incident) // #424: the Verlauf the Einsatzleiter is actually looking for, indented // under its unit. Only from two readings up -- with one it just repeats - // the ppm on the line above. Deliberately grey rather than + // the value on the line above. Deliberately grey rather than // severity-coloured: this page is scanned as a whole for red, and a red // historical value would announce a danger that has already passed. The // current value one line up carries the coloured statement. if (unit.Readings.Count >= 2) { - var series = string.Join(" · ", unit.Readings.Select(CoMeasurementLabels.ReadingLabel)); + var series = string.Join(" · ", unit.Readings.Select(r => CoMeasurementLabels.ReadingLabel(r, gases))); column.Item().PaddingLeft(10).Text($"Messreihe: {series}") .FontSize(7).FontColor(Colors.Grey.Darken1); } @@ -104,12 +120,15 @@ public static void Compose(IContainer container, Incident incident) var location = CoMeasurementLabels.DwellingLocation(building, d.FloorOrdinal, d.ApartmentNumber); var resident = d.ResidentName ?? "—"; var key = KeyText(d.KeyAvailable, d.KeyNumber); - var co = d.CoValue is { } v ? $"{v} ppm" : "—"; + var measured = CoMeasurementLabels.ValuesInOrder(gases, d.Values); + var values = measured.Count > 0 + ? string.Join(" · ", measured.Select(m => CoMeasurementLabels.GasValueLabel(m.Gas, m.Value, withName: true))) + : "—"; // #702: who the Beteiligte list records as found here, after what was measured. var parties = incident.InvolvedPartiesIn(d.Id); var found = parties.Count > 0 ? $", Beteiligte: {string.Join(", ", parties.Select(p => p.Name))}" : string.Empty; - column.Item().Text($"• {location}, Bewohner: {resident}, Schlüssel: {key}, CO: {co}{found}"); + column.Item().Text($"• {location}, Bewohner: {resident}, Schlüssel: {key}, Messwerte: {values}{found}"); } } diff --git a/src/LageBuch.Domain/CoMeasurement/CoMeasurementLabels.cs b/src/LageBuch.Domain/CoMeasurement/CoMeasurementLabels.cs index 6c206f2f..e80a3006 100644 --- a/src/LageBuch.Domain/CoMeasurement/CoMeasurementLabels.cs +++ b/src/LageBuch.Domain/CoMeasurement/CoMeasurementLabels.cs @@ -122,13 +122,44 @@ public static string DwellingLocation(Building building, int floorOrdinal, int a return $"{building.Name}, {FloorLabel(floorOrdinal)}, {ApartmentLabel(building, floorOrdinal, apartmentNumber)}"; } + /// One gas value as "120 ppm", or "H2S 3 ppm" once the Einsatz measures more than one + /// gas (#410) -- a CO-only Einsatz reads exactly as it did before. + public static string GasValueLabel(IncidentGas gas, decimal value, bool withName) + { + ArgumentNullException.ThrowIfNull(gas); + var measurement = Formatting.Measurement(value, gas.Unit); + return withName ? $"{gas.Name} {measurement}" : measurement; + } + + /// Every measured gas of a Wohnung in list order, each with its band, for the tooltip, + /// the sidebar and the report. Empty when nothing was measured. + public static IReadOnlyList ValuesInOrder(IReadOnlyList gases, IReadOnlyDictionary values) + { + ArgumentNullException.ThrowIfNull(gases); + ArgumentNullException.ThrowIfNull(values); + return gases + .Where(g => values.ContainsKey(g.Id)) + .Select(g => new GasValue(g, values[g.Id], GasSeverityClassifier.SeverityOf(g.Definition, values[g.Id]))) + .ToList(); + } + /// One reading of a Messreihe as "08:41 40 ppm", or "09:02 gelöscht" where the value - /// was cleared. Lives here rather than in either renderer so the CO tab and the report cannot - /// word the same series differently. - public static string ReadingLabel(CoReading reading) + /// was cleared; with more than one gas the gas is named, "08:41 H2S 3 ppm". Lives here rather + /// than in either renderer so the CO tab and the report cannot word the same series + /// differently. + public static string ReadingLabel(CoReading reading, IReadOnlyList gases) { ArgumentNullException.ThrowIfNull(reading); - var value = reading.Value is { } v ? $"{v} ppm" : "gelöscht"; + ArgumentNullException.ThrowIfNull(gases); + var gas = gases.FirstOrDefault(g => g.Id == reading.GasId); + var withName = gases.Count > 1 && gas is not null; + var value = (reading.Value, gas) switch + { + ({ } v, { } g) => GasValueLabel(g, v, withName), + ({ } v, null) => Formatting.Measurement(v, string.Empty), + (null, { } g) when withName => $"{g.Name} gelöscht", + _ => "gelöscht", + }; return $"{Formatting.TimeOfDay(reading.MeasuredAt)} {value}"; } diff --git a/src/LageBuch.Domain/CoMeasurement/CoReading.cs b/src/LageBuch.Domain/CoMeasurement/CoReading.cs index a04f6f8f..4c1de028 100644 --- a/src/LageBuch.Domain/CoMeasurement/CoReading.cs +++ b/src/LageBuch.Domain/CoMeasurement/CoReading.cs @@ -1,7 +1,7 @@ namespace LageBuch.Domain.CoMeasurement; /// -/// One CO reading taken in a Wohnung (#424) — the CO sibling of +/// One gas reading taken in a Wohnung (#424, per gas since #410) — the CO sibling of /// : what was measured, when, by whom. /// /// @@ -14,14 +14,18 @@ namespace LageBuch.Domain.CoMeasurement; /// parent's value, at an unknown time". /// /// +/// points into the incident's own gas list (), never +/// into the Stammdaten. is decimal because 20,9 Vol-% O₂ is not an integer. +/// +/// /// is nullable because clearing a reading is a correction worth keeping, not /// an absence: after a deletion the Wohnung shows "kein Messwert" and the series is the only /// remaining record that 120 ppm was ever there. /// /// /// No identity of its own. A reading is immutable and never addressed singly; its identity is -/// (Wohnung, position in the series), exactly as with force_unit_edits. #410 extends this -/// record with a gas slot and a unit as trailing defaults rather than reshaping it. +/// (Wohnung, position in the series), exactly as with force_unit_edits. Readings of several +/// gases taken at one FERTIG share their . /// /// -public sealed record CoReading(DateTimeOffset MeasuredAt, int? Value, string RecordedBy); +public sealed record CoReading(DateTimeOffset MeasuredAt, Guid GasId, decimal? Value, string RecordedBy); diff --git a/src/LageBuch.Domain/CoMeasurement/CoSeverity.cs b/src/LageBuch.Domain/CoMeasurement/CoSeverity.cs index 9a84c4f8..eea9ba70 100644 --- a/src/LageBuch.Domain/CoMeasurement/CoSeverity.cs +++ b/src/LageBuch.Domain/CoMeasurement/CoSeverity.cs @@ -1,9 +1,9 @@ namespace LageBuch.Domain.CoMeasurement; -/// How dangerous a ppm reading is, independent of (which -/// tracks search progress, not the measured value). Bands anchor on the German AGW -/// (Arbeitsplatzgrenzwert, 30 ppm 8h-TWA) at the low end and the commonly-cited CO lethality -/// range (800+ ppm: collapse/death within 2-3h) at the high end. +/// How dangerous a gas reading is, independent of (which +/// tracks search progress, not the measured value). Each gas sets its own bands in the +/// Stammdaten (#410, see ); the name dates from when CO was the only +/// gas. public enum CoSeverity { Normal, diff --git a/src/LageBuch.Domain/CoMeasurement/CoSeverityClassifier.cs b/src/LageBuch.Domain/CoMeasurement/CoSeverityClassifier.cs deleted file mode 100644 index 94216b56..00000000 --- a/src/LageBuch.Domain/CoMeasurement/CoSeverityClassifier.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace LageBuch.Domain.CoMeasurement; - -public static class CoSeverityClassifier -{ - public const int ElevatedThresholdPpm = 30; - public const int DangerousThresholdPpm = 200; - public const int LethalThresholdPpm = 800; - - /// Above the range a handheld fire-service CO meter typically reads -- not a hard - /// domain limit, just the point where a reading is more likely a typo (e.g. 9999 vs 999) than - /// a real measurement, so the UI can flag it for a second look without rejecting it. - public const int ImplausibleThresholdPpm = 2000; - - public static CoSeverity SeverityOf(int? ppm) => ppm switch - { - >= LethalThresholdPpm => CoSeverity.Lethal, - >= DangerousThresholdPpm => CoSeverity.Dangerous, - >= ElevatedThresholdPpm => CoSeverity.Elevated, - _ => CoSeverity.Normal, - }; - - public static bool IsImplausible(int? ppm) => ppm is { } v && v > ImplausibleThresholdPpm; -} diff --git a/src/LageBuch.Domain/CoMeasurement/Dwelling.cs b/src/LageBuch.Domain/CoMeasurement/Dwelling.cs index 9e7d2a16..76b502da 100644 --- a/src/LageBuch.Domain/CoMeasurement/Dwelling.cs +++ b/src/LageBuch.Domain/CoMeasurement/Dwelling.cs @@ -24,12 +24,17 @@ public sealed record Dwelling /// Only ever set while is . public string? KeyNumber { get; private init; } - public int? CoValue { get; private init; } + /// The current value of each gas measured here, keyed by the incident's own gas id + /// (#410). A gas without a key has no value: never measured, or cleared. + public IReadOnlyDictionary Values { get; private init; } = EmptyValues; - /// Every reading taken here, oldest first; the last one is . - /// Empty for a Wohnung measured before #424 — no history is invented for old files. + /// Every reading taken here, oldest first; per gas, the last one is that gas's entry + /// in . Empty for a Wohnung measured before #424 — no history is invented + /// for old files. public IReadOnlyList Readings { get; private init; } = Array.Empty(); + private static readonly IReadOnlyDictionary EmptyValues = new Dictionary(); + public static Dwelling Create(Guid buildingId, int floorOrdinal, int apartmentNumber) => new() { @@ -54,7 +59,7 @@ public static Dwelling Rehydrate( string? residentName, DwellingStatus status, KeyAvailability keyAvailable, - int? coValue, + IReadOnlyDictionary? values, IEnumerable? readings = null, string? keyNumber = null) => new() @@ -67,32 +72,70 @@ public static Dwelling Rehydrate( Status = status, KeyAvailable = keyAvailable, KeyNumber = keyNumber, - CoValue = coValue, + Values = values is null ? EmptyValues : new Dictionary(values), Readings = (readings ?? Enumerable.Empty()).ToList(), }; + /// This Wohnung with every value and reading dropped whose gas is not among + /// -- what a file or snapshot naming a gas its own list lacks gets on + /// load, so nothing renders against a gas nobody defined. + public Dwelling KeepingGases(IReadOnlySet gasIds) + { + ArgumentNullException.ThrowIfNull(gasIds); + if (Values.Keys.All(gasIds.Contains) && Readings.All(r => gasIds.Contains(r.GasId))) + { + return this; + } + + return this with + { + Values = Values.Where(kv => gasIds.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value), + Readings = Readings.Where(r => gasIds.Contains(r.GasId)).ToList(), + }; + } + + /// The current value of one gas, or null when it has none. + public decimal? ValueOf(Guid gasId) => Values.TryGetValue(gasId, out var value) ? value : null; + /// - /// Records a reading: moves and appends to as one - /// operation, so the value cannot move without leaving a trace — the bug class behind #424. - /// Callers guard against no-op writes themselves (see Incident.RecordCoValue), which is - /// also what keeps a retried sync command from inflating the series. + /// Records readings: moves each gas's entry in and appends one reading per + /// gas to as one operation, all with the same time, so a value cannot + /// move without leaving a trace — the bug class behind #424. Callers pass only gases that + /// changed (see Incident.RecordCoValues), which is also what keeps a retried sync command + /// from inflating the series. /// - public Dwelling WithCoReading(int? coValue, DateTimeOffset measuredAt, string recordedBy) => this with + public Dwelling WithCoReadings(IEnumerable> changes, DateTimeOffset measuredAt, string recordedBy) { - CoValue = coValue, - Readings = new List(Readings) { new(measuredAt, coValue, recordedBy) }, - }; + ArgumentNullException.ThrowIfNull(changes); + var values = new Dictionary(Values); + var readings = new List(Readings); + foreach (var (gasId, value) in changes) + { + if (value is { } v) + { + values[gasId] = v; + } + else + { + values.Remove(gasId); + } + + readings.Add(new CoReading(measuredAt, gasId, value, recordedBy)); + } + + return this with { Values = values, Readings = readings }; + } /// Whether a crew ever recorded anything here — what makes deleting this Wohnung /// worth asking about rather than doing silently (#419). is checked in - /// its own right and not folded into : clearing a measurement is itself + /// its own right and not folded into : clearing a measurement is itself /// recorded as a reading (see ), so a corrected Wohnung has a null /// value and a real history behind it. public bool HasData => ResidentName is not null || Status != DwellingStatus.NotSearched || KeyAvailable != KeyAvailability.Unknown - || CoValue is not null + || Values.Count > 0 || Readings.Count > 0; public Dwelling WithStatus(DwellingStatus status) => this with { Status = status }; diff --git a/src/LageBuch.Domain/CoMeasurement/GasDefinition.cs b/src/LageBuch.Domain/CoMeasurement/GasDefinition.cs new file mode 100644 index 00000000..ad457888 --- /dev/null +++ b/src/LageBuch.Domain/CoMeasurement/GasDefinition.cs @@ -0,0 +1,134 @@ +namespace LageBuch.Domain.CoMeasurement; + +/// +/// One gas a brigade measures (#410): its name, its unit, which way it gets worse and up to three +/// bands. It lives in the Stammdaten as the "Messgase" list and is copied by value into an incident +/// the first time that incident opens a Haus (see ), so editing the +/// Stammdaten later never changes how an old Messprotokoll reads. +/// +/// +/// Every threshold is optional. A gas without any is recorded and shown in neutral: it never earns +/// a colour nobody configured. only ever produces a "check this" hint, +/// never a rejection. +/// +public sealed record GasDefinition( + string Name, + string Unit, + GasDirection Direction, + decimal? Elevated, + decimal? Dangerous, + decimal? Lethal, + decimal? PlausibleUpTo) +{ + /// The longest list a brigade can keep. Enforced in the editor, on import, and on an + /// incident's copied list arriving from a file or a sync peer. + public const int MaxCount = 8; + + /// A gas name is a tile label ("H2S", "CH4"), not a sentence. + public const int MaxNameLength = 12; + + public const int MaxUnitLength = 10; + + /// The largest reading accepted. Far above any handheld meter's range; it is there + /// because the value also arrives from a sync peer. + public const decimal MaxValue = 100_000m; + + /// A reading keeps two decimals: 20,9 Vol-% O₂ needs one, %UEG sometimes two. + public const int MaxDecimals = 2; + + /// The gas every Einsatz had before #410, and what a Stammdaten without a Messgase + /// list still yields: CO in ppm with the bands the app always used, so a brigade that never + /// opens the new tab sees no change. + public static GasDefinition DefaultCo { get; } = new("CO", "ppm", GasDirection.Rising, 30m, 200m, 800m, 2000m); + + /// What the editor offers for ; the unit itself stays free text. + public static IReadOnlyList UnitSuggestions { get; } = ["ppm", "%UEG", "Vol-%", "mg/m³"]; + + /// Whether the thresholds that are set climb in the gas's own direction: + /// Erhöht < Gefährlich < Lebensgefährlich for a rising gas, the reverse for a falling + /// one. Missing thresholds are skipped, so 30 / — / 800 is in order. + public bool ThresholdsInOrder + { + get + { + decimal? previous = null; + foreach (var threshold in new[] { Elevated, Dangerous, Lethal }) + { + if (threshold is not { } current) + { + continue; + } + + if (previous is { } p && (Direction == GasDirection.Rising ? current <= p : current >= p)) + { + return false; + } + + previous = current; + } + + return true; + } + } + + /// + /// The same gas with every rule that cannot be trusted from outside applied: name and unit + /// trimmed and cut to their caps, an unknown direction read as rising, a negative or oversized + /// number dropped, and thresholds that are out of order dropped altogether, so the gas falls + /// back to neutral rather than showing a colour it has not earned. Returns null for a gas + /// without a name. Used on everything an incident file or a sync peer hands over; the + /// Stammdaten import rejects out-of-order thresholds outright instead. + /// + public GasDefinition? Sanitized() + { + var name = Cut(Name, MaxNameLength); + if (name.Length == 0) + { + return null; + } + + var sanitized = new GasDefinition( + name, + Cut(Unit, MaxUnitLength), + Enum.IsDefined(Direction) ? Direction : GasDirection.Rising, + InRange(Elevated), + InRange(Dangerous), + InRange(Lethal), + InRange(PlausibleUpTo)); + return sanitized.ThresholdsInOrder ? sanitized : sanitized with { Elevated = null, Dangerous = null, Lethal = null }; + } + + /// Caps a list at after sanitising each entry and dropping + /// nameless and same-named ones (first wins, case-insensitive). + public static IReadOnlyList SanitizeList(IEnumerable? gases) + { + var result = new List(); + foreach (var gas in gases ?? []) + { + if (gas?.Sanitized() is { } clean + && !result.Exists(g => string.Equals(g.Name, clean.Name, StringComparison.OrdinalIgnoreCase))) + { + result.Add(clean); + if (result.Count == MaxCount) + { + break; + } + } + } + + return result; + } + + /// Rounds a reading to , or returns null when it cannot be + /// a reading at all (negative or above ). + public static decimal? NormalizeValue(decimal value) => + value is < 0 or > MaxValue ? null : decimal.Round(value, MaxDecimals, MidpointRounding.AwayFromZero); + + private static decimal? InRange(decimal? value) => value is { } v ? NormalizeValue(v) : null; + + private static string Cut(string? value, int max) + { + var trimmed = (value ?? string.Empty).Trim(); + return trimmed.Length > max ? trimmed[..max].TrimEnd() : trimmed; + } +} diff --git a/src/LageBuch.Domain/CoMeasurement/GasDirection.cs b/src/LageBuch.Domain/CoMeasurement/GasDirection.cs new file mode 100644 index 00000000..47c14c19 --- /dev/null +++ b/src/LageBuch.Domain/CoMeasurement/GasDirection.cs @@ -0,0 +1,12 @@ +namespace LageBuch.Domain.CoMeasurement; + +/// Which way a gas gets worse (#410). Almost every gas is ; O₂ is the +/// one a crew watches fall. A gas has exactly one direction, so O₂ enrichment is out of scope. +public enum GasDirection +{ + /// "steigend" — a higher reading is worse. + Rising, + + /// "fallend" — a lower reading is worse. + Falling, +} diff --git a/src/LageBuch.Domain/CoMeasurement/GasSeverityClassifier.cs b/src/LageBuch.Domain/CoMeasurement/GasSeverityClassifier.cs new file mode 100644 index 00000000..50f1b9da --- /dev/null +++ b/src/LageBuch.Domain/CoMeasurement/GasSeverityClassifier.cs @@ -0,0 +1,71 @@ +namespace LageBuch.Domain.CoMeasurement; + +/// Judges a reading against its own gas's bands (#410). Replaces the three CO constants +/// that used to live here: every brigade now sets its own bands in the Stammdaten, and +/// carries the old ones for everybody who does not. +public static class GasSeverityClassifier +{ + /// The band a reading falls in, read in the gas's own direction: a rising gas is + /// Erhöht from its threshold upwards, a falling gas from its threshold downwards. A gas with no + /// thresholds is always . + public static CoSeverity SeverityOf(GasDefinition gas, decimal? value) + { + ArgumentNullException.ThrowIfNull(gas); + if (value is not { } v) + { + return CoSeverity.Normal; + } + + if (Reached(gas.Direction, v, gas.Lethal)) + { + return CoSeverity.Lethal; + } + + if (Reached(gas.Direction, v, gas.Dangerous)) + { + return CoSeverity.Dangerous; + } + + return Reached(gas.Direction, v, gas.Elevated) ? CoSeverity.Elevated : CoSeverity.Normal; + } + + /// Whether a reading is beyond the gas's Plausibel-bis limit -- more likely a typo + /// (9999 vs 999) than a measurement, so the UI asks for a second look without rejecting it. + /// The limit is an upper bound in either direction: 210 Vol-% O₂ is the typo there. + public static bool IsImplausible(GasDefinition gas, decimal? value) + { + ArgumentNullException.ThrowIfNull(gas); + return value is { } v && gas.PlausibleUpTo is { } limit && v > limit; + } + + /// + /// The reading that decides a Wohnung's colour: the highest severity across its gases, a tie + /// going to the gas earlier in the list, which also makes it the first measured gas while every + /// gas is normal. Null when nothing was measured. + /// + public static GasValue? Worst(IReadOnlyList gases, IReadOnlyDictionary values) + { + ArgumentNullException.ThrowIfNull(gases); + ArgumentNullException.ThrowIfNull(values); + + GasValue? worst = null; + foreach (var gas in gases) + { + if (!values.TryGetValue(gas.Id, out var value)) + { + continue; + } + + var severity = SeverityOf(gas.Definition, value); + if (worst is null || severity > worst.Severity) + { + worst = new GasValue(gas, value, severity); + } + } + + return worst; + } + + private static bool Reached(GasDirection direction, decimal value, decimal? threshold) => + threshold is { } t && (direction == GasDirection.Falling ? value <= t : value >= t); +} diff --git a/src/LageBuch.Domain/CoMeasurement/GasValue.cs b/src/LageBuch.Domain/CoMeasurement/GasValue.cs new file mode 100644 index 00000000..b6ce5f18 --- /dev/null +++ b/src/LageBuch.Domain/CoMeasurement/GasValue.cs @@ -0,0 +1,4 @@ +namespace LageBuch.Domain.CoMeasurement; + +/// One gas's current value in a Wohnung, with the band it falls in (#410). +public sealed record GasValue(IncidentGas Gas, decimal Value, CoSeverity Severity); diff --git a/src/LageBuch.Domain/CoMeasurement/IncidentGas.cs b/src/LageBuch.Domain/CoMeasurement/IncidentGas.cs new file mode 100644 index 00000000..d950b35a --- /dev/null +++ b/src/LageBuch.Domain/CoMeasurement/IncidentGas.cs @@ -0,0 +1,21 @@ +namespace LageBuch.Domain.CoMeasurement; + +/// +/// A gas as an incident holds it (#410): its own copy of a , taken from +/// the Stammdaten when the Einsatz opened its first Haus, with an id that its readings point at. +/// The id belongs to the incident, never to the Stammdaten, so the file reads the same after the +/// Stammdaten are edited, on another Feuerwehr's machine, or years later. +/// +public sealed record IncidentGas(Guid Id, GasDefinition Definition) +{ + /// The id of the CO gas every file from before #410 gets on migration, so its + /// co_value and Messreihe have a gas to belong to. Fixed, because the migration writes + /// it in SQL and the domain falls back on it for a file whose gas table is missing. + public static readonly Guid LegacyCoId = new("c0c0c0c0-0410-4c0c-8c0c-000000000001"); + + public string Name => Definition.Name; + + public string Unit => Definition.Unit; + + public static IncidentGas LegacyCo { get; } = new(LegacyCoId, GasDefinition.DefaultCo); +} diff --git a/src/LageBuch.Domain/Formatting.cs b/src/LageBuch.Domain/Formatting.cs index 00705503..ed223f59 100644 --- a/src/LageBuch.Domain/Formatting.cs +++ b/src/LageBuch.Domain/Formatting.cs @@ -8,6 +8,10 @@ public static class Formatting { private static readonly CultureInfo De = CultureInfo.GetCultureInfo("de-DE"); + /// The de-DE number format, for an input that takes a decimal the way the user types + /// it ("20,9"), whatever culture the device runs in (#410). + public static NumberFormatInfo NumberFormat => De.NumberFormat; + /// A whole number the way the user reads it (de-DE grouping). public static string Number(int value) => value.ToString("N0", De); @@ -64,6 +68,16 @@ public static string Coordinates(GeoPoint point) return $"{lat}° {(point.Latitude < 0 ? "S" : "N")}, {lon}° {(point.Longitude < 0 ? "W" : "O")}"; } + /// A gas reading the way the meter shows it: "20,9 Vol-%", "120 ppm" (#410). At most + /// two decimals and no grouping, so a CO value reads exactly as it did when it was an integer. + /// + public static string Measurement(decimal value, string unit) + { + ArgumentNullException.ThrowIfNull(unit); + var number = value.ToString("0.##", De); + return unit.Length == 0 ? number : $"{number} {unit}"; + } + public static string Timestamp(DateTimeOffset t) => t.ToString("dd.MM.yyyy HH:mm", De); /// A calendar day alone, "27.10.2026", for something dated rather than timed. diff --git a/src/LageBuch.Domain/Incident.cs b/src/LageBuch.Domain/Incident.cs index 1294e2d1..d7908e32 100644 --- a/src/LageBuch.Domain/Incident.cs +++ b/src/LageBuch.Domain/Incident.cs @@ -43,6 +43,7 @@ public sealed class Incident private readonly List _tasks = new(); private readonly List _buildings = new(); private readonly List _dwellings = new(); + private readonly List _gases = new(); private readonly List _involvedParties = new(); private readonly List _situationReports = new(); private readonly List _issuedItems = new(); @@ -118,6 +119,11 @@ private Incident() public IReadOnlyList Dwellings => _dwellings; + /// The gases this Einsatz measures, in display order (#410): a copy of the Stammdaten + /// list taken when the first Haus was opened, never a reference into them. Empty until then. + /// + public IReadOnlyList Gases => _gases; + /// The Beteiligte — people involved who are not forces — in creation order. public IReadOnlyList InvolvedParties => _involvedParties; @@ -216,7 +222,8 @@ public static Incident Rehydrate( LeadershipPost? leadershipPost = null, GeoPoint? location = null, IReadOnlyDictionary? navOverrides = null, - IEnumerable? mapOverlays = null) + IEnumerable? mapOverlays = null, + IEnumerable? gases = null) { var incident = new Incident { @@ -255,7 +262,9 @@ public static Incident Rehydrate( incident._files.AddRange(files); incident._tasks.AddRange(tasks); incident._buildings.AddRange(buildings); - incident._dwellings.AddRange(dwellings); + incident._gases.AddRange(RehydrateGases(gases, incident._buildings.Count > 0)); + var gasIds = incident._gases.Select(g => g.Id).ToHashSet(); + incident._dwellings.AddRange(dwellings.Select(d => d.KeepingGases(gasIds))); incident._involvedParties.AddRange(involvedParties); incident._situationReports.AddRange(situationReports ?? []); incident._issuedItems.AddRange(issuedItems ?? []); @@ -2369,7 +2378,8 @@ private AtemschutzTrupp FindScbaTrupp(Guid truppId) => _scbaTrupps.FirstOrDefault(t => t.Id == truppId); // apartmentLabels are copied from an Objekt in the Stammdaten (#420): the Haus keeps them as - // its own, and nothing points back at the Objekt. + // its own, and nothing points back at the Objekt. gases are the Stammdaten Messgase (#410), + // copied the same way -- but only by the first Haus; after that the Einsatz keeps its list. public void AddCoBuilding( IClock clock, SessionOperator op, @@ -2377,12 +2387,19 @@ public void AddCoBuilding( int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0, - IReadOnlyDictionary? apartmentLabels = null) + IReadOnlyDictionary? apartmentLabels = null, + IEnumerable? gases = null) { EnsureOpen(); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(op); + if (_gases.Count == 0) + { + var copied = GasDefinition.SanitizeList(gases); + _gases.AddRange((copied.Count > 0 ? copied : [GasDefinition.DefaultCo]).Select(g => new IncidentGas(Guid.NewGuid(), g))); + } + var ordinal = _buildings.Count; var building = Building.Create(name, floorCount, apartmentsPerFloor, ordinal, undergroundFloorCount, apartmentLabels); _buildings.Add(building); @@ -2398,7 +2415,7 @@ public void AddCoBuilding( AppendSystemEntry( clock, op, - $"CO-Messprotokoll eröffnet: {building.Name} ({FloorRangeLabel(undergroundFloorCount, floorCount)}, {apartmentsPerFloor} Wohnungen je Geschoss)"); + $"Gasmessprotokoll eröffnet: {building.Name} ({FloorRangeLabel(undergroundFloorCount, floorCount)}, {apartmentsPerFloor} Wohnungen je Geschoss)"); } // Underground floor count defaults to 0 so a pre-#218 sync payload (no such property on the @@ -2419,7 +2436,7 @@ public void UpdateCoBuildingStructure(IClock clock, SessionOperator op, Guid bui .Where(d => d.BuildingId == buildingId && (d.FloorOrdinal > floorCount || d.FloorOrdinal < -undergroundFloorCount)) .GroupBy(d => d.FloorOrdinal) .OrderByDescending(g => g.Key) - .Select(g => (Count: g.Count(), Text: RemovedFloorDescription(building, g.Key, g.OrderBy(d => d.ApartmentNumber).ToList()))) + .Select(g => (Count: g.Count(), Text: RemovedFloorDescription(building, g.Key, g.OrderBy(d => d.ApartmentNumber).ToList(), _gases))) .ToList(); var index = _buildings.IndexOf(building); @@ -2480,11 +2497,11 @@ public void UpdateCoBuildingStructure(IClock clock, SessionOperator op, Guid bui /// Wohnung that carried something a crew put there, by the label they had on screen (#443). /// Same notion of "carried" as the #419 picker: a Bezeichnung counts, since it lives on the /// Building and Dwelling.HasData can't see it. - private static string RemovedFloorDescription(Building building, int floorOrdinal, List onFloor) + private static string RemovedFloorDescription(Building building, int floorOrdinal, List onFloor, List gases) { var carrying = onFloor .Where(d => d.HasData || building.HasApartmentLabel(floorOrdinal, d.ApartmentNumber)) - .Select(d => $"{CoMeasurementLabels.ApartmentLabel(building, floorOrdinal, d.ApartmentNumber)}{DwellingContentSuffix(d)}") + .Select(d => $"{CoMeasurementLabels.ApartmentLabel(building, floorOrdinal, d.ApartmentNumber)}{DwellingContentSuffix(d, gases)}") .ToList(); var contents = carrying.Count > 0 ? $": {string.Join(", ", carrying)}" : ", leer"; @@ -2501,40 +2518,73 @@ public void RemoveCoBuilding(IClock clock, SessionOperator op, Guid buildingId) _buildings.Remove(building); _dwellings.RemoveAll(d => d.BuildingId == buildingId); - AppendSystemEntry(clock, op, $"CO-Messprotokoll entfernt: {building.Name}"); + AppendSystemEntry(clock, op, $"Gasmessprotokoll entfernt: {building.Name}"); } - public void RecordCoValue(IClock clock, SessionOperator op, Guid buildingId, int floorOrdinal, int apartmentNumber, int? coValue) + /// + /// Records what a crew measured in one Wohnung at one FERTIG (#410): one reading per gas that + /// changed, all with the same time, and one ETB entry naming them all -- + /// "Gasmessung Haus A, 2. OG, Whg. 1: CO 120 ppm, H2S 3 ppm". A null value clears that gas. + /// + public void RecordCoValues(IClock clock, SessionOperator op, Guid buildingId, int floorOrdinal, int apartmentNumber, IReadOnlyDictionary values) { EnsureOpen(); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(op); + ArgumentNullException.ThrowIfNull(values); + + if (values.Count > GasDefinition.MaxCount) + { + throw new ArgumentOutOfRangeException(nameof(values), $"Höchstens {GasDefinition.MaxCount} Messgase."); + } - if (coValue is < 0) + if (values.Keys.Any(id => !_gases.Exists(g => g.Id == id))) { - throw new ArgumentOutOfRangeException(nameof(coValue), "CO-Messwert darf nicht negativ sein."); + throw new ArgumentException("Unbekanntes Messgas.", nameof(values)); } var building = FindBuilding(buildingId); var dwelling = FindDwelling(buildingId, floorOrdinal, apartmentNumber); - // No-op writes return before anything is recorded. This is what keeps a retried or - // duplicated RecordCoValueCommand from inflating the series, and it is deliberately the - // same guard that already suppresses a duplicate ETB line. Consequence worth knowing: a - // genuine re-measurement that returns the identical value is not captured. - if (dwelling.CoValue == coValue) + var changes = new List>(); + var parts = new List(); + foreach (var gas in _gases) + { + if (!values.TryGetValue(gas.Id, out var raw)) + { + continue; + } + + decimal? value = null; + if (raw is { } r) + { + value = GasDefinition.NormalizeValue(r) + ?? throw new ArgumentOutOfRangeException(nameof(values), $"Messwert {gas.Name} liegt außerhalb von 0 bis {Formatting.Measurement(GasDefinition.MaxValue, gas.Unit)}."); + } + + // No-op writes are skipped before anything is recorded. This is what keeps a retried or + // duplicated command from inflating the series, and it is deliberately the same guard + // that already suppresses a duplicate ETB line. Consequence worth knowing: a genuine + // re-measurement that returns the identical value is not captured. + if (dwelling.ValueOf(gas.Id) == value) + { + continue; + } + + changes.Add(new(gas.Id, value)); + parts.Add(value is { } v ? CoMeasurementLabels.GasValueLabel(gas, v, withName: true) : $"{gas.Name} gelöscht"); + } + + if (changes.Count == 0) { return; } var index = _dwellings.IndexOf(dwelling); - _dwellings[index] = dwelling.WithCoReading(coValue, clock.Now, op.Display); + _dwellings[index] = dwelling.WithCoReadings(changes, clock.Now, op.Display); var location = CoMeasurementLabels.DwellingLocation(building, floorOrdinal, apartmentNumber); - var text = coValue is { } v - ? $"CO-Messung {location}: {v} ppm" - : $"CO-Messung {location}: Messwert gelöscht"; - AppendMeasurementEntry(clock, op, text); + AppendMeasurementEntry(clock, op, $"Gasmessung {location}: {string.Join(", ", parts)}"); } public void SetDwellingStatus(IClock clock, SessionOperator op, Guid buildingId, int floorOrdinal, int apartmentNumber, DwellingStatus status) @@ -2700,7 +2750,7 @@ public void RemoveDwellings(IClock clock, SessionOperator op, Guid buildingId, i // effective label back would freeze "Rechts" onto a survivor as if a crew had typed it. var removedLabels = onFloor .Where(d => doomed.Contains(d.ApartmentNumber)) - .Select(d => $"{CoMeasurementLabels.ApartmentLabel(building, floorOrdinal, d.ApartmentNumber)}{DwellingContentSuffix(d)}") + .Select(d => $"{CoMeasurementLabels.ApartmentLabel(building, floorOrdinal, d.ApartmentNumber)}{DwellingContentSuffix(d, _gases)}") .ToList(); var carriedLabels = new Dictionary(); @@ -2733,7 +2783,34 @@ public void RemoveDwellings(IClock clock, SessionOperator op, Guid buildingId, i /// What a Wohnung was carrying, for the ETB line that records its removal (#419) -- /// the point being that the log says what was lost, not just how many. - private static string DwellingContentSuffix(Dwelling dwelling) + // A file or snapshot hands its gas list over as stored, so it is sanitised and capped like any + // other outside input. A file with Häuser but no gases is one whose gas table went missing: + // its readings carry the legacy CO id, so that gas is what it gets back. + private static List RehydrateGases(IEnumerable? gases, bool hasBuildings) + { + var result = new List(); + foreach (var gas in gases ?? []) + { + if (gas.Definition.Sanitized() is { } clean + && !result.Exists(g => g.Id == gas.Id || string.Equals(g.Name, clean.Name, StringComparison.OrdinalIgnoreCase))) + { + result.Add(gas with { Definition = clean }); + if (result.Count == GasDefinition.MaxCount) + { + break; + } + } + } + + if (result.Count == 0 && hasBuildings) + { + result.Add(IncidentGas.LegacyCo); + } + + return result; + } + + private static string DwellingContentSuffix(Dwelling dwelling, List gases) { var carried = new List(); if (dwelling.ResidentName is not null) @@ -2746,9 +2823,10 @@ private static string DwellingContentSuffix(Dwelling dwelling) carried.Add(dwelling.Status == DwellingStatus.Searched ? "durchsucht" : "betroffen"); } - if (dwelling.CoValue is { } ppm) + var measured = CoMeasurementLabels.ValuesInOrder(gases, dwelling.Values); + if (measured.Count > 0) { - carried.Add($"{ppm} ppm"); + carried.AddRange(measured.Select(m => CoMeasurementLabels.GasValueLabel(m.Gas, m.Value, gases.Count > 1))); } else if (dwelling.Readings.Count > 0) { diff --git a/src/LageBuch.Persistence/IncidentRepository.cs b/src/LageBuch.Persistence/IncidentRepository.cs index 88632d5a..23940546 100644 --- a/src/LageBuch.Persistence/IncidentRepository.cs +++ b/src/LageBuch.Persistence/IncidentRepository.cs @@ -3,6 +3,7 @@ using System.Globalization; using LageBuch.Domain; using LageBuch.Domain.Leadership; +using LageBuch.Persistence.MasterData; using LageBuch.Persistence.Sqlite; using Microsoft.Data.Sqlite; @@ -64,7 +65,7 @@ private static void Write(string path, Incident incident, bool migrate) "role_assignments", "force_units", "force_unit_edits", "scba_trupps", "scba_trupp_members", "scba_pressure_readings", "audit_events", "incident_timers", "incident_files", "incident_tasks", - "co_buildings", "co_dwellings", "co_readings", "involved_parties", "situation_reports", + "co_buildings", "co_dwellings", "co_readings", "co_gases", "involved_parties", "situation_reports", "issued_items", "command_nodes", "map_overlays", }) { @@ -116,6 +117,7 @@ private static void Write(string path, Incident incident, bool migrate) WriteTimers(inserts, incident); WriteFiles(inserts, incident); WriteCoBuildings(inserts, incident); + WriteCoGases(inserts, incident); WriteCoDwellings(inserts, incident); WriteTasks(inserts, incident); WriteInvolvedParties(inserts, incident); @@ -409,6 +411,30 @@ private static void WriteCoBuildings(InsertCommands inserts, Incident incident) } } + // The incident's own copy of its gases (#410), in display order. Decimals as invariant text. + private static void WriteCoGases(InsertCommands inserts, Incident incident) + { + for (var i = 0; i < incident.Gases.Count; i++) + { + var g = incident.Gases[i]; + Run( + inserts, + "INSERT INTO co_gases (id, ordinal, name, unit, direction, elevated, dangerous, lethal, plausible_up_to) VALUES ($id,$o,$n,$u,$d,$e,$g,$l,$p);", + p => + { + p("$id", g.Id.ToString()); + p("$o", i); + p("$n", g.Name); + p("$u", g.Unit); + p("$d", (int)g.Definition.Direction); + p("$e", (object?)GasDefinitionJson.ToText(g.Definition.Elevated) ?? DBNull.Value); + p("$g", (object?)GasDefinitionJson.ToText(g.Definition.Dangerous) ?? DBNull.Value); + p("$l", (object?)GasDefinitionJson.ToText(g.Definition.Lethal) ?? DBNull.Value); + p("$p", (object?)GasDefinitionJson.ToText(g.Definition.PlausibleUpTo) ?? DBNull.Value); + }); + } + } + private static void WriteCoDwellings(InsertCommands inserts, Incident incident) { for (var i = 0; i < incident.Dwellings.Count; i++) @@ -416,7 +442,7 @@ private static void WriteCoDwellings(InsertCommands inserts, Incident incident) var d = incident.Dwellings[i]; Run( inserts, - "INSERT INTO co_dwellings (id, building_id, floor_ordinal, apartment_number, resident_name, status, key_available, co_value, key_number) VALUES ($id,$bid,$fo,$an,$rn,$st,$kv,$cv,$kn);", + "INSERT INTO co_dwellings (id, building_id, floor_ordinal, apartment_number, resident_name, status, key_available, gas_values, key_number) VALUES ($id,$bid,$fo,$an,$rn,$st,$kv,$gv,$kn);", p => { p("$id", d.Id.ToString()); @@ -426,7 +452,8 @@ private static void WriteCoDwellings(InsertCommands inserts, Incident incident) p("$rn", (object?)d.ResidentName ?? DBNull.Value); p("$st", (int)d.Status); p("$kv", Domain.CoMeasurement.KeyAvailabilityEncoding.ToNullableBool(d.KeyAvailable) is { } k ? (k ? 1 : 0) : DBNull.Value); - p("$cv", (object?)d.CoValue ?? DBNull.Value); + p("$gv", System.Text.Json.JsonSerializer.Serialize( + d.Values.ToDictionary(kv => kv.Key.ToString(), kv => GasDefinitionJson.ToText(kv.Value)))); p("$kn", (object?)d.KeyNumber ?? DBNull.Value); }); @@ -435,14 +462,15 @@ private static void WriteCoDwellings(InsertCommands inserts, Incident incident) var reading = d.Readings[j]; Run( inserts, - "INSERT INTO co_readings (id, dwelling_id, ordinal, measured_at, value, recorded_by) " + "VALUES ($id,$did,$o,$at,$v,$by);", + "INSERT INTO co_readings (id, dwelling_id, ordinal, measured_at, gas_id, measured_value, recorded_by) " + "VALUES ($id,$did,$o,$at,$g,$v,$by);", p => { p("$id", Guid.NewGuid().ToString()); p("$did", d.Id.ToString()); p("$o", j); p("$at", reading.MeasuredAt.ToString(Iso)); - p("$v", (object?)reading.Value ?? DBNull.Value); + p("$g", reading.GasId.ToString()); + p("$v", (object?)GasDefinitionJson.ToText(reading.Value) ?? DBNull.Value); p("$by", reading.RecordedBy); }); } @@ -890,17 +918,39 @@ public static Incident Load(string path) // Grouped up front rather than queried per Wohnung, the same shape as strengthEditsByUnit // above. Ordered by dwelling_id as well as ordinal: grouping alone would survive a bare // "ORDER BY ordinal", but the series' order is the whole point of storing it. + // A reading whose gas id does not parse is dropped here; one naming a gas the list lacks is + // dropped by Incident.Rehydrate, which applies the same rule to a sync snapshot. var readingsByDwelling = ReadAll( cn, - "SELECT dwelling_id, measured_at, value, recorded_by FROM co_readings ORDER BY dwelling_id, ordinal;", + "SELECT dwelling_id, measured_at, gas_id, measured_value, recorded_by FROM co_readings ORDER BY dwelling_id, ordinal;", r => (DwellingId: Guid.Parse(r.GetString(0)), - Reading: new Domain.CoMeasurement.CoReading(ParseDate(r.GetString(1)), NullableInt(r, 2), r.GetString(3)))) + GasId: NullableGuid(r, 2), + MeasuredAt: ParseDate(r.GetString(1)), + Value: GasDefinitionJson.FromText(Str(r, 3)), + RecordedBy: r.GetString(4))) + .Where(x => x.GasId is not null) .GroupBy(x => x.DwellingId) - .ToDictionary(g => g.Key, g => g.Select(x => x.Reading).ToList()); + .ToDictionary( + g => g.Key, + g => g.Select(x => new Domain.CoMeasurement.CoReading(x.MeasuredAt, x.GasId.GetValueOrDefault(), x.Value, x.RecordedBy)).ToList()); + + var gases = ReadAll( + cn, + "SELECT id, name, unit, direction, elevated, dangerous, lethal, plausible_up_to FROM co_gases ORDER BY ordinal;", + r => new Domain.CoMeasurement.IncidentGas( + Guid.Parse(r.GetString(0)), + new Domain.CoMeasurement.GasDefinition( + r.GetString(1), + r.GetString(2), + (Domain.CoMeasurement.GasDirection)r.GetInt32(3), + GasDefinitionJson.FromText(Str(r, 4)), + GasDefinitionJson.FromText(Str(r, 5)), + GasDefinitionJson.FromText(Str(r, 6)), + GasDefinitionJson.FromText(Str(r, 7))))); var dwellings = ReadAll( cn, - "SELECT id, building_id, floor_ordinal, apartment_number, resident_name, status, key_available, co_value, key_number FROM co_dwellings ORDER BY floor_ordinal, apartment_number;", + "SELECT id, building_id, floor_ordinal, apartment_number, resident_name, status, key_available, gas_values, key_number FROM co_dwellings ORDER BY floor_ordinal, apartment_number;", r => { var id = Guid.Parse(r.GetString(0)); @@ -912,7 +962,7 @@ public static Incident Load(string path) Str(r, 4), (Domain.CoMeasurement.DwellingStatus)r.GetInt32(5), Domain.CoMeasurement.KeyAvailabilityEncoding.FromNullableBool(r.IsDBNull(6) ? null : r.GetInt32(6) == 1), - NullableInt(r, 7), + GasValues(r.GetString(7)), readingsByDwelling.TryGetValue(id, out var rs) ? rs : null, Str(r, 8)); }); @@ -1058,7 +1108,8 @@ public static Incident Load(string path) meta[14] as string, meta[15] as string, meta[16] as string, FunkgruppenJson.Read(meta[17] as string), meta[21] as string), Domain.ValueObjects.GeoPoint.TryCreate(Real(meta[18]), Real(meta[19])), NavOverridesJson.Read(meta[20] as string), - mapOverlays); + mapOverlays, + gases); } private static DateTimeOffset ParseDate(string s) => @@ -1079,6 +1130,23 @@ private static DateTimeOffset ParseDate(string s) => _ => null, }; + // co_dwellings.gas_values (#410): gas id -> invariant decimal text. An entry whose key or value + // does not parse is dropped rather than failing the whole file. + private static Dictionary GasValues(string json) + { + var raw = System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; + var values = new Dictionary(); + foreach (var (key, text) in raw) + { + if (Guid.TryParse(key, out var gasId) && GasDefinitionJson.FromText(text) is { } value) + { + values[gasId] = value; + } + } + + return values; + } + // TryParse rather than Parse: an unreadable id degrades to "no Sicherheitstrupp recorded", // which is the same stance Rehydrate takes on a stored crew -- a file that opens imperfectly // beats one that will not open at all. diff --git a/src/LageBuch.Persistence/MasterData/GasDefinitionJson.cs b/src/LageBuch.Persistence/MasterData/GasDefinitionJson.cs new file mode 100644 index 00000000..039e7a99 --- /dev/null +++ b/src/LageBuch.Persistence/MasterData/GasDefinitionJson.cs @@ -0,0 +1,93 @@ +using System.Globalization; +using System.Text.Json; +using LageBuch.Domain.CoMeasurement; + +namespace LageBuch.Persistence.MasterData; + +/// +/// The Messgase list's file format (#410): the spelling of a gas's direction, and the reading of +/// the gases array from a Stammdaten file. A file is hostile input -- an import, or a sync +/// host's /masterdata -- so everything here either clamps or throws one of the exception +/// types the callers already catch (, , +/// , ). +/// +internal static class GasDefinitionJson +{ + public static string DirectionName(GasDirection direction) => + direction == GasDirection.Falling ? "fallend" : "steigend"; + + /// Total, like Role.UniquenessFrom: anything that is not "fallend" is rising, + /// because a hand-edited file may carry anything and rising is how every gas but O₂ reads. + public static GasDirection DirectionFrom(string? name) => + string.Equals(name?.Trim(), "fallend", StringComparison.OrdinalIgnoreCase) ? GasDirection.Falling : GasDirection.Rising; + + /// + /// Reads gases. Absent, not an array or empty yields + /// alone, so a file from before #410 measures exactly what it always did. Names and units are + /// trimmed and cut to their caps, same-named gases after the first are dropped, and the list is + /// cut at . A threshold that is not a number, or is out of + /// range, fails the read; thresholds out of order reject the file outright with a German + /// message, because guessing which of them the brigade meant would colour a Wohnung wrongly. + /// + public static IReadOnlyList Parse(JsonElement root) + { + if (!root.TryGetProperty("gases", out var arr) || arr.ValueKind != JsonValueKind.Array) + { + return [GasDefinition.DefaultCo]; + } + + var read = new List(); + foreach (var x in arr.EnumerateArray()) + { + if (x.ValueKind != JsonValueKind.Object) + { + continue; + } + + var gas = new GasDefinition( + x.GetProperty("name").GetString() ?? throw new JsonException("Messgas: \"name\" darf nicht null sein."), + x.TryGetProperty("unit", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() ?? string.Empty : string.Empty, + DirectionFrom(x.TryGetProperty("direction", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null), + Number(x, "elevated"), + Number(x, "dangerous"), + Number(x, "lethal"), + Number(x, "plausibleUpTo")); + if (!gas.ThresholdsInOrder) + { + throw new JsonException($"Messgas „{gas.Name.Trim()}“: Schwellen nicht in Reihenfolge."); + } + + read.Add(gas); + } + + var gases = GasDefinition.SanitizeList(read); + return gases.Count > 0 ? gases : [GasDefinition.DefaultCo]; + } + + /// A decimal the way the store and the incident file keep it: invariant culture, no + /// grouping, so it reads back the same on any machine. + public static string? ToText(decimal? value) => value?.ToString(CultureInfo.InvariantCulture); + + /// The reverse of . Text that is not a number reads as null -- + /// a stored file is not the place to fail an Einsatz over one threshold. + public static decimal? FromText(string? text) => + decimal.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out var value) ? value : null; + + // A JSON null or a missing key is "not set"; anything else must be a number in range. GetDecimal + // throws FormatException for a number decimal cannot hold, and a string or NaN is refused here. + private static decimal? Number(JsonElement e, string key) + { + if (!e.TryGetProperty(key, out var v) || v.ValueKind == JsonValueKind.Null) + { + return null; + } + + if (v.ValueKind != JsonValueKind.Number) + { + throw new FormatException($"Messgas: \"{key}\" muss eine Zahl sein."); + } + + return GasDefinition.NormalizeValue(v.GetDecimal()) + ?? throw new JsonException($"Messgas: \"{key}\" liegt außerhalb von 0 bis {GasDefinition.MaxValue.ToString(CultureInfo.InvariantCulture)}."); + } +} diff --git a/src/LageBuch.Persistence/MasterData/MasterDataSet.cs b/src/LageBuch.Persistence/MasterData/MasterDataSet.cs index 0bb93581..d6bbfca1 100644 --- a/src/LageBuch.Persistence/MasterData/MasterDataSet.cs +++ b/src/LageBuch.Persistence/MasterData/MasterDataSet.cs @@ -60,6 +60,11 @@ public sealed record MasterDataSet( // lands in an incident, so renaming one here never changes a past Einsatz. IReadOnlyList TalkGroups, + // Messgase (#410): the gases a crew measures in the Gasmessung, at most eight, each with its + // unit and bands. Copied into an incident when it opens its first Haus (#337); nothing points + // back here. Like Settings, never empty -- a store without any yields CO alone. + IReadOnlyList Gases, + // Operational defaults (timers, durations). Unlike the lists, always populated — a store with // no overrides yields IncidentSettings.Defaults, never a zeroed record. IncidentSettings Settings) @@ -85,6 +90,7 @@ public sealed record MasterDataSet( Array.Empty(), Array.Empty(), Array.Empty(), + [GasDefinition.DefaultCo], IncidentSettings.Defaults); /// @@ -95,6 +101,7 @@ public sealed record MasterDataSet( /// mark the set non-empty would ask for confirmation on an otherwise fresh install. /// is excluded for exactly the same reason — a layout saved once would /// otherwise permanently turn the silent bootstrap into a confirm prompt. + /// is excluded too: like Settings it always carries at least the default CO. /// public bool IsEmpty => Roles.Count == 0 @@ -1136,6 +1143,7 @@ private static MasterDataSet ParseRoot(JsonElement root) ParsePremises(root), ParseDevices(root), ParseTalkGroups(root), + GasDefinitionJson.Parse(root), ParseSettings(root)); } @@ -1575,6 +1583,16 @@ public static string Serialize(MasterDataSet set) etb = t.ForEtb, tasks = t.ForTasks, }), + gases = set.Gases.Select(g => new + { + name = g.Name, + unit = g.Unit, + direction = GasDefinitionJson.DirectionName(g.Direction), + elevated = g.Elevated, + dangerous = g.Dangerous, + lethal = g.Lethal, + plausibleUpTo = g.PlausibleUpTo, + }), premises = set.Premises.Select(p => new { name = p.Name, diff --git a/src/LageBuch.Persistence/MasterData/MasterDataStore.cs b/src/LageBuch.Persistence/MasterData/MasterDataStore.cs index 2812e8ed..6d97a4bc 100644 --- a/src/LageBuch.Persistence/MasterData/MasterDataStore.cs +++ b/src/LageBuch.Persistence/MasterData/MasterDataStore.cs @@ -1,6 +1,7 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json; using LageBuch.Domain.Atemschutz; +using LageBuch.Domain.CoMeasurement; using LageBuch.Domain.Leadership; using LageBuch.Persistence.Sqlite; using Microsoft.Data.Sqlite; @@ -194,6 +195,25 @@ public static void Save(string path, MasterDataSet set) }); } + Run(cn, tx, "DELETE FROM md_gases;", _ => { }); + foreach (var g in set.Gases) + { + Run( + cn, + tx, + "INSERT INTO md_gases (name, unit, direction, elevated, dangerous, lethal, plausible_up_to) VALUES ($n,$u,$d,$e,$g,$l,$p);", + p => + { + p("$n", g.Name); + p("$u", g.Unit); + p("$d", (int)g.Direction); + p("$e", (object?)GasDefinitionJson.ToText(g.Elevated) ?? DBNull.Value); + p("$g", (object?)GasDefinitionJson.ToText(g.Dangerous) ?? DBNull.Value); + p("$l", (object?)GasDefinitionJson.ToText(g.Lethal) ?? DBNull.Value); + p("$p", (object?)GasDefinitionJson.ToText(g.PlausibleUpTo) ?? DBNull.Value); + }); + } + WriteChecklists(cn, tx, set.ChecklistTemplates); WriteNavigation(cn, tx, set.Navigation); @@ -346,6 +366,7 @@ private static void EnsureSchema(SqliteConnection cn) CREATE TABLE IF NOT EXISTS md_links (name TEXT NOT NULL, url TEXT NOT NULL, group_name TEXT NOT NULL DEFAULT ''); CREATE TABLE IF NOT EXISTS md_vehicles (wache TEXT NOT NULL, call_sign TEXT NOT NULL, seats INTEGER NOT NULL DEFAULT 0, has_zugfuehrer INTEGER NOT NULL DEFAULT 0, is_own INTEGER NOT NULL DEFAULT 1, phone TEXT, email TEXT, vehicle_type TEXT); CREATE TABLE IF NOT EXISTS md_talk_groups (value TEXT NOT NULL, number TEXT, kind TEXT NOT NULL, note TEXT, is_favorite INTEGER NOT NULL DEFAULT 0); + CREATE TABLE IF NOT EXISTS md_gases (name TEXT NOT NULL, unit TEXT NOT NULL DEFAULT '', direction INTEGER NOT NULL DEFAULT 0, elevated TEXT, dangerous TEXT, lethal TEXT, plausible_up_to TEXT); CREATE TABLE IF NOT EXISTS md_checklist_lists ( id TEXT PRIMARY KEY, ordinal INTEGER NOT NULL, @@ -503,6 +524,15 @@ apartment_labels TEXT NOT NULL DEFAULT '{}' // The favourite flag (#833). A store from before it reads 0: no favourites, as it was. SchemaHelpers.AddColumnIfMissing(cn, null, "md_talk_groups", "is_favorite", "INTEGER NOT NULL DEFAULT 0"); + // md_gases' optional columns (#410): the table is new, but #397's sweep holds every + // repairable column to the same rule. + SchemaHelpers.AddColumnIfMissing(cn, null, "md_gases", "unit", "TEXT NOT NULL DEFAULT ''"); + SchemaHelpers.AddColumnIfMissing(cn, null, "md_gases", "direction", "INTEGER NOT NULL DEFAULT 0"); + SchemaHelpers.AddColumnIfMissing(cn, null, "md_gases", "elevated", "TEXT"); + SchemaHelpers.AddColumnIfMissing(cn, null, "md_gases", "dangerous", "TEXT"); + SchemaHelpers.AddColumnIfMissing(cn, null, "md_gases", "lethal", "TEXT"); + SchemaHelpers.AddColumnIfMissing(cn, null, "md_gases", "plausible_up_to", "TEXT"); + // Wachen and Funkrufnamen used to be lists of their own; they are derived from md_vehicles // (and md_personnel) now. Drop the stale tables a pre-change store still carries -- their // rows were never more than the names already on the vehicles, and nothing reads them. @@ -669,6 +699,7 @@ private static MasterDataSet Read(SqliteConnection cn) ReadPremises(cn), ReadDevices(cn), ReadTalkGroups(cn), + ReadGases(cn), ReadSettings(cn)); } @@ -971,6 +1002,30 @@ private static List ReadTalkGroups(SqliteConnection cn) return list; } + // Rowid order is the list order. A store saved before #410 has no rows and reads as CO alone; + // the rows are sanitised on the way in, because the file may have been edited by hand. + private static IReadOnlyList ReadGases(SqliteConnection cn) + { + using var cmd = cn.CreateCommand(); + cmd.CommandText = "SELECT name, unit, direction, elevated, dangerous, lethal, plausible_up_to FROM md_gases;"; + using var r = cmd.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(new GasDefinition( + r.GetString(0), + r.GetString(1), + (GasDirection)r.GetInt32(2), + GasDefinitionJson.FromText(Str(r, 3)), + GasDefinitionJson.FromText(Str(r, 4)), + GasDefinitionJson.FromText(Str(r, 5)), + GasDefinitionJson.FromText(Str(r, 6)))); + } + + var gases = GasDefinition.SanitizeList(list); + return gases.Count > 0 ? gases : [GasDefinition.DefaultCo]; + } + private static List ReadPersonnel(SqliteConnection cn) { using var cmd = cn.CreateCommand(); diff --git a/src/LageBuch.Persistence/Sqlite/Migrations.cs b/src/LageBuch.Persistence/Sqlite/Migrations.cs index 72a55ab0..efab505e 100644 --- a/src/LageBuch.Persistence/Sqlite/Migrations.cs +++ b/src/LageBuch.Persistence/Sqlite/Migrations.cs @@ -8,7 +8,7 @@ namespace LageBuch.Persistence.Sqlite; public static class Migrations { - public const int CurrentVersion = 42; + public const int CurrentVersion = 43; public static int GetVersion(SqliteConnection cn) { @@ -295,6 +295,11 @@ public static void Migrate(SqliteConnection cn) ApplyV42(cn, tx); } + if (version < 43) + { + ApplyV43(cn, tx); + } + // The version gate above is not proof that the steps it skipped ever ran: a build from a // parallel branch numbers its own migrations too, so a file can carry a marker this lineage // never put there and be missing a column no `version < N` will ever add back. Reconcile the @@ -1266,6 +1271,72 @@ internal static Domain.Leadership.Funkgruppen FunkgruppenFromSingle(string value return new([trimmed.StartsWith("TMO ", StringComparison.OrdinalIgnoreCase) ? trimmed[4..].Trim() : trimmed], null); } + // #410: up to eight gases instead of one CO value. The incident gets its own gas table -- a + // copy of the Stammdaten list, never a reference into it -- and the current values move into a + // per-gas JSON map on co_dwellings, the shape floor_descriptions already has. Readings gain the + // gas they belong to and a decimal value kept as invariant text (20.9 Vol-% O2 is not an + // INTEGER). Every file from before carries exactly one gas, CO, with the bands the app always + // used: this step writes that gas and moves co_value and the Messreihe onto it, so nothing is + // lost and nothing reads as an unnamed gas. co_value and co_readings.value stay where they are, + // unread: SchemaGuard never drops a column, and neither does a migration here. + private static void ApplyV43(SqliteConnection cn, SqliteTransaction tx) + { + const string sql43 = """ + CREATE TABLE IF NOT EXISTS co_gases ( + id TEXT PRIMARY KEY, + ordinal INTEGER NOT NULL, + name TEXT NOT NULL, + unit TEXT NOT NULL DEFAULT '', + direction INTEGER NOT NULL DEFAULT 0, + elevated TEXT, + dangerous TEXT, + lethal TEXT, + plausible_up_to TEXT + ); + """; + Exec(cn, tx, sql43); + SchemaHelpers.AddColumnIfMissing(cn, tx, "co_dwellings", "gas_values", "TEXT NOT NULL DEFAULT '{}'"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "co_readings", "gas_id", "TEXT"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "co_readings", "measured_value", "TEXT"); + + // Each backfill only where its table exists, the way AddColumnIfMissing skips a missing + // table: a file need not carry every table an older step would have created. + const string legacyGas = """ + INSERT INTO co_gases (id, ordinal, name, unit, direction, elevated, dangerous, lethal, plausible_up_to) + SELECT $id, 0, 'CO', 'ppm', 0, '30', '200', '800', '2000' + WHERE EXISTS (SELECT 1 FROM co_buildings) AND NOT EXISTS (SELECT 1 FROM co_gases); + """; + const string legacyValues = "UPDATE co_dwellings SET gas_values = json_object($id, CAST(co_value AS TEXT)) WHERE co_value IS NOT NULL;"; + const string legacyReadings = "UPDATE co_readings SET gas_id = $id, measured_value = CAST(value AS TEXT) WHERE gas_id IS NULL;"; + if (SchemaHelpers.TableExists(cn, tx, "co_buildings")) + { + ExecWithLegacyCoId(cn, tx, legacyGas); + } + + if (SchemaHelpers.TableExists(cn, tx, "co_dwellings")) + { + ExecWithLegacyCoId(cn, tx, legacyValues); + } + + if (SchemaHelpers.TableExists(cn, tx, "co_readings")) + { + ExecWithLegacyCoId(cn, tx, legacyReadings); + } + } + + [SuppressMessage( + "Security", + "CA2100", + Justification = "Audited: SQL is migration data built from compile-time constants; the gas id is a bound parameter.")] + private static void ExecWithLegacyCoId(SqliteConnection cn, SqliteTransaction tx, string sql) + { + using var cmd = cn.CreateCommand(); + cmd.Transaction = tx; + cmd.CommandText = sql; + cmd.Parameters.AddWithValue("$id", Domain.CoMeasurement.IncidentGas.LegacyCoId.ToString()); + cmd.ExecuteNonQuery(); + } + private static void SetVersion(SqliteConnection cn, SqliteTransaction tx, int version) { Exec(cn, tx, "DELETE FROM schema_version;"); diff --git a/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs b/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs index 57278b91..047ac2f5 100644 --- a/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs +++ b/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs @@ -39,6 +39,7 @@ internal static class SchemaGuard "checklist_lists", "co_buildings", "co_dwellings", + "co_gases", "co_readings", "command_nodes", "etb_entries", @@ -76,7 +77,16 @@ internal static class SchemaGuard new("co_dwellings", "key_available", "INTEGER", false, null), new("co_dwellings", "co_value", "INTEGER", false, null), new("co_dwellings", "key_number", "TEXT", false, null), + new("co_dwellings", "gas_values", "TEXT", true, "'{}'"), + new("co_gases", "unit", "TEXT", true, "''"), + new("co_gases", "direction", "INTEGER", true, "0"), + new("co_gases", "elevated", "TEXT", false, null), + new("co_gases", "dangerous", "TEXT", false, null), + new("co_gases", "lethal", "TEXT", false, null), + new("co_gases", "plausible_up_to", "TEXT", false, null), new("co_readings", "value", "INTEGER", false, null), + new("co_readings", "gas_id", "TEXT", false, null), + new("co_readings", "measured_value", "TEXT", false, null), new("command_nodes", "parent_id", "TEXT", false, null), new("command_nodes", "auftrag", "TEXT", false, null), new("command_nodes", "standort", "TEXT", false, null), diff --git a/src/LageBuch.Sync/CommandApplier.cs b/src/LageBuch.Sync/CommandApplier.cs index a25a2c99..4cfa5fa8 100644 --- a/src/LageBuch.Sync/CommandApplier.cs +++ b/src/LageBuch.Sync/CommandApplier.cs @@ -301,7 +301,7 @@ public static class CommandApplier incident.ExtendTaskTimer(c.TaskId, c.Minutes, clock); break; case AddCoBuildingCommand c: - incident.AddCoBuilding(clock, Operator(c.Operator), c.Name, c.FloorCount, c.ApartmentsPerFloor, c.UndergroundFloorCount, c.ApartmentLabels); + incident.AddCoBuilding(clock, Operator(c.Operator), c.Name, c.FloorCount, c.ApartmentsPerFloor, c.UndergroundFloorCount, c.ApartmentLabels, c.Gases?.OfType().Select(g => g.ToDefinition())); break; case UpdateCoBuildingStructureCommand c: incident.UpdateCoBuildingStructure(clock, Operator(c.Operator), c.BuildingId, c.FloorCount, c.ApartmentsPerFloor, c.UndergroundFloorCount); @@ -309,8 +309,8 @@ public static class CommandApplier case RemoveCoBuildingCommand c: incident.RemoveCoBuilding(clock, Operator(c.Operator), c.BuildingId); break; - case RecordCoValueCommand c: - incident.RecordCoValue(clock, Operator(c.Operator), c.BuildingId, c.FloorOrdinal, c.ApartmentNumber, c.CoValue); + case RecordCoValuesCommand c: + incident.RecordCoValues(clock, Operator(c.Operator), c.BuildingId, c.FloorOrdinal, c.ApartmentNumber, GasValues(c.Values)); break; case SetDwellingStatusCommand c: incident.SetDwellingStatus(clock, Operator(c.Operator), c.BuildingId, c.FloorOrdinal, c.ApartmentNumber, c.Status); @@ -367,4 +367,26 @@ dx is null && dy is null ? null : LabelOffset.TryCreate(dx, dy) ?? throw new ArgumentException("Ungültiger Versatz.", nameof(dx)); + + // A peer's list, capped before anything is built from it: more than eight values, or one gas + // named twice, is a malformed command and is refused as one (ArgumentException, which the host + // turns into a 400). Incident.RecordCoValues checks the ids against the Einsatz's own list. + private static Dictionary GasValues(IReadOnlyList? values) + { + if (values is null || values.Count > GasDefinition.MaxCount) + { + throw new ArgumentOutOfRangeException(nameof(values), $"Höchstens {GasDefinition.MaxCount} Messgase."); + } + + var result = new Dictionary(); + foreach (var value in values) + { + if (value is null || !result.TryAdd(value.GasId, value.Value)) + { + throw new ArgumentException("Messgas doppelt oder leer.", nameof(values)); + } + } + + return result; + } } diff --git a/src/LageBuch.Sync/IIncidentSession.cs b/src/LageBuch.Sync/IIncidentSession.cs index e0e1068e..f34fecd6 100644 --- a/src/LageBuch.Sync/IIncidentSession.cs +++ b/src/LageBuch.Sync/IIncidentSession.cs @@ -330,13 +330,16 @@ void AddCoBuilding( int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0, - IReadOnlyDictionary? apartmentLabels = null); + IReadOnlyDictionary? apartmentLabels = null, + IReadOnlyList? gases = null); void UpdateCoBuildingStructure(Guid buildingId, int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0); void RemoveCoBuilding(Guid buildingId); - void RecordCoValue(Guid buildingId, int floorOrdinal, int apartmentNumber, int? coValue); + /// Records one FERTIG's gas values (#410), keyed by the Einsatz's own gas ids; a null + /// value clears that gas. See . + void RecordCoValues(Guid buildingId, int floorOrdinal, int apartmentNumber, IReadOnlyDictionary values); void SetDwellingStatus(Guid buildingId, int floorOrdinal, int apartmentNumber, DwellingStatus status); diff --git a/src/LageBuch.Sync/IncidentSnapshot.cs b/src/LageBuch.Sync/IncidentSnapshot.cs index d9050dd3..aadcd991 100644 --- a/src/LageBuch.Sync/IncidentSnapshot.cs +++ b/src/LageBuch.Sync/IncidentSnapshot.cs @@ -85,7 +85,12 @@ public sealed record IncidentSnapshot( // The Kartenebenen, metadata only: the geometry is a file, fetched like any attachment. A // snapshot without the key reads as no Ebenen. - IReadOnlyList? MapOverlays = null); + IReadOnlyList? MapOverlays = null, + + // Protocol 39 (#410): the Einsatz's own gas list. A joined client shows exactly this, never + // its own Stammdaten. Null reads as no list, which Incident.Rehydrate turns into the legacy CO + // gas once a Haus exists. + IReadOnlyList? Gases = null); public sealed record MapOverlayDto( Guid Id, @@ -266,7 +271,11 @@ public sealed record BuildingDto( public sealed record DwellingDto( Guid Id, Guid BuildingId, int FloorOrdinal, int ApartmentNumber, - string? ResidentName, DwellingStatus Status, bool? KeyAvailable, int? CoValue, + string? ResidentName, DwellingStatus Status, bool? KeyAvailable, + + // Protocol 26 (#410): the current value per gas, keyed by the Einsatz's own gas id. Replaced + // the single CoValue, which is why the floor rose with it. + IReadOnlyDictionary? Values, // Appended with a default, the BuildingDto convention: a snapshot written before #424 has no // readings key, deserializes to null, and maps to an empty series. That default is this @@ -276,6 +285,25 @@ public sealed record DwellingDto( // Protocol 24, appended the same way: a snapshot without it reads as no Schlüsselnummer. string? KeyNumber = null); -/// One CO reading on the wire; the JSON-shaped sibling of +/// One gas reading on the wire; the JSON-shaped sibling of /// . -public sealed record CoReadingDto(DateTimeOffset MeasuredAt, int? Value, string RecordedBy); +public sealed record CoReadingDto(DateTimeOffset MeasuredAt, Guid GasId, decimal? Value, string RecordedBy); + +/// A gas definition on the wire (#410): a Messgas from the Stammdaten in +/// , or the definition half of an . +/// Hostile like everything a peer sends: runs on the way +/// in. +public sealed record GasDefinitionDto( + string Name, string Unit, GasDirection Direction, decimal? Elevated, decimal? Dangerous, decimal? Lethal, decimal? PlausibleUpTo) +{ + public static GasDefinitionDto From(GasDefinition gas) + { + ArgumentNullException.ThrowIfNull(gas); + return new(gas.Name, gas.Unit, gas.Direction, gas.Elevated, gas.Dangerous, gas.Lethal, gas.PlausibleUpTo); + } + + public GasDefinition ToDefinition() => new(Name, Unit, Direction, Elevated, Dangerous, Lethal, PlausibleUpTo); +} + +/// One of the Einsatz's own gases on the wire; mirrors . +public sealed record IncidentGasDto(Guid Id, GasDefinitionDto Definition); diff --git a/src/LageBuch.Sync/RemoteIncidentSession.cs b/src/LageBuch.Sync/RemoteIncidentSession.cs index 8d1d637f..a2124099 100644 --- a/src/LageBuch.Sync/RemoteIncidentSession.cs +++ b/src/LageBuch.Sync/RemoteIncidentSession.cs @@ -943,8 +943,9 @@ public void AddCoBuilding( int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0, - IReadOnlyDictionary? apartmentLabels = null) => - Send(new AddCoBuildingCommand(Op(), name, floorCount, apartmentsPerFloor, undergroundFloorCount, apartmentLabels)); + IReadOnlyDictionary? apartmentLabels = null, + IReadOnlyList? gases = null) => + Send(new AddCoBuildingCommand(Op(), name, floorCount, apartmentsPerFloor, undergroundFloorCount, apartmentLabels, gases?.Select(GasDefinitionDto.From).ToList())); public void UpdateCoBuildingStructure(Guid buildingId, int floorCount, int apartmentsPerFloor, int undergroundFloorCount = 0) => Send(new UpdateCoBuildingStructureCommand(Op(), buildingId, floorCount, apartmentsPerFloor, undergroundFloorCount)); @@ -952,8 +953,11 @@ public void UpdateCoBuildingStructure(Guid buildingId, int floorCount, int apart public void RemoveCoBuilding(Guid buildingId) => Send(new RemoveCoBuildingCommand(Op(), buildingId)); - public void RecordCoValue(Guid buildingId, int floorOrdinal, int apartmentNumber, int? coValue) => - Send(new RecordCoValueCommand(Op(), buildingId, floorOrdinal, apartmentNumber, coValue)); + public void RecordCoValues(Guid buildingId, int floorOrdinal, int apartmentNumber, IReadOnlyDictionary values) + { + ArgumentNullException.ThrowIfNull(values); + Send(new RecordCoValuesCommand(Op(), buildingId, floorOrdinal, apartmentNumber, values.Select(kv => new GasValueDto(kv.Key, kv.Value)).ToList())); + } public void SetDwellingStatus(Guid buildingId, int floorOrdinal, int apartmentNumber, DwellingStatus status) => Send(new SetDwellingStatusCommand(Op(), buildingId, floorOrdinal, apartmentNumber, status)); diff --git a/src/LageBuch.Sync/SnapshotMapper.cs b/src/LageBuch.Sync/SnapshotMapper.cs index de070550..27da09a9 100644 --- a/src/LageBuch.Sync/SnapshotMapper.cs +++ b/src/LageBuch.Sync/SnapshotMapper.cs @@ -102,8 +102,8 @@ public static IncidentSnapshot ToSnapshot(Incident incident) d.ResidentName, d.Status, d.KeyAvailable.ToNullableBool(), - d.CoValue, - d.Readings.Select(r => new CoReadingDto(r.MeasuredAt, r.Value, r.RecordedBy)).ToList(), + d.Values.ToDictionary(kv => kv.Key, kv => kv.Value), + d.Readings.Select(r => new CoReadingDto(r.MeasuredAt, r.GasId, r.Value, r.RecordedBy)).ToList(), d.KeyNumber)).ToList(), incident.InvolvedParties.Select(p => new InvolvedPartyDto(p.Id, p.Name, p.Phone, p.Notes, p.CreatedBy, p.CreatedAt, p.DwellingId, p.DwellingLabel, p.Whereabouts, p.WhereaboutsAt)).ToList(), HouseNumber: incident.HouseNumber, @@ -158,7 +158,8 @@ public static IncidentSnapshot ToSnapshot(Incident incident) NavOverrides: incident.NavOverrides.ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.Ordinal), ElFuehrungsfahrzeug: incident.LeadershipPost.Fuehrungsfahrzeug, MapOverlays: incident.MapOverlays.Select(o => new MapOverlayDto( - o.Id, o.FileId, o.Name, o.ImportedAt, o.ImportedBy, o.FrameCount, o.FirstTime, o.LastTime)).ToList()); + o.Id, o.FileId, o.Name, o.ImportedAt, o.ImportedBy, o.FrameCount, o.FirstTime, o.LastTime)).ToList(), + Gases: incident.Gases.Select(g => new IncidentGasDto(g.Id, GasDefinitionDto.From(g.Definition))).ToList()); } public static Incident FromSnapshot(IncidentSnapshot snapshot) @@ -238,8 +239,8 @@ public static Incident FromSnapshot(IncidentSnapshot snapshot) d.ResidentName, d.Status, KeyAvailabilityEncoding.FromNullableBool(d.KeyAvailable), - d.CoValue, - d.Readings?.Select(r => new CoReading(r.MeasuredAt, r.Value, r.RecordedBy)), + d.Values, + d.Readings?.Select(r => new CoReading(r.MeasuredAt, r.GasId, r.Value, r.RecordedBy)), d.KeyNumber)), (snapshot.InvolvedParties ?? []).Select(p => InvolvedParty.Rehydrate(p.Id, p.Name, p.Phone, p.Notes, p.CreatedBy, p.CreatedAt, p.DwellingId, p.DwellingLabel, p.Whereabouts, p.WhereaboutsAt)), snapshot.HouseNumber, @@ -292,7 +293,8 @@ public static Incident FromSnapshot(IncidentSnapshot snapshot) GeoPoint.TryCreate(snapshot.LocationLatitude, snapshot.LocationLongitude), snapshot.NavOverrides, (snapshot.MapOverlays ?? []).Select(o => MapOverlay.Rehydrate( - o.Id, o.FileId, o.Name, o.ImportedAt, o.ImportedBy, o.FrameCount, o.FirstTime, o.LastTime))); + o.Id, o.FileId, o.Name, o.ImportedAt, o.ImportedBy, o.FrameCount, o.FirstTime, o.LastTime)), + snapshot.Gases?.Where(g => g?.Definition is not null).Select(g => new IncidentGas(g.Id, g.Definition.ToDefinition()))); } private static ScbaTruppDto ToDto(AtemschutzTrupp t) => new( diff --git a/src/LageBuch.Sync/SyncCommand.cs b/src/LageBuch.Sync/SyncCommand.cs index 40d6a72f..657aec70 100644 --- a/src/LageBuch.Sync/SyncCommand.cs +++ b/src/LageBuch.Sync/SyncCommand.cs @@ -65,7 +65,7 @@ namespace LageBuch.Sync; [JsonDerivedType(typeof(AddCoBuildingCommand), "addCoBuilding")] [JsonDerivedType(typeof(UpdateCoBuildingStructureCommand), "updateCoBuildingStructure")] [JsonDerivedType(typeof(RemoveCoBuildingCommand), "removeCoBuilding")] -[JsonDerivedType(typeof(RecordCoValueCommand), "recordCoValue")] +[JsonDerivedType(typeof(RecordCoValuesCommand), "recordGasValues")] [JsonDerivedType(typeof(SetDwellingStatusCommand), "setDwellingStatus")] [JsonDerivedType(typeof(UpdateDwellingDetailsCommand), "updateDwellingDetails")] [JsonDerivedType(typeof(SetFloorDescriptionCommand), "setFloorDescription")] @@ -370,14 +370,17 @@ public sealed record ExtendTaskTimerCommand(Guid TaskId, int Minutes) : SyncComm // UndergroundFloorCount defaults to 0 so a pre-#218 payload deserializes as "keine // Untergeschosse" instead of failing the contract (same convention as #76's OfficerCount). // ApartmentLabels are an Objekt's Wohnungsbezeichnungen (#420), optional for the same reason; the -// host keeps only those that fit the Haus (Building.Create). +// host keeps only those that fit the Haus (Building.Create). Gases are the sender's Stammdaten +// Messgase (#410): the host copies them only when this is the Einsatz's first Haus, sanitised and +// capped at eight, and ignores them otherwise. public sealed record AddCoBuildingCommand( OperatorDto Operator, string Name, int FloorCount, int ApartmentsPerFloor, int UndergroundFloorCount = 0, - IReadOnlyDictionary? ApartmentLabels = null) : SyncCommand; + IReadOnlyDictionary? ApartmentLabels = null, + IReadOnlyList? Gases = null) : SyncCommand; public sealed record UpdateCoBuildingStructureCommand( OperatorDto Operator, Guid BuildingId, int FloorCount, int ApartmentsPerFloor, int UndergroundFloorCount = 0) : SyncCommand; @@ -385,8 +388,12 @@ public sealed record UpdateCoBuildingStructureCommand( public sealed record RemoveCoBuildingCommand( OperatorDto Operator, Guid BuildingId) : SyncCommand; -public sealed record RecordCoValueCommand( - OperatorDto Operator, Guid BuildingId, int FloorOrdinal, int ApartmentNumber, int? CoValue) : SyncCommand; +// Protocol 26 (#410): one FERTIG's values, one per changed gas, keyed by the Einsatz's own gas id. +// Replaced recordCoValue, which carried a single integer ppm. A null value clears that gas. +public sealed record RecordCoValuesCommand( + OperatorDto Operator, Guid BuildingId, int FloorOrdinal, int ApartmentNumber, IReadOnlyList Values) : SyncCommand; + +public sealed record GasValueDto(Guid GasId, decimal? Value); public sealed record SetDwellingStatusCommand( OperatorDto Operator, Guid BuildingId, int FloorOrdinal, int ApartmentNumber, DwellingStatus Status) : SyncCommand; diff --git a/src/LageBuch.Sync/SyncProtocol.cs b/src/LageBuch.Sync/SyncProtocol.cs index 060396cd..99839ca2 100644 --- a/src/LageBuch.Sync/SyncProtocol.cs +++ b/src/LageBuch.Sync/SyncProtocol.cs @@ -219,15 +219,23 @@ public static class SyncProtocol /// host at 37 does not know, so the floor rises to 38. The snapshot carries the Ebenen as /// mapOverlays; their files travel over /files like any attachment. /// + /// + /// 39: the Gasmessung measures up to eight gases (#410). recordCoValue is replaced by + /// recordGasValues, which carries decimal values keyed by the Einsatz's own gas ids; the + /// snapshot's Wohnungen carry those values instead of coValue, its readings a gas id, + /// and the snapshot the Einsatz's gas list. addCoBuilding carries the sender's Messgase + /// for the first Haus. A peer at 38 can neither send a value a host at 39 understands nor read + /// one, so the floor rises to 39. + /// /// - public const int ProtocolVersion = 38; + public const int ProtocolVersion = 39; /// /// The oldest contract this build still speaks. A peer below it is refused with a message naming /// which end to update; a peer at or above it is served. See for /// when to raise this. /// - public const int MinimumProtocolVersion = 38; + public const int MinimumProtocolVersion = 39; /// /// What an absent or zero protocol number on the wire means: the contract as it stood at v0.6.1, diff --git a/tests/LageBuch.Acceptance.Tests/AutomationPropertiesTests.cs b/tests/LageBuch.Acceptance.Tests/AutomationPropertiesTests.cs index a732b050..efaf7c52 100644 --- a/tests/LageBuch.Acceptance.Tests/AutomationPropertiesTests.cs +++ b/tests/LageBuch.Acceptance.Tests/AutomationPropertiesTests.cs @@ -431,7 +431,7 @@ public void Every_co_unit_tile_is_named_for_its_unit_and_state() { var (window, _, session) = Workspace(1920, 1032); session.AddCoBuilding("Mehrfamilienhaus A", 2, 2); - WorkspaceRenderHelper.SelectTab(window, "CO-MESSUNG"); + WorkspaceRenderHelper.SelectTab(window, "GASMESSUNG"); Dispatcher.UIThread.RunJobs(); List