diff --git a/CHANGELOG.md b/CHANGELOG.md index 87505881..69d2c85b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ sheets becomes or updates a module, its vendor, a usage for the municipality and a contact person for its owner; a repeat import matches on APPID, so it updates instead of duplicating. See `docs/features/cmdb-import.md`. +- CMDB import, repeat imports: applications that left the CMDB sheets are + archived when the sheet "Gearchiveerde Applicaties" lists them and moved to + OpenRegister's trash when no sheet does; one that returns is unarchived or + restored, never duplicated. The new option `missingRecords` (`archive`, the + default, or `keep`) is a choice in the CMDB import section, and the report + counts archived, unarchived, deleted and restored applications. The module + (0.3.9) and usage (1.5.7) schemas opt into OpenRegister's archive state, and + the Applications and Applications in use pages get an "Archived" quick + filter. (cmdb-import-archive-reconciliation) ### Changed - EOL feed: the register and schema slugs the feature reads from are corrected. diff --git a/docs/features/README.md b/docs/features/README.md index 7fa964f0..c57ff848 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -158,7 +158,7 @@ The ArchiMate integration maps GEMMA Softwarecatalogus objects to ArchiMate appl ## CMDB Import -Import a TOPdesk CMDB export (`.xlsx`) for one municipality from the **CMDB import** section of the admin settings. Every application row of the two CMDB sheets ("Onbeh Applicaties CMDB" and "Beheerde Applicaties CMDB") becomes or updates a module, its vendor as a Supplier organisation, a usage that links it to the municipality and records whether maintenance is arranged, and a contact person for its owner (identity in Nextcloud Contacts, never public). A repeat import matches on APPID per municipality, so it updates instead of duplicating, and leaves applications missing from the newer export as they are. The column mapping is declarative JSON executed by OpenRegister's mapping engine. +Import a TOPdesk CMDB export (`.xlsx`) for one municipality from the **CMDB import** section of the admin settings. Every application row of the two CMDB sheets ("Onbeh Applicaties CMDB" and "Beheerde Applicaties CMDB") becomes or updates a module, its vendor as a Supplier organisation, a usage that links it to the municipality and records whether maintenance is arranged, and a contact person for its owner (identity in Nextcloud Contacts, never public). A repeat import matches on APPID per municipality, so it updates instead of duplicating. By default it archives the applications that moved to the sheet "Gearchiveerde Applicaties" and moves those on no sheet any more to OpenRegister's trash, and brings either back when it returns; the admin can choose to keep them instead. The Applications and Applications in use pages list the archive under the quick filter "Archived". The column mapping is declarative JSON executed by OpenRegister's mapping engine. See [CMDB import](cmdb-import.md) for the steps, the expected file structure, the error codes and how to adjust the mapping. diff --git a/docs/features/cmdb-import.md b/docs/features/cmdb-import.md index b9d505ab..d4077f95 100644 --- a/docs/features/cmdb-import.md +++ b/docs/features/cmdb-import.md @@ -17,9 +17,11 @@ updates: in Nextcloud Contacts. Owners are never readable by the public. All of it is stored as OpenRegister objects in the stackiq register. Import a -newer export later and the same applications are updated, not duplicated. +newer export later and the same applications are updated, not duplicated; +applications that left the export are archived or moved to the trash (see +[Repeat imports](#repeat-imports)). -Specification: [`openspec/specs/cmdb-export-import/spec.md`](https://github.com/ConductionNL/stackiq/blob/development/openspec/specs/cmdb-export-import/spec.md) (change archived in [`openspec/changes/archive/2026-10-05-cmdb-export-import/`](https://github.com/ConductionNL/stackiq/tree/development/openspec/changes/archive/2026-10-05-cmdb-export-import)). +Specification: [`openspec/specs/cmdb-export-import/spec.md`](https://github.com/ConductionNL/stackiq/blob/development/openspec/specs/cmdb-export-import/spec.md) (change archived in [`openspec/changes/archive/2026-10-05-cmdb-export-import/`](https://github.com/ConductionNL/stackiq/tree/development/openspec/changes/archive/2026-10-05-cmdb-export-import); archiving and deleting on a repeat import in [`openspec/changes/cmdb-import-archive-reconciliation/`](https://github.com/ConductionNL/stackiq/tree/development/openspec/changes/cmdb-import-archive-reconciliation)). ## Who can import @@ -77,9 +79,15 @@ page in stackiq. and the summary counts them as *created unpublished*. Applications that were imported before keep their publication as it is, whichever you choose. -6. Press **Import**. A progress bar shows how many rows have been processed. - **Cancel import** stops the import before the next row; rows that were - already processed stay imported. The section says whether the server +6. **Applications missing from the export.** **Archive or delete them** is + the default: an application of this municipality that is on neither CMDB + sheet any more is archived or moved to the trash after the last row (see + [Repeat imports](#repeat-imports)). Choose **Keep them as they are** to + leave such applications untouched. +7. Press **Import**. A progress bar shows how many rows have been processed. + **Cancel import** stops the import before the next row, or, while the + missing applications are compared, before the next application; what + was already processed stays imported. The section says whether the server accepted the cancel; one pressed before the server has started on the rows cannot take effect yet, and the section says so. @@ -92,11 +100,15 @@ When the import finishes, the section shows: - the **summary**: rows read, created, updated, unchanged, skipped, failed and warnings, and, when publishing was off, how many applications were - created unpublished; + created unpublished; after a repeat import also how many applications + were archived, unarchived, deleted (moved to the trash) or restored, when + there are any; - **warnings for the whole file**, for example an optional column that is missing; - the **rows** table: sheet, row number, APPID, application, outcome, - and the reasons and warnings for that row. Filter it with **Show rows with + and the reasons and warnings for that row. An application archived or + deleted because it left the export has no row number; its sheet is + `Gearchiveerde Applicaties` when that sheet listed it. Filter it with **Show rows with outcome**, and sort it by clicking a column header. It shows 100 rows at a time; **Show 100 more rows** adds the next ones. The application name links to the module in stackiq. @@ -106,8 +118,10 @@ the same organisation. ## The file -The import reads the two CMDB sheets of the export and ignores all others, -including the `Invoer` sheets they are derived from: +The import reads the two CMDB sheets of the export, and of the sheet +`Gearchiveerde Applicaties` only the `APPID` column (see +[Repeat imports](#repeat-imports)). It ignores all other sheets, including +the `Invoer` sheets they are derived from: | Sheet | What it holds | Recorded on the usage | |---|---|---| @@ -213,9 +227,9 @@ colliding. - **Known APPID, nothing changed**: nothing is saved; the row is reported as *unchanged*. Importing the same export twice creates nothing the second time. -- **APPID missing from a newer export**: the application, its usage and - its contact persons are left as they are. They are not changed, depublished - or deleted. +- **APPID missing from a newer export**: see + [Applications that left the export](#applications-that-left-the-export) + below. - Each application keeps exactly one usage for the municipality. - **Known APPID, but the application belongs to another organisation**: an application found by its match key is only updated when the municipality @@ -243,6 +257,55 @@ OpenRegister refuses to save it, that row is reported as *failed* with the step that failed, and the other rows are imported. Importing again completes the failed row. +### Applications that left the export + +With **Archive or delete them** (the default; `missingRecords=archive` in +the API), the import compares the municipality's applications with the +export after the last row. It looks only at the municipality's own usages +and the applications its import created, never at an application only +another organisation uses or one added by hand. For an application whose +APPID is on neither CMDB sheet: + +| The APPID is | The application and its usage | +|---|---| +| on the sheet `Gearchiveerde Applicaties` | are **archived**: OpenRegister's archive state, with the reason `cmdb-import: on sheet "Gearchiveerde Applicaties"`. Reported as *archived*. | +| on no sheet at all | are **deleted**: moved to OpenRegister's trash, where they stay restorable for 30 days. Reported as *deleted*. | +| on no sheet, and the workbook has no sheet `Gearchiveerde Applicaties` (or it has no `APPID` column) | are **archived**, never deleted, and the result warns that the sheet was not found. A workbook saved without that sheet therefore never moves anything to the trash. | + +An archived or deleted application disappears from the stackiq lists, from +OpenCatalogi and from Portaliq's **Software we use**. In stackiq, the quick +filter **Archived** on the **Applications** and **Applications in use** pages +lists the archive. An OpenCatalogi caller finds archived applications by +adding `_archived=true` to its request. Contact persons are never archived +or deleted: an owner is shared with the municipality's other applications. +An application that is already in the state the export asks for is left +alone and not reported again. + +When an archived or deleted application **returns** in a later export, it is +taken out of the archive (*unarchived*) or out of the trash (*restored*), +and then updated as usual. No second application is created. With **Update +existing records** off, it is skipped as `exists` and stays archived or in +the trash. When an application was deleted by hand and a later import +created it again, the working one is updated and the deleted one stays in +the trash. + +The comparison runs only when the import went through all rows: an import +cancelled or failed before the comparison archives or deletes nothing. +**Cancel import** during the comparison stops it before the next +application; what was archived or deleted until then stays so, and the +result lists it. The progress bar shows the +step as *Checking the applications missing from the export*. Each +application is handled on its own; one that cannot be archived is reported +as *failed* with the step (`archive`, `restore` or `delete`) and the others +continue. Archiving needs module schema 0.3.9 and usage schema 1.5.7 or +later, which declare that their objects can be archived; on an older register configuration each application fails +with the step `archive`, and **Force Update** at the top of the stackiq admin +settings fixes it. + +With **Keep them as they are** (`missingRecords=keep`), the application, its +usage and its contact persons are left as they are: not changed, archived, +depublished or deleted. + ## Owners The owner becomes a **contact person of the municipality**, never a @@ -293,7 +356,8 @@ and the section shows the reason and the error code. | `IMPORT_IN_PROGRESS` | Another CMDB import is running. Only one import runs at a time. | Wait until it has finished and try again. | | `FIELD_INVALID` | A form field of the request has a value the import does not accept, for example an `updateExisting` or `publish` that is neither `true` nor `false`. The message names the field. | Not reachable from the section; reported for API callers. | | `UPLOAD_FAILED` | The file reached the server but could not be stored there. | Try again; the Nextcloud log has the details. | -| `MISSING_RECORDS_UNSUPPORTED` | The request asked to mark or remove records missing from the export. Only keeping them is supported. | Not reachable from the section; reported for API callers. | +| `MISSING_RECORDS_UNSUPPORTED` | The request asked for something other than `keep` or `archive` for records missing from the export, for example `mark` or `remove`. The details list the accepted values. | Not reachable from the section; reported for API callers. | +| `ARCHIVE_UNAVAILABLE` | **Archive or delete them** was chosen, but the OpenRegister on this server cannot archive or restore objects (it is missing or too old). Nothing was read or written. | Choose **Keep them as they are** and import again, or update OpenRegister. | | `MAPPING_UNAVAILABLE` | OpenRegister's mapping engine is missing, or one of the mapping files is invalid. | Update OpenRegister. If you changed a mapping file, check it against the Nextcloud log. | | `READER_UNAVAILABLE` | The Excel reader that ships with OpenRegister cannot be loaded. | Make sure OpenRegister is installed and enabled. | | `NOT_CONFIGURED` | The stackiq register or its schemas cannot be found. | Run **Auto Configure** at the top of the stackiq admin settings. | diff --git a/l10n/en.js b/l10n/en.js index 8dd84a2f..8e95ef02 100644 --- a/l10n/en.js +++ b/l10n/en.js @@ -1038,7 +1038,21 @@ OC.L10N.register( "The stackiq register or its schemas cannot be found. Run Auto Configure at the top of this page, then try again.": "The stackiq register or its schemas cannot be found. Run Auto Configure at the top of this page, then try again.", "Choose a municipality or enter the name of a new one.": "Choose a municipality or enter the name of a new one.", "No running CMDB import has this id.": "No running CMDB import has this id.", - "Only keeping records that are missing from the export is supported.": "Only keeping records that are missing from the export is supported.", + "Applications missing from the export can only be archived or kept.": "Applications missing from the export can only be archived or kept.", + "Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.": "Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.", + "Sheet \"%1$s\" has no column \"%2$s\", so applications missing from the export are archived, not deleted.": "Sheet \"%1$s\" has no column \"%2$s\", so applications missing from the export are archived, not deleted.", + "Sheet \"%s\" was not found, so applications missing from the export are archived, not deleted.": "Sheet \"%s\" was not found, so applications missing from the export are archived, not deleted.", + "Unarchived": "Unarchived", + "Restored": "Restored", + "Archived": "Archived", + "Deleted": "Deleted", + "Applications missing from the export": "Applications missing from the export", + "Archive or delete them": "Archive or delete them", + "Keep them as they are": "Keep them as they are", + "An application of this municipality that is on neither CMDB sheet any more is archived when the sheet \"Gearchiveerde Applicaties\" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.": "An application of this municipality that is on neither CMDB sheet any more is archived when the sheet \"Gearchiveerde Applicaties\" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.", + "Applications missing from the export cannot be archived.": "Applications missing from the export cannot be archived.", + "OpenRegister is missing or too old to archive objects. Choose \"Keep them as they are\" and import again, or update OpenRegister. Nothing was imported.": "OpenRegister is missing or too old to archive objects. Choose \"Keep them as they are\" and import again, or update OpenRegister. Nothing was imported.", + "Checking the applications missing from the export: {processed} of {total}": "Checking the applications missing from the export: {processed} of {total}", "Sheet \"%1$s\" has more than %2$s rows.": "Sheet \"%1$s\" has more than %2$s rows.", "Sheet \"%1$s\" has no column \"%2$s\".": "Sheet \"%1$s\" has no column \"%2$s\".", "Stackiq is not configured: the register or its schemas cannot be found.": "Stackiq is not configured: the register or its schemas cannot be found.", diff --git a/l10n/en.json b/l10n/en.json index 313f968e..0d85cfba 100644 --- a/l10n/en.json +++ b/l10n/en.json @@ -1037,7 +1037,21 @@ "The stackiq register or its schemas cannot be found. Run Auto Configure at the top of this page, then try again.": "The stackiq register or its schemas cannot be found. Run Auto Configure at the top of this page, then try again.", "Choose a municipality or enter the name of a new one.": "Choose a municipality or enter the name of a new one.", "No running CMDB import has this id.": "No running CMDB import has this id.", - "Only keeping records that are missing from the export is supported.": "Only keeping records that are missing from the export is supported.", + "Applications missing from the export can only be archived or kept.": "Applications missing from the export can only be archived or kept.", + "Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.": "Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.", + "Sheet \"%1$s\" has no column \"%2$s\", so applications missing from the export are archived, not deleted.": "Sheet \"%1$s\" has no column \"%2$s\", so applications missing from the export are archived, not deleted.", + "Sheet \"%s\" was not found, so applications missing from the export are archived, not deleted.": "Sheet \"%s\" was not found, so applications missing from the export are archived, not deleted.", + "Unarchived": "Unarchived", + "Restored": "Restored", + "Archived": "Archived", + "Deleted": "Deleted", + "Applications missing from the export": "Applications missing from the export", + "Archive or delete them": "Archive or delete them", + "Keep them as they are": "Keep them as they are", + "An application of this municipality that is on neither CMDB sheet any more is archived when the sheet \"Gearchiveerde Applicaties\" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.": "An application of this municipality that is on neither CMDB sheet any more is archived when the sheet \"Gearchiveerde Applicaties\" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.", + "Applications missing from the export cannot be archived.": "Applications missing from the export cannot be archived.", + "OpenRegister is missing or too old to archive objects. Choose \"Keep them as they are\" and import again, or update OpenRegister. Nothing was imported.": "OpenRegister is missing or too old to archive objects. Choose \"Keep them as they are\" and import again, or update OpenRegister. Nothing was imported.", + "Checking the applications missing from the export: {processed} of {total}": "Checking the applications missing from the export: {processed} of {total}", "Sheet \"%1$s\" has more than %2$s rows.": "Sheet \"%1$s\" has more than %2$s rows.", "Sheet \"%1$s\" has no column \"%2$s\".": "Sheet \"%1$s\" has no column \"%2$s\".", "Stackiq is not configured: the register or its schemas cannot be found.": "Stackiq is not configured: the register or its schemas cannot be found.", diff --git a/l10n/nl.js b/l10n/nl.js index 3151813d..b0311833 100644 --- a/l10n/nl.js +++ b/l10n/nl.js @@ -1106,7 +1106,21 @@ OC.L10N.register( "The stackiq register or its schemas cannot be found. Run Auto Configure at the top of this page, then try again.": "Het stackiq-register of de schema's ervan zijn niet gevonden. Voer bovenaan deze pagina Auto Configure uit en probeer het daarna opnieuw.", "Choose a municipality or enter the name of a new one.": "Kies een gemeente of voer de naam van een nieuwe in.", "No running CMDB import has this id.": "Er loopt geen CMDB-import met deze id.", - "Only keeping records that are missing from the export is supported.": "Alleen het behouden van records die in de export ontbreken, wordt ondersteund.", + "Applications missing from the export can only be archived or kept.": "Applicaties die in de export ontbreken, kunnen alleen worden gearchiveerd of behouden.", + "Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.": "Applicaties die in de export ontbreken, kunnen niet worden gearchiveerd: OpenRegister ontbreekt of is te oud. Kies ervoor ze te behouden, of werk OpenRegister bij.", + "Sheet \"%1$s\" has no column \"%2$s\", so applications missing from the export are archived, not deleted.": "Tabblad \"%1$s\" heeft geen kolom \"%2$s\", dus applicaties die in de export ontbreken, worden gearchiveerd en niet verwijderd.", + "Sheet \"%s\" was not found, so applications missing from the export are archived, not deleted.": "Tabblad \"%s\" is niet gevonden, dus applicaties die in de export ontbreken, worden gearchiveerd en niet verwijderd.", + "Unarchived": "Uit archief gehaald", + "Restored": "Hersteld", + "Archived": "Gearchiveerd", + "Deleted": "Verwijderd", + "Applications missing from the export": "Applicaties die in de export ontbreken", + "Archive or delete them": "Archiveren of verwijderen", + "Keep them as they are": "Laat ze zoals ze zijn", + "An application of this municipality that is on neither CMDB sheet any more is archived when the sheet \"Gearchiveerde Applicaties\" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.": "Een applicatie van deze gemeente die op geen van beide CMDB-tabbladen meer staat, wordt gearchiveerd als het tabblad \"Gearchiveerde Applicaties\" haar noemt, en naar de prullenbak verplaatst als geen enkel tabblad dat doet. Beide verdwijnen uit de lijsten, uit OpenCatalogi en uit Portaliq; een applicatie die in een latere export terugkomt, wordt teruggezet. Staat dat tabblad niet in het bestand, dan worden applicaties alleen gearchiveerd. Kies Laat ze zoals ze zijn om ze ongemoeid te laten.", + "Applications missing from the export cannot be archived.": "Applicaties die in de export ontbreken, kunnen niet worden gearchiveerd.", + "OpenRegister is missing or too old to archive objects. Choose \"Keep them as they are\" and import again, or update OpenRegister. Nothing was imported.": "OpenRegister ontbreekt of is te oud om objecten te archiveren. Kies \"Laat ze zoals ze zijn\" en importeer opnieuw, of werk OpenRegister bij. Er is niets geïmporteerd.", + "Checking the applications missing from the export: {processed} of {total}": "Applicaties controleren die in de export ontbreken: {processed} van {total}", "Sheet \"%1$s\" has more than %2$s rows.": "Tabblad \"%1$s\" heeft meer dan %2$s rijen.", "Sheet \"%1$s\" has no column \"%2$s\".": "Tabblad \"%1$s\" heeft geen kolom \"%2$s\".", "Stackiq is not configured: the register or its schemas cannot be found.": "Stackiq is niet ingesteld: het register of de schema's ervan zijn niet gevonden.", diff --git a/l10n/nl.json b/l10n/nl.json index 680f6f85..92a16d73 100644 --- a/l10n/nl.json +++ b/l10n/nl.json @@ -1105,7 +1105,21 @@ "The stackiq register or its schemas cannot be found. Run Auto Configure at the top of this page, then try again.": "Het stackiq-register of de schema's ervan zijn niet gevonden. Voer bovenaan deze pagina Auto Configure uit en probeer het daarna opnieuw.", "Choose a municipality or enter the name of a new one.": "Kies een gemeente of voer de naam van een nieuwe in.", "No running CMDB import has this id.": "Er loopt geen CMDB-import met deze id.", - "Only keeping records that are missing from the export is supported.": "Alleen het behouden van records die in de export ontbreken, wordt ondersteund.", + "Applications missing from the export can only be archived or kept.": "Applicaties die in de export ontbreken, kunnen alleen worden gearchiveerd of behouden.", + "Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.": "Applicaties die in de export ontbreken, kunnen niet worden gearchiveerd: OpenRegister ontbreekt of is te oud. Kies ervoor ze te behouden, of werk OpenRegister bij.", + "Sheet \"%1$s\" has no column \"%2$s\", so applications missing from the export are archived, not deleted.": "Tabblad \"%1$s\" heeft geen kolom \"%2$s\", dus applicaties die in de export ontbreken, worden gearchiveerd en niet verwijderd.", + "Sheet \"%s\" was not found, so applications missing from the export are archived, not deleted.": "Tabblad \"%s\" is niet gevonden, dus applicaties die in de export ontbreken, worden gearchiveerd en niet verwijderd.", + "Unarchived": "Uit archief gehaald", + "Restored": "Hersteld", + "Archived": "Gearchiveerd", + "Deleted": "Verwijderd", + "Applications missing from the export": "Applicaties die in de export ontbreken", + "Archive or delete them": "Archiveren of verwijderen", + "Keep them as they are": "Laat ze zoals ze zijn", + "An application of this municipality that is on neither CMDB sheet any more is archived when the sheet \"Gearchiveerde Applicaties\" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.": "Een applicatie van deze gemeente die op geen van beide CMDB-tabbladen meer staat, wordt gearchiveerd als het tabblad \"Gearchiveerde Applicaties\" haar noemt, en naar de prullenbak verplaatst als geen enkel tabblad dat doet. Beide verdwijnen uit de lijsten, uit OpenCatalogi en uit Portaliq; een applicatie die in een latere export terugkomt, wordt teruggezet. Staat dat tabblad niet in het bestand, dan worden applicaties alleen gearchiveerd. Kies Laat ze zoals ze zijn om ze ongemoeid te laten.", + "Applications missing from the export cannot be archived.": "Applicaties die in de export ontbreken, kunnen niet worden gearchiveerd.", + "OpenRegister is missing or too old to archive objects. Choose \"Keep them as they are\" and import again, or update OpenRegister. Nothing was imported.": "OpenRegister ontbreekt of is te oud om objecten te archiveren. Kies \"Laat ze zoals ze zijn\" en importeer opnieuw, of werk OpenRegister bij. Er is niets geïmporteerd.", + "Checking the applications missing from the export: {processed} of {total}": "Applicaties controleren die in de export ontbreken: {processed} van {total}", "Sheet \"%1$s\" has more than %2$s rows.": "Tabblad \"%1$s\" heeft meer dan %2$s rijen.", "Sheet \"%1$s\" has no column \"%2$s\".": "Tabblad \"%1$s\" heeft geen kolom \"%2$s\".", "Stackiq is not configured: the register or its schemas cannot be found.": "Stackiq is niet ingesteld: het register of de schema's ervan zijn niet gevonden.", diff --git a/lib/Controller/CmdbImportController.php b/lib/Controller/CmdbImportController.php index 7d1c00a8..bc7869cb 100644 --- a/lib/Controller/CmdbImportController.php +++ b/lib/Controller/CmdbImportController.php @@ -86,7 +86,8 @@ public function __construct( * Import a TOPdesk CMDB export for one municipality. * * Multipart fields: `cmdbFile`, `municipalityUuid` or `municipalityName`, - * `updateExisting` (default true), `publish` (default true), `missingRecords` (only `keep`) and + * `updateExisting` (default true), `publish` (default true), `missingRecords` (`keep` or `archive`, + * default `archive`) and * `operationId` (pattern `cmdb-` plus 8 to 64 letters, digits or hyphens). * * @return JSONResponse The report (200), or an error envelope with the contract code. @@ -94,6 +95,7 @@ public function __construct( * @auth admin-only the import writes with RBAC and multitenancy off, across tenants, so only a full Nextcloud admin may run it. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-8 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012 */ public function import(): JSONResponse { try { @@ -247,15 +249,21 @@ protected function iniBytes(string $name): ?int { * @return array{path: string, options: array}|JSONResponse The import input, or the first error. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-8 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012 */ private function readOptions(string $path, string $fileName): array|JSONResponse { - $missingRecords = $this->stringParam(name: 'missingRecords', default: 'keep'); + $missingRecords = $this->stringParam(name: 'missingRecords', default: CmdbExportImportService::DEFAULT_MISSING_RECORDS); if ($missingRecords === null) { return $this->invalidField(field: 'missingRecords'); } - if ($this->importService->supportsMissingRecords(mode: $missingRecords) === false) { - return $this->error(code: 'MISSING_RECORDS_UNSUPPORTED', status: Http::STATUS_UNPROCESSABLE_ENTITY, details: ['accepted' => ['keep']]); + $accepted = $this->importService->missingRecordsModes(); + if (in_array($missingRecords, $accepted, true) === false) { + return $this->error( + code: 'MISSING_RECORDS_UNSUPPORTED', + status: Http::STATUS_UNPROCESSABLE_ENTITY, + details: ['accepted' => $accepted] + ); } // An unrecognised value is refused rather than read as true: true is the mode that overwrites. @@ -293,6 +301,7 @@ private function readOptions(string $path, string $fileName): array|JSONResponse 'municipalityName' => $municipalityName, 'updateExisting' => $updateExisting, 'publish' => $publish, + 'missingRecords' => $missingRecords, 'operationId' => $this->request->getParam('operationId'), 'fileName' => basename(str_replace('\\', '/', $fileName)), ], @@ -394,7 +403,7 @@ private function message(string $code, array $details): string { 'NO_FILE_UPLOADED' => $this->l10n->t('No file was uploaded.'), 'NOT_XLSX' => $this->l10n->t('The file is not an Excel workbook (.xlsx).'), 'FILE_TOO_LARGE' => $this->l10n->t('The file is larger than the maximum of %s MB.', [$megabytes]), - 'MISSING_RECORDS_UNSUPPORTED' => $this->l10n->t('Only keeping records that are missing from the export is supported.'), + 'MISSING_RECORDS_UNSUPPORTED' => $this->l10n->t('Applications missing from the export can only be archived or kept.'), 'FIELD_INVALID' => $this->fieldMessage(field: (string)($details['field'] ?? ''), accepted: $accepted), 'MUNICIPALITY_REQUIRED' => $this->l10n->t('Choose a municipality or enter the name of a new one.'), 'MUNICIPALITY_INVALID' => $this->l10n->t('The chosen organisation is not a municipality.'), @@ -410,6 +419,9 @@ private function message(string $code, array $details): string { 'SCHEMA_OUTDATED' => $this->l10n->t('The stackiq register is out of date; import its configuration again.'), 'IMPORT_IN_PROGRESS' => $this->l10n->t('Another CMDB import is running; try again when it has finished.'), 'MUNICIPALITY_AMBIGUOUS' => $this->l10n->t('Several municipalities have this name; choose one from the list.'), + 'ARCHIVE_UNAVAILABLE' => $this->l10n->t( + 'Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.' + ), default => $this->l10n->t('The import failed. The details are in the Nextcloud log.'), }; }//end message() diff --git a/lib/Exception/CmdbImportException.php b/lib/Exception/CmdbImportException.php index 31404c50..65127a9f 100644 --- a/lib/Exception/CmdbImportException.php +++ b/lib/Exception/CmdbImportException.php @@ -50,6 +50,7 @@ class CmdbImportException extends RuntimeException { public const SCHEMA_OUTDATED = 'SCHEMA_OUTDATED'; public const IMPORT_IN_PROGRESS = 'IMPORT_IN_PROGRESS'; public const MUNICIPALITY_AMBIGUOUS = 'MUNICIPALITY_AMBIGUOUS'; + public const ARCHIVE_UNAVAILABLE = 'ARCHIVE_UNAVAILABLE'; /** * HTTP status per error code. @@ -70,6 +71,7 @@ class CmdbImportException extends RuntimeException { self::SCHEMA_OUTDATED => 503, self::IMPORT_IN_PROGRESS => 409, self::MUNICIPALITY_AMBIGUOUS => 422, + self::ARCHIVE_UNAVAILABLE => 503, ]; /** diff --git a/lib/Service/Cmdb/CmdbImportProfile.php b/lib/Service/Cmdb/CmdbImportProfile.php index 1e8805c9..183c02fe 100644 --- a/lib/Service/Cmdb/CmdbImportProfile.php +++ b/lib/Service/Cmdb/CmdbImportProfile.php @@ -332,6 +332,42 @@ public function sheetNames(): array { return array_column($this->sheets(), 'name'); }//end sheetNames() + /** + * The name of the archive sheet, or null when the profile names none. + * + * The archive sheet lists the applications the municipality archived; the + * import reads only its key column (`archiveSheet.name` in the profile). + * + * @return string|null + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + public function archiveSheetName(): ?string { + $name = $this->profile()['archiveSheet']['name'] ?? null; + if (is_string($name) === false || $name === '' || in_array($name, $this->sheetNames(), true) === true) { + return null; + } + + return $name; + }//end archiveSheetName() + + /** + * Every sheet the reader may parse: the source sheets, then the archive sheet. + * + * @return array + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + public function readSheetNames(): array { + $names = $this->sheetNames(); + $archive = $this->archiveSheetName(); + if ($archive !== null) { + $names[] = $archive; + } + + return $names; + }//end readSheetNames() + /** * The rank of a sheet when an APPID is on more than one: lower wins. * @@ -574,19 +610,28 @@ public function neverWrittenOnUpdate(string $target): array { }//end neverWrittenOnUpdate() /** - * The accepted values of the missingRecords option. + * The accepted values of the missingRecords option, readable without validating the packs. + * + * The controller checks the option before the import runs, so, like + * maxFileBytes(), this must not depend on OpenRegister being available. * * @return array * - * @spec openspec/changes/cmdb-export-import/tasks.md#task-8 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012 */ public function missingRecordsModes(): array { - $modes = $this->stringList(key: 'missingRecords'); - if ($modes === []) { + try { + $profile = $this->profile ?? $this->decodeFile(fileName: $this->profileFile); + } catch (CmdbImportException $e) { + return ['keep']; + } + + $modes = $profile['missingRecords'] ?? []; + if (is_array($modes) === false || $modes === []) { return ['keep']; } - return $modes; + return array_values(array_map('strval', $modes)); }//end missingRecordsModes() /** diff --git a/lib/Service/Cmdb/CmdbImportReport.php b/lib/Service/Cmdb/CmdbImportReport.php index 730365fd..2615c8b0 100644 --- a/lib/Service/Cmdb/CmdbImportReport.php +++ b/lib/Service/Cmdb/CmdbImportReport.php @@ -36,6 +36,10 @@ class CmdbImportReport { public const UNCHANGED = 'unchanged'; public const SKIPPED = 'skipped'; public const FAILED = 'failed'; + public const ARCHIVED = 'archived'; + public const UNARCHIVED = 'unarchived'; + public const DELETED = 'deleted'; + public const RESTORED = 'restored'; /** * The row entries, in processing order. @@ -90,7 +94,7 @@ public function __construct( * Add one row outcome. * * @param string $sheet The sheet name. - * @param int $row The 1-based sheet row number. + * @param int $row The 1-based sheet row number, or 0 for an application the reconciliation archived or deleted. * @param string $appId The APPID ('' when missing). * @param string $name The application name ('' when missing). * @param string $outcome One of the outcome constants. @@ -180,14 +184,25 @@ public function markCancelled(): void { }//end markCancelled() /** - * The number of rows processed so far. + * Whether the run stopped on a cancel. + * + * @return bool + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + public function isCancelled(): bool { + return $this->cancelled; + }//end isCancelled() + + /** + * The number of sheet rows processed so far; reconciliation entries (row 0) are not sheet rows. * * @return int * * @spec openspec/changes/cmdb-export-import/tasks.md#task-7 */ public function processed(): int { - return count($this->rows); + return count(array_filter($this->rows, static fn (array $row): bool => $row['row'] > 0)); }//end processed() /** @@ -195,21 +210,28 @@ public function processed(): int { * * `unpublished` counts the modules created without a publication date; * a row whose module was created but whose usage then failed counts too. + * `processed` counts sheet rows only; every outcome, also of a + * reconciliation entry, is counted under its own key. * * @return array{rowsRead: int, processed: int, created: int, updated: int, unchanged: int, skipped: int, failed: int, - * warnings: int, unpublished: int} + * archived: int, unarchived: int, deleted: int, restored: int, warnings: int, unpublished: int} * * @spec openspec/changes/cmdb-export-import/tasks.md#task-7 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 */ public function summary(): array { $summary = [ 'rowsRead' => $this->rowsRead, - 'processed' => count($this->rows), + 'processed' => $this->processed(), self::CREATED => 0, self::UPDATED => 0, self::UNCHANGED => 0, self::SKIPPED => 0, self::FAILED => 0, + self::ARCHIVED => 0, + self::UNARCHIVED => 0, + self::DELETED => 0, + self::RESTORED => 0, 'warnings' => 0, 'unpublished' => $this->unpublished, ]; diff --git a/lib/Service/Cmdb/CmdbWorkbookReader.php b/lib/Service/Cmdb/CmdbWorkbookReader.php index 3ff3e918..9bdf9b9a 100644 --- a/lib/Service/Cmdb/CmdbWorkbookReader.php +++ b/lib/Service/Cmdb/CmdbWorkbookReader.php @@ -42,6 +42,9 @@ * beyond twice the row limit is `TOO_MANY_ROWS`. A read filter then materialises only the * header row and the resolved columns of the rows up to that bound * (CmdbReadFilter), which bounds the cell objects, not the parse. + * 7. The archive sheet ("Gearchiveerde Applicaties"), when the workbook has + * it, counts as a read sheet for every bound above, and only its key + * column is resolved and read (openspec/changes/cmdb-import-archive-reconciliation). * * @category Service * @package OCA\Stackiq\Service\Cmdb @@ -151,17 +154,21 @@ public function isAvailable(): bool { * The sheets are then read twice through a read filter: once for the * header row, once for the resolved columns of the data rows, so no other * cell is ever materialised. + * The archive sheet, when the workbook has it, is read under the same + * bounds as a source sheet, for its key column only. * * @param string $path The xlsx file, already checked by assertXlsx(). * @param CmdbImportProfile $profile The import profile. * * @return array `rows` (list of {sheet, row, cells, uncached}), `importWarnings` - * (list of {sheet, message}) and `date1904` (bool). + * (list of {sheet, message}), `date1904` (bool) and `archive` + * ({sheet, present, keyColumnMissing, appIds}). * * @throws CmdbImportException WORKBOOK_TOO_LARGE, READER_UNAVAILABLE, NOT_XLSX, NO_SOURCE_SHEET, * MISSING_COLUMN or TOO_MANY_ROWS. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-4 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 */ public function read(string $path, CmdbImportProfile $profile): array { $oversized = $this->assertUncompressedSize(path: $path, limit: $profile->maxUncompressedBytes(), partLimit: $profile->maxPartBytes()); @@ -177,7 +184,7 @@ public function read(string $path, CmdbImportProfile $profile): array { $blank = (new CmdbPartReferences())->assertPartSizes( path: $path, oversized: $oversized, - sourceSheets: $profile->sheetNames(), + sourceSheets: $profile->readSheetNames(), limit: $profile->maxPartBytes(), scanner: $scanner ); @@ -303,10 +310,81 @@ private function readBounded(string $path, CmdbImportProfile $profile, object $s $bounds->assertReferencedStringBytes( path: $path, limit: $profile->maxReferencedStringBytes(), - sheetCount: count($profile->sheetNames()), + sheetCount: count($profile->readSheetNames()), scanner: $scanner ); + ['present' => $present, 'available' => $available] = $this->sourceSheets(path: $path, profile: $profile); + + $archiveSheet = $profile->archiveSheetName(); + $loaded = $present; + if ($archiveSheet !== null && in_array($archiveSheet, $available, true) === true) { + $loaded[] = $archiveSheet; + } + + $limit = $profile->maxRowsPerSheet(); + $lastRow = self::lastReadableRow(limit: $limit); + $this->assertRowSpan(path: $path, sheetNames: $loaded, lastRow: $lastRow, limit: $limit); + + $headers = $this->load(path: $path, sheetNames: $loaded, filter: new CmdbReadFilter(lastRow: 1)); + try { + $resolved = $this->resolveSheets(spreadsheet: $headers, sheetNames: $present, profile: $profile); + $archiveColumns = []; + if ($loaded !== $present) { + // Only the key column of the archive sheet is read; the allowlist does not grow. + $archiveColumns = $this->resolveColumns(worksheet: $headers->getSheetByName($archiveSheet), referenced: [$profile->keyColumn()]); + } + } finally { + $headers->disconnectWorksheets(); + } + + // A sheet without the key column is not read; the import reports it as missing its key column. + $archive = [ + 'sheet' => (string)$archiveSheet, + 'present' => false, + 'keyColumnMissing' => ($loaded !== $present && $archiveColumns === []), + 'appIds' => [], + ]; + $letters = array_map(static fn (array $columns): array => array_keys($columns), $resolved['columns']); + $loaded = $present; + if ($archiveColumns !== []) { + $letters[$archiveSheet] = array_keys($archiveColumns); + $loaded[] = $archiveSheet; + } + + $spreadsheet = $this->load(path: $path, sheetNames: $loaded, filter: new CmdbReadFilter(lastRow: $lastRow, columns: $letters)); + try { + $rows = $this->readSourceRows(spreadsheet: $spreadsheet, sheetNames: $present, columnsPerSheet: $resolved['columns'], limit: $limit); + if ($archiveColumns !== []) { + $archiveRows = $this->readRows( + worksheet: $spreadsheet->getSheetByName($archiveSheet), + columns: $archiveColumns, + sheetName: (string)$archiveSheet, + limit: $limit + ); + $archive['present'] = true; + $archive['appIds'] = array_column(array_column($archiveRows, 'cells'), $profile->keyColumn()); + } + + $date1904 = self::usesDate1904(spreadsheet: $spreadsheet); + } finally { + $spreadsheet->disconnectWorksheets(); + } + + return ['rows' => $rows, 'importWarnings' => $resolved['warnings'], 'date1904' => $date1904, 'archive' => $archive]; + }//end readBounded() + + /** + * The profile's source sheets that the workbook has, and every sheet it has. + * + * @param string $path The xlsx file. + * @param CmdbImportProfile $profile The import profile. + * + * @return array{present: array, available: array} + * + * @throws CmdbImportException NOT_XLSX when the sheet list cannot be read, NO_SOURCE_SHEET when no source sheet is there. + */ + private function sourceSheets(string $path, CmdbImportProfile $profile): array { $reader = $this->newReader(sheetNames: null); try { $available = $reader->listWorksheetNames($path); @@ -328,41 +406,50 @@ private function readBounded(string $path, CmdbImportProfile $profile, object $s ); } - $limit = $profile->maxRowsPerSheet(); - $lastRow = self::lastReadableRow(limit: $limit); - $this->assertRowSpan(path: $path, sheetNames: $present, lastRow: $lastRow, limit: $limit); + return ['present' => $present, 'available' => $available]; + }//end sourceSheets() - $headers = $this->load(path: $path, sheetNames: $present, filter: new CmdbReadFilter(lastRow: 1)); - try { - $resolved = $this->resolveSheets(spreadsheet: $headers, sheetNames: $present, profile: $profile); - } finally { - $headers->disconnectWorksheets(); + /** + * The data rows of the source sheets, in sheet order. + * + * @param object $spreadsheet The spreadsheet, loaded through the data-pass read filter. + * @param array $sheetNames The source sheets the workbook has. + * @param array> $columnsPerSheet Sheet name => column letter => column name. + * @param int $limit The row limit per sheet. + * + * @return array> See read(). + * + * @throws CmdbImportException TOO_MANY_ROWS. + */ + private function readSourceRows(object $spreadsheet, array $sheetNames, array $columnsPerSheet, int $limit): array { + $rows = []; + foreach ($sheetNames as $sheetName) { + $sheetRows = $this->readRows( + worksheet: $spreadsheet->getSheetByName($sheetName), + columns: $columnsPerSheet[$sheetName], + sheetName: $sheetName, + limit: $limit + ); + array_push($rows, ...$sheetRows); } - $letters = array_map(static fn (array $columns): array => array_keys($columns), $resolved['columns']); - $spreadsheet = $this->load(path: $path, sheetNames: $present, filter: new CmdbReadFilter(lastRow: $lastRow, columns: $letters)); - try { - $rows = []; - foreach ($present as $sheetName) { - $sheetRows = $this->readRows( - worksheet: $spreadsheet->getSheetByName($sheetName), - columns: $resolved['columns'][$sheetName], - sheetName: $sheetName, - limit: $limit - ); - array_push($rows, ...$sheetRows); - } + return $rows; + }//end readSourceRows() - $date1904 = false; - if (method_exists($spreadsheet, 'getExcelCalendar') === true) { - $date1904 = ((int)$spreadsheet->getExcelCalendar() === 1904); - } - } finally { - $spreadsheet->disconnectWorksheets(); + /** + * Whether the workbook uses the 1904 date system. + * + * @param object $spreadsheet The spreadsheet. + * + * @return bool + */ + private static function usesDate1904(object $spreadsheet): bool { + if (method_exists($spreadsheet, 'getExcelCalendar') === false) { + return false; } - return ['rows' => $rows, 'importWarnings' => $resolved['warnings'], 'date1904' => $date1904]; - }//end readBounded() + return ((int)$spreadsheet->getExcelCalendar() === 1904); + }//end usesDate1904() /** * The last row number the data pass reads. diff --git a/lib/Service/CmdbExportImportService.php b/lib/Service/CmdbExportImportService.php index 1efc049d..3c98a3f1 100644 --- a/lib/Service/CmdbExportImportService.php +++ b/lib/Service/CmdbExportImportService.php @@ -30,7 +30,14 @@ * - `publicationDate` is set to the import's start on create, unless the * admin chose not to publish (`publish` false), and never written on * update; neither is `depublicationDate`. - * - Records missing from a newer export are left untouched. + * - Records missing from a newer export are left untouched with + * `missingRecords` `keep`. With `archive` (the default) the municipality's + * usages and their modules are reconciled after the last row: archived + * when the APPID is on the archive sheet, soft-deleted when it is on no + * sheet, archived only when the workbook has no archive sheet + * (openspec/changes/cmdb-import-archive-reconciliation, design D5). A + * module or usage matched among archived or soft-deleted objects is + * unarchived or restored before it is updated, never duplicated. * - Owners become contact persons, never Nextcloud user accounts, and no * report entry or log line carries an owner name or e-mail address. * - One import runs per register at a time: every match is find-then-create, @@ -55,6 +62,7 @@ use DateTimeImmutable; use DateTimeZone; +use JsonSerializable; use OCA\OpenRegister\Contract\ObjectServiceInterface; use OCA\Stackiq\Exception\CmdbImportException; use OCA\Stackiq\Service\Cmdb\CmdbImportProfile; @@ -68,6 +76,7 @@ use OCP\Lock\LockedException; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; +use RuntimeException; use Throwable; /** @@ -111,6 +120,58 @@ class CmdbExportImportService { */ public const SCHEMA_MAPPER_CLASS = 'OCA\OpenRegister\Db\SchemaMapper'; + /** + * OpenRegister's archive handler, behind POST and DELETE .../archive (not a public contract). + */ + public const ARCHIVE_HANDLER_CLASS = 'OCA\OpenRegister\Service\Object\ArchiveHandler'; + + /** + * OpenRegister's object mapper, whose restoreObject() empties the trash of one object (not a public contract). + */ + public const OBJECT_MAPPER_CLASS = 'OCA\OpenRegister\Db\MagicMapper'; + + /** + * What happens to records missing from the export when the request does not say. + */ + public const DEFAULT_MISSING_RECORDS = 'archive'; + + /** + * The start of every archive reason the import writes, so the audit trail says who archived and why. + */ + private const REASON_PREFIX = 'cmdb-import: '; + + /** + * The search lens that lists the archive alone (OpenRegister's `_archived=true`). + * + * The state of a stored object is read from the lens that found it, never + * from the archive marker of a search result: OpenRegister's list search + * does not hydrate that marker (design D9). + * + * @var array + */ + private const ARCHIVED_LENS = ['_archived' => 'true']; + + /** + * The state of an object found without a lens. + * + * @var array{archived: bool, deleted: bool} + */ + private const STATE_WORKING = ['archived' => false, 'deleted' => false]; + + /** + * The state of an object found with ARCHIVED_LENS. + * + * @var array{archived: bool, deleted: bool} + */ + private const STATE_ARCHIVED = ['archived' => true, 'deleted' => false]; + + /** + * The state of an object found in the trash; whether it was archived too is read when it is restored. + * + * @var array{archived: bool, deleted: bool} + */ + private const STATE_DELETED = ['archived' => false, 'deleted' => true]; + /** * The properties every match search and the module key rely on, per schema. * @@ -222,6 +283,20 @@ class CmdbExportImportService { */ private array $winningSheets = []; + /** + * OpenRegister's archive handler and object mapper, once resolved. + * + * @var array{handler: object, mapper: object}|null + */ + private ?array $archiveServices = null; + + /** + * The register's soft-deleted modules and usages, read once per run: schema key => uuid => entity. + * + * @var array{module: array, usage: array}|null + */ + private ?array $trash = null; + /** * Contact UIDs by e-mail or display name, per run. * @@ -300,17 +375,16 @@ public function assertXlsx(string $path, string $fileName): void { }//end assertXlsx() /** - * Whether a `missingRecords` value is supported (only `keep`). - * - * @param string $mode The requested value. + * The accepted `missingRecords` values: the profile's modes (`keep`, `archive`); any other is refused. * - * @return bool + * @return array * * @spec openspec/changes/cmdb-export-import/tasks.md#task-8 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012 */ - public function supportsMissingRecords(string $mode): bool { - return $mode === 'keep'; - }//end supportsMissingRecords() + public function missingRecordsModes(): array { + return $this->profile->missingRecordsModes(); + }//end missingRecordsModes() /** * Ask a running import to stop between rows. @@ -349,19 +423,21 @@ public function requestCancel(string $operationId): bool { * * @param string $path The xlsx file, already checked by assertXlsx(). * @param array $options municipalityUuid, municipalityName, updateExisting, publish, - * operationId, and fileName (the upload's name, for the audit log line). + * missingRecords (keep or archive, default archive), operationId, + * and fileName (the upload's name, for the audit log line). * * @return array The report (contract.md). * * @throws CmdbImportException MAPPING_UNAVAILABLE, NOT_CONFIGURED, SCHEMA_OUTDATED, IMPORT_IN_PROGRESS, * WORKBOOK_TOO_LARGE, READER_UNAVAILABLE, NOT_XLSX, NO_SOURCE_SHEET, * MISSING_COLUMN, TOO_MANY_ROWS, MUNICIPALITY_REQUIRED, - * MUNICIPALITY_INVALID or MUNICIPALITY_AMBIGUOUS. + * MUNICIPALITY_INVALID, MUNICIPALITY_AMBIGUOUS or ARCHIVE_UNAVAILABLE. * @throws \Exception An unexpected OpenRegister error outside a row, such as * creating the municipality; rows catch their own. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 * @spec openspec/changes/cmdb-export-import/tasks.md#task-7 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 */ public function import(string $path, array $options): array { $this->resetRun(); @@ -371,6 +447,10 @@ public function import(string $path, array $options): array { $this->profile->load(); $this->engine = $this->resolveEngine(); $this->coordinates = $this->resolveCoordinates(); + if (self::missingRecordsFrom(options: $options) === 'archive') { + // Refused before the lock and the file: an import that cannot reconcile must not half-run. + $this->archiveServices(); + } $lock = $this->acquireImportLock(register: $this->coordinates['register']); try { @@ -442,29 +522,20 @@ private function acquireImportLock(int $register): string { * @return array The report. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-7 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 */ private function runImport(string $path, array $options, string $startedAt): array { $workbook = $this->reader->read(path: $path, profile: $this->profile); $municipality = $this->resolveMunicipality(options: $options); $operationId = $this->operationIdFrom(options: $options); + $missingRecords = self::missingRecordsFrom(options: $options); $rows = array_values($workbook['rows']); $report = new CmdbImportReport(operationId: $operationId, rowsRead: count($rows)); $report->setMunicipality(uuid: $municipality['uuid'], name: $municipality['name'], created: $municipality['created']); $report->addImportWarnings(warnings: $this->translateImportWarnings(warnings: $workbook['importWarnings'])); - if ($municipality['created'] === true) { - $report->addImportWarnings( - warnings: [ - [ - 'sheet' => '', - 'message' => $this->l10n->t( - 'No municipality named "%s" was found, so it was created. Check the name if you meant an existing one.', - [$municipality['name']] - ), - ], - ] - ); - } + $archive = $this->archiveSheet(workbook: $workbook); + $this->addRunWarnings(report: $report, municipality: $municipality, archive: $archive, missingRecords: $missingRecords); $this->progressTracker->startOperation( operationType: self::OPERATION_TYPE, @@ -488,6 +559,7 @@ private function runImport(string $path, array $options, string $startedAt): arr 'municipalityCreated' => $municipality['created'], 'updateExisting' => $updateExisting, 'publish' => $publish, + 'missingRecords' => $missingRecords, ]; $this->logger->info('CmdbExportImportService: import started', array_merge($audit, ['rows' => count($rows)])); try { @@ -507,6 +579,16 @@ private function runImport(string $path, array $options, string $startedAt): arr $this->progressTracker->updateProgress(processedItems: ($index + 1)); } + if ($missingRecords === 'archive' && $report->isCancelled() === false) { + $this->reconcile( + municipalityUuid: $municipality['uuid'], + archive: $archive, + operationId: $operationId, + processedItems: count($rows), + report: $report + ); + } + $result = $report->toArray(); $this->finishOperation(report: $report->toStoredArray(maxRows: self::STORED_REPORT_ROWS)); } catch (Throwable $e) { @@ -528,6 +610,39 @@ private function runImport(string $path, array $options, string $startedAt): arr return $result; }//end runImport() + /** + * Add the run's own warnings: a missing archive sheet on an archiving import, and a created municipality. + * + * @param CmdbImportReport $report The report. + * @param array{uuid: string, name: string, created: bool} $municipality The consumer, as resolveMunicipality() found it. + * @param array{sheet: string, present: bool, keyColumnMissing: bool, keys: array} $archive The archive sheet. + * @param string $missingRecords The import's `missingRecords` mode. + * + * @return void + * + * @spec openspec/changes/cmdb-export-import/tasks.md#task-7 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function addRunWarnings(CmdbImportReport $report, array $municipality, array $archive, string $missingRecords): void { + if ($missingRecords === 'archive' && $archive['present'] === false) { + $report->addImportWarnings(warnings: [['sheet' => $archive['sheet'], 'message' => $this->archiveSheetWarning(archive: $archive)]]); + } + + if ($municipality['created'] === true) { + $report->addImportWarnings( + warnings: [ + [ + 'sheet' => '', + 'message' => $this->l10n->t( + 'No municipality named "%s" was found, so it was created. Check the name if you meant an existing one.', + [$municipality['name']] + ), + ], + ] + ); + } + }//end addRunWarnings() + /** * Process one row in its own error boundary and add its outcome. * @@ -748,11 +863,20 @@ private function translateImportWarnings(array $warnings): array { * @param string $module The module outcome. * @param string $usage The usage outcome. * - * @return string created when the module was created, updated when anything was saved, else unchanged. + * @return string restored when either was restored from the trash, else unarchived when either was + * unarchived, else created when the module was created, updated when anything was saved, + * else unchanged. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-7 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 */ private static function rowOutcome(string $module, string $usage): string { + foreach ([CmdbImportReport::RESTORED, CmdbImportReport::UNARCHIVED] as $revived) { + if ($module === $revived || $usage === $revived) { + return $revived; + } + } + if ($module === CmdbImportReport::CREATED) { return CmdbImportReport::CREATED; } @@ -781,7 +905,7 @@ private function finishOperation(array $report): void { } $this->progressTracker->completeOperation(finalStatistics: ['report' => $report]); - // A cancel that came in after the last row's check has nothing left to stop. + // A cancel that came in after the last check has nothing left to stop. $this->progressTracker->clearCancelRequested(operationId: (string)$report['operationId']); }//end finishOperation() @@ -1028,19 +1152,19 @@ private function resolveManufacturer(array $values, int $rowNumber): ?string { * @param string $matchKey The APPID's match key. * @param array{updateExisting: bool} $options Whether a match is updated. * - * @return array{existing: object|null, uuid: string|null, skipReason: string|null} The stored module, the uuid - * to report for a skipped row, - * and why the row is skipped. + * @return array{existing: array{entity: object, state: array{archived: bool, deleted: bool}}|null, uuid: string|null, skipReason: string|null} + * The stored module with its state, the uuid to report for a skipped row, and why the row is skipped. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 */ private function matchModule(string $externalKey, string $municipalityUuid, string $matchKey, array $options): array { - $existing = $this->findOne(schemaKey: 'module', filters: ['externalKey' => $externalKey]); + $existing = $this->findInAnyState(schemaKey: 'module', filters: ['externalKey' => $externalKey]); if ($existing === null) { return ['existing' => null, 'uuid' => null, 'skipReason' => null]; } - $uuid = (string)$existing->getUuid(); + $uuid = (string)$existing['entity']->getUuid(); if ($this->moduleBelongsTo(moduleUuid: $uuid, municipalityUuid: $municipalityUuid) === false) { $this->logger->warning( 'CmdbExportImportService: import key belongs to a module another organisation uses; row not imported', @@ -1062,7 +1186,8 @@ private function matchModule(string $externalKey, string $municipalityUuid, stri * * @param array $data The mapped module fields. * @param string $externalKey The module's import key. - * @param object|null $existing The module matchModule() found, or null to create one. + * @param array{entity: object, state: array{archived: bool, deleted: bool}}|null $existing The module matchModule() + * found, or null to create one. * @param string|null $providerUuid The supplier, when there is one. * @param string|null $publicationDate ISO start time of the import for a module that is published * when created, or null to create it unpublished. @@ -1075,7 +1200,7 @@ private function matchModule(string $externalKey, string $municipalityUuid, stri private function importModule( array $data, string $externalKey, - ?object $existing, + ?array $existing, ?string $providerUuid, ?string $publicationDate, CmdbImportReport $report, @@ -1102,6 +1227,8 @@ private function importModule( * together with the usages: the module must already have a usage whose * consumer is this municipality, or, before the first import, no usage * at all. A module only another organisation uses is never taken over. + * This municipality's usage counts in every state: an archived or + * soft-deleted usage still says the module is the municipality's. * * @param string $moduleUuid The module found by its import key. * @param string $municipalityUuid The consumer of this import. @@ -1109,9 +1236,10 @@ private function importModule( * @return bool * * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 */ private function moduleBelongsTo(string $moduleUuid, string $municipalityUuid): bool { - if ($this->findOne(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid]) !== null) { + if ($this->findInAnyState(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid]) !== null) { return true; } @@ -1123,19 +1251,22 @@ private function moduleBelongsTo(string $moduleUuid, string $municipalityUuid): * * @param array $data The mapped module fields. * @param string $externalKey The match key. - * @param object|null $existing The stored module, or null to create one. + * @param array{entity: object, state: array{archived: bool, deleted: bool}}|null $existing The stored module and its + * state, or null to create one. * @param string|null $providerUuid The supplier, when there is one. * @param string|null $publicationDate ISO start time of the import for a module that is published * when created, or null to create it unpublished. * - * @return array{uuid: string, outcome: string} Outcome created, updated or unchanged. + * @return array{uuid: string, outcome: string} Outcome created, updated or unchanged, or restored or + * unarchived when the stored module was revived first. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 */ private function upsertModule( array $data, string $externalKey, - ?object $existing, + ?array $existing, ?string $providerUuid, ?string $publicationDate, ): array { @@ -1154,14 +1285,15 @@ private function upsertModule( return ['uuid' => $this->save(schemaKey: 'module', data: $create, uuid: null), 'outcome' => CmdbImportReport::CREATED]; } - $uuid = (string)$existing->getUuid(); - $merged = $this->merge(target: 'module', stored: $existing->getObject(), mapped: $data); + $uuid = (string)$existing['entity']->getUuid(); + $revived = $this->revive(found: $existing); + $merged = $this->merge(target: 'module', stored: $revived['entity']->getObject(), mapped: $data); if ($merged === null) { - return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UNCHANGED]; + return ['uuid' => $uuid, 'outcome' => ($revived['outcome'] ?? CmdbImportReport::UNCHANGED)]; } $this->save(schemaKey: 'module', data: $merged, uuid: $uuid); - return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UPDATED]; + return ['uuid' => $uuid, 'outcome' => ($revived['outcome'] ?? CmdbImportReport::UPDATED)]; }//end upsertModule() /** @@ -1173,9 +1305,11 @@ private function upsertModule( * @param string|null $providerUuid The supplier, when there is one. * @param array{businessOwner: string|null} $owners The owner contact person. * - * @return array{uuid: string, outcome: string} + * @return array{uuid: string, outcome: string} Outcome created, updated or unchanged, or restored or + * unarchived when the stored usage was revived first. * * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 */ private function upsertUsage(array $data, string $municipalityUuid, string $moduleUuid, ?string $providerUuid, array $owners): array { if (isset($data['interneAnnotation']) === true && is_string($data['interneAnnotation']) === true) { @@ -1199,19 +1333,20 @@ private function upsertUsage(array $data, string $municipalityUuid, string $modu } } - $existing = $this->findOne(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid]); + $existing = $this->findInAnyState(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid]); if ($existing === null) { return ['uuid' => $this->save(schemaKey: 'usage', data: $data, uuid: null), 'outcome' => CmdbImportReport::CREATED]; } - $uuid = (string)$existing->getUuid(); - $merged = $this->merge(target: 'usage', stored: $existing->getObject(), mapped: $data); + $uuid = (string)$existing['entity']->getUuid(); + $revived = $this->revive(found: $existing); + $merged = $this->merge(target: 'usage', stored: $revived['entity']->getObject(), mapped: $data); if ($merged === null) { - return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UNCHANGED]; + return ['uuid' => $uuid, 'outcome' => ($revived['outcome'] ?? CmdbImportReport::UNCHANGED)]; } $this->save(schemaKey: 'usage', data: $merged, uuid: $uuid); - return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UPDATED]; + return ['uuid' => $uuid, 'outcome' => ($revived['outcome'] ?? CmdbImportReport::UPDATED)]; }//end upsertUsage() /** @@ -1633,7 +1768,7 @@ private function organisationsOfType(string $type): array { }//end organisationsOfType() /** - * The one object matching every filter, or null. + * The working object matching every filter, or null. * * @param string $schemaKey The coordinates key of the schema. * @param array $filters Field => exact value. @@ -1643,10 +1778,67 @@ private function organisationsOfType(string $type): array { * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 */ private function findOne(string $schemaKey, array $filters): ?object { + return $this->search(schemaKey: $schemaKey, filters: $filters, lens: []); + }//end findOne() + + /** + * The object matching every filter in any state, with that state, or null. + * + * A working object wins over an archived one, and an archived one over one + * in the trash: an object deleted by hand may share its import key with the + * one a later import created, and bringing the deleted one back would + * duplicate it. The state is the lens that found the object (design D9): + * a search without a lens finds only working objects, the archive lens only + * archived ones, and the trash is read from OpenRegister's trash listing, + * because its list search cannot return a soft-deleted object. + * + * @param string $schemaKey module or usage. + * @param array $filters Field => exact value. + * + * @return array{entity: object, state: array{archived: bool, deleted: bool}}|null + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private function findInAnyState(string $schemaKey, array $filters): ?array { + $entity = $this->search(schemaKey: $schemaKey, filters: $filters, lens: []); + if ($entity !== null) { + return ['entity' => $entity, 'state' => self::STATE_WORKING]; + } + + $entity = $this->search(schemaKey: $schemaKey, filters: $filters, lens: self::ARCHIVED_LENS); + if ($entity !== null) { + return ['entity' => $entity, 'state' => self::STATE_ARCHIVED]; + } + + foreach (($this->trash()[$schemaKey] ?? []) as $entity) { + if (self::matchesFilters(entity: $entity, filters: $filters) === true) { + return ['entity' => $entity, 'state' => self::STATE_DELETED]; + } + } + + return null; + }//end findInAnyState() + + /** + * The first object a search with one lens returns that matches every filter, or null. + * + * The filters are checked again on the result: a filter OpenRegister cannot + * apply must not turn into a match. + * + * @param string $schemaKey The coordinates key of the schema. + * @param array $filters Field => exact value. + * @param array $lens No lens (working objects) or ARCHIVED_LENS. + * + * @return object|null The entity (ObjectEntityInterface). + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private function search(string $schemaKey, array $filters, array $lens): ?object { $coordinates = $this->coordinates(); $results = $coordinates['objectService']->searchObjects( query: array_merge( ['@self' => ['register' => $coordinates['register'], 'schema' => $coordinates[$schemaKey]], '_limit' => 10], + $lens, $filters ), _rbac: false, @@ -1657,22 +1849,34 @@ private function findOne(string $schemaKey, array $filters): ?object { } foreach ($results as $entity) { - $data = $entity->getObject(); - $matches = true; - foreach ($filters as $field => $value) { - if (self::relationUuid(value: ($data[$field] ?? null)) !== $value) { - $matches = false; - break; - } - } - - if ($matches === true) { + if (self::matchesFilters(entity: $entity, filters: $filters) === true) { return $entity; } } return null; - }//end findOne() + }//end search() + + /** + * Whether an object's data has every filter's value. + * + * @param object $entity The entity (ObjectEntityInterface). + * @param array $filters Field => exact value. + * + * @return bool + * + * @spec openspec/changes/cmdb-export-import/tasks.md#task-5 + */ + private static function matchesFilters(object $entity, array $filters): bool { + $data = $entity->getObject(); + foreach ($filters as $field => $value) { + if (self::relationUuid(value: ($data[$field] ?? null)) !== $value) { + return false; + } + } + + return true; + }//end matchesFilters() /** * Save an object through OpenRegister and return its uuid. @@ -1699,6 +1903,621 @@ private function save(string $schemaKey, array $data, ?string $uuid): string { return (string)$entity->getUuid(); }//end save() + /** + * The `missingRecords` mode of an import: the option, or DEFAULT_MISSING_RECORDS. + * + * @param array $options The import options. + * + * @return string + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012 + */ + private static function missingRecordsFrom(array $options): string { + $mode = ($options['missingRecords'] ?? null); + if (is_string($mode) === false || $mode === '') { + return self::DEFAULT_MISSING_RECORDS; + } + + return $mode; + }//end missingRecordsFrom() + + /** + * The archive sheet as the reader found it, with its APPIDs as match keys. + * + * @param array $workbook What the reader returned. + * + * @return array{sheet: string, present: bool, keyColumnMissing: bool, keys: array} + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function archiveSheet(array $workbook): array { + $archive = ($workbook['archive'] ?? []); + $key = $this->profile->keyColumn(); + $keys = []; + foreach (($archive['appIds'] ?? []) as $appId) { + $values = $this->normaliser->normalise(cells: [$key => $appId], dateColumns: [], idColumns: $this->profile->idColumns()); + $matchKey = self::matchKey(appId: ($values[$key] ?? '')); + if ($matchKey !== '') { + $keys[$matchKey] = true; + } + } + + return [ + 'sheet' => (string)($archive['sheet'] ?? ($this->profile->archiveSheetName() ?? '')), + 'present' => (($archive['present'] ?? false) === true), + 'keyColumnMissing' => (($archive['keyColumnMissing'] ?? false) === true), + 'keys' => $keys, + ]; + }//end archiveSheet() + + /** + * The report warning of an archiving import whose workbook lacks the archive sheet or its key column. + * + * @param array{sheet: string, keyColumnMissing: bool} $archive The archive sheet. + * + * @return string + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function archiveSheetWarning(array $archive): string { + if ($archive['keyColumnMissing'] === true) { + return $this->l10n->t( + 'Sheet "%1$s" has no column "%2$s", so applications missing from the export are archived, not deleted.', + [$archive['sheet'], $this->profile->keyColumn()] + ); + } + + return $this->l10n->t('Sheet "%s" was not found, so applications missing from the export are archived, not deleted.', [$archive['sheet']]); + }//end archiveSheetWarning() + + /** + * Resolve OpenRegister's archive handler and object mapper, failing closed. + * + * @return array{handler: object, mapper: object} The handler, with `archive()` and `unarchive()`, and the + * mapper, with `restoreObject()` and `findDeletedAcrossAllMagicTables()`. + * + * @throws CmdbImportException ARCHIVE_UNAVAILABLE. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function archiveServices(): array { + if ($this->archiveServices !== null) { + return $this->archiveServices; + } + + try { + $handler = $this->container->get(static::ARCHIVE_HANDLER_CLASS); + $mapper = $this->container->get(static::OBJECT_MAPPER_CLASS); + } catch (Throwable $e) { + $handler = null; + $mapper = null; + } + + if (is_object($handler) === false || method_exists($handler, 'archive') === false || method_exists($handler, 'unarchive') === false + || is_object($mapper) === false || method_exists($mapper, 'restoreObject') === false + || method_exists($mapper, 'findDeletedAcrossAllMagicTables') === false + ) { + throw new CmdbImportException( + errorCode: CmdbImportException::ARCHIVE_UNAVAILABLE, + message: 'OpenRegister ArchiveHandler or MagicMapper is not available' + ); + } + + $this->archiveServices = ['handler' => $handler, 'mapper' => $mapper]; + return $this->archiveServices; + }//end archiveServices() + + /** + * Whether an object as OpenRegister's mapper reads it by uuid is archived and whether it is in the trash. + * + * Read from its `@self` metadata. Only for an object the mapper read + * itself (the one restoreObject() answers): a list search result carries + * no archive marker (design D9). + * + * @param object $entity The entity (ObjectEntityInterface). + * + * @return array{archived: bool, deleted: bool} + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private static function objectState(object $entity): array { + $self = []; + if ($entity instanceof JsonSerializable) { + $serialised = $entity->jsonSerialize(); + if (is_array($serialised) === true && is_array($serialised['@self'] ?? null) === true) { + $self = $serialised['@self']; + } + } + + return [ + 'archived' => (self::isEmptyValue(value: ($self['archived'] ?? null)) === false), + 'deleted' => (self::isEmptyValue(value: ($self['deleted'] ?? null)) === false), + ]; + }//end objectState() + + /** + * Bring a matched module or usage back before it is written: out of the trash, then out of the archive. + * + * OpenRegister refuses a data write to an archived object, and the + * archive handler cannot reach one in the trash, hence the order. The + * trash listing does not say whether an object was archived before it was + * deleted; the restored object, read by the mapper, does. The update then + * starts from that object: the trash listing decodes every string that + * parses as JSON, so its copy of the data must not be written back. + * + * @param array{entity: object, state: array{archived: bool, deleted: bool}} $found The matched entity and its state. + * + * @return array{outcome: string|null, entity: object} restored, unarchived, or null when it was neither, and the + * entity whose data the update starts from. + * + * @throws CmdbImportException ARCHIVE_UNAVAILABLE when the archive services are missing. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private function revive(array $found): array { + $entity = $found['entity']; + $archived = $found['state']['archived']; + if ($found['state']['deleted'] === false && $archived === false) { + return ['outcome' => null, 'entity' => $entity]; + } + + $uuid = (string)$entity->getUuid(); + $outcome = null; + if ($found['state']['deleted'] === true) { + $restored = $this->restore(uuid: $uuid); + $outcome = CmdbImportReport::RESTORED; + if (is_object($restored) === true && method_exists($restored, 'getObject') === true) { + $entity = $restored; + $archived = self::objectState(entity: $restored)['archived']; + } + } + + if ($archived === true) { + $this->archiveServices()['handler']->unarchive(identifier: $uuid, reason: self::REASON_PREFIX . 'back in the export'); + $outcome = ($outcome ?? CmdbImportReport::UNARCHIVED); + } + + return ['outcome' => $outcome, 'entity' => $entity]; + }//end revive() + + /** + * Take one object out of the trash, and out of this run's copy of the trash. + * + * @param string $uuid The object. + * + * @return mixed What MagicMapper::restoreObject() answers: the object as it reads it. + * + * @throws CmdbImportException ARCHIVE_UNAVAILABLE when the archive services are missing. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private function restore(string $uuid): mixed { + $restored = $this->archiveServices()['mapper']->restoreObject(uuid: $uuid); + if ($this->trash !== null) { + unset($this->trash['module'][$uuid], $this->trash['usage'][$uuid]); + } + + return $restored; + }//end restore() + + /** + * The register's soft-deleted modules and usages, read once per run. + * + * OpenRegister's list search cannot return a soft-deleted object, whatever + * `_includeDeleted` says, so the trash is read from the trash listing that + * the Deleted page uses (design D9). That listing scans every magic table + * of the instance, so it is read once, lazily, and only this register's + * modules and usages are kept. Its objects carry no archive or trash + * marker; everything in it is deleted. Without the archive services (a + * `keep` import on an OpenRegister without them) the trash cannot be read: + * nothing in it is matched, and the log says so. + * + * @return array{module: array, usage: array} Schema key => uuid => entity. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private function trash(): array { + if ($this->trash !== null) { + return $this->trash; + } + + $this->trash = ['module' => [], 'usage' => []]; + try { + $services = $this->archiveServices(); + } catch (CmdbImportException $e) { + $this->logger->warning('CmdbExportImportService: OpenRegister trash is not readable; soft-deleted modules and usages are not matched'); + return $this->trash; + } + + $coordinates = $this->coordinates(); + $deleted = $services['mapper']->findDeletedAcrossAllMagicTables(limit: null, offset: null, _rbac: false, _multitenancy: false); + $this->trash = self::registerTrash(deleted: $deleted, coordinates: $coordinates); + + return $this->trash; + }//end trash() + + /** + * The modules and usages of this register among the instance's soft-deleted objects. + * + * @param mixed $deleted What MagicMapper::findDeletedAcrossAllMagicTables() answered. + * @param array $coordinates The register and schema ids, from coordinates(). + * + * @return array{module: array, usage: array} Schema key => uuid => entity. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016 + */ + private static function registerTrash(mixed $deleted, array $coordinates): array { + $trash = ['module' => [], 'usage' => []]; + if (is_array($deleted) === false) { + return $trash; + } + + foreach ($deleted as $entity) { + if (is_object($entity) === false || (string)$entity->getRegister() !== (string)$coordinates['register'] || $entity->getUuid() === null) { + continue; + } + + foreach (['module', 'usage'] as $schemaKey) { + if ((string)$entity->getSchema() === (string)$coordinates[$schemaKey]) { + $trash[$schemaKey][(string)$entity->getUuid()] = $entity; + } + } + } + + return $trash; + }//end registerTrash() + + /** + * Archive or soft-delete every application of the municipality whose APPID left the CMDB sheets. + * + * Runs after the last row of an import that was not cancelled, under the + * same register lock. The whole scope is loaded before anything is + * written, so the paging is not shifted by the writes. Every application + * has its own error boundary. A cancel is honoured before the scope is + * loaded and before each application: what was archived or deleted so far + * stays, and the report says the run was cancelled. + * + * @param string $municipalityUuid The consumer of this import. + * @param array{sheet: string, present: bool, keyColumnMissing: bool, keys: array} $archive The archive sheet. + * @param string $operationId The operation id, for the archive reason. + * @param int $processedItems The rows already counted as processed. + * @param CmdbImportReport $report The report. + * + * @return void + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function reconcile(string $municipalityUuid, array $archive, string $operationId, int $processedItems, CmdbImportReport $report): void { + // A cancel that came in during the last row stops the import before anything is archived or deleted. + if ($this->progressTracker->isCancelRequested(operationId: $operationId) === true) { + $report->markCancelled(); + return; + } + + $scope = $this->reconciliationScope(municipalityUuid: $municipalityUuid); + $this->progressTracker->setPhase(phase: 'reconciling', data: ['total_items' => ($processedItems + count($scope))]); + + foreach ($scope as $index => $application) { + if ($this->progressTracker->isCancelRequested(operationId: $operationId) === true) { + $report->markCancelled(); + return; + } + + // Every APPID on a CMDB sheet was handled by its row, whatever the row's outcome. + if (isset($this->winningSheets[$application['key']]) === false) { + $this->reconcileApplication(application: $application, archive: $archive, operationId: $operationId, report: $report); + } + + $this->progressTracker->updateProgress(processedItems: ($processedItems + $index + 1)); + } + }//end reconcile() + + /** + * The municipality's usages, in every state, each with its module when that module carries this municipality's import key. + * + * A usage of a hand-made module, or of a module another organisation + * imported, is left out: only what this municipality's import created is + * reconciled. Working and archived usages are paged with one lens each, + * soft-deleted ones come from the trash (design D9); each object keeps the + * state its lens or the trash gave it. + * + * @param string $municipalityUuid The consumer of this import. + * + * @return array}> + * Per application, the APPID's match key, the usage, the module and the state of both by schema key. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function reconciliationScope(string $municipalityUuid): array { + $usages = $this->usagesInEveryState(municipalityUuid: $municipalityUuid); + + $owned = []; + foreach ($usages as $usage) { + $data = $usage['entity']->getObject(); + $moduleUuid = self::relationUuid(value: ($data['module'] ?? null)); + // The filter is checked again: a filter OpenRegister cannot apply must not widen the scope. + if (self::relationUuid(value: ($data['consumer'] ?? null)) === $municipalityUuid && $moduleUuid !== null && $usage['entity']->getUuid() !== null) { + $owned[] = $usage + ['module' => $moduleUuid]; + } + } + + $prefix = $this->profile->externalKeyPrefix() . ':' . $municipalityUuid . ':'; + $modules = $this->modulesByUuid(uuids: array_values(array_unique(array_column($owned, 'module')))); + $scope = []; + foreach ($owned as $usage) { + $module = ($modules[$usage['module']] ?? null); + if ($module === null) { + continue; + } + + $externalKey = (string)($module['entity']->getObject()['externalKey'] ?? ''); + if (str_starts_with($externalKey, $prefix) === true && strlen($externalKey) > strlen($prefix)) { + $scope[] = [ + 'key' => substr($externalKey, strlen($prefix)), + 'usage' => $usage['entity'], + 'module' => $module['entity'], + 'states' => ['usage' => $usage['state'], 'module' => $module['state']], + ]; + } + } + + return $scope; + }//end reconciliationScope() + + /** + * The usages that name this municipality as consumer, in every state, each with that state. + * + * Working and archived usages are paged with one lens each; soft-deleted + * ones come from the trash, which is not filtered by consumer, so the + * caller checks the consumer of every usage. + * + * @param string $municipalityUuid The consumer of this import. + * + * @return array + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function usagesInEveryState(string $municipalityUuid): array { + $coordinates = $this->coordinates(); + $usages = []; + foreach ([[[], self::STATE_WORKING], [self::ARCHIVED_LENS, self::STATE_ARCHIVED]] as [$lens, $state]) { + $offset = 0; + do { + $page = $coordinates['objectService']->searchObjects( + query: array_merge( + [ + '@self' => ['register' => $coordinates['register'], 'schema' => $coordinates['usage']], + 'consumer' => $municipalityUuid, + '_limit' => self::PAGE_SIZE, + '_offset' => $offset, + ], + $lens + ), + _rbac: false, + _multitenancy: false + ); + if (is_array($page) === false) { + $page = []; + } + + foreach ($page as $usage) { + $usages[] = ['entity' => $usage, 'state' => $state]; + } + + $offset += self::PAGE_SIZE; + $pageSize = count($page); + } while ($pageSize === self::PAGE_SIZE); + }//end foreach + + foreach ($this->trash()['usage'] as $usage) { + $usages[] = ['entity' => $usage, 'state' => self::STATE_DELETED]; + } + + return $usages; + }//end usagesInEveryState() + + /** + * The modules with these uuids, in every state, each with its state. + * + * Per chunk of PAGE_SIZE uuids one search without a lens and one with + * the archive lens; the rest is looked up in the trash. + * + * @param array $uuids The module uuids. + * + * @return array Uuid => entity and state. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function modulesByUuid(array $uuids): array { + $coordinates = $this->coordinates(); + $modules = []; + foreach (array_chunk($uuids, self::PAGE_SIZE) as $chunk) { + // The chunks are disjoint, so a uuid found in an earlier chunk is never overwritten. + $modules += $this->modulesInChunk(chunk: $chunk, coordinates: $coordinates); + } + + foreach ($uuids as $uuid) { + $trashed = ($this->trash()['module'][$uuid] ?? null); + if (isset($modules[$uuid]) === false && $trashed !== null) { + $modules[$uuid] = ['entity' => $trashed, 'state' => self::STATE_DELETED]; + } + } + + return $modules; + }//end modulesByUuid() + + /** + * The working and archived modules of one chunk of uuids; a module both lenses return keeps the first state. + * + * @param array $chunk At most PAGE_SIZE module uuids. + * @param array $coordinates The object service and register and schema ids, from coordinates(). + * + * @return array Uuid => entity and state. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function modulesInChunk(array $chunk, array $coordinates): array { + $modules = []; + foreach ([[[], self::STATE_WORKING], [self::ARCHIVED_LENS, self::STATE_ARCHIVED]] as [$lens, $state]) { + $results = $coordinates['objectService']->searchObjects( + query: array_merge( + ['@self' => ['register' => $coordinates['register'], 'schema' => $coordinates['module']], '_ids' => $chunk, '_limit' => count($chunk)], + $lens + ), + _rbac: false, + _multitenancy: false + ); + if (is_array($results) === false) { + continue; + } + + foreach ($results as $entity) { + $uuid = (string)$entity->getUuid(); + if (in_array($uuid, $chunk, true) === true && isset($modules[$uuid]) === false) { + $modules[$uuid] = ['entity' => $entity, 'state' => $state]; + } + } + } + + return $modules; + }//end modulesInChunk() + + /** + * Archive or soft-delete one application that left the CMDB sheets, usage first, in its own error boundary. + * + * The usage is written before the module, so a failure between the two + * leaves the municipality's view right and the module at worst visible. + * An application already in the state the export asks for is not reported. + * + * @param array{key: string, usage: object, module: object, states: array} $application Application. + * @param array{sheet: string, present: bool, keyColumnMissing: bool, keys: array} $archive The archive sheet. + * @param string $operationId The operation id, for the archive reason. + * @param CmdbImportReport $report The report. + * + * @return void + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function reconcileApplication(array $application, array $archive, string $operationId, CmdbImportReport $report): void { + $moduleData = $application['module']->getObject(); + $onArchiveSheet = ($archive['present'] === true && isset($archive['keys'][$application['key']]) === true); + $entry = [ + 'sheet' => '', + 'row' => 0, + 'appId' => (string)($moduleData['externalNumber'] ?? $application['key']), + 'name' => (string)($moduleData['name'] ?? ''), + ]; + + $target = CmdbImportReport::ARCHIVED; + $reason = self::REASON_PREFIX . 'not in the export (' . $operationId . ')'; + if ($onArchiveSheet === true) { + $entry['sheet'] = $archive['sheet']; + $reason = self::REASON_PREFIX . 'on sheet "' . $archive['sheet'] . '" (' . $operationId . ')'; + } elseif ($archive['present'] === true) { + $target = CmdbImportReport::DELETED; + } + + $uuids = ['module' => (string)$application['module']->getUuid(), 'usage' => (string)$application['usage']->getUuid()]; + $step = 'archive'; + $changed = false; + try { + foreach (['usage', 'module'] as $schemaKey) { + foreach (self::transitions(state: $application['states'][$schemaKey], target: $target, restoreDeleted: $onArchiveSheet) as $step) { + $this->transition(step: $step, schemaKey: $schemaKey, uuid: $uuids[$schemaKey], reason: $reason); + $changed = true; + } + } + } catch (Throwable $e) { + // The module's stored values are taken out of the log line, as a row's cells are. + $values = array_map('strval', array_filter($moduleData, static fn (mixed $value): bool => is_scalar($value))); + $this->failRow(report: $report, entry: $entry, step: $step, e: $e, warnings: [], uuids: [$uuids['module'], $uuids['usage']], values: $values); + return; + } + + if ($changed === true) { + $this->addRow(report: $report, entry: $entry, outcome: $target, moduleUuid: $uuids['module'], usageUuid: $uuids['usage']); + } + }//end reconcileApplication() + + /** + * The steps that bring one module or usage to the state the export asks for (design D5). + * + * Deleted: soft-delete what is not in the trash yet. Archived: archive + * what is working; an object in the trash is restored first only when the + * archive sheet lists it, so a workbook without the sheet never takes + * anything out of the trash. + * + * @param array{archived: bool, deleted: bool} $state The object's state. + * @param string $target archived or deleted. + * @param bool $restoreDeleted Whether an object in the trash is restored to be archived. + * + * @return array delete, restore and archive, in order; empty when nothing changes. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private static function transitions(array $state, string $target, bool $restoreDeleted): array { + if ($target === CmdbImportReport::DELETED) { + if ($state['deleted'] === true) { + return []; + } + + return ['delete']; + } + + if ($state['deleted'] === true) { + if ($restoreDeleted === true) { + return ['restore', 'archive']; + } + + return []; + } + + if ($state['archived'] === true) { + return []; + } + + return ['archive']; + }//end transitions() + + /** + * Run one step through OpenRegister: soft delete, restore from the trash, or archive. + * + * @param string $step delete, restore or archive. + * @param string $schemaKey The coordinates key of the schema. + * @param string $uuid The object. + * @param string $reason The archive reason. + * + * @return void + * + * @throws RuntimeException When OpenRegister does not delete the object. + * + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 + */ + private function transition(string $step, string $schemaKey, string $uuid, string $reason): void { + if ($step === 'delete') { + $coordinates = $this->coordinates(); + $deleted = $coordinates['objectService']->deleteObject( + uuid: $uuid, + register: $coordinates['register'], + schema: $coordinates[$schemaKey], + _rbac: false, + _multitenancy: false + ); + if ($deleted !== true) { + throw new RuntimeException('OpenRegister did not delete the object'); + } + + return; + } + + if ($step === 'restore') { + $this->restore(uuid: $uuid); + return; + } + + $this->archiveServices()['handler']->archive(identifier: $uuid, reason: $reason); + }//end transition() + /** * Resolve OpenRegister's mapping engine. * @@ -1915,6 +2734,8 @@ private function resetRun(): void { $this->winningSheets = []; $this->contactUids = []; $this->contactPersons = []; + $this->archiveServices = null; + $this->trash = null; }//end resetRun() /** diff --git a/lib/Service/ProgressTracker.php b/lib/Service/ProgressTracker.php index b0c9ce22..5a9706ad 100644 --- a/lib/Service/ProgressTracker.php +++ b/lib/Service/ProgressTracker.php @@ -62,6 +62,11 @@ class ProgressTracker { 'processing_relationships' => ['weight' => 15, 'description' => 'Processing relationships'], 'processing_organizations' => ['weight' => 10, 'description' => 'Processing organizations'], 'processing_views' => ['weight' => 10, 'description' => 'Processing views'], + // The CMDB import's reconciliation of records missing from the source + // (openspec/changes/cmdb-import-archive-reconciliation). Weight 0, so the + // weighted percentage of the ArchiMate import's phases is unchanged; the + // CMDB section computes its own percentage from the item counts. + 'reconciling' => ['weight' => 0, 'description' => 'Reconciling records missing from the source'], 'finalizing' => ['weight' => 5, 'description' => 'Finalizing import'], 'completed' => ['weight' => 0, 'description' => 'Completed'], ]; diff --git a/lib/Settings/cmdb-import/topdesk-profile.json b/lib/Settings/cmdb-import/topdesk-profile.json index 79dc4325..a6b3df2d 100644 --- a/lib/Settings/cmdb-import/topdesk-profile.json +++ b/lib/Settings/cmdb-import/topdesk-profile.json @@ -1,8 +1,8 @@ { "id": "topdesk-cmdb", "name": "TOPdesk CMDB export", - "version": "2.0.0", - "description": "How stackiq reads a TOPdesk CMDB export (xlsx): the two CMDB sheets, the key and required columns, date and id columns, values that mean empty, the pack per target and the limits. Columns that neither this profile nor a pack names are never read.", + "version": "2.1.0", + "description": "How stackiq reads a TOPdesk CMDB export (xlsx): the two CMDB sheets, the archive sheet (APPID column only), the key and required columns, date and id columns, values that mean empty, the pack per target, the accepted missingRecords modes and the limits. Columns that neither this profile nor a pack names are never read.", "maxFileBytes": 10485760, "maxRowsPerSheet": 10000, "maxUncompressedBytes": 52428800, @@ -21,6 +21,7 @@ } ], "sheetPrecedence": ["Beheerde Applicaties CMDB", "Onbeh Applicaties CMDB"], + "archiveSheet": { "name": "Gearchiveerde Applicaties" }, "keyColumn": "APPID", "nameColumn": "Applicatie Naam", "requiredColumns": ["APPID", "Applicatie Naam"], @@ -44,5 +45,5 @@ "neverWritten": { "module": ["publicationDate", "depublicationDate"] }, - "missingRecords": ["keep"] + "missingRecords": ["keep", "archive"] } diff --git a/lib/Settings/register.d/topdesk-cmdb-import.json b/lib/Settings/register.d/topdesk-cmdb-import.json index 5fb30009..977c5db2 100644 --- a/lib/Settings/register.d/topdesk-cmdb-import.json +++ b/lib/Settings/register.d/topdesk-cmdb-import.json @@ -2,7 +2,10 @@ "components": { "schemas": { "module": { - "version": "0.3.8", + "version": "0.3.9", + "configuration": { + "x-openregister-archive": { "enabled": true } + }, "properties": { "externalId": { "type": "string", @@ -72,8 +75,9 @@ } }, "usage": { - "version": "1.5.6", + "version": "1.5.7", "configuration": { + "x-openregister-archive": { "enabled": true }, "x-openregister-lifecycle": { "transitions": { "importAcquisition": { diff --git a/openapi.json b/openapi.json index 7ee628b8..6469cf20 100644 --- a/openapi.json +++ b/openapi.json @@ -62,10 +62,11 @@ "missingRecords": { "type": "string", "enum": [ - "keep" + "keep", + "archive" ], - "default": "keep", - "description": "Only keep is accepted; mark and remove are reserved" + "default": "archive", + "description": "What happens to the municipality's applications whose APPID is no longer on either CMDB sheet. archive: after the last row, archive module and usage when the sheet \"Gearchiveerde Applicaties\" lists the APPID, soft-delete them when no sheet does, and archive only when the workbook has no archive sheet; an archived or deleted application that returns is unarchived or restored. keep: leave them as they are. mark and remove are reserved and refused with 422 MISSING_RECORDS_UNSUPPORTED" }, "operationId": { "type": "string", @@ -128,7 +129,7 @@ } }, "422": { - "description": "MISSING_RECORDS_UNSUPPORTED, MUNICIPALITY_REQUIRED, MUNICIPALITY_INVALID, MUNICIPALITY_AMBIGUOUS (more than one live Municipality has the typed name; details.matches lists their uuids), NO_SOURCE_SHEET, MISSING_COLUMN or TOO_MANY_ROWS", + "description": "MISSING_RECORDS_UNSUPPORTED (details.accepted lists keep and archive), MUNICIPALITY_REQUIRED, MUNICIPALITY_INVALID, MUNICIPALITY_AMBIGUOUS (more than one live Municipality has the typed name; details.matches lists their uuids), NO_SOURCE_SHEET, MISSING_COLUMN or TOO_MANY_ROWS", "content": { "application/json": { "schema": { @@ -148,7 +149,7 @@ } }, "503": { - "description": "MAPPING_UNAVAILABLE, READER_UNAVAILABLE, NOT_CONFIGURED, or SCHEMA_OUTDATED (a stackiq schema lacks a property the import matches on, or the module schema predates 0.3.8; details.schema names it and details.missing lists the properties, and externalKey.authorization.update for a missing admin-only write rule)", + "description": "MAPPING_UNAVAILABLE, READER_UNAVAILABLE, NOT_CONFIGURED, or SCHEMA_OUTDATED (a stackiq schema lacks a property the import matches on, or the module schema predates 0.3.8; details.schema names it and details.missing lists the properties, and externalKey.authorization.update for a missing admin-only write rule), or ARCHIVE_UNAVAILABLE (missingRecords=archive, but OpenRegister's archive handler or object mapper is missing; nothing is read or written)", "content": { "application/json": { "schema": { @@ -499,6 +500,10 @@ "unchanged", "skipped", "failed", + "archived", + "unarchived", + "deleted", + "restored", "warnings", "unpublished" ], @@ -524,6 +529,22 @@ "failed": { "type": "integer" }, + "archived": { + "type": "integer", + "description": "Applications whose module and usage this import archived because they left the CMDB sheets" + }, + "unarchived": { + "type": "integer", + "description": "Rows whose archived module or usage this import unarchived before updating it" + }, + "deleted": { + "type": "integer", + "description": "Applications whose module and usage this import soft-deleted because no sheet lists them any more" + }, + "restored": { + "type": "integer", + "description": "Rows whose soft-deleted module or usage this import restored from the trash before updating it" + }, "warnings": { "type": "integer" }, @@ -571,7 +592,8 @@ "type": "string" }, "row": { - "type": "integer" + "type": "integer", + "description": "The sheet row, or 0 for an application the reconciliation archived or deleted" }, "appId": { "type": "string" @@ -586,7 +608,11 @@ "updated", "unchanged", "skipped", - "failed" + "failed", + "archived", + "unarchived", + "deleted", + "restored" ] }, "reasons": { diff --git a/openspec/changes/cmdb-import-archive-reconciliation/.openspec.yaml b/openspec/changes/cmdb-import-archive-reconciliation/.openspec.yaml new file mode 100644 index 00000000..5c0f6674 --- /dev/null +++ b/openspec/changes/cmdb-import-archive-reconciliation/.openspec.yaml @@ -0,0 +1,2 @@ +schema: conduction +created: 2026-10-09 diff --git a/openspec/changes/cmdb-import-archive-reconciliation/design.md b/openspec/changes/cmdb-import-archive-reconciliation/design.md new file mode 100644 index 00000000..f71cfcce --- /dev/null +++ b/openspec/changes/cmdb-import-archive-reconciliation/design.md @@ -0,0 +1,207 @@ +# Design: cmdb-import-archive-reconciliation + +## Context + +The CMDB import (archived change `2026-10-05-cmdb-export-import`) matches rows on `module.externalKey` = `topdesk::` and leaves records that are missing from a newer export untouched (REQ-CMDB-012). The municipality's export carries, next to the two CMDB sheets, a sheet "Gearchiveerde Applicaties" (columns Applicatiecomponent, APPID, Applicatie Code, Applicatie Naam, Roepnaam, Applicatie Status, Bron, Datum Interface, Datum wijziging), derived from the raw "Invoer gearchiveerde appl" sheet. The municipality wants an application that moved there to be archived, and one that is on no sheet any more to be soft-deleted (2026-10-01). + +What OpenRegister offers (origin/beta `ff4dad5c`, identical to development for `lib/`): + +- **Soft delete.** `ObjectServiceInterface::deleteObject(uuid, register, schema, ...)` writes `@self.deleted` (`deletedBy`, `deletedAt`, `purgeDate` 30 days on). Lists exclude deleted objects unless `_includeDeleted=true`, but the list search cannot return one even then (D9). `MagicMapper::findDeletedAcrossAllMagicTables()` lists the trash; `MagicMapper::restoreObject(uuid)` clears the marker. `DeletedController` uses both. +- **Archive.** `ObjectEntity::archive()` / `unarchive()` write and clear `@self.archived` (`by`, `at`, `reason`). `Service\Object\ArchiveHandler::archive()` / `unarchive()` is the service path behind `POST` / `DELETE /api/objects/{register}/{schema}/{id}/archive`: it resolves the object, refuses a schema without `x-openregister-archive: {enabled: true}` (`ArchiveNotOfferedException`), checks `update` on the object for the session user, persists the marker and writes an audit entry. Lists exclude archived objects unless `_archived=true` (only the archive) or `_archived=any`. A read by identifier is unaffected. `SaveObject` refuses a data write to an archived object (`ObjectStateWriteException`). +- **Search lenses** combine in SQL: `_ids`, `_includeDeleted` and `_archived` apply together in `MagicSearchHandler`. Its row conversion, however, drops a soft-deleted row and hydrates no archive marker (D9). + +OpenCatalogi (beta `df25ff75`) passes list parameters through to OpenRegister and forces `_includeDeleted=false`; it has no archive filter of its own, so `_archived=true` reaches OpenRegister unchanged. Portaliq (beta `8287e390`) lists usages with neither lens. Both hide archived and deleted records as they are (decided 2026-10-09). + +## Goals / Non-Goals + +**Goals** + +- A re-import archives what moved to the archive sheet and soft-deletes what left the export entirely, for the imported municipality only. +- A returning application is revived, never duplicated. +- The admin sees and chooses the behaviour, and the report accounts for every archived, unarchived, deleted and restored application. +- Archived applications and usages can be listed in stackiq on request and stay out of OpenCatalogi and Portaliq without a change there. + +**Non-Goals** + +- Hard deletion, the trash's retention, contact persons, suppliers, modules another organisation imported (a module carrying this municipality's import key is this municipality's record, also when another organisation uses it; D5), changes to OpenCatalogi or Portaliq, an archive widget on the detail pages. + +## Architecture Overview + +``` +CmdbImportController::import() missingRecords: keep | archive (default archive); remove → 422 + ▼ +CmdbExportImportService::import() + ├─ resolve ArchiveHandler + MagicMapper (archive mode only; missing → 503 ARCHIVE_UNAVAILABLE) + ├─ lock the register + ├─ CmdbWorkbookReader::read() CMDB sheets as before + the archive sheet's APPID column + ├─ rows, each in its own boundary match module and usage: working, then _archived=true, then the trash (D9) + │ archived match → unarchive, deleted match → restore (and unarchive), then the usual update + └─ reconcile() (archive mode, not cancelled) phase `reconciling`, same lock + page usages (consumer = municipality): working, then _archived=true; deleted ones from the trash + load their modules in batches (_ids: working, then _archived=true; the rest from the trash) + per application: key on CMDB sheets → nothing + key on archive sheet → archive module + usage (restore first when deleted) + key nowhere → soft-delete module + usage, or archive when the sheet is absent + each in its own boundary → report rows archived | deleted | failed + ▼ +OpenRegister: module, usage (archived / deleted markers); contactPerson, organization untouched + ├─▶ OpenCatalogi: archived modules only with _archived=true + └─▶ Portaliq: archived and deleted usages disappear from "Software we use" +``` + +## Decisions + +### D1. "Archived" is OpenRegister's archive state on the module and on the usage + +Decided by the product owner on 2026-10-09. No new field, no new `usage.status` value, no `depublicationDate`. + +- **Alternative: `usage.status` `Archived`.** Rejected: OpenCatalogi drops `status === 'archived'` only on `/api/search`, so `/api/{catalogSlug}` and the federation route would need an OpenCatalogi change and a new beta. +- **Alternative: `module.depublicationDate`.** Rejected: the module read rule does not look at it, and the import never writes it (D6 of the first change). + +Both schemas opt in through the register fragment: `module` 0.3.8 → 0.3.9 and `usage` 1.5.6 → 1.5.7 get `configuration.x-openregister-archive: {"enabled": true}`. Fragments are merged by key union and the loader keeps the highest `version` per schema, so the bump deploys with the existing register import. The `SCHEMA_OUTDATED` check is not widened: an installation whose schemas predate the annotation gets `ArchiveNotOfferedException` per object, which the reconciliation reports as a failed row (D7), and the docs point to Force Update. + +### D2. The option: `keep | archive`, default `archive` + +`CmdbImportProfile::missingRecordsModes()` reads the accepted values from the profile (`["keep", "archive"]`) without validating the packs, like `maxFileBytes()`, because the controller checks the option before the import runs. The default lives in `CmdbExportImportService::DEFAULT_MISSING_RECORDS`. `remove` and `mark` stay reserved: 422 `MISSING_RECORDS_UNSUPPORTED` with `details.accepted` naming both accepted values. The section sends the admin's choice as `missingRecords` and defaults to `archive`. + +With `updateExisting=false`, a matched row is skipped as `exists` before anything is revived, as before: the admin asked to leave existing records alone. + +### D3. Reading the archive sheet + +The profile names the sheet (`archiveSheet.name`: "Gearchiveerde Applicaties"). The reader lists the workbook's sheets, and when the archive sheet is present it is loaded with the CMDB sheets under the same bounds: it counts as a read sheet for `CmdbPartReferences` (an oversized archive sheet is refused, not blanked) and for the referenced-string budget, its row span is bounded like a source sheet, and `TOO_MANY_ROWS` names it. Only its APPID column is resolved and read; the allowlist does not grow. The reader returns `archive: {present, keyColumnMissing, appIds}` next to `rows`. + +- Sheet absent, or present without an APPID column: `present` false (with `keyColumnMissing`), and the service adds a report warning. The reconciliation then archives every missing application and soft-deletes nothing: a workbook saved without the sheet must not empty the trash-bound set by accident. +- The archive sheet's other columns are not read; `Applicatie Status` there is always `Verwijderd` in the municipality's export and adds nothing. + +### D4. Matching widens to archived and deleted objects, and revives what it matches + +`matchModule()` looks the module up by `externalKey` in every state, as D9 reads it; `moduleBelongsTo()` looks up this municipality's usage the same way (a module whose usage is archived still belongs to the municipality), and keeps the working lens for "does any other organisation use it". `upsertUsage()` finds the usage in every state. Whatever is matched is revived before it is written: a soft-deleted object is restored (`MagicMapper::restoreObject()`), and unarchived as well when the restored object says it was archived; an archived one is unarchived (`ArchiveHandler::unarchive()`), because `SaveObject` refuses a write to an archived object. The update starts from the object `restoreObject()` answers, not from the trash listing's copy. The row outcome is `restored` when anything was restored, else `unarchived` when anything was unarchived, else the usual `created | updated | unchanged`. When more than one object matches, `findInAnyState()` takes a working one before an archived one, and an archived one before one in the trash: before this change a module deleted by hand was invisible to the match, so the next import created a second one with the same `externalKey`, and reviving the deleted one would make two live modules. Organisations and contact persons keep the working lens: a deleted supplier is never matched. + +### D5. The reconciliation step + +Runs inside `runImport()` after the row loop, only when the loop finished (not cancelled) and `missingRecords` is `archive`, under the register lock the import already holds. It checks for a cancel once before it loads the scope (a cancel that came in during the last row) and again before each application; a cancel stops it there, keeps what was already archived or deleted, and marks the report cancelled. An exception outside an object's boundary fails the run like any other (`IMPORT_FAILED`, operation `failed`), so a half-done reconciliation is visible. + +Scope: the usages whose `consumer` is the municipality, in every state as D9 reads it: paged with `PAGE_SIZE` without a lens and with `_archived=true`, plus the deleted ones from the trash. Their modules are loaded in chunks of `PAGE_SIZE` with `_ids`, without a lens and with `_archived=true`, and the rest from the trash. Every usage and module keeps the state D9 gave it; the table below decides on that state. Only a module whose `externalKey` starts with `topdesk::` is an imported application; the key after the last `:` is the APPID's match key. A usage without such a module (a hand-made usage, or a module another organisation imported) is left alone. + +Per application, with `processed` = every APPID match key on the CMDB sheets (whatever the row's outcome: a row that failed or was skipped is still in the export) and `archived` = the match keys on the archive sheet: + +| key is | module/usage state | action | outcome | +|---|---|---|---| +| on a CMDB sheet | any | nothing (the row handled it) | — | +| on the archive sheet | working | archive usage, then module | `archived` | +| on the archive sheet | archived | nothing | — | +| on the archive sheet | deleted | restore, then archive | `archived` | +| nowhere, sheet present | working or archived | soft-delete usage, then module | `deleted` | +| nowhere, sheet present | deleted | nothing | — | +| nowhere, sheet absent | working | archive usage, then module | `archived` | +| nowhere, sheet absent | archived or deleted | nothing | — | + +The usage is written before the module, so a failure between the two leaves the municipality's usage in the new state and the module visible, never the reverse. A module another municipality still uses is archived or deleted all the same when this municipality's usage says so: the module carries this municipality's import key, so it is this municipality's record (REQ-CMDB-006 allows a shared module only when the other organisation's usage was added by hand). The archive reason is `cmdb-import: on sheet "Gearchiveerde Applicaties"` or `cmdb-import: not in the export`, plus the operation id, so the audit trail says why. + +Each application runs in its own boundary: a failure is a `failed` row naming the step (`archive`, `restore`, `delete`) and the exception class, as row failures do, and the other applications continue. Contact persons are never touched. + +Progress: the operation gets the phase `reconciling` (added to `ProgressTracker::PHASES` with weight 0, so the ArchiMate import's weighted percentage is unchanged), `total_items` grows by the number of usages in scope, and `processed_items` advances per application; the section's own percentage comes from those counts. + +### D6. The report + +`CmdbImportReport` gains the outcomes `archived`, `unarchived`, `deleted` and `restored`; `summary()` counts them like the others. Reconciliation rows carry the archive sheet's name (for `archived` from the sheet) or an empty sheet, row 0, the APPID (`externalNumber`), the module name and both uuids: no person data. `toStoredArray()` ranks them with the rest. The section shows the four counts as summary tiles when they are non-zero, and the outcome filter offers them. + +### D7. Failure modes + +- `ArchiveHandler` or `MagicMapper` missing, or without a method the import calls (`archive`, `unarchive`, `restoreObject`, `findDeletedAcrossAllMagicTables`): 503 `ARCHIVE_UNAVAILABLE` before the lock is taken, only in archive mode. `keep` needs neither: without them the trash cannot be read, so a soft-deleted module or usage is not matched (the log says so) and a row whose match must be unarchived fails at step `module` or `usage`. +- A schema without `x-openregister-archive`: `ArchiveNotOfferedException` from OpenRegister per object → a failed row with the exception class; the docs say to run Force Update. +- A failure while reviving a matched row: the row fails at step `module` or `usage` like any other row failure. + +### D8. Stackiq UI + +The Applications (`Modules`, a `FacetedCatalogIndexView` that forwards `quickFilters` to `CnIndexPage`) and Applications in use (`Gebruik`) pages get the quick filter `{"label": "Archived", "filter": {"_archived": "true"}}`. `useSelfFetchList` spreads the active tab's filter into the fetch parameters as they are, so `_archived=true` reaches OpenRegister and the list shows the archive alone; the facet narrowing's `_ids` composes with it (AND). The icon `ArchiveOutline` is registered in `src/icons.js`. `@conduction/nextcloud-vue` 2.65 renders no `@self.archived` on a detail page or in the sidebar metadata, so the detail pages show no archive state yet; that is a library follow-up, not a stackiq widget. + +### D9. How the import reads the state of a stored object + +Found on a Nextcloud 35 rig with OpenRegister 2.1.37-beta (origin/beta `ff4dad5c`): the second import of the original export left APPID 1234 archived (`unchanged`) and created a second module for APPID 2. `ObjectService::searchObjects()` (via `QueryHandler::searchObjects()` → `MagicMapper::searchObjects()` → `MagicSearchHandler::searchObjects()`) applies the lenses in SQL (`buildFilteredQuery()` → `applyBasicFilters()`, `MagicSearchHandler.php` 2135–2153), but converts each row with `MagicSearchHandler::convertRowToObjectEntity()` (3780), which: + +- reads no `_archived` column, so every result keeps `ObjectEntity::$archived = []` (`ObjectEntity.php` 334) and looks working; +- turns the `_deleted` marker into `new DateTime(...)` (3896–3898), but `DeleteObject` writes it as a JSON object (`DeleteObject.php` 361), so the conversion throws, the row becomes null (4035) and `executeSearchQuery()` skips it (3714): `_includeDeleted=true` returns no soft-deleted object. + +So the import never reads the state from a search result: + +- **Working**: found by a search without a lens. **Archived**: found by a search with `_archived=true` (the archive alone, not deleted). An object is looked up working first, then archived. +- **Deleted**: from `MagicMapper::findDeletedAcrossAllMagicTables(_rbac: false, _multitenancy: false)`, the listing behind the Deleted page, which reads the rows itself (`MagicMapper.php` 7001). It scans every magic table of the instance and pages only after merging them, so the import reads it once per run, lazily, and keeps this register's modules and usages. Its objects carry data but no markers (`MagicMapper::rowToObjectEntity()`, 9131), and that data has every string that parses as JSON decoded ("2" becomes 2), so it is never written back. +- **Deleted and archived**: the trash does not say. `MagicMapper::restoreObject()` clears `_deleted` (10078) and answers the object as the mapper reads it by uuid, through `MagicStatisticsHandler::convertRowToObjectEntity()`, which does decode `_archived` (`MagicStatisticsHandler.php` 631–652). A returning row unarchives it when that object is archived, and updates from it. The reconciliation does not need to know: an object in the trash is either left there or restored and archived, and `ArchiveHandler::archive()` leaves an archived object as it is (`ArchiveHandler.php` 111). + +`ArchiveHandler::unarchive()` clears the marker to SQL NULL, so the object is back in the working lists, and does nothing for an object that is not archived (161). A lookup costs one search for a working match and two for an archived one or none, plus the one trash read per run. When OpenRegister hydrates both markers on search results, this can go back to one search with both lenses; the lens-based reading stays correct either way. + +## API Design + +`POST /api/cmdb-import`: `missingRecords` accepts `keep` and `archive` (default `archive`). The report's `summary` gains `archived`, `unarchived`, `deleted` and `restored`; `rows[].outcome` may be any of the four; reconciliation rows have `row: 0`. New error code 503 `ARCHIVE_UNAVAILABLE`. `MISSING_RECORDS_UNSUPPORTED` keeps its status and gains both accepted values in `details.accepted`. `openapi.json` is updated accordingly. + +## Database Changes + +None. The archive and delete markers are OpenRegister's metadata columns. + +## Mixed-spec rationale (ADR-032) + +The change is `kind: code`. Its only schema delta is the annotation `x-openregister-archive: {enabled: true}` on `module` and `usage` in the existing fragment `topdesk-cmdb-import.json`, with a version bump of both. The annotation is glue for this code: OpenRegister refuses to archive an object of a schema without it, and nothing else in stackiq reads it. It follows the fragment convention (ADR-037) and deploys with the existing register import. + +## Declarative-vs-imperative decision (ADR-031) + +- **Declarative:** which schemas may be archived (`x-openregister-archive` on `module` and `usage`), which sheet is the archive sheet and which option values are accepted (`topdesk-profile.json`), and which list shows the archive (the manifest quick filter `_archived=true`). +- **Imperative, because it is the external-integration exception the first change already claimed:** comparing an uploaded workbook with the register and deciding per application between nothing, archive, unarchive, soft-delete and restore. No `x-openregister-*` block can express "archive when the source lists it as archived and delete when the source no longer lists it": that rule depends on a file the register never sees. The state transitions themselves are OpenRegister's (`ArchiveHandler`, `deleteObject()`, `restoreObject()`); stackiq only decides when to call them. +- **Rule stated once, enforced in code:** the table in D5. + +## Nextcloud Integration + +- Controller: `CmdbImportController::import()` (unchanged auth: Nextcloud admins only, CSRF). +- Services: `CmdbExportImportService` (lenses, revival, reconciliation), `Cmdb\CmdbWorkbookReader` and `Cmdb\CmdbImportProfile` (archive sheet), `Cmdb\CmdbImportReport` (outcomes), `ProgressTracker` (phase). +- OpenRegister: `ObjectServiceInterface::searchObjects()` with `_archived` and `_ids`, `::deleteObject()` (contract); `Service\Object\ArchiveHandler::archive()` / `unarchive()` and `Db\MagicMapper::restoreObject()` / `findDeletedAcrossAllMagicTables()` (container, guarded, like the mapping engine). The handler checks `update` for the session user with RBAC on; the import is admin-only, so the check passes, and the audit entry names the admin. + +## Security Considerations + +- Still admin-only, CSRF-protected, with the file bounds of the first change; the archive sheet is read under the same bounds, APPID column only. +- Scope is the imported municipality's usages; a supplier's or another municipality's module is never archived or deleted through this municipality's import. +- Nothing is hard-deleted; every transition is an OpenRegister audit entry with a reason. +- The report and the logs carry APPIDs, module names and uuids, never owner data; contact persons are untouched. + +## NL Design System + +The section adds one radio group with a help text, built from `NcCheckboxRadioSwitch` like the existing switches, labelled and translated. The quick filter is the library's own chip. + +## File Structure + +``` +lib/Service/CmdbExportImportService.php lenses, revival, reconcile(), state helpers +lib/Service/Cmdb/CmdbWorkbookReader.php the archive sheet +lib/Service/Cmdb/CmdbImportProfile.php archiveSheetName(), readSheetNames(), missingRecordsModes() +lib/Service/Cmdb/CmdbImportReport.php archived | unarchived | deleted | restored +lib/Controller/CmdbImportController.php default archive, accepted values, ARCHIVE_UNAVAILABLE +lib/Exception/CmdbImportException.php ARCHIVE_UNAVAILABLE +lib/Service/ProgressTracker.php phase reconciling +lib/Settings/cmdb-import/topdesk-profile.json archiveSheet, missingRecords +lib/Settings/register.d/topdesk-cmdb-import.json x-openregister-archive, module 0.3.9, usage 1.5.7 +src/utils/cmdbImport.js, src/views/settings/sections/CmdbImport.vue +src/manifest.json, src/manifest.d/usages.json, src/icons.js +tests/Unit/..., tests/fixtures/cmdb/topdesk-archived-applications.xlsx, tests/e2e/spec-coverage/cmdb-import.spec.ts +docs/features/cmdb-import.md, l10n/en.json, l10n/nl.json +``` + +## Seed Data + +No seed objects change. The fragment's three seed modules stay as they are; the `module` and `usage` schemas gain only the archive annotation. + +## Risks / Trade-offs + +- [The default archives on the first re-import after the upgrade] → The section shows the choice with help text; the report lists every archived and deleted application; nothing is hard-deleted. +- [A workbook saved without the archive sheet] → archive only, never delete, plus a warning (D3). +- [A failure between the usage and the module] → the usage is written first, so the municipality's view is right and the module is at worst still visible (D5). +- [Reviving before writing adds calls per returning row] → only for rows whose match is archived or deleted; a row whose module is working costs the same searches as before, a new row one more search (the archive lens). +- [The trash listing scans every magic table of the instance] → read once per import, not per row (D9). +- [OpenRegister internals change shape] → guarded resolution, 503 before the file is read (D7). + +## Migration Plan + +No data migration. The fragment deploys with the existing register import (Force Update on an installation that already has the register). Rollback is a revert of the PR; archived or deleted objects keep their state and can be unarchived or restored by hand. + +## Open Questions + +- Should the library render `@self.archived` on detail pages, so an admin sees why an application is not in the list? (library follow-up) +- Should a module that no usage points at any more be archived as well? Out of scope here. diff --git a/openspec/changes/cmdb-import-archive-reconciliation/proposal.md b/openspec/changes/cmdb-import-archive-reconciliation/proposal.md new file mode 100644 index 00000000..7c27fdd8 --- /dev/null +++ b/openspec/changes/cmdb-import-archive-reconciliation/proposal.md @@ -0,0 +1,95 @@ +--- +kind: code +depends_on: [] +--- + +# Proposal: cmdb-import-archive-reconciliation + +## Summary + +A repeated CMDB import now reconciles the applications a municipality uses with the newer export. An application whose APPID is no longer on the two CMDB sheets but is listed on the export's sheet "Gearchiveerde Applicaties" is archived: its `module` and the municipality's `usage` get OpenRegister's archive state, so they drop out of every list and search until an admin asks for the archive. An application whose APPID is on no sheet at all is soft-deleted through OpenRegister's trash, from which it can be restored. An application that returns to the export is unarchived, or restored from the trash, and then updated as usual, so no duplicate is ever created. The import option `missingRecords` accepts `keep` and `archive`, and `archive` is the default; the settings section shows the choice. Stackiq's Applications and Applications in use pages get an "Archived" quick filter. The report gets the outcomes `archived`, `unarchived`, `deleted` and `restored`. + +## Motivation + +The first version of the import (openspec/changes/archive/2026-10-05-cmdb-export-import) left records that disappeared from a newer export untouched. The municipality delivers a new export every month and asked on 2026-10-01 (Jira WOO-587, parent WOO-586, epic WOO-281): an application that left the CMDB sheets but is on the archive sheet must be marked as archived and be findable in OpenCatalogi only with an explicit filter; an application that is on no sheet any more must be soft-deleted with the existing functionality. Without this, the catalogue keeps showing applications the municipality retired, and Portaliq keeps listing them under "Software we use". + +OpenRegister already has both states. Its archive state (`@self.archived`, `POST /api/objects/{register}/{schema}/{id}/archive`) keeps an object whole but out of every list unless `_archived=true` or `_archived=any` is asked; its soft delete (`@self.deleted`) puts an object in the trash for 30 days, from which it can be restored. OpenCatalogi passes the list parameters through to OpenRegister, and Portaliq lists usages without either lens, so both apps hide archived and deleted records with no change of their own (decided 2026-10-09). + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `cmdb-export-import`: `missingRecords` becomes `keep | archive` with `archive` as the default (REQ-CMDB-012 modified); the reconciliation of missing records against the archive sheet (REQ-CMDB-015), the return of an archived or deleted application (REQ-CMDB-016) and the archive lens in stackiq (REQ-CMDB-017) are added; the settings section shows the choice (REQ-CMDB-014 modified). The `module` and `usage` schemas opt into OpenRegister's archive state through the register fragment (see design.md, Mixed-spec rationale). + +## Affected Projects + +- [ ] Project: `stackiq`: import service, workbook reader and profile, controller option, register fragment, the "CMDB import" settings section, the manifest quick filters, tests, fixtures, administrator docs and translations. + +## Scope + +### In Scope + +- The sheet "Gearchiveerde Applicaties" (columns Applicatiecomponent, APPID, Applicatie Code, Applicatie Naam, Roepnaam, Applicatie Status, Bron, Datum Interface, Datum wijziging) is read for its APPID column only, when it is present. +- After every row of a completed import: the municipality's usages, with their modules, are compared with the APPIDs on the CMDB sheets and on the archive sheet. Missing and on the archive sheet: module and usage archived. Missing everywhere: module and usage soft-deleted. Without the archive sheet: archived only, with a warning in the report. +- A returning APPID: an archived module or usage is unarchived, a soft-deleted one is restored from the trash, and the row is then updated as before. +- `missingRecords`: `keep` leaves everything as it is (the behaviour so far), `archive` reconciles and is the default; `remove` stays reserved and is refused. +- The settings section offers the choice with help text; the report shows the new outcomes in its summary and rows. +- `x-openregister-archive` on the `module` and `usage` schemas through the register fragment, with a version bump. +- An "Archived" quick filter on the Applications and Applications in use pages. +- PHPUnit, Jest, a Playwright e2e for the re-import with the archive sheet, a fixture variant, docs and Dutch and English strings. + +### Out of Scope + +- Hard deletion of objects; the trash's own retention (30 days) stays OpenRegister's. +- Changes to the municipality's TOPdesk export, and the raw "Invoer gearchiveerde appl" sheet (the derived "Gearchiveerde Applicaties" sheet is the source). +- Contact persons: the owner of an archived or deleted application stays, because it is shared with the municipality's other applications. +- Modules only other organisations use, and organisations (suppliers) that no application names any more. +- An archive widget on the detail pages: `@conduction/nextcloud-vue` 2.65 does not render `@self.archived`; a follow-up once the library does. +- Changes to OpenCatalogi or Portaliq. + +## Approach + +`CmdbWorkbookReader` loads the archive sheet next to the two CMDB sheets when the workbook has it, under the same size and row bounds, and hands the import service the APPIDs it holds. `CmdbExportImportService` widens the match of a module (by import key) and of a usage (by consumer and module) to archived and soft-deleted objects, and revives what it matches before the usual update. After the last row, when the import was not cancelled and `missingRecords` is `archive`, a reconciliation step pages through the municipality's usages with no lens and with OpenRegister's `_archived=true` lens, reads the trash once through `MagicMapper::findDeletedAcrossAllMagicTables()` (a search with `_includeDeleted=true` returns no deleted rows on the current OpenRegister beta; design.md D9), loads their modules in batches, and archives, unarchives, soft-deletes or restores module and usage through OpenRegister's `ArchiveHandler`, `ObjectServiceInterface::deleteObject()` and `MagicMapper::restoreObject()`, each object in its own error boundary. The step runs under the import's register lock, reports its progress in a phase of its own, and adds its outcomes to the report. Details are in design.md. + +## New Dependencies + +None. `ArchiveHandler` and `MagicMapper` come from OpenRegister, which stackiq already requires; both are resolved through the container behind a guard, like the mapping engine. + +## Impact + +- **Backend**: `lib/Service/CmdbExportImportService.php` (match lenses, revival, reconciliation), `lib/Service/Cmdb/CmdbWorkbookReader.php` and `CmdbImportProfile.php` (archive sheet), `CmdbImportReport.php` (outcomes), `lib/Controller/CmdbImportController.php` (option default and accepted values), `lib/Service/ProgressTracker.php` (phase `reconciling`), `lib/Exception/CmdbImportException.php` (`ARCHIVE_UNAVAILABLE`). +- **Configuration**: `lib/Settings/cmdb-import/topdesk-profile.json` (archive sheet, accepted modes). +- **Schema**: `lib/Settings/register.d/topdesk-cmdb-import.json` declares `x-openregister-archive` on `module` (0.3.9) and `usage` (1.5.7). +- **Frontend**: `src/views/settings/sections/CmdbImport.vue`, `src/utils/cmdbImport.js`, `src/manifest.json`, `src/manifest.d/usages.json`, `src/icons.js`. +- **Data**: a re-import with the default option archives or soft-deletes modules and usages the export no longer lists. Nothing is hard-deleted; a soft-deleted object can be restored from OpenRegister's trash for 30 days. + +## Cross-Project Dependencies + +- **openregister** (consumed, not changed): `ObjectServiceInterface::deleteObject()` (contract), `Service\Object\ArchiveHandler` and `Db\MagicMapper::restoreObject()` and `findDeletedAcrossAllMagicTables()` (not public contracts, guarded), the `_archived` list lens, and the schema annotation `x-openregister-archive`. +- **opencatalogi** and **portaliq** (consumers, not changed): both list through OpenRegister's default lens, so archived and deleted applications disappear from them without a change; an OpenCatalogi caller finds archived applications with `_archived=true` on the existing public routes. + +## Risks + +### Risk 1: A re-import with the new default archives what an admin did not expect +**Severity:** Medium — **Mitigation:** only the municipality's own usages and the modules they point at are in scope, never a supplier's or another municipality's module; nothing is hard-deleted; the choice is visible in the section with help text, and the report lists every archived and deleted application. A cancelled or failed import never reconciles. + +### Risk 2: A workbook without the archive sheet soft-deletes everything that moved there +**Severity:** Medium — **Mitigation:** without the sheet, missing applications are archived, never soft-deleted, and the report warns that the sheet was not found. + +### Risk 3: The archive services are OpenRegister internals +**Severity:** Low — **Mitigation:** resolved through the container behind a guard; when missing, an import with `missingRecords=archive` is refused with 503 `ARCHIVE_UNAVAILABLE` before the file is read, and `keep` still works. + +### Risk 4: The schemas on an installation predate the annotation +**Severity:** Low — **Mitigation:** OpenRegister refuses to archive an object of a schema without `x-openregister-archive`; the import reports that object as failed and the docs point to Force Update, which deploys the fragment. + +## Rollback Strategy + +Revert the PR. Objects archived or soft-deleted by an import keep their state; an admin unarchives them through OpenRegister's object actions or restores them from the trash. The schema annotation may stay deployed without harm. + +## Open Questions + +- Should a module that no usage points at any more (every municipality archived it) be archived as well? Out of scope here; a supplier's module stays. diff --git a/openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md b/openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md new file mode 100644 index 00000000..1ac82745 --- /dev/null +++ b/openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md @@ -0,0 +1,191 @@ +# cmdb-export-import Specification + +**Status**: in-progress +**Scope**: stackiq +**OpenSpec changes**: +- [cmdb-export-import](../../../archive/2026-10-05-cmdb-export-import/) _(archived 2026-10-05)_ +- [cmdb-import-archive-reconciliation](../../) + +## Purpose + +A repeated CMDB import reconciles the applications a municipality uses with the newer export. An application whose APPID left the two CMDB sheets is archived in OpenRegister's archive state when the export's sheet "Gearchiveerde Applicaties" lists it, and soft-deleted into OpenRegister's trash when no sheet lists it any more; one that returns is unarchived or restored and updated as usual, never duplicated. Archived and deleted applications disappear from OpenCatalogi and Portaliq without a change there, and stackiq lists the archive on request (Jira WOO-587). + +OpenRegister: `OCA\OpenRegister\Contract\ObjectServiceInterface` (`searchObjects()` with no lens and with the `_archived=true` and `_ids` lenses, `deleteObject()`), `Service\Object\ArchiveHandler` (`archive()`, `unarchive()`) and `Db\MagicMapper` (`findDeletedAcrossAllMagicTables()` for the trash, `restoreObject()`) (both resolved through the container behind a guard; why the trash is read that way: design.md D9), and the schema annotation `x-openregister-archive`. + +## ADDED Requirements + +### Requirement: An application missing from the CMDB sheets SHALL be archived when the archive sheet lists it and soft-deleted when no sheet does (REQ-CMDB-015) + +With `missingRecords` `archive`, after every row of an import that was not cancelled and did not fail, the import SHALL reconcile, under the register lock it already holds, every `usage` whose `consumer` is the imported municipality together with the `module` it points at, including archived and soft-deleted ones, and only those whose module carries this municipality's import key (`topdesk::`). It SHALL read the APPID column of the sheet "Gearchiveerde Applicaties" when the workbook has it, under the same size and row bounds as the CMDB sheets and without reading any other column of it. For an application whose APPID is on neither CMDB sheet: when the archive sheet lists the APPID, the import SHALL archive the usage and then the module through OpenRegister's archive state with a reason that names the import, restoring a soft-deleted one from the trash first; when no sheet lists it, the import SHALL soft-delete the usage and then the module through OpenRegister's trash. When the workbook has no archive sheet, or the sheet has no APPID column, the import SHALL archive and SHALL NOT soft-delete, and SHALL add a warning to the report. An application that is already in the state the export asks for SHALL be left alone and not reported. The import SHALL NOT touch contact persons, organisations, modules that carry another municipality's import key or no import key, or usages of another organisation. Each application SHALL be reconciled in its own error boundary: a failure SHALL be a `failed` report row naming the step and the exception class, and the other applications SHALL still be reconciled. The reconciliation SHALL report its progress as the phase `reconciling` of the import's operation. A cancel SHALL also be honoured after the last row and before each application of the reconciliation: the import SHALL stop there, SHALL keep what it archived or deleted so far, and SHALL report the run as cancelled. The report SHALL count `archived` and `deleted` in its summary and SHALL list each as a row with the APPID, the application name and both uuids, never person data. When OpenRegister's archive handler or object mapper is not available, an import with `missingRecords` `archive` SHALL be refused with 503 `ARCHIVE_UNAVAILABLE` before the file is read. + +#### Scenario: An application that moved to the archive sheet is archived +@e2e tests/e2e/spec-coverage/cmdb-import.spec.ts + +- **GIVEN** the modules with APPID `1234` and `2` were imported for "Gemeente Voorbeeldstad" with their usages +- **WHEN** an export is imported in which `1234` is only on "Gearchiveerde Applicaties" and `2` is on no sheet +- **THEN** the module and the usage of `1234` SHALL carry OpenRegister's archive state and the report row SHALL be `archived` +- **AND** the module and the usage of `2` SHALL be in OpenRegister's trash and the report row SHALL be `deleted` +- **AND** the Applications page SHALL list `1234` under the quick filter "Archived" and neither under "All" +- **AND** the owner contact person SHALL be unchanged + +#### Scenario: Without the archive sheet a missing application is archived, never deleted +@e2e exclude Covered by the service test; tests/Unit/Service/CmdbExportImportServiceTest.php testWithoutTheArchiveSheetMissingApplicationsAreArchivedNotDeleted imports a workbook without the sheet and asserts the archive state, no delete, and the warning naming the sheet. + +- **GIVEN** the module with APPID `7` and its usage were imported +- **WHEN** a workbook without "Gearchiveerde Applicaties" that no longer lists `7` is imported +- **THEN** the module and the usage of `7` SHALL be archived and SHALL NOT be deleted +- **AND** the report SHALL carry a warning that the sheet "Gearchiveerde Applicaties" was not found + +#### Scenario: Keeping missing records, a cancelled import and another municipality leave everything as it is +@e2e exclude Covered by the service test; tests/Unit/Service/CmdbExportImportServiceTest.php testRecordsMissingFromTheExportStayWhenKept, testACancelledImportDoesNotReconcile and testAnotherMunicipalitysUsagesAreNeverReconciled assert no archive, no delete and no reconciliation row. + +- **GIVEN** the modules with APPID `1` and `7` and their usages for "Gemeente Voorbeeldstad", and a usage of `7` for "Gemeente Anders" +- **WHEN** an export with only `1` is imported with `missingRecords` `keep`, or with `archive` but cancelled after row 1 +- **THEN** no module or usage SHALL be archived or deleted +- **AND** when it is imported with `archive` and completes, only the usage of "Gemeente Voorbeeldstad" for `7` and the module SHALL be archived; the usage of "Gemeente Anders" SHALL be untouched + +#### Scenario: A cancel after the last row or during the reconciliation stops it +@e2e exclude Timing-dependent; tests/Unit/Service/CmdbExportImportServiceTest.php testACancelDuringTheLastRowArchivesNothing and testACancelDuringTheReconciliationStopsBeforeTheNextApplication request the cancel at those two moments and assert the transitions and the cancelled report. + +- **GIVEN** the modules with APPID `1`, `7` and `8` and their usages for "Gemeente Voorbeeldstad" +- **WHEN** an export with only `1`, and `7` and `8` on the archive sheet, is imported with `archive` and a cancel arrives while row `1` is processed +- **THEN** no module or usage SHALL be archived or deleted, and the report SHALL be cancelled +- **AND** when the cancel arrives instead while `7` is archived, `7` SHALL stay archived, `8` SHALL be left as it is, and the report SHALL be cancelled + +#### Scenario: One application that cannot be archived does not stop the others +@e2e exclude Fault injection; tests/Unit/Service/CmdbExportImportServiceTest.php testAFailingArchiveIsAFailedRowAndTheOthersAreReconciled makes the archive of one application throw and asserts a failed row naming the step, the other application archived, and the log line without a name. + +- **GIVEN** the modules with APPID `7` and `8` left the export and are on the archive sheet +- **WHEN** archiving `7` throws +- **THEN** the report SHALL list `7` as `failed` with the step `archive` and the exception class +- **AND** `8` SHALL be archived + +#### Scenario: Without the archive services an archiving import is refused before reading +@e2e exclude Environment condition; tests/Unit/Service/CmdbExportImportServiceTest.php testMissingArchiveServicesRefuseAnArchivingImport asserts 503 ARCHIVE_UNAVAILABLE with no read and no save, and that keep still imports; tests/Unit/Controller/CmdbImportControllerTest.php asserts the status and the translated message. + +- **GIVEN** an OpenRegister without `ArchiveHandler` +- **WHEN** an export is imported with `missingRecords` `archive` +- **THEN** the endpoint SHALL answer 503 with error `ARCHIVE_UNAVAILABLE` and nothing SHALL be read or written +- **AND** the same export with `keep` SHALL be imported + +### Requirement: An application that returns to the export SHALL be unarchived or restored, never duplicated (REQ-CMDB-016) + +The import SHALL match a module by its import key, and a usage by consumer and module, among archived and soft-deleted objects as well as working ones. Before it updates a matched module or usage that is archived, it SHALL unarchive it through OpenRegister's archive state; before it updates one that is soft-deleted, it SHALL restore it from the trash. It SHALL then update the row as REQ-CMDB-006 and REQ-CMDB-009 describe, and SHALL NOT create a second module or usage. The row's outcome SHALL be `restored` when a module or usage was restored, else `unarchived` when one was unarchived, else the usual outcome; the summary SHALL count both. With `updateExisting` false the row SHALL be skipped as `exists` and nothing SHALL be revived. When more than one module or usage matches, the import SHALL take a working one before an archived one, and an archived one before one in the trash, so a module deleted by hand next to the one a later import created SHALL NOT be restored. Organisations and contact persons SHALL keep matching among working objects only. + +#### Scenario: An archived application returns to the export +@e2e tests/e2e/spec-coverage/cmdb-import.spec.ts + +- **GIVEN** the module and the usage of APPID `1234` are archived and those of APPID `2` are in the trash +- **WHEN** an export that lists both on the CMDB sheets is imported +- **THEN** the report SHALL show `1234` as `unarchived` and `2` as `restored` +- **AND** there SHALL still be one module and one usage for each +- **AND** both SHALL be listed again without a lens + +#### Scenario: A returning application is not revived when existing records are not updated +@e2e exclude Covered by the service test; tests/Unit/Service/CmdbExportImportServiceTest.php testUpdateExistingFalseLeavesAnArchivedMatchArchived asserts the row is skipped as `exists`, the archive state stays and no object is created. + +- **GIVEN** the module and the usage of APPID `7` are archived +- **WHEN** a row with APPID `7` is imported with `updateExisting` false +- **THEN** the row SHALL be skipped with reason `exists` +- **AND** both SHALL stay archived, and no module or usage SHALL be created + +#### Scenario: A working match wins over a deleted one with the same import key +@e2e exclude Data condition from earlier imports; tests/Unit/Service/CmdbExportImportServiceTest.php testAWorkingMatchWinsOverADeletedOneWithTheSameKey stores a deleted module and usage ahead of the working ones and asserts the working ones are updated and nothing is restored. + +- **GIVEN** a module with APPID `7` in the trash and a working module with the same import key, each with a usage of "Gemeente Voorbeeldstad" +- **WHEN** a row with APPID `7` is imported +- **THEN** the working module and its usage SHALL be updated +- **AND** the module and the usage in the trash SHALL stay there, and nothing SHALL be restored + +### Requirement: Archived applications and usages SHALL be listable in stackiq and SHALL stay out of OpenCatalogi and Portaliq by default (REQ-CMDB-017) + +The `module` and `usage` schemas SHALL declare `x-openregister-archive` with `enabled` true through the register fragment `topdesk-cmdb-import.json`, as `module` 0.3.9 and `usage` 1.5.7, so OpenRegister offers the archive state on both. Stackiq's Applications and Applications in use pages SHALL offer a quick filter "Archived" that lists the archive alone (`_archived=true`). No change SHALL be made to OpenCatalogi or Portaliq: both list through OpenRegister's default lens, so an archived or deleted application is not in OpenCatalogi's search results or in Portaliq's "Software we use", and an OpenCatalogi caller finds archived applications with `_archived=true` on the existing routes. + +#### Scenario: The merged register offers the archive state on both schemas +@e2e exclude Configuration; tests/Unit/Settings/TopdeskCmdbFragmentTest.php testTheMergedSchemasOfferTheArchiveState asserts the versions and the annotation after merging every fragment. + +- **GIVEN** every register fragment merged in filename order +- **THEN** `module` SHALL be version 0.3.9 and `usage` 1.5.7 +- **AND** both SHALL declare `configuration.x-openregister-archive.enabled` true, and the usage lifecycle of 1.5.6 SHALL still be declared + +#### Scenario: The Applications page lists the archive on request +@e2e tests/e2e/spec-coverage/cmdb-import.spec.ts + +- **GIVEN** the module of APPID `1234` is archived +- **WHEN** an admin opens the Applications page +- **THEN** the module SHALL NOT be listed +- **AND** under the quick filter "Archived" it SHALL be listed + +## MODIFIED Requirements + +### Requirement: Records missing from a newer export SHALL be archived by default or kept on request (REQ-CMDB-012) + +The import SHALL accept `missingRecords` with the values `keep` and `archive`; `archive` is the default. With `keep` it SHALL NOT change, archive, depublish or delete a module, usage, organisation or contact person because its APPID is absent from the upload. With `archive` it SHALL reconcile as REQ-CMDB-015 describes. Any other value, including the reserved `mark` and `remove`, SHALL be refused with 422 `MISSING_RECORDS_UNSUPPORTED`, naming both accepted values in `details.accepted`. The accepted values SHALL be declared in the import profile. + +(Previously: `keep` was the only accepted value and the default; records missing from a newer export were always left untouched.) + +#### Scenario: An application dropped from the export stays when records are kept +@e2e exclude Covered by the service test; tests/Unit/Service/CmdbExportImportServiceTest.php testRecordsMissingFromTheExportStayWhenKept imports two rows, then one with `missingRecords` `keep`, and asserts the other module and usage are unchanged. + +- **GIVEN** the modules with APPID `1` and `7` were imported for "Gemeente Voorbeeldstad" +- **WHEN** a newer export that only contains APPID `1` is imported with `missingRecords` `keep` +- **THEN** the module with APPID `7` and its usage SHALL be unchanged + +#### Scenario: Without the option a missing application is reconciled +@e2e exclude Validation; tests/Unit/Controller/CmdbImportControllerTest.php testMissingRecordsDefaultsToArchive asserts the service receives `archive` when the field is absent and the sent value otherwise. + +- **GIVEN** a valid export +- **WHEN** a Nextcloud admin posts it without `missingRecords` +- **THEN** the import SHALL run with `archive` + +#### Scenario: A reserved value is refused +@e2e exclude Validation; tests/Unit/Controller/CmdbImportControllerTest.php testAReservedMissingRecordsValueIsRefused. + +- **GIVEN** a valid export +- **WHEN** a Nextcloud admin posts it with `missingRecords=remove` +- **THEN** the endpoint SHALL answer 422 with error `MISSING_RECORDS_UNSUPPORTED` and `details.accepted` `["keep", "archive"]` +- **AND** no object SHALL be written + +### Requirement: The admin settings SHALL offer a CMDB import section (REQ-CMDB-014) + +Stackiq's admin settings page SHALL show a section "CMDB import", rendered by the settings page and not registered as an in-app route. The section SHALL let the admin choose an existing municipality or type the name of a new one, choose an `.xlsx` file, choose what happens to applications missing from the export (archive, the default, or keep) with help text that says what each does, and start the import. While the import runs it SHALL show a progress bar and a Cancel button. Afterwards it SHALL show the summary, including the archived, unarchived, deleted and restored counts when they are not zero, and a report table that can be filtered by outcome, including the four new ones; a reconciliation row SHALL show no row number. Every control SHALL have a visible label, and every string SHALL be translatable. + +(Previously: the section had no choice for missing records; the request always sent `keep`.) + +#### Scenario: The admin runs an import from the settings page +@e2e tests/e2e/spec-coverage/cmdb-import.spec.ts + +- **GIVEN** a Nextcloud admin on stackiq's admin settings page +- **WHEN** they choose "Gemeente Voorbeeldstad", choose the anonymised export and press "Import" +- **THEN** a progress bar SHALL appear while the import runs +- **AND** afterwards the summary and the report table SHALL be shown +- **AND** filtering the table on `created` SHALL show the two imported rows + +#### Scenario: The admin chooses to keep missing applications +@e2e exclude Covered by the Jest test; src/utils/cmdbImport.spec.js asserts buildImportForm() sends `archive` by default and `keep` when chosen, and src/views/settings/sections/CmdbImport.spec.js asserts the section's default. + +- **GIVEN** the section +- **WHEN** the admin selects "Keep them as they are" and starts the import +- **THEN** the request SHALL carry `missingRecords=keep` +- **AND** without a choice it SHALL carry `missingRecords=archive` + +## Non-Functional Requirements + +- **Performance:** the reconciliation SHALL page the municipality's usages with the import's page size and load their modules in one search per page, so an export of 1,100 rows adds a handful of searches, and SHALL make no write for an application that is already in the state the export asks for. +- **Security:** unchanged from the first change; the archive sheet is read under the same bounds, APPID column only; the scope is the imported municipality's usages; nothing is hard-deleted; every state change is an OpenRegister audit entry. +- **Privacy:** reconciliation rows and log lines carry APPIDs, module names and uuids only; contact persons are never touched. +- **Accessibility:** Target WCAG 2.2 AA. The new choice is a labelled radio group (SC 1.3.1, 3.3.2; gates `form-label-association`, `nc-input-labels`) with help text; the summary tiles and the outcome filter follow the existing pattern. New in 2.2: 2.4.11, 2.5.8 and 3.3.7 apply as before; 2.5.7, 3.2.6 and 3.3.8 do not apply (no dragging, no help mechanism, no authentication). +- **Internationalization:** Dutch and English MUST be supported (ADR-005) for the choice, the outcomes, the warning and the error message. + +## Acceptance Criteria + +- [ ] A re-import with the archive sheet archives the application that moved there and soft-deletes the one on no sheet; the report shows `archived` and `deleted`. +- [ ] Importing the original export again unarchives and restores them; no duplicate is created. +- [ ] With "Keep them as they are" nothing is archived or deleted. +- [ ] The Applications and Applications in use pages list archived records only under "Archived". +- [ ] OpenCatalogi's search and Portaliq's "Software we use" no longer show an archived application; `_archived=true` on OpenCatalogi's route finds it. + +## Notes + +- The decision table per application is in the change's [design.md](../../design.md), D5. +- The library does not render `@self.archived` on detail pages yet; a follow-up for `@conduction/nextcloud-vue`. diff --git a/openspec/changes/cmdb-import-archive-reconciliation/tasks.md b/openspec/changes/cmdb-import-archive-reconciliation/tasks.md new file mode 100644 index 00000000..4ae74b82 --- /dev/null +++ b/openspec/changes/cmdb-import-archive-reconciliation/tasks.md @@ -0,0 +1,89 @@ +# Tasks: cmdb-import-archive-reconciliation + +Spec: `openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md` (`SPEC` below). Design: `design.md` (the decision table in D5 is authoritative for what happens per application). + +## Implementation Tasks + +### Task 1: Schema opt-in and the import profile +- **spec_ref**: `SPEC#requirement-archived-applications-and-usages-shall-be-listable-in-stackiq-and-shall-stay-out-of-opencatalogi-and-portaliq-by-default-req-cmdb-017`, `SPEC#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012` +- **files**: `lib/Settings/register.d/topdesk-cmdb-import.json`, `lib/Settings/cmdb-import/topdesk-profile.json`, `lib/Service/Cmdb/CmdbImportProfile.php`, `tests/Unit/Settings/TopdeskCmdbFragmentTest.php`, `tests/Unit/Settings/PublicationFieldRulesTest.php`, `tests/Unit/Service/Cmdb/CmdbImportProfileTest.php` +- **acceptance_criteria**: + - GIVEN every register fragment merged in filename order THEN `module` is 0.3.9 and `usage` is 1.5.7, both with `configuration.x-openregister-archive.enabled` true, and the usage lifecycle of 1.5.6 is still there + - GIVEN the profile THEN `archiveSheetName()` is "Gearchiveerde Applicaties", `readSheetNames()` lists the two CMDB sheets plus the archive sheet, and `missingRecordsModes()` is `["keep", "archive"]` without OpenRegister +- [x] Implement +- [x] Test + +### Task 2: The reader reads the archive sheet's APPIDs +- **spec_ref**: `SPEC#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015` +- **files**: `lib/Service/Cmdb/CmdbWorkbookReader.php`, `tests/Unit/Service/Cmdb/CmdbWorkbookReaderTest.php` +- **acceptance_criteria**: + - GIVEN the anonymised fixture THEN `read()` returns `archive.present` true and `archive.appIds` `["1198"]`, and the rows of the CMDB sheets are unchanged + - GIVEN a workbook without the sheet, or with the sheet but without an APPID column THEN `archive.present` is false (and `keyColumnMissing` says which), and the CMDB rows are still read + - GIVEN an archive sheet beyond the row limit THEN `TOO_MANY_ROWS` names it; only its APPID column is materialised +- [x] Implement +- [x] Test + +### Task 3: Matching revives archived and deleted applications +- **spec_ref**: `SPEC#requirement-an-application-that-returns-to-the-export-shall-be-unarchived-or-restored-never-duplicated-req-cmdb-016` +- **files**: `lib/Service/CmdbExportImportService.php`, `lib/Service/Cmdb/CmdbImportReport.php`, `tests/Unit/Service/CmdbExportImportServiceTest.php`, `tests/Unit/Service/Cmdb/CmdbImportReportTest.php` +- **acceptance_criteria**: + - GIVEN an archived module and usage for an APPID WHEN a row with that APPID is imported THEN both are unarchived before the update, no second module or usage exists, and the row's outcome is `unarchived` + - GIVEN a soft-deleted module and usage WHEN the row returns THEN both are restored from the trash and the outcome is `restored` + - GIVEN only the usage archived or soft-deleted THEN the usage alone is unarchived or restored, with that outcome, and no second usage exists + - GIVEN a module and usage soft-deleted while archived THEN both are restored and unarchived, the outcome is `restored`, and the update starts from the restored object (design D9) + - GIVEN OpenRegister's search results (no archive marker; no soft-deleted row, `_includeDeleted` or not) THEN the state comes from the lens that found the object and from the trash listing, read once per import (design D9) + - GIVEN `updateExisting` false THEN the row is skipped as `exists` and nothing is revived + - GIVEN a deleted and a working module (and usage) sharing one import key THEN the working one is updated and nothing is restored +- [x] Implement +- [x] Test + +### Task 4: Reconciliation after the rows +- **spec_ref**: `SPEC#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015` +- **files**: `lib/Service/CmdbExportImportService.php`, `lib/Service/ProgressTracker.php`, `lib/Exception/CmdbImportException.php`, `tests/Unit/Service/CmdbExportImportServiceTest.php` +- **acceptance_criteria**: + - GIVEN APPIDs 1 and 7 imported WHEN an export with row 1 and 7 on the archive sheet is imported THEN module and usage of 7 are archived with a reason, the report row is `archived`, and the owner contact person is untouched + - GIVEN APPID 7 on no sheet THEN module and usage are soft-deleted and the row is `deleted`; GIVEN the archive sheet absent THEN they are archived instead and the report warns + - GIVEN APPID 7 soft-deleted and listed on the archive sheet THEN module and usage are restored and archived; GIVEN it already archived or, when on no sheet, already deleted THEN nothing is written + - GIVEN `missingRecords` `keep`, a cancelled import, or a usage of another municipality THEN nothing is archived or deleted + - GIVEN a cancel during the last row THEN nothing is archived or deleted; GIVEN a cancel during the reconciliation THEN it stops before the next application and the report is cancelled + - GIVEN the archive of one application throws THEN that application is a `failed` row and the others are reconciled; GIVEN no ArchiveHandler THEN 503 `ARCHIVE_UNAVAILABLE` before reading + - GIVEN the step runs THEN the operation is in phase `reconciling` and its progress advances per application +- [x] Implement +- [x] Test + +### Task 5: Controller option +- **spec_ref**: `SPEC#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012` +- **files**: `lib/Controller/CmdbImportController.php`, `tests/Unit/Controller/CmdbImportControllerTest.php`, `openapi.json`, `postman/stackiq-tests.json`, `l10n/en.json`, `l10n/nl.json` +- **acceptance_criteria**: + - GIVEN no `missingRecords` THEN the service receives `archive`; GIVEN `keep` or `archive` THEN it is passed through; GIVEN `remove` or `mark` THEN 422 `MISSING_RECORDS_UNSUPPORTED` with `details.accepted` `["keep", "archive"]` and no import + - GIVEN `ARCHIVE_UNAVAILABLE` from the service THEN 503 with its own translated message +- [x] Implement +- [x] Test + +### Task 6: Settings section, report words and the archive quick filter +- **spec_ref**: `SPEC#requirement-the-admin-settings-shall-offer-a-cmdb-import-section-req-cmdb-014`, `SPEC#requirement-archived-applications-and-usages-shall-be-listable-in-stackiq-and-shall-stay-out-of-opencatalogi-and-portaliq-by-default-req-cmdb-017` +- **files**: `src/views/settings/sections/CmdbImport.vue`, `src/utils/cmdbImport.js`, `src/utils/cmdbImport.spec.js`, `src/views/settings/sections/CmdbImport.spec.js`, `tests/vitest/cmdbArchiveQuickFilter.spec.js`, `src/manifest.json`, `src/manifest.d/usages.json`, `src/icons.js`, `l10n/en.json`, `l10n/nl.json` +- **acceptance_criteria**: + - GIVEN the section THEN a labelled choice "Applications missing from the export" offers Archive (default) and Keep with help text, and `buildImportForm()` sends the choice as `missingRecords` + - GIVEN a report with the new outcomes THEN the summary shows their tiles, the outcome filter offers them, and a reconciliation row shows no row number + - GIVEN the Applications and Applications in use pages THEN a quick filter "Archived" sends `_archived=true` + - Every new string is in `l10n/en.json` and `l10n/nl.json`, and the generated `l10n/*.js` are current +- [x] Implement +- [x] Test + +### Task 7: Fixture, docs and e2e +- **spec_ref**: `SPEC#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015` +- **files**: `tests/fixtures/cmdb/build-fixtures.py`, `tests/fixtures/cmdb/topdesk-archived-applications.xlsx`, `tests/fixtures/cmdb/README.md`, `tests/Unit/Fixtures/CmdbFixtureHygieneTest.php`, `tests/Unit/Service/Cmdb/CmdbWorkbookReaderTest.php`, `tests/Unit/Service/CmdbExportImportServiceTest.php`, `tests/e2e/spec-coverage/cmdb-import.spec.ts`, `docs/features/cmdb-import.md`, `docs/features/README.md`, `CHANGELOG.md` +- **acceptance_criteria**: + - GIVEN `build-fixtures.py` THEN it derives `topdesk-archived-applications.xlsx`: APPID 1234 on the archive sheet only, APPID 2 on no sheet, both CMDB sheets present and empty; the hygiene test passes on it + - GIVEN the e2e THEN after the first import, importing the variant archives 1234 and soft-deletes 2, the Applications page lists 1234 under "Archived", and importing the original again reports 1234 `unarchived` and 2 `restored` with the object counts back to the first import's + - GIVEN the docs THEN "Repeat imports" describes archive, soft delete, the archive sheet, the option and the return of an application, and the error table has `ARCHIVE_UNAVAILABLE` and the new meaning of `MISSING_RECORDS_UNSUPPORTED` +- [x] Implement +- [ ] Test + - Status: PHPUnit covers the fixture round trip (testTheArchivedApplicationsFixtureArchivesDeletesAndBringsBack); the Playwright test is written and not run yet, because no Nextcloud was reachable from the worktree. + +## Quality checklist + +- PHPUnit for every new rule in the service, the reader and the controller; the fixture hygiene test covers the new variant +- Jest for the section's request and the report words; Playwright for the re-import with the archive sheet +- `composer test:unit`, `composer phpcs`, `composer lint`, `npm run test:unit`, `npm run lint`, `npm run format`, `npm run test:l10n`, `npm run check:l10n-js`, `npm run check:manifest`, `npm run check:schema-l10n` and `npm run check:vue-demi` pass diff --git a/openspec/specs/cmdb-export-import/spec.md b/openspec/specs/cmdb-export-import/spec.md index d2f7fd4b..927da9cf 100644 --- a/openspec/specs/cmdb-export-import/spec.md +++ b/openspec/specs/cmdb-export-import/spec.md @@ -1,15 +1,16 @@ --- capability: cmdb-export-import -status: done +status: in-progress built_by: openspec/changes/archive/2026-10-05-cmdb-export-import --- # cmdb-export-import Specification -**Status**: done +**Status**: in-progress **Scope**: stackiq **OpenSpec changes**: - [cmdb-export-import](../../changes/archive/2026-10-05-cmdb-export-import/) _(archived 2026-10-05)_ — admin uploads a TOPdesk CMDB export (xlsx); stackiq upserts modules, vendor organisations, usages and owner contact persons for one municipality from the two CMDB sheets, matched on APPID, mapped by OpenRegister migration packs (kind: code) +- [cmdb-import-archive-reconciliation](../../changes/cmdb-import-archive-reconciliation/) — a re-import archives the applications that moved to the sheet "Gearchiveerde Applicaties" and soft-deletes the ones on no sheet, revives the ones that return, with `missingRecords: keep | archive` (default archive) and an "Archived" quick filter (kind: code) ## Purpose diff --git a/postman/stackiq-tests.json b/postman/stackiq-tests.json index 385214b7..0da0499b 100644 --- a/postman/stackiq-tests.json +++ b/postman/stackiq-tests.json @@ -23073,9 +23073,10 @@ "listen": "test", "script": { "exec": [ - "pm.test(\"Only missingRecords=keep is accepted\", function () {", + "pm.test(\"Only missingRecords=keep or archive is accepted\", function () {", " pm.response.to.have.status(422);", " pm.expect(pm.response.json().error).to.eql(\"MISSING_RECORDS_UNSUPPORTED\");", + " pm.expect(pm.response.json().details.accepted).to.eql([\"keep\", \"archive\"]);", "});" ], "type": "text/javascript" diff --git a/src/icons.js b/src/icons.js index 865c514c..34ffbfdf 100644 --- a/src/icons.js +++ b/src/icons.js @@ -17,6 +17,7 @@ import AccountGroup from 'vue-material-design-icons/AccountGroup.vue' import AccountMultiple from 'vue-material-design-icons/AccountMultiple.vue' import AlertCircle from 'vue-material-design-icons/AlertCircle.vue' import ApplicationOutline from 'vue-material-design-icons/ApplicationOutline.vue' +import ArchiveOutline from 'vue-material-design-icons/ArchiveOutline.vue' import ArrowRight from 'vue-material-design-icons/ArrowRight.vue' import BookOpenVariant from 'vue-material-design-icons/BookOpenVariant.vue' import BookOpenVariantOutline from 'vue-material-design-icons/BookOpenVariantOutline.vue' @@ -79,6 +80,7 @@ export default { AccountMultiple, AlertCircle, ApplicationOutline, + ArchiveOutline, ArrowRight, BookOpenVariant, BookOpenVariantOutline, diff --git a/src/manifest.d/usages.json b/src/manifest.d/usages.json index 66990ad7..eec9d124 100644 --- a/src/manifest.d/usages.json +++ b/src/manifest.d/usages.json @@ -35,7 +35,8 @@ { "label": "Planned", "filter": { "status": "Planned" } }, { "label": "In production", "filter": { "status": "In production" }, "icon": "CheckCircle" }, { "label": "To be phased out", "filter": { "status": "To be phased out" }, "icon": "AlertCircle" }, - { "label": "Phased out", "filter": { "status": "Phased out" } } + { "label": "Phased out", "filter": { "status": "Phased out" } }, + { "label": "Archived", "filter": { "_archived": "true" }, "icon": "ArchiveOutline" } ], "sidebar": { "enabled": true, "showMetadata": true }, "documentationUrl": "https://stackiq.conduction.nl" diff --git a/src/manifest.json b/src/manifest.json index 22b32168..7df63875 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -662,6 +662,13 @@ "dpiaStatus": ["not required", "required"] }, "icon": "AlertCircle" + }, + { + "label": "Archived", + "filter": { + "_archived": "true" + }, + "icon": "ArchiveOutline" } ] } diff --git a/src/utils/cmdbImport.js b/src/utils/cmdbImport.js index ab7fa708..64d7df36 100644 --- a/src/utils/cmdbImport.js +++ b/src/utils/cmdbImport.js @@ -42,8 +42,27 @@ export const PROFILE_DEFAULTS = Object.freeze({ */ export const AS_TEXT = Object.freeze({ escape: false, sanitize: false }) -/** Every row outcome the report can carry, in display order. */ -export const OUTCOMES = ['created', 'updated', 'unchanged', 'skipped', 'failed'] +/** + * Every row outcome the report can carry, in display order: the outcomes of a + * sheet row, then those of an application that left the export or came back. + */ +export const OUTCOMES = [ + 'created', + 'updated', + 'unchanged', + 'skipped', + 'failed', + 'unarchived', + 'restored', + 'archived', + 'deleted', +] + +/** + * What the import may do with applications missing from the export (the + * profile's `missingRecords`), the default first. + */ +export const MISSING_RECORDS_MODES = Object.freeze(['archive', 'keep']) /** * The words for one row outcome. @@ -51,6 +70,7 @@ export const OUTCOMES = ['created', 'updated', 'unchanged', 'skipped', 'failed'] * @param {string} outcome The outcome key from the report * @return {string} The label * @spec openspec/changes/cmdb-export-import/specs/cmdb-export-import/spec.md#requirement-each-row-shall-be-processed-in-isolation-and-reported-with-its-outcome-req-cmdb-011 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-the-admin-settings-shall-offer-a-cmdb-import-section-req-cmdb-014 */ export function outcomeLabel(outcome) { switch (outcome) { @@ -64,6 +84,14 @@ export function outcomeLabel(outcome) { return t('stackiq', 'Skipped') case 'failed': return t('stackiq', 'Failed') + case 'unarchived': + return t('stackiq', 'Unarchived') + case 'restored': + return t('stackiq', 'Restored') + case 'archived': + return t('stackiq', 'Archived') + case 'deleted': + return t('stackiq', 'Deleted') default: return String(outcome ?? '') } @@ -141,16 +169,19 @@ export function checkFile(file) { * @param {{uuid: string|null, name: string}} options.municipality The chosen municipality: an existing one has a uuid, a new one only a name * @param {boolean} options.updateExisting Whether matched rows are updated * @param {boolean} [options.publish] Whether the modules the import creates are published; true when left out + * @param {string} [options.missingRecords] What happens to applications missing from the export: 'archive' (when left out) or 'keep' * @param {string} options.operationId The progress operation id * @return {FormData} The body * @spec openspec/changes/cmdb-export-import/specs/cmdb-export-import/spec.md#requirement-every-import-shall-have-exactly-one-consuming-municipality-chosen-by-the-admin-req-cmdb-004 * @spec openspec/changes/cmdb-export-import/specs/cmdb-export-import/spec.md#requirement-a-newly-created-module-shall-get-a-publicationdate-when-the-admin-publishes-and-an-existing-one-shall-keep-its-own-req-cmdb-007 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-records-missing-from-a-newer-export-shall-be-archived-by-default-or-kept-on-request-req-cmdb-012 */ export function buildImportForm({ file, municipality, updateExisting, publish = true, + missingRecords = MISSING_RECORDS_MODES[0], operationId, }) { const form = new FormData() @@ -162,7 +193,7 @@ export function buildImportForm({ } form.append('updateExisting', updateExisting ? 'true' : 'false') form.append('publish', publish ? 'true' : 'false') - form.append('missingRecords', 'keep') + form.append('missingRecords', missingRecords) form.append('operationId', operationId) return form } @@ -465,6 +496,7 @@ const KNOWN_ERRORS = new Set([ 'SCHEMA_OUTDATED', 'IMPORT_IN_PROGRESS', 'MUNICIPALITY_AMBIGUOUS', + 'ARCHIVE_UNAVAILABLE', 'OPERATION_NOT_FOUND', 'IMPORT_INTERRUPTED', 'NOT_SIGNED_IN', @@ -626,7 +658,7 @@ export function errorText(error) { return { title: t( 'stackiq', - 'Records missing from the export can only be kept.', + 'Applications missing from the export can only be archived or kept.', ), hint: '', } @@ -807,6 +839,17 @@ export function errorText(error) { 'Choose the municipality from the list instead of typing its name. Nothing was imported.', ), } + case 'ARCHIVE_UNAVAILABLE': + return { + title: t( + 'stackiq', + 'Applications missing from the export cannot be archived.', + ), + hint: t( + 'stackiq', + 'OpenRegister is missing or too old to archive objects. Choose "Keep them as they are" and import again, or update OpenRegister. Nothing was imported.', + ), + } case 'OPERATION_NOT_FOUND': return { title: t('stackiq', 'This import is no longer running.'), @@ -886,9 +929,13 @@ export function cancelFailureText(error) { * server has set them, because the tracker's own percentage is weighted by * the phases of the ArchiMate import. * + * In the phase `reconciling` the counts also hold the applications the + * import checks against the export after its rows. + * * @param {object|null} progress The snapshot from `GET /api/progress/{operationId}` * @return {{percentage: number, detail: string}|null} The view, or null before any progress * @spec openspec/changes/cmdb-export-import/specs/cmdb-export-import/spec.md#requirement-a-running-import-shall-report-its-progress-and-shall-stop-when-cancelled-req-cmdb-013 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-an-application-missing-from-the-cmdb-sheets-shall-be-archived-when-the-archive-sheet-lists-it-and-soft-deleted-when-no-sheet-does-req-cmdb-015 */ export function cmdbProgressView(progress) { if (!progress) { @@ -900,6 +947,17 @@ export function cmdbProgressView(progress) { total > 0 ? Math.min(100, Math.round((processed / total) * 100)) : Number(progress.percentage) || 0 + if (total > 0 && progress.phase === 'reconciling') { + return { + percentage, + detail: t( + 'stackiq', + 'Checking the applications missing from the export: {processed} of {total}', + { processed, total }, + AS_TEXT, + ), + } + } return { percentage, detail: @@ -960,9 +1018,13 @@ export function sortReportRows(rows, key, order) { /** * The rows of the report as the table shows them. * + * An application the import archived or deleted after its rows has row 0 + * in the report and no row number in the table. + * * @param {Array} rows The report's `rows` * @return {Array} The table rows * @spec openspec/changes/cmdb-export-import/specs/cmdb-export-import/spec.md#requirement-each-row-shall-be-processed-in-isolation-and-reported-with-its-outcome-req-cmdb-011 + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-the-admin-settings-shall-offer-a-cmdb-import-section-req-cmdb-014 */ export function reportRows(rows) { if (!Array.isArray(rows)) { @@ -971,7 +1033,7 @@ export function reportRows(rows) { return rows.map((row, index) => ({ key: `${row.sheet ?? ''}:${row.row ?? index}:${index}`, sheet: String(row.sheet ?? ''), - row: row.row ?? '', + row: Number(row.row) > 0 ? row.row : '', appId: String(row.appId ?? ''), name: String(row.name ?? ''), outcome: String(row.outcome ?? ''), diff --git a/src/utils/cmdbImport.spec.js b/src/utils/cmdbImport.spec.js index 8f566d6c..9377f3b5 100644 --- a/src/utils/cmdbImport.spec.js +++ b/src/utils/cmdbImport.spec.js @@ -22,6 +22,7 @@ import { interruptedImportError, isKnownError, makeCmdbOperationId, + MISSING_RECORDS_MODES, municipalityOptions, normaliseError, outcomeLabel, @@ -58,6 +59,7 @@ const SERVER_CODES = [ 'SCHEMA_OUTDATED', 'IMPORT_IN_PROGRESS', 'MUNICIPALITY_AMBIGUOUS', + 'ARCHIVE_UNAVAILABLE', 'OPERATION_NOT_FOUND', 'IMPORT_INTERRUPTED', 'NOT_SIGNED_IN', @@ -198,10 +200,26 @@ describe('buildImportForm', () => { expect(form.get('municipalityUuid')).toBe('uuid-1') expect(form.has('municipalityName')).toBe(false) expect(form.get('updateExisting')).toBe('true') - expect(form.get('missingRecords')).toBe('keep') + expect(form.get('missingRecords')).toBe('archive') expect(form.get('operationId')).toBe('cmdb-abcdefgh') }) + it('sends the choice for applications missing from the export, archive by default', () => { + const options = { + file, + municipality: { uuid: 'uuid-1', name: 'Tilburg' }, + updateExisting: true, + operationId: 'cmdb-abcdefgh', + } + expect(MISSING_RECORDS_MODES).toEqual(['archive', 'keep']) + expect(buildImportForm(options).get('missingRecords')).toBe('archive') + expect( + buildImportForm({ ...options, missingRecords: 'keep' }).get( + 'missingRecords', + ), + ).toBe('keep') + }) + it('sends a typed new municipality by name, and updateExisting as an explicit false', () => { const form = buildImportForm({ file, @@ -642,6 +660,19 @@ describe('cmdbProgressView', () => { ).toEqual({ percentage: 25, detail: '1 of 4 rows processed' }) }) + it('says when the import checks the applications missing from the export', () => { + expect( + cmdbProgressView({ + phase: 'reconciling', + processed_items: 3, + total_items: 4, + }), + ).toEqual({ + percentage: 75, + detail: 'Checking the applications missing from the export: 3 of 4', + }) + }) + it('shows nothing before any progress', () => { expect(cmdbProgressView(null)).toBeNull() }) @@ -683,6 +714,31 @@ describe('the report table', () => { expect(reportRows(null)).toEqual([]) }) + it('shows no row number for an application archived or deleted after the rows', () => { + const [row] = reportRows([ + { + sheet: 'Gearchiveerde Applicaties', + row: 0, + appId: '7', + name: 'Zeven', + outcome: 'archived', + reasons: [], + warnings: [], + moduleUuid: 'm-7', + }, + ]) + expect(row.row).toBe('') + expect(outcomeLabel('archived')).toBe('Archived') + expect(OUTCOMES).toEqual( + expect.arrayContaining([ + 'archived', + 'unarchived', + 'deleted', + 'restored', + ]), + ) + }) + it('sorts numbers by value and keeps the report order for ties', () => { const rows = [ { key: 'a', row: 10, sheet: 'B' }, diff --git a/src/views/settings/sections/CmdbImport.spec.js b/src/views/settings/sections/CmdbImport.spec.js index 931f7edb..7a16b985 100644 --- a/src/views/settings/sections/CmdbImport.spec.js +++ b/src/views/settings/sections/CmdbImport.spec.js @@ -147,3 +147,61 @@ describe('CmdbImport municipality chooser', () => { expect(wrapper.vm.report).toBe(null) }) }) + +/** + * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-the-admin-settings-shall-offer-a-cmdb-import-section-req-cmdb-014 + */ +describe('CmdbImport applications missing from the export', () => { + afterEach(() => { + jest.clearAllMocks() + }) + + it('archives by default and posts the choice the admin made', async () => { + const wrapper = await mountSection() + axios.post.mockResolvedValue({ + data: { success: true, summary: {}, rows: [] }, + }) + wrapper.vm.municipality = wrapper.vm.municipalityOptions[0] + wrapper.vm.selectedFile = new File(['x'], 'export.xlsx') + + expect(wrapper.vm.missingRecords).toBe('archive') + await wrapper.vm.startImport() + wrapper.vm.missingRecords = 'keep' + await wrapper.vm.startImport() + + expect( + axios.post.mock.calls.map(([, form]) => form.get('missingRecords')), + ).toEqual(['archive', 'keep']) + }) + + it('shows the archived, unarchived, deleted and restored counts only when there are any', async () => { + const wrapper = await mountSection() + const tileKeys = () => wrapper.vm.summaryTiles.map((tile) => tile.key) + + wrapper.vm.report = { summary: { rowsRead: 2, created: 2 }, rows: [] } + expect(tileKeys()).not.toContain('archived') + + wrapper.vm.report = { + summary: { + rowsRead: 1, + archived: 1, + deleted: 1, + unarchived: 0, + restored: 2, + }, + rows: [], + } + expect(tileKeys()).toEqual( + expect.arrayContaining(['archived', 'deleted', 'restored']), + ) + expect(tileKeys()).not.toContain('unarchived') + expect(wrapper.vm.outcomeFilterOptions.map((option) => option.id)).toEqual( + expect.arrayContaining([ + 'archived', + 'unarchived', + 'deleted', + 'restored', + ]), + ) + }) +}) diff --git a/src/views/settings/sections/CmdbImport.vue b/src/views/settings/sections/CmdbImport.vue index f8bbc1e4..00af6889 100644 --- a/src/views/settings/sections/CmdbImport.vue +++ b/src/views/settings/sections/CmdbImport.vue @@ -143,6 +143,40 @@ }}

+
+ + {{ t('stackiq', 'Applications missing from the export') }} + + + {{ t('stackiq', 'Archive or delete them') }} + + + {{ t('stackiq', 'Keep them as they are') }} + +

+ {{ + t( + 'stackiq', + 'An application of this municipality that is on neither CMDB sheet any more is archived when the sheet "Gearchiveerde Applicaties" lists it, and moved to the trash when no sheet does. Both disappear from the lists, from OpenCatalogi and from Portaliq; one that returns in a later export is brought back. Without that sheet in the file, applications are only archived. Choose Keep to leave them as they are.', + ) + }} +

+
@@ -304,7 +338,7 @@