From c0de84cdd825ba4527d03c19ae34e8e7d3d0a010 Mon Sep 17 00:00:00 2001
From: WilcoLouwerse
Date: Fri, 9 Oct 2026 15:22:42 +0200
Subject: [PATCH 01/18] docs(openspec): add change
cmdb-import-archive-reconciliation
Proposal, design, tasks and the delta spec for archiving and soft-deleting
applications that left a newer CMDB export (REQ-CMDB-015..017, REQ-CMDB-012
and REQ-CMDB-014 modified).
Co-Authored-By: Claude Opus 5.5
---
.../.openspec.yaml | 2 +
.../design.md | 191 ++++++++++++++++++
.../proposal.md | 95 +++++++++
.../specs/cmdb-export-import/spec.md | 175 ++++++++++++++++
.../tasks.md | 82 ++++++++
openspec/specs/cmdb-export-import/spec.md | 5 +-
6 files changed, 548 insertions(+), 2 deletions(-)
create mode 100644 openspec/changes/cmdb-import-archive-reconciliation/.openspec.yaml
create mode 100644 openspec/changes/cmdb-import-archive-reconciliation/design.md
create mode 100644 openspec/changes/cmdb-import-archive-reconciliation/proposal.md
create mode 100644 openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md
create mode 100644 openspec/changes/cmdb-import-archive-reconciliation/tasks.md
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..d916937b
--- /dev/null
+++ b/openspec/changes/cmdb-import-archive-reconciliation/design.md
@@ -0,0 +1,191 @@
+# 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`. `MagicMapper::restoreObject(uuid)` clears the marker; `DeletedController::restore()` uses it.
+- **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: `_ids`, `_includeDeleted` and `_archived` apply together in `MagicSearchHandler`.
+
+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 other organisations use, 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 with _archived=any, _includeDeleted=true
+ │ archived match → unarchive, deleted match → restore, then the usual update
+ └─ reconcile() (archive mode, not cancelled) phase `reconciling`, same lock
+ page usages (consumer = municipality, both lenses)
+ load their modules in batches (_ids, both lenses)
+ 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()` searches the module by `externalKey` with `_archived=any` and `_includeDeleted=true`; `moduleBelongsTo()` checks this municipality's usage with the same lenses (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 with both lenses. Whatever is matched is revived before it is written: a soft-deleted object is restored (`MagicMapper::restoreObject()`), an archived one unarchived (`ArchiveHandler::unarchive()`), because `SaveObject` refuses a write to an archived object. The row outcome is `restored` when anything was restored, else `unarchived` when anything was unarchived, else the usual `created | updated | unchanged`. 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. 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, paged with `PAGE_SIZE` and both lenses. Their modules are loaded per page in one search with `_ids`, both lenses. 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 the method the import calls: 503 `ARCHIVE_UNAVAILABLE` before the lock is taken, only in archive mode. `keep` needs neither.
+- 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.
+
+## 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`, `_includeDeleted` and `_ids`, `::deleteObject()` (contract); `Service\Object\ArchiveHandler::archive()` / `unarchive()` and `Db\MagicMapper::restoreObject()` (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; an ordinary row costs the same searches as before.
+- [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..7c532f62
--- /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 OpenRegister's `_archived=any` and `_includeDeleted=true` lenses, 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()` (not public contracts, guarded), the `_archived` and `_includeDeleted` list lenses, 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..81e72cc7
--- /dev/null
+++ b/openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md
@@ -0,0 +1,175 @@
+# 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 the `_archived`, `_includeDeleted` and `_ids` lenses, `deleteObject()`), `Service\Object\ArchiveHandler` (`archive()`, `unarchive()`) and `Db\MagicMapper::restoreObject()` (both resolved through the container behind a guard), 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. 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: 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. 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
+
+### 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..e50e646a
--- /dev/null
+++ b/openspec/changes/cmdb-import-archive-reconciliation/tasks.md
@@ -0,0 +1,82 @@
+# 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/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
+- [ ] Implement
+- [ ] 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
+- [ ] Implement
+- [ ] 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`
+- **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 `updateExisting` false THEN the row is skipped as `exists` and nothing is revived
+- [ ] Implement
+- [ ] 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 `missingRecords` `keep`, a cancelled import, or a usage of another municipality THEN nothing is archived or deleted
+ - 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
+- [ ] Implement
+- [ ] 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`
+- **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
+- [ ] Implement
+- [ ] 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/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
+- [ ] Implement
+- [ ] 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/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`
+- [ ] Implement
+- [ ] Test
+
+## 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
From fd4aa7e337c05ee2adbd64e6d917b2a73e1dc39b Mon Sep 17 00:00:00 2001
From: WilcoLouwerse
Date: Fri, 9 Oct 2026 15:22:42 +0200
Subject: [PATCH 02/18] feat(cmdb-import): let module and usage be archived and
name the archive sheet
The register fragment opts module (0.3.9) and usage (1.5.7) into
OpenRegister's archive state. The import profile names the sheet
"Gearchiveerde Applicaties" and accepts missingRecords keep and archive,
readable before the packs are validated.
Co-Authored-By: Claude Opus 5.5
---
lib/Service/Cmdb/CmdbImportProfile.php | 55 +++++++++++++++++--
lib/Settings/cmdb-import/topdesk-profile.json | 7 ++-
.../register.d/topdesk-cmdb-import.json | 8 ++-
.../Service/Cmdb/CmdbImportProfileTest.php | 24 ++++++++
.../Settings/PublicationFieldRulesTest.php | 2 +-
.../Unit/Settings/TopdeskCmdbFragmentTest.php | 30 ++++++++--
6 files changed, 110 insertions(+), 16 deletions(-)
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/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/tests/Unit/Service/Cmdb/CmdbImportProfileTest.php b/tests/Unit/Service/Cmdb/CmdbImportProfileTest.php
index 2d330258..17e11067 100644
--- a/tests/Unit/Service/Cmdb/CmdbImportProfileTest.php
+++ b/tests/Unit/Service/Cmdb/CmdbImportProfileTest.php
@@ -306,4 +306,28 @@ public function testTheUploadLimitNeedsNoOpenRegister(): void {
$profile = new CmdbImportProfile(container: $this->emptyContainer(), directory: '/nonexistent');
$this->assertSame(CmdbImportProfile::DEFAULT_MAX_FILE_BYTES, $profile->maxFileBytes());
}//end testTheUploadLimitNeedsNoOpenRegister()
+
+ /**
+ * The archive sheet is read after the source sheets, and the accepted missingRecords values need no OpenRegister.
+ *
+ * @return void
+ *
+ * @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 testTheArchiveSheetAndTheMissingRecordsModes(): void {
+ $profile = new CmdbImportProfile(container: $this->emptyContainer());
+ $this->assertSame(['keep', 'archive'], $profile->missingRecordsModes(), 'readable before load(), without the pack validator');
+
+ CmdbTestSupport::loadMigrationPack();
+ $profile->load();
+ $this->assertSame('Gearchiveerde Applicaties', $profile->archiveSheetName());
+ $this->assertSame(
+ ['Onbeh Applicaties CMDB', 'Beheerde Applicaties CMDB', 'Gearchiveerde Applicaties'],
+ $profile->readSheetNames()
+ );
+ $this->assertNotContains('Gearchiveerde Applicaties', $profile->sheetNames(), 'the archive sheet holds no rows to import');
+
+ $missing = new CmdbImportProfile(container: $this->emptyContainer(), directory: '/nonexistent');
+ $this->assertSame(['keep'], $missing->missingRecordsModes(), 'without a profile only keep is safe');
+ }//end testTheArchiveSheetAndTheMissingRecordsModes()
}//end class
diff --git a/tests/Unit/Settings/PublicationFieldRulesTest.php b/tests/Unit/Settings/PublicationFieldRulesTest.php
index f5ee7d5b..84026c2a 100644
--- a/tests/Unit/Settings/PublicationFieldRulesTest.php
+++ b/tests/Unit/Settings/PublicationFieldRulesTest.php
@@ -173,7 +173,7 @@ public function testAFragmentNeverLowersAVersion(): void {
$this->assertSame('1.5.5', $merged['components']['schemas']['usage']['version']);
$schemas = $this->register()['components']['schemas'];
- $this->assertSame('1.5.6', $schemas['usage']['version'], 'topdesk-cmdb-import.json bumps it past publication-field-rules.json; value-assessment.json, sorting last, does not lower it');
+ $this->assertSame('1.5.7', $schemas['usage']['version'], 'topdesk-cmdb-import.json bumps it past publication-field-rules.json; value-assessment.json, sorting last, does not lower it');
$this->assertSame('0.3.5', $schemas['connection']['version']);
$this->assertSame('0.1.6', $schemas['moduleVersion']['version']);
}//end testAFragmentNeverLowersAVersion()
diff --git a/tests/Unit/Settings/TopdeskCmdbFragmentTest.php b/tests/Unit/Settings/TopdeskCmdbFragmentTest.php
index 7ef15d1f..df49a455 100644
--- a/tests/Unit/Settings/TopdeskCmdbFragmentTest.php
+++ b/tests/Unit/Settings/TopdeskCmdbFragmentTest.php
@@ -58,14 +58,14 @@ private function mergedRegister(): array {
}//end mergedRegister()
/**
- * The merged module is 0.3.8, carries the six optional, titled properties and allows BBN2+.
+ * The merged module is 0.3.9, carries the six optional, titled properties and allows BBN2+.
*
* @return void
*/
- public function testTheMergedModuleIsVersion038WithTheExternalIds(): void {
+ public function testTheMergedModuleIsVersion039WithTheExternalIds(): void {
$module = $this->mergedRegister()['components']['schemas']['module'];
- $this->assertSame('0.3.8', $module['version'], 'a fragment sorting after topdesk-cmdb-import.json overwrote the bump');
+ $this->assertSame('0.3.9', $module['version'], 'a fragment sorting after topdesk-cmdb-import.json overwrote the bump');
foreach (self::PROPERTIES as $property) {
$this->assertArrayHasKey($property, $module['properties']);
$this->assertNotEmpty($module['properties'][$property]['title'] ?? '', $property);
@@ -91,7 +91,7 @@ public function testTheMergedModuleIsVersion038WithTheExternalIds(): void {
$this->assertSame(['BBN1', 'BBN2', 'BBN3', 'BBN2+'], $module['properties']['bbnLevel']['enum'], 'the fragment adds BBN2+ to the BIO levels');
$this->assertArrayHasKey('roadmapStatement', $module['properties'], 'the 0.3.4 fragment still applies');
$this->assertSame(['name'], $module['required']);
- }//end testTheMergedModuleIsVersion038WithTheExternalIds()
+ }//end testTheMergedModuleIsVersion039WithTheExternalIds()
/**
* A CMDB import sets the usage status TOPdesk records from any state; only an administrator may.
@@ -104,7 +104,7 @@ public function testTheMergedModuleIsVersion038WithTheExternalIds(): void {
*/
public function testAnAdministratorMayMoveAUsageToAnyStateTheSourceRecords(): void {
$usage = $this->mergedRegister()['components']['schemas']['usage'];
- $this->assertSame('1.5.6', $usage['version'], 'a lifecycle-only edit deploys only with a version bump');
+ $this->assertSame('1.5.7', $usage['version'], 'a configuration-only edit deploys only with a version bump');
$lifecycle = $usage['configuration']['x-openregister-lifecycle'];
$states = $usage['properties']['status']['enum'];
@@ -167,4 +167,24 @@ public function testTheSeedModulesShowTheNewProperties(): void {
// The base seeds are still there: the fragment appends, it does not replace.
$this->assertGreaterThan(3, count($register['components']['objects']));
}//end testTheSeedModulesShowTheNewProperties()
+
+ /**
+ * Module and usage offer OpenRegister's archive state, and the usage keeps its lifecycle.
+ *
+ * @return void
+ *
+ * @spec openspec/changes/cmdb-import-archive-reconciliation/specs/cmdb-export-import/spec.md#requirement-archived-applications-and-usages-shall-be-listable-in-stackiq-and-shall-stay-out-of-opencatalogi-and-portaliq-by-default-req-cmdb-017
+ */
+ public function testTheMergedSchemasOfferTheArchiveState(): void {
+ $schemas = $this->mergedRegister()['components']['schemas'];
+
+ $this->assertSame('0.3.9', $schemas['module']['version']);
+ $this->assertSame('1.5.7', $schemas['usage']['version']);
+ foreach (['module', 'usage'] as $slug) {
+ $this->assertSame(['enabled' => true], $schemas[$slug]['configuration']['x-openregister-archive'] ?? null, $slug);
+ }
+
+ $this->assertArrayHasKey('importAcquisition', $schemas['usage']['configuration']['x-openregister-lifecycle']['transitions'], 'the 1.5.6 lifecycle is still declared');
+ $this->assertArrayNotHasKey('x-openregister-archive', $schemas['contactPerson']['configuration'] ?? [], 'contact persons are never archived by the import');
+ }//end testTheMergedSchemasOfferTheArchiveState()
}//end class
From ed61ce70f7de11a34d1f15ebbbc9f420528beebf Mon Sep 17 00:00:00 2001
From: WilcoLouwerse
Date: Fri, 9 Oct 2026 15:24:52 +0200
Subject: [PATCH 03/18] feat(cmdb-import): read the APPIDs of the archive sheet
When the workbook has the sheet "Gearchiveerde Applicaties", the reader
loads it under the same bounds as the CMDB sheets, resolves only its APPID
column and returns the APPIDs next to the rows, with whether the sheet and
its key column were found.
Co-Authored-By: Claude Opus 5.5
---
lib/Service/Cmdb/CmdbWorkbookReader.php | 51 +++++++++--
.../Service/Cmdb/CmdbWorkbookReaderTest.php | 89 +++++++++++++++++++
2 files changed, 133 insertions(+), 7 deletions(-)
diff --git a/lib/Service/Cmdb/CmdbWorkbookReader.php b/lib/Service/Cmdb/CmdbWorkbookReader.php
index 3ff3e918..7073736e 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,7 +310,7 @@ 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
);
@@ -328,19 +335,38 @@ private function readBounded(string $path, CmdbImportProfile $profile, object $s
);
}
+ $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: $present, lastRow: $lastRow, limit: $limit);
+ $this->assertRowSpan(path: $path, sheetNames: $loaded, lastRow: $lastRow, limit: $limit);
- $headers = $this->load(path: $path, sheetNames: $present, filter: new CmdbReadFilter(lastRow: 1));
+ $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();
}
+ $archive = ['sheet' => (string)$archiveSheet, 'present' => false, 'keyColumnMissing' => ($loaded !== $present), 'appIds' => []];
$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));
+ if ($archiveColumns !== []) {
+ $letters[$archiveSheet] = array_keys($archiveColumns);
+ $archive['keyColumnMissing'] = false;
+ } else {
+ $loaded = $present;
+ }
+
+ $spreadsheet = $this->load(path: $path, sheetNames: $loaded, filter: new CmdbReadFilter(lastRow: $lastRow, columns: $letters));
try {
$rows = [];
foreach ($present as $sheetName) {
@@ -353,6 +379,17 @@ private function readBounded(string $path, CmdbImportProfile $profile, object $s
array_push($rows, ...$sheetRows);
}
+ 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 = false;
if (method_exists($spreadsheet, 'getExcelCalendar') === true) {
$date1904 = ((int)$spreadsheet->getExcelCalendar() === 1904);
@@ -361,7 +398,7 @@ private function readBounded(string $path, CmdbImportProfile $profile, object $s
$spreadsheet->disconnectWorksheets();
}
- return ['rows' => $rows, 'importWarnings' => $resolved['warnings'], 'date1904' => $date1904];
+ return ['rows' => $rows, 'importWarnings' => $resolved['warnings'], 'date1904' => $date1904, 'archive' => $archive];
}//end readBounded()
/**
diff --git a/tests/Unit/Service/Cmdb/CmdbWorkbookReaderTest.php b/tests/Unit/Service/Cmdb/CmdbWorkbookReaderTest.php
index 2e0e0673..95a444e2 100644
--- a/tests/Unit/Service/Cmdb/CmdbWorkbookReaderTest.php
+++ b/tests/Unit/Service/Cmdb/CmdbWorkbookReaderTest.php
@@ -920,6 +920,95 @@ public function testOneRowOverTheLimitWithinTheSpanIsRefused(): void {
}
}//end testOneRowOverTheLimitWithinTheSpanIsRefused()
+ /**
+ * The archive sheet of the anonymised export yields its APPIDs; the CMDB rows are unchanged.
+ *
+ * @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
+ */
+ public function testTheArchiveSheetYieldsItsAppIds(): void {
+ $result = $this->read(name: 'topdesk-export-anonymised.xlsx');
+
+ $this->assertSame('Gearchiveerde Applicaties', $result['archive']['sheet']);
+ $this->assertTrue($result['archive']['present']);
+ $this->assertFalse($result['archive']['keyColumnMissing']);
+ $this->assertSame(['1198'], array_map('strval', $result['archive']['appIds']));
+ $this->assertSame(['Onbeh Applicaties CMDB', 'Beheerde Applicaties CMDB'], array_column($result['rows'], 'sheet'), 'the archive sheet adds no rows to import');
+ }//end testTheArchiveSheetYieldsItsAppIds()
+
+ /**
+ * Only the APPID column of the archive sheet is read; without the sheet or its APPID column it is absent.
+ *
+ * @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
+ */
+ public function testTheArchiveSheetIsOptionalAndReadForItsKeyOnly(): void {
+ $this->requireSpreadsheet();
+ $cmdb = [['APPID', 'Applicatie Naam'], [1, 'Een']];
+ $cases = [
+ 'with the sheet' => [
+ ['Beheerde Applicaties CMDB' => $cmdb, 'Gearchiveerde Applicaties' => [['APPID', 'Applicatie Naam', 'Bron'], [7, 'Zeven', 'P-0007'], [], [8, 'Acht', 'P-0008']]],
+ ['present' => true, 'keyColumnMissing' => false, 'appIds' => ['7', '8']],
+ ],
+ 'without the sheet' => [
+ ['Beheerde Applicaties CMDB' => $cmdb],
+ ['present' => false, 'keyColumnMissing' => false, 'appIds' => []],
+ ],
+ 'without its APPID column' => [
+ ['Beheerde Applicaties CMDB' => $cmdb, 'Gearchiveerde Applicaties' => [['Applicatie Code', 'Applicatie Naam'], ['APP-7', 'Zeven']]],
+ ['present' => false, 'keyColumnMissing' => true, 'appIds' => []],
+ ],
+ ];
+
+ foreach ($cases as $case => [$sheets, $expected]) {
+ $path = CmdbTestSupport::buildWorkbook(sheets: $sheets);
+ try {
+ $result = (new CmdbWorkbookReader())->read(path: $path, profile: $this->profile());
+ } finally {
+ unlink($path);
+ }
+
+ $archive = $result['archive'];
+ $archive['appIds'] = array_map('strval', $archive['appIds']);
+ unset($archive['sheet']);
+ $this->assertSame($expected, $archive, $case);
+ $this->assertSame([2], array_column($result['rows'], 'row'), $case);
+ $this->assertStringNotContainsString('P-000', (string)json_encode($result), $case);
+ $this->assertStringNotContainsString('Zeven', (string)json_encode($result), $case . ': only the key column is read');
+ }
+ }//end testTheArchiveSheetIsOptionalAndReadForItsKeyOnly()
+
+ /**
+ * An archive sheet with more rows than the profile allows is refused and named, like a source sheet.
+ *
+ * @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
+ */
+ public function testAnArchiveSheetOverTheRowLimitIsRefused(): void {
+ $this->requireSpreadsheet();
+ $path = CmdbTestSupport::buildWorkbook(
+ sheets: [
+ 'Beheerde Applicaties CMDB' => [['APPID', 'Applicatie Naam'], [1, 'Een']],
+ 'Gearchiveerde Applicaties' => [['APPID'], [7], [8]],
+ ]
+ );
+ $directory = CmdbTestSupport::profileDirectory(overrides: ['maxRowsPerSheet' => 1]);
+
+ try {
+ (new CmdbWorkbookReader())->read(path: $path, profile: $this->profile(directory: $directory));
+ $this->fail('TOO_MANY_ROWS expected');
+ } catch (CmdbImportException $e) {
+ $this->assertSame('TOO_MANY_ROWS', $e->getErrorCode());
+ $this->assertSame(['sheet' => 'Gearchiveerde Applicaties', 'limit' => 1], $e->getDetails());
+ } finally {
+ unlink($path);
+ CmdbTestSupport::removeDirectory(directory: $directory);
+ }
+ }//end testAnArchiveSheetOverTheRowLimitIsRefused()
+
/**
* A text file named .xlsx, a .xlsm and a CSV are refused before PhpSpreadsheet is touched.
*
From ed59f25483ceaa7b525bae4468947a8e101a7d67 Mon Sep 17 00:00:00 2001
From: WilcoLouwerse
Date: Fri, 9 Oct 2026 15:36:47 +0200
Subject: [PATCH 04/18] feat(cmdb-import): archive or soft-delete applications
that left the export
With missingRecords archive, the default, a completed import reconciles
the municipality's usages and the modules its import created: an APPID
that moved to the archive sheet is archived through OpenRegister's
ArchiveHandler, one on no sheet is soft-deleted, and without the archive
sheet missing applications are archived only, with a report warning. The
step runs under the register lock in its own progress phase, with an error
boundary per application. A module or usage matched among archived or
soft-deleted objects is unarchived or restored before it is updated, so a
returning application is never duplicated. The report counts archived,
unarchived, deleted and restored. Without the archive services an archiving
import is refused with 503 ARCHIVE_UNAVAILABLE before the file is read.
Co-Authored-By: Claude Opus 5.5
---
lib/Exception/CmdbImportException.php | 2 +
lib/Service/Cmdb/CmdbImportReport.php | 32 +-
lib/Service/CmdbExportImportService.php | 580 ++++++++++++++++-
lib/Service/ProgressTracker.php | 5 +
.../Service/Cmdb/CmdbImportReportTest.php | 23 +
.../Service/CmdbExportImportServiceTest.php | 612 +++++++++++++++++-
6 files changed, 1213 insertions(+), 41 deletions(-)
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/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/CmdbExportImportService.php b/lib/Service/CmdbExportImportService.php
index 1efc049d..1a6804fe 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,36 @@ 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 lenses that make archived and soft-deleted objects matchable too.
+ *
+ * Without them OpenRegister leaves both out of every list, so a returning
+ * application would be created a second time instead of revived.
+ *
+ * @var array
+ */
+ private const EVERY_STATE = ['_archived' => 'any', '_includeDeleted' => true];
+
/**
* The properties every match search and the module key rely on, per schema.
*
@@ -222,6 +261,13 @@ 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;
+
/**
* Contact UIDs by e-mail or display name, per run.
*
@@ -300,18 +346,30 @@ public function assertXlsx(string $path, string $fileName): void {
}//end assertXlsx()
/**
- * Whether a `missingRecords` value is supported (only `keep`).
+ * Whether a `missingRecords` value is supported: one of the profile's modes (`keep`, `archive`).
*
* @param string $mode The requested value.
*
* @return bool
*
* @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';
+ return in_array($mode, $this->missingRecordsModes(), true);
}//end supportsMissingRecords()
+ /**
+ * The accepted `missingRecords` values, for the refusal of any other.
+ *
+ * @return array
+ *
+ * @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 {
+ return $this->profile->missingRecordsModes();
+ }//end missingRecordsModes()
+
/**
* Ask a running import to stop between rows.
*
@@ -349,19 +407,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 +431,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,16 +506,23 @@ 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']));
+ $archive = $this->archiveSheet(workbook: $workbook);
+ if ($missingRecords === 'archive' && $archive['present'] === false) {
+ $report->addImportWarnings(warnings: [['sheet' => $archive['sheet'], 'message' => $this->archiveSheetWarning(archive: $archive)]]);
+ }
+
if ($municipality['created'] === true) {
$report->addImportWarnings(
warnings: [
@@ -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) {
@@ -748,11 +830,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;
}
@@ -1033,9 +1124,10 @@ private function resolveManufacturer(array $values, int $rowNumber): ?string {
* 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->findOne(schemaKey: 'module', filters: ['externalKey' => $externalKey], everyState: true);
if ($existing === null) {
return ['existing' => null, 'uuid' => null, 'skipReason' => null];
}
@@ -1102,6 +1194,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 +1203,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->findOne(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid], everyState: true) !== null) {
return true;
}
@@ -1128,9 +1223,11 @@ private function moduleBelongsTo(string $moduleUuid, string $municipalityUuid):
* @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,
@@ -1155,13 +1252,14 @@ private function upsertModule(
}
$uuid = (string)$existing->getUuid();
+ $revived = $this->revive(entity: $existing);
$merged = $this->merge(target: 'module', stored: $existing->getObject(), mapped: $data);
if ($merged === null) {
- return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UNCHANGED];
+ return ['uuid' => $uuid, 'outcome' => ($revived ?? CmdbImportReport::UNCHANGED)];
}
$this->save(schemaKey: 'module', data: $merged, uuid: $uuid);
- return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UPDATED];
+ return ['uuid' => $uuid, 'outcome' => ($revived ?? CmdbImportReport::UPDATED)];
}//end upsertModule()
/**
@@ -1173,9 +1271,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 +1299,20 @@ private function upsertUsage(array $data, string $municipalityUuid, string $modu
}
}
- $existing = $this->findOne(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid]);
+ $existing = $this->findOne(schemaKey: 'usage', filters: ['consumer' => $municipalityUuid, 'module' => $moduleUuid], everyState: true);
if ($existing === null) {
return ['uuid' => $this->save(schemaKey: 'usage', data: $data, uuid: null), 'outcome' => CmdbImportReport::CREATED];
}
$uuid = (string)$existing->getUuid();
+ $revived = $this->revive(entity: $existing);
$merged = $this->merge(target: 'usage', stored: $existing->getObject(), mapped: $data);
if ($merged === null) {
- return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UNCHANGED];
+ return ['uuid' => $uuid, 'outcome' => ($revived ?? CmdbImportReport::UNCHANGED)];
}
$this->save(schemaKey: 'usage', data: $merged, uuid: $uuid);
- return ['uuid' => $uuid, 'outcome' => CmdbImportReport::UPDATED];
+ return ['uuid' => $uuid, 'outcome' => ($revived ?? CmdbImportReport::UPDATED)];
}//end upsertUsage()
/**
@@ -1637,16 +1738,24 @@ private function organisationsOfType(string $type): array {
*
* @param string $schemaKey The coordinates key of the schema.
* @param array $filters Field => exact value.
+ * @param bool $everyState Also match archived and soft-deleted objects.
*
* @return object|null The entity (ObjectEntityInterface).
*
* @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 findOne(string $schemaKey, array $filters): ?object {
+ private function findOne(string $schemaKey, array $filters, bool $everyState = false): ?object {
$coordinates = $this->coordinates();
+ $lenses = [];
+ if ($everyState === true) {
+ $lenses = self::EVERY_STATE;
+ }
+
$results = $coordinates['objectService']->searchObjects(
query: array_merge(
['@self' => ['register' => $coordinates['register'], 'schema' => $coordinates[$schemaKey]], '_limit' => 10],
+ $lenses,
$filters
),
_rbac: false,
@@ -1699,6 +1808,444 @@ 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()`.
+ *
+ * @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
+ ) {
+ 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 a stored object is archived and whether it is in the trash, from its `@self` metadata.
+ *
+ * @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.
+ *
+ * @param object $entity The matched entity (ObjectEntityInterface).
+ *
+ * @return string|null restored, unarchived, or null when it was neither archived nor deleted.
+ *
+ * @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(object $entity): ?string {
+ $state = self::objectState(entity: $entity);
+ if ($state['deleted'] === false && $state['archived'] === false) {
+ return null;
+ }
+
+ $uuid = (string)$entity->getUuid();
+ $services = $this->archiveServices();
+ $outcome = null;
+ if ($state['deleted'] === true) {
+ $services['mapper']->restoreObject(uuid: $uuid);
+ $outcome = CmdbImportReport::RESTORED;
+ }
+
+ if ($state['archived'] === true) {
+ $services['handler']->unarchive(identifier: $uuid, reason: self::REASON_PREFIX . 'back in the export');
+ $outcome = ($outcome ?? CmdbImportReport::UNARCHIVED);
+ }
+
+ return $outcome;
+ }//end revive()
+
+ /**
+ * 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.
+ *
+ * @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 {
+ $scope = $this->reconciliationScope(municipalityUuid: $municipalityUuid);
+ $this->progressTracker->setPhase(phase: 'reconciling', data: ['total_items' => ($processedItems + count($scope))]);
+
+ foreach ($scope as $index => $application) {
+ // 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.
+ *
+ * @param string $municipalityUuid The consumer of this import.
+ *
+ * @return array Per application, the APPID's match key,
+ * the usage and the module.
+ *
+ * @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 {
+ $coordinates = $this->coordinates();
+ $prefix = $this->profile->externalKeyPrefix() . ':' . $municipalityUuid . ':';
+ $scope = [];
+ $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,
+ ],
+ self::EVERY_STATE
+ ),
+ _rbac: false,
+ _multitenancy: false
+ );
+ if (is_array($page) === false) {
+ $page = [];
+ }
+
+ $usages = [];
+ foreach ($page as $usage) {
+ $data = $usage->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->getUuid() !== null) {
+ $usages[] = ['usage' => $usage, 'module' => $moduleUuid];
+ }
+ }
+
+ $modules = $this->modulesByUuid(uuids: array_values(array_unique(array_column($usages, 'module'))));
+ foreach ($usages as $usage) {
+ $module = ($modules[$usage['module']] ?? null);
+ $externalKey = '';
+ if ($module !== null) {
+ $externalKey = (string)($module->getObject()['externalKey'] ?? '');
+ }
+
+ if (str_starts_with($externalKey, $prefix) === true && strlen($externalKey) > strlen($prefix)) {
+ $scope[] = ['key' => substr($externalKey, strlen($prefix)), 'usage' => $usage['usage'], 'module' => $module];
+ }
+ }
+
+ $offset += self::PAGE_SIZE;
+ $pageSize = count($page);
+ } while ($pageSize === self::PAGE_SIZE);
+
+ return $scope;
+ }//end reconciliationScope()
+
+ /**
+ * The modules with these uuids, in every state, in one search.
+ *
+ * @param array $uuids The module uuids.
+ *
+ * @return array Uuid => entity.
+ *
+ * @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 {
+ if ($uuids === []) {
+ return [];
+ }
+
+ $coordinates = $this->coordinates();
+ $results = $coordinates['objectService']->searchObjects(
+ query: array_merge(
+ ['@self' => ['register' => $coordinates['register'], 'schema' => $coordinates['module']], '_ids' => $uuids, '_limit' => count($uuids)],
+ self::EVERY_STATE
+ ),
+ _rbac: false,
+ _multitenancy: false
+ );
+ if (is_array($results) === false) {
+ return [];
+ }
+
+ $modules = [];
+ foreach ($results as $entity) {
+ $uuid = (string)$entity->getUuid();
+ if (in_array($uuid, $uuids, true) === true) {
+ $modules[$uuid] = $entity;
+ }
+ }
+
+ return $modules;
+ }//end modulesByUuid()
+
+ /**
+ * 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} $application The 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) {
+ $state = self::objectState(entity: $application[$schemaKey]);
+ foreach (self::transitions(state: $state, 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;
+ }
+
+ $services = $this->archiveServices();
+ if ($step === 'restore') {
+ $services['mapper']->restoreObject(uuid: $uuid);
+ return;
+ }
+
+ $services['handler']->archive(identifier: $uuid, reason: $reason);
+ }//end transition()
+
/**
* Resolve OpenRegister's mapping engine.
*
@@ -1915,6 +2462,7 @@ private function resetRun(): void {
$this->winningSheets = [];
$this->contactUids = [];
$this->contactPersons = [];
+ $this->archiveServices = 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/tests/Unit/Service/Cmdb/CmdbImportReportTest.php b/tests/Unit/Service/Cmdb/CmdbImportReportTest.php
index a3d7a576..ef208a36 100644
--- a/tests/Unit/Service/Cmdb/CmdbImportReportTest.php
+++ b/tests/Unit/Service/Cmdb/CmdbImportReportTest.php
@@ -69,4 +69,27 @@ public function testWithinTheLimitEveryRowIsStored(): void {
$this->assertSame(array_merge($report->toArray(), ['rowsStored' => 5, 'rowsTruncated' => false]), $stored);
}//end testWithinTheLimitEveryRowIsStored()
+
+ /**
+ * The reconciliation outcomes are counted, and their entries (row 0) are not counted as processed sheet rows.
+ *
+ * @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
+ */
+ public function testTheReconciliationOutcomesAreCounted(): void {
+ $report = new CmdbImportReport(operationId: 'cmdb-report-02', rowsRead: 2);
+ $report->addRow(sheet: 'S', row: 2, appId: '1', name: 'Een', outcome: CmdbImportReport::UNARCHIVED);
+ $report->addRow(sheet: 'S', row: 3, appId: '2', name: 'Twee', outcome: CmdbImportReport::RESTORED);
+ $report->addRow(sheet: 'Gearchiveerde Applicaties', row: 0, appId: '7', name: 'Zeven', outcome: CmdbImportReport::ARCHIVED);
+ $report->addRow(sheet: '', row: 0, appId: '8', name: 'Acht', outcome: CmdbImportReport::DELETED);
+
+ $summary = $report->summary();
+ $this->assertSame(2, $summary['processed']);
+ $this->assertSame(2, $report->processed());
+ $this->assertSame([1, 1, 1, 1], [$summary['archived'], $summary['unarchived'], $summary['deleted'], $summary['restored']]);
+ $this->assertFalse($report->isCancelled());
+ $report->markCancelled();
+ $this->assertTrue($report->isCancelled());
+ }//end testTheReconciliationOutcomesAreCounted()
}//end class
diff --git a/tests/Unit/Service/CmdbExportImportServiceTest.php b/tests/Unit/Service/CmdbExportImportServiceTest.php
index d81417ea..4c247d5b 100644
--- a/tests/Unit/Service/CmdbExportImportServiceTest.php
+++ b/tests/Unit/Service/CmdbExportImportServiceTest.php
@@ -91,6 +91,34 @@ class CmdbExportImportServiceTest extends TestCase {
*/
private $beforeSave = null;
+ /**
+ * The archive and trash markers per schema id and uuid, as OpenRegister keeps them in `@self`.
+ *
+ * @var array|null, deleted?: array|null}>>
+ */
+ private array $states = [];
+
+ /**
+ * Every archive, unarchive, restore and delete: verb, schema id, uuid, reason.
+ *
+ * @var array
+ */
+ private array $transitions = [];
+
+ /**
+ * Called before every archive, unarchive, restore and delete with the verb and the uuid; may throw.
+ *
+ * @var callable|null
+ */
+ private $beforeTransition = null;
+
+ /**
+ * Whether the container knows OpenRegister's archive handler and object mapper.
+ *
+ * @var bool
+ */
+ private bool $archiveServicesAvailable = true;
+
/**
* Contacts in the fake address book: uid => name, email.
*
@@ -215,6 +243,10 @@ protected function setUp(): void {
$this->store = [self::MODULE => [], self::ORGANIZATION => [], self::USAGE => [], self::CONTACT_PERSON => []];
$this->saves = [];
$this->beforeSave = null;
+ $this->states = [];
+ $this->transitions = [];
+ $this->beforeTransition = null;
+ $this->archiveServicesAvailable = true;
$this->contacts = [];
$this->addressBooks = [];
$this->contactsEnabled = true;
@@ -341,20 +373,23 @@ private function noteScope(string $method, bool $rbac, bool $multitenancy): void
*
* @param string $uuid The uuid.
* @param array $data The object data.
+ * @param array $state The archive and trash markers, serialised under `@self`.
*
* @return ObjectEntityInterface
*/
- private function entity(string $uuid, array $data): ObjectEntityInterface {
- return new class($uuid, $data) implements ObjectEntityInterface {
+ private function entity(string $uuid, array $data, array $state = []): ObjectEntityInterface {
+ return new class($uuid, $data, $state) implements ObjectEntityInterface {
/**
* Constructor.
*
* @param string $uuid The uuid.
* @param array $data The data.
+ * @param array $state The markers.
*/
public function __construct(
private string $uuid,
private array $data,
+ private array $state,
) {
}
@@ -383,7 +418,7 @@ public function getOwner(): ?string {
}
public function jsonSerialize(): array {
- return $this->data;
+ return array_merge($this->data, ['@self' => array_merge(['archived' => null, 'deleted' => null], $this->state)]);
}
};
}//end entity()
@@ -403,6 +438,11 @@ function (array $object, ?array $extend = [], $register = null, $schema = null,
($this->beforeSave)($schema, $object);
}
+ // OpenRegister refuses a data write to an archived object (ObjectStateWriteException).
+ if ($uuid !== null && empty($this->states[$schema][$uuid]['archived']) === false) {
+ throw new RuntimeException('write to an archived object');
+ }
+
$create = ($uuid === null);
if ($create === true) {
$uuid = sprintf('00000000-0000-4000-8000-%012d', count($this->saves) + 1);
@@ -435,12 +475,24 @@ function (array $query = [], bool $_rbac = true, bool $_multitenancy = true): ar
}
}
- $found[] = $this->entity(uuid: $uuid, data: $data);
+ $state = ($this->states[$schema][$uuid] ?? []);
+ if (self::inLens(query: $query, uuid: (string)$uuid, state: $state) === false) {
+ continue;
+ }
+
+ $found[] = $this->entity(uuid: $uuid, data: $data, state: $state);
}
return array_slice($found, $offset, $limit);
}
);
+ $service->method('deleteObject')->willReturnCallback(
+ function (string $uuid, $register = null, $schema = null, bool $_rbac = true, bool $_multitenancy = true): bool {
+ $this->noteScope(method: 'deleteObject', rbac: $_rbac, multitenancy: $_multitenancy);
+ $this->changeState(verb: 'delete', uuid: $uuid, reason: null);
+ return true;
+ }
+ );
$service->method('find')->willReturnCallback(
function ($id, ?array $_extend = [], bool $files = false, $register = null, $schema = null, bool $_rbac = true, bool $_multitenancy = true): ?ObjectEntityInterface {
$this->noteScope(method: 'find', rbac: $_rbac, multitenancy: $_multitenancy);
@@ -459,6 +511,154 @@ function ($id, ?array $_extend = [], bool $files = false, $register = null, $sch
return $service;
}//end objectService()
+ /**
+ * Whether an object is in the list a query asks for, as OpenRegister's lenses decide.
+ *
+ * Archived and soft-deleted objects are left out unless `_archived`
+ * (`true` only the archive, `any` both) or `_includeDeleted` asks for them;
+ * `_ids` narrows to those uuids.
+ *
+ * @param array $query The search query.
+ * @param string $uuid The object.
+ * @param array $state Its markers.
+ *
+ * @return bool
+ */
+ private static function inLens(array $query, string $uuid, array $state): bool {
+ if (isset($query['_ids']) === true && in_array($uuid, (array)$query['_ids'], true) === false) {
+ return false;
+ }
+
+ if (empty($state['deleted']) === false && filter_var(($query['_includeDeleted'] ?? false), FILTER_VALIDATE_BOOLEAN) === false) {
+ return false;
+ }
+
+ $archived = (empty($state['archived']) === false);
+ $lens = ($query['_archived'] ?? null);
+ if ($lens === 'any') {
+ return true;
+ }
+
+ if (filter_var($lens, FILTER_VALIDATE_BOOLEAN) === true) {
+ return $archived;
+ }
+
+ return $archived === false;
+ }//end inLens()
+
+ /**
+ * Archive, unarchive, restore or soft-delete a stored object, as OpenRegister's handlers do.
+ *
+ * @param string $verb archive, unarchive, restore or delete.
+ * @param string $uuid The object.
+ * @param string|null $reason The archive reason.
+ *
+ * @return array{uuid: string, archived: array|null}
+ */
+ public function changeState(string $verb, string $uuid, ?string $reason): array {
+ if ($this->beforeTransition !== null) {
+ ($this->beforeTransition)($verb, $uuid);
+ }
+
+ $schema = 0;
+ foreach ($this->store as $id => $objects) {
+ if (isset($objects[$uuid]) === true) {
+ $schema = $id;
+ }
+ }
+
+ $this->assertNotSame(0, $schema, 'no stored object ' . $uuid);
+ $this->transitions[] = [$verb, $schema, $uuid, $reason];
+ $state = ($this->states[$schema][$uuid] ?? []);
+ if ($verb !== 'restore' && empty($state['deleted']) === false) {
+ // The archive handler and the delete resolve the object without the trash.
+ throw new \OCP\AppFramework\Db\DoesNotExistException('object is in the trash');
+ }
+
+ match ($verb) {
+ 'archive' => $state['archived'] = ($state['archived'] ?? null) ?: ['by' => 'admin', 'at' => '2026-10-09T00:00:00+00:00', 'reason' => $reason],
+ 'unarchive' => $state['archived'] = null,
+ 'restore' => $state['deleted'] = null,
+ 'delete' => $state['deleted'] = ['deletedBy' => 'admin', 'deletedAt' => '2026-10-09T00:00:00+00:00'],
+ };
+ $this->states[$schema][$uuid] = $state;
+
+ return ['uuid' => $uuid, 'archived' => ($state['archived'] ?? null)];
+ }//end changeState()
+
+ /**
+ * OpenRegister's archive handler and object mapper over the in-memory store.
+ *
+ * @return array{0: object, 1: object}
+ */
+ private function archiveDoubles(): array {
+ $test = $this;
+ $handler = new class($test) {
+ /**
+ * Constructor.
+ *
+ * @param CmdbExportImportServiceTest $test The test, which holds the markers.
+ */
+ public function __construct(
+ private CmdbExportImportServiceTest $test,
+ ) {
+ }
+
+ /**
+ * Archive an object.
+ *
+ * @param string $identifier The uuid.
+ * @param string|null $reason The reason.
+ * @param string|null $register Ignored.
+ * @param string|null $schema Ignored.
+ *
+ * @return array
+ */
+ public function archive(string $identifier, ?string $reason = null, ?string $register = null, ?string $schema = null): array {
+ return $this->test->changeState(verb: 'archive', uuid: $identifier, reason: $reason);
+ }
+
+ /**
+ * Unarchive an object.
+ *
+ * @param string $identifier The uuid.
+ * @param string|null $reason The reason.
+ * @param string|null $register Ignored.
+ * @param string|null $schema Ignored.
+ *
+ * @return array
+ */
+ public function unarchive(string $identifier, ?string $reason = null, ?string $register = null, ?string $schema = null): array {
+ return $this->test->changeState(verb: 'unarchive', uuid: $identifier, reason: $reason);
+ }
+ };
+ $mapper = new class($test) {
+ /**
+ * Constructor.
+ *
+ * @param CmdbExportImportServiceTest $test The test, which holds the markers.
+ */
+ public function __construct(
+ private CmdbExportImportServiceTest $test,
+ ) {
+ }
+
+ /**
+ * Take an object out of the trash.
+ *
+ * @param string $uuid The uuid.
+ *
+ * @return object
+ */
+ public function restoreObject(string $uuid): object {
+ $this->test->changeState(verb: 'restore', uuid: $uuid, reason: null);
+ return new \stdClass();
+ }
+ };
+
+ return [$handler, $mapper];
+ }//end archiveDoubles()
+
/**
* OpenRegister's schema mapper over the declared properties.
*
@@ -674,19 +874,24 @@ function (&$value): void {
/**
* A reader that hands out given rows, for tests that do not need the fixture.
*
+ * The workbook has the archive sheet, listing $archived; null is a workbook without the sheet.
+ *
* @param array}> $rows The rows.
+ * @param array|null $archived The APPIDs on the archive sheet, or null when there is no such sheet.
*
* @return CmdbWorkbookReader
*/
- private function rowsReader(array $rows): CmdbWorkbookReader {
- return new class($rows) extends CmdbWorkbookReader {
+ private function rowsReader(array $rows, ?array $archived = []): CmdbWorkbookReader {
+ return new class($rows, $archived) extends CmdbWorkbookReader {
/**
* Constructor.
*
* @param array> $rows The rows.
+ * @param array|null $archived The archive sheet's APPIDs, or null.
*/
public function __construct(
private array $rows,
+ private ?array $archived,
) {
}
@@ -699,7 +904,8 @@ public function __construct(
* @return array
*/
public function read(string $path, CmdbImportProfile $profile): array {
- return ['rows' => $this->rows, 'importWarnings' => [], 'date1904' => false];
+ $archive = ['sheet' => 'Gearchiveerde Applicaties', 'present' => ($this->archived !== null), 'keyColumnMissing' => false, 'appIds' => ($this->archived ?? [])];
+ return ['rows' => $this->rows, 'importWarnings' => [], 'date1904' => false, 'archive' => $archive];
}
};
}//end rowsReader()
@@ -716,10 +922,11 @@ public function read(string $path, CmdbImportProfile $profile): array {
private function service(?CmdbWorkbookReader $reader = null, ?string $profileDir = null, array $config = ['register' => '20']): CmdbExportImportService {
$objectService = $this->objectService();
$schemaMapper = $this->schemaMapper();
+ [$archiveHandler, $objectMapper] = $this->archiveDoubles();
$container = $this->createMock(ContainerInterface::class);
$container->method('has')->willReturn(false);
$container->method('get')->willReturnCallback(
- function (string $id) use ($objectService, $schemaMapper) {
+ function (string $id) use ($objectService, $schemaMapper, $archiveHandler, $objectMapper) {
if ($id === ObjectServiceInterface::class) {
return $objectService;
}
@@ -728,6 +935,14 @@ function (string $id) use ($objectService, $schemaMapper) {
return $schemaMapper;
}
+ if ($this->archiveServicesAvailable === true && $id === CmdbExportImportService::ARCHIVE_HANDLER_CLASS) {
+ return $archiveHandler;
+ }
+
+ if ($this->archiveServicesAvailable === true && $id === CmdbExportImportService::OBJECT_MAPPER_CLASS) {
+ return $objectMapper;
+ }
+
throw new RuntimeException('not in this container: ' . $id);
}
);
@@ -846,7 +1061,7 @@ public function testTheFixtureCreatesModulesUsagesAndSuppliers(): void {
$this->assertTrue($report['success']);
$this->assertFalse($report['cancelled']);
$this->assertSame('cmdb-test-0001', $report['operationId']);
- $this->assertSame(['rowsRead' => 2, 'processed' => 2, 'created' => 2, 'updated' => 0, 'unchanged' => 0, 'skipped' => 0, 'failed' => 0, 'warnings' => 0, 'unpublished' => 0], $report['summary']);
+ $this->assertSame(['rowsRead' => 2, 'processed' => 2, 'created' => 2, 'updated' => 0, 'unchanged' => 0, 'skipped' => 0, 'failed' => 0, 'archived' => 0, 'unarchived' => 0, 'deleted' => 0, 'restored' => 0, 'warnings' => 0, 'unpublished' => 0], $report['summary']);
$this->assertSame('Gemeente Voorbeeldstad', $report['municipality']['name']);
$this->assertTrue($report['municipality']['created']);
$this->assertSame(['No municipality named "Gemeente Voorbeeldstad" was found, so it was created. Check the name if you meant an existing one.'], array_column($report['importWarnings'], 'message'), 'only the warning that the municipality was created');
@@ -1448,29 +1663,386 @@ public function testUpdateExistingFalseSkipsMatches(): void {
}//end testUpdateExistingFalseSkipsMatches()
/**
- * A module missing from a newer export, and its usage, are left as they are.
+ * The uuid of the stored module with this APPID.
+ *
+ * @param string $appId The APPID.
+ *
+ * @return string
+ */
+ private function moduleOf(string $appId): string {
+ foreach ($this->store[self::MODULE] as $uuid => $module) {
+ if (($module['externalNumber'] ?? null) === $appId) {
+ return (string)$uuid;
+ }
+ }
+
+ $this->fail('no module with APPID ' . $appId);
+ }//end moduleOf()
+
+ /**
+ * The uuid of the stored usage of a module by a consumer.
+ *
+ * @param string $moduleUuid The module.
+ * @param string $consumer The consumer.
+ *
+ * @return string
+ */
+ private function usageOf(string $moduleUuid, string $consumer = 'muni-1'): string {
+ foreach ($this->store[self::USAGE] as $uuid => $usage) {
+ if (($usage['module'] ?? null) === $moduleUuid && ($usage['consumer'] ?? null) === $consumer) {
+ return (string)$uuid;
+ }
+ }
+
+ $this->fail('no usage of ' . $moduleUuid . ' by ' . $consumer);
+ }//end usageOf()
+
+ /**
+ * Whether a stored object carries the archive marker, and whether the trash marker.
+ *
+ * @param int $schema The schema id.
+ * @param string $uuid The object.
+ *
+ * @return array{0: bool, 1: bool} Archived, deleted.
+ */
+ private function stateOf(int $schema, string $uuid): array {
+ $state = ($this->states[$schema][$uuid] ?? []);
+ return [empty($state['archived']) === false, empty($state['deleted']) === false];
+ }//end stateOf()
+
+ /**
+ * Import APPIDs 1, 7 and 8 for muni-1, as a first import would.
*
* @return void
*/
- public function testRecordsMissingFromTheExportStay(): void {
+ private function importOneSevenAndEight(): void {
$this->seedOrganisation(uuid: 'muni-1', name: 'Gemeente Voorbeeldstad', type: 'Municipality');
- $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1', row: 2), $this->row(appId: '7', row: 3, sheet: 'Onbeh Applicaties CMDB')]))
- ->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+ $rows = [
+ $this->row(appId: '1', row: 2),
+ $this->row(appId: '7', row: 3, sheet: 'Onbeh Applicaties CMDB'),
+ $this->row(appId: '8', row: 4, cells: ['Applicatie Eigenaar (Persoon)' => 'Achternaam, Voornaam']),
+ ];
+ $this->service(reader: $this->rowsReader(rows: $rows))->import(path: '', options: ['municipalityUuid' => 'muni-1', 'missingRecords' => 'keep']);
+ $this->transitions = [];
+ }//end importOneSevenAndEight()
+
+ /**
+ * A module missing from a newer export, and its usage, are left as they are when records are kept.
+ *
+ * @return void
+ *
+ * @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 testRecordsMissingFromTheExportStayWhenKept(): void {
+ $this->importOneSevenAndEight();
$modules = $this->store[self::MODULE];
$usages = $this->store[self::USAGE];
- $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1', cells: ['Applicatie Naam' => 'Nieuw'])]))
- ->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+ $report = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1', cells: ['Applicatie Naam' => 'Nieuw'])]))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1', 'missingRecords' => 'keep']);
foreach ($modules as $uuid => $module) {
- if ($module['externalNumber'] === '7') {
+ if ($module['externalNumber'] !== '1') {
$this->assertSame($module, $this->store[self::MODULE][$uuid]);
}
}
$this->assertSame($usages, $this->store[self::USAGE]);
- $this->assertCount(2, $this->store[self::MODULE]);
- }//end testRecordsMissingFromTheExportStay()
+ $this->assertSame([], $this->transitions, 'nothing is archived or deleted');
+ $this->assertSame([], $this->states);
+ $this->assertSame(['updated'], array_column($report['rows'], 'outcome'));
+ $this->assertSame([], $report['importWarnings'], 'keep does not need the archive sheet');
+ }//end testRecordsMissingFromTheExportStayWhenKept()
+
+ /**
+ * By default an application that moved to the archive sheet is archived and one on no sheet is soft-deleted,
+ * usage before module, and the owner contact person stays.
+ *
+ * @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
+ */
+ public function testMissingApplicationsAreArchivedOrDeletedByDefault(): void {
+ $this->importOneSevenAndEight();
+ $contactPersons = $this->store[self::CONTACT_PERSON];
+ $this->assertNotSame([], $contactPersons, 'APPID 8 has an owner');
+ [$seven, $eight] = [$this->moduleOf(appId: '7'), $this->moduleOf(appId: '8')];
+
+ $report = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')], archived: ['7', '1198']))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1', 'operationId' => 'cmdb-archive-01']);
+
+ $this->assertSame([true, false], $this->stateOf(schema: self::MODULE, uuid: $seven));
+ $this->assertSame([true, false], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $seven)));
+ $this->assertSame([false, true], $this->stateOf(schema: self::MODULE, uuid: $eight));
+ $this->assertSame([false, true], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $eight)));
+ $this->assertSame([false, false], $this->stateOf(schema: self::MODULE, uuid: $this->moduleOf(appId: '1')));
+ $this->assertSame(
+ [
+ ['archive', self::USAGE, $this->usageOf(moduleUuid: $seven)],
+ ['archive', self::MODULE, $seven],
+ ['delete', self::USAGE, $this->usageOf(moduleUuid: $eight)],
+ ['delete', self::MODULE, $eight],
+ ],
+ array_map(static fn (array $t): array => array_slice($t, 0, 3), $this->transitions),
+ 'the usage is written before its module'
+ );
+ $this->assertSame('cmdb-import: on sheet "Gearchiveerde Applicaties" (cmdb-archive-01)', $this->transitions[0][3]);
+ $this->assertSame($contactPersons, $this->store[self::CONTACT_PERSON], 'contact persons are never touched');
+
+ $reconciled = array_values(array_filter($report['rows'], static fn (array $row): bool => $row['row'] === 0));
+ $this->assertSame(
+ [
+ ['sheet' => 'Gearchiveerde Applicaties', 'row' => 0, 'appId' => '7', 'name' => 'Applicatie 7', 'outcome' => 'archived', 'reasons' => [], 'warnings' => [], 'moduleUuid' => $seven, 'usageUuid' => $this->usageOf(moduleUuid: $seven)],
+ ['sheet' => '', 'row' => 0, 'appId' => '8', 'name' => 'Applicatie 8', 'outcome' => 'deleted', 'reasons' => [], 'warnings' => [], 'moduleUuid' => $eight, 'usageUuid' => $this->usageOf(moduleUuid: $eight)],
+ ],
+ $reconciled
+ );
+ $this->assertSame(1, $report['summary']['processed'], 'reconciliation entries are not sheet rows');
+ $this->assertSame([1, 1], [$report['summary']['archived'], $report['summary']['deleted']]);
+ $this->assertStringNotContainsString('Achternaam', (string)json_encode($report));
+ $this->assertSame([], $report['importWarnings']);
+
+ $this->transitions = [];
+ $again = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')], archived: ['7']))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+ $this->assertSame([], $this->transitions, 'an application already in the state the export asks for is left alone');
+ $this->assertSame(['unchanged'], array_column($again['rows'], 'outcome'));
+ }//end testMissingApplicationsAreArchivedOrDeletedByDefault()
+
+ /**
+ * Without the archive sheet a missing application is archived, never deleted, and the report warns.
+ *
+ * @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
+ */
+ public function testWithoutTheArchiveSheetMissingApplicationsAreArchivedNotDeleted(): void {
+ $this->importOneSevenAndEight();
+ $eight = $this->moduleOf(appId: '8');
+ $this->states[self::MODULE][$eight] = ['deleted' => ['deletedBy' => 'admin']];
+
+ $report = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')], archived: null))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+
+ $this->assertSame([true, false], $this->stateOf(schema: self::MODULE, uuid: $this->moduleOf(appId: '7')));
+ $this->assertSame([true, false], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $this->moduleOf(appId: '7'))));
+ $this->assertSame([false, true], $this->stateOf(schema: self::MODULE, uuid: $eight), 'what is in the trash stays there');
+ $this->assertSame([true, false], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $eight)));
+ $this->assertNotContains('delete', array_column($this->transitions, 0));
+ $this->assertNotContains('restore', array_column($this->transitions, 0));
+ $this->assertSame('cmdb-import: not in the export (' . $report['operationId'] . ')', $this->transitions[0][3]);
+ $this->assertSame(['unchanged', 'archived', 'archived'], array_column($report['rows'], 'outcome'));
+ $this->assertSame(
+ [['sheet' => 'Gearchiveerde Applicaties', 'message' => 'Sheet "Gearchiveerde Applicaties" was not found, so applications missing from the export are archived, not deleted.']],
+ $report['importWarnings']
+ );
+ }//end testWithoutTheArchiveSheetMissingApplicationsAreArchivedNotDeleted()
+
+ /**
+ * A cancelled import reconciles nothing.
+ *
+ * @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
+ */
+ public function testACancelledImportDoesNotReconcile(): void {
+ $this->importOneSevenAndEight();
+ $service = null;
+ $this->beforeSave = function (int $schema) use (&$service): void {
+ if ($schema === self::MODULE) {
+ $service->requestCancel(operationId: 'cmdb-cancel-02');
+ }
+ };
+ $service = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1', cells: ['Applicatie Naam' => 'Nieuw']), $this->row(appId: '2', row: 3)]));
+
+ $report = $service->import(path: '', options: ['municipalityUuid' => 'muni-1', 'operationId' => 'cmdb-cancel-02']);
+
+ $this->assertTrue($report['cancelled']);
+ $this->assertSame([], $this->transitions);
+ $this->assertSame(['updated'], array_column($report['rows'], 'outcome'));
+ }//end testACancelledImportDoesNotReconcile()
+
+ /**
+ * Only this municipality's usages and the modules its import created are reconciled.
+ *
+ * @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
+ */
+ public function testAnotherMunicipalitysUsagesAreNeverReconciled(): void {
+ $this->importOneSevenAndEight();
+ $this->seedOrganisation(uuid: 'muni-2', name: 'Gemeente Anders', type: 'Municipality');
+ $seven = $this->moduleOf(appId: '7');
+ // Another municipality uses the same module (added by hand), and muni-1 uses a hand-made module.
+ $this->store[self::USAGE]['usage-other'] = ['id' => 'usage-other', 'consumer' => 'muni-2', 'module' => $seven];
+ $this->store[self::MODULE]['module-manual'] = ['id' => 'module-manual', 'name' => 'Handmatig', 'externalKey' => 'topdesk:muni-2:9'];
+ $this->store[self::USAGE]['usage-manual'] = ['id' => 'usage-manual', 'consumer' => 'muni-1', 'module' => 'module-manual'];
+
+ $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1'), $this->row(appId: '8', row: 3)], archived: ['7']))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+
+ $this->assertSame([true, false], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $seven)));
+ $this->assertSame([true, false], $this->stateOf(schema: self::MODULE, uuid: $seven), 'the module carries this municipality\'s import key');
+ $this->assertSame([false, false], $this->stateOf(schema: self::USAGE, uuid: 'usage-other'));
+ $this->assertSame([false, false], $this->stateOf(schema: self::USAGE, uuid: 'usage-manual'));
+ $this->assertSame([false, false], $this->stateOf(schema: self::MODULE, uuid: 'module-manual'));
+ $this->assertSame(2, count($this->transitions));
+ }//end testAnotherMunicipalitysUsagesAreNeverReconciled()
+
+ /**
+ * One application that cannot be archived is a failed row; the others are still reconciled.
+ *
+ * @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
+ */
+ public function testAFailingArchiveIsAFailedRowAndTheOthersAreReconciled(): void {
+ $this->importOneSevenAndEight();
+ $seven = $this->moduleOf(appId: '7');
+ $this->beforeTransition = function (string $verb, string $uuid) use ($seven): void {
+ if ($uuid === $seven) {
+ throw new RuntimeException('Schema "Applicatie 7" does not declare x-openregister-archive');
+ }
+ };
+
+ $report = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')], archived: ['7', '8']))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+
+ $rows = array_values(array_filter($report['rows'], static fn (array $row): bool => $row['row'] === 0));
+ $this->assertSame(['failed', 'archived'], array_column($rows, 'outcome'));
+ $this->assertSame(['step "archive" failed (RuntimeException)'], $rows[0]['reasons']);
+ $this->assertSame([true, false], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $seven)), 'the usage went first');
+ $this->assertSame([true, false], $this->stateOf(schema: self::MODULE, uuid: $this->moduleOf(appId: '8')));
+ $this->assertSame(1, $report['summary']['failed']);
+ $failed = array_values(array_filter($this->logLines, static fn (string $line): bool => str_starts_with($line, 'CmdbExportImportService: row failed')));
+ $this->assertCount(1, $failed);
+ $this->assertStringNotContainsString('Applicatie 7', $failed[0]);
+ }//end testAFailingArchiveIsAFailedRowAndTheOthersAreReconciled()
+
+ /**
+ * Without OpenRegister's archive services an archiving import is refused before the file is read; keep still imports.
+ *
+ * @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
+ */
+ public function testMissingArchiveServicesRefuseAnArchivingImport(): void {
+ $this->seedOrganisation(uuid: 'muni-1', name: 'Gemeente Voorbeeldstad', type: 'Municipality');
+ $this->archiveServicesAvailable = false;
+ $reader = new class extends CmdbWorkbookReader {
+ /**
+ * Constructor.
+ */
+ public function __construct() {
+ }
+
+ /**
+ * Never reached.
+ *
+ * @param string $path Ignored.
+ * @param CmdbImportProfile $profile Ignored.
+ *
+ * @return array
+ */
+ public function read(string $path, CmdbImportProfile $profile): array {
+ throw new RuntimeException('the file was read');
+ }
+ };
+
+ try {
+ $this->service(reader: $reader)->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+ $this->fail('ARCHIVE_UNAVAILABLE expected');
+ } catch (CmdbImportException $e) {
+ $this->assertSame('ARCHIVE_UNAVAILABLE', $e->getErrorCode());
+ $this->assertSame(503, $e->getHttpStatus());
+ }
+
+ $this->assertSame([], $this->saves);
+ $report = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')]))->import(path: '', options: ['municipalityUuid' => 'muni-1', 'missingRecords' => 'keep']);
+ $this->assertSame(['created'], array_column($report['rows'], 'outcome'));
+ }//end testMissingArchiveServicesRefuseAnArchivingImport()
+
+ /**
+ * An archived application that returns is unarchived and a soft-deleted one restored, before the write; no duplicates.
+ *
+ * @return void
+ *
+ * @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
+ */
+ public function testAReturningApplicationIsUnarchivedOrRestoredNotDuplicated(): void {
+ $this->importOneSevenAndEight();
+ [$seven, $eight] = [$this->moduleOf(appId: '7'), $this->moduleOf(appId: '8')];
+ $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')], archived: ['7']))->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+ $modules = count($this->store[self::MODULE]);
+ $usages = count($this->store[self::USAGE]);
+ $this->transitions = [];
+
+ $rows = [
+ $this->row(appId: '1'),
+ $this->row(appId: '7', row: 3, sheet: 'Onbeh Applicaties CMDB', cells: ['Applicatie Naam' => 'Terug']),
+ $this->row(appId: '8', row: 4),
+ ];
+ $report = $this->service(reader: $this->rowsReader(rows: $rows))->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+
+ $this->assertSame(['unchanged', 'unarchived', 'restored'], array_column($report['rows'], 'outcome'));
+ $this->assertSame([1, 1], [$report['summary']['unarchived'], $report['summary']['restored']]);
+ $this->assertSame([$modules, $usages], [count($this->store[self::MODULE]), count($this->store[self::USAGE])], 'no second module or usage');
+ foreach ([$seven, $eight] as $module) {
+ $this->assertSame([false, false], $this->stateOf(schema: self::MODULE, uuid: $module));
+ $this->assertSame([false, false], $this->stateOf(schema: self::USAGE, uuid: $this->usageOf(moduleUuid: $module)));
+ }
+
+ $this->assertSame('Terug', $this->store[self::MODULE][$seven]['name'], 'the row is updated after the unarchive');
+ $this->assertSame(['unarchive', 'unarchive', 'restore', 'restore'], array_column($this->transitions, 0));
+ }//end testAReturningApplicationIsUnarchivedOrRestoredNotDuplicated()
+
+ /**
+ * With updateExisting false a returning application is skipped as `exists` and stays archived.
+ *
+ * @return void
+ *
+ * @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
+ */
+ public function testUpdateExistingFalseLeavesAnArchivedMatchArchived(): void {
+ $this->importOneSevenAndEight();
+ $seven = $this->moduleOf(appId: '7');
+ $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1'), $this->row(appId: '8', row: 3)], archived: ['7']))->import(path: '', options: ['municipalityUuid' => 'muni-1']);
+ $modules = $this->store[self::MODULE];
+ $this->transitions = [];
+
+ $report = $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '7', sheet: 'Onbeh Applicaties CMDB')]))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1', 'updateExisting' => false, 'missingRecords' => 'keep']);
+
+ $this->assertSame(['skipped'], array_column($report['rows'], 'outcome'));
+ $this->assertSame(['exists'], $report['rows'][0]['reasons']);
+ $this->assertSame([true, false], $this->stateOf(schema: self::MODULE, uuid: $seven));
+ $this->assertSame([], $this->transitions);
+ $this->assertSame($modules, $this->store[self::MODULE]);
+ }//end testUpdateExistingFalseLeavesAnArchivedMatchArchived()
+
+ /**
+ * The reconciliation reports its own progress phase and advances per application.
+ *
+ * @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
+ */
+ public function testTheReconciliationHasItsOwnProgressPhase(): void {
+ $this->importOneSevenAndEight();
+ $seen = [];
+ $this->beforeTransition = function () use (&$seen): void {
+ $progress = $this->tracker->getProgress(operationId: 'cmdb-reconcile-1');
+ $seen[] = [$progress['phase'], $progress['processed_items'], $progress['total_items']];
+ };
+
+ $this->service(reader: $this->rowsReader(rows: [$this->row(appId: '1')], archived: ['7', '8']))
+ ->import(path: '', options: ['municipalityUuid' => 'muni-1', 'operationId' => 'cmdb-reconcile-1']);
+
+ // One row, then three usages in scope: APPID 1 (on a CMDB sheet), 7 and 8.
+ $this->assertSame([['reconciling', 2, 4], ['reconciling', 2, 4], ['reconciling', 3, 4], ['reconciling', 3, 4]], $seen);
+ $this->assertSame('completed', $this->cache['progress_cmdb-reconcile-1']['status']);
+ $this->assertSame(4, $this->cache['progress_cmdb-reconcile-1']['processed_items']);
+ }//end testTheReconciliationHasItsOwnProgressPhase()
/**
* An unknown Applicatie Status drops only that field and warns with column and value.
@@ -1806,7 +2378,7 @@ public function testAnImportLeavesAnAuditRecord(): void {
options: ['municipalityUuid' => 'muni-1', 'updateExisting' => false, 'publish' => false, 'operationId' => 'cmdb-audit-01', 'fileName' => 'C:\\Users\\beheer\\export.xlsx']
);
- $audit = '"operationId":"cmdb-audit-01","uid":"admin","fileName":"export.xlsx","municipality":"muni-1","municipalityCreated":false,"updateExisting":false,"publish":false';
+ $audit = '"operationId":"cmdb-audit-01","uid":"admin","fileName":"export.xlsx","municipality":"muni-1","municipalityCreated":false,"updateExisting":false,"publish":false,"missingRecords":"archive"';
$started = array_values(array_filter($this->logLines, static fn (string $line): bool => str_starts_with($line, 'CmdbExportImportService: import started')));
$finished = array_values(array_filter($this->logLines, static fn (string $line): bool => str_starts_with($line, 'CmdbExportImportService: import finished')));
$this->assertCount(1, $started);
@@ -1879,7 +2451,7 @@ public function testOneBadRowDoesNotStopTheOthers(): void {
$this->assertSame(['created', 'failed', 'created'], array_column($report['rows'], 'outcome'));
$this->assertStringStartsWith('step "module" failed', $report['rows'][1]['reasons'][0]);
- $this->assertSame(['rowsRead' => 3, 'processed' => 3, 'created' => 2, 'updated' => 0, 'unchanged' => 0, 'skipped' => 0, 'failed' => 1, 'warnings' => 0, 'unpublished' => 0], $report['summary']);
+ $this->assertSame(['rowsRead' => 3, 'processed' => 3, 'created' => 2, 'updated' => 0, 'unchanged' => 0, 'skipped' => 0, 'failed' => 1, 'archived' => 0, 'unarchived' => 0, 'deleted' => 0, 'restored' => 0, 'warnings' => 0, 'unpublished' => 0], $report['summary']);
$this->assertCount(2, $this->store[self::MODULE]);
}//end testOneBadRowDoesNotStopTheOthers()
From 2919497b2ebfd72937577ce32205e615da332701 Mon Sep 17 00:00:00 2001
From: WilcoLouwerse
Date: Fri, 9 Oct 2026 15:46:04 +0200
Subject: [PATCH 05/18] feat(cmdb-import): accept missingRecords keep or
archive, default archive
The endpoint passes the option to the import, names both accepted values
when it refuses a reserved one, and translates ARCHIVE_UNAVAILABLE. The
OpenAPI document and the Postman test describe the new values, outcomes and
error.
Co-Authored-By: Claude Opus 5.5
---
l10n/en.js | 5 ++-
l10n/en.json | 5 ++-
l10n/nl.js | 5 ++-
l10n/nl.json | 5 ++-
lib/Controller/CmdbImportController.php | 17 ++++++--
openapi.json | 40 +++++++++++++++----
postman/stackiq-tests.json | 3 +-
.../Controller/CmdbImportControllerTest.php | 34 +++++++++++++++-
8 files changed, 96 insertions(+), 18 deletions(-)
diff --git a/l10n/en.js b/l10n/en.js
index 8dd84a2f..a5d73758 100644
--- a/l10n/en.js
+++ b/l10n/en.js
@@ -1038,7 +1038,10 @@ 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.",
"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..c14c8424 100644
--- a/l10n/en.json
+++ b/l10n/en.json
@@ -1037,7 +1037,10 @@
"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.",
"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..e0ce1d95 100644
--- a/l10n/nl.js
+++ b/l10n/nl.js
@@ -1106,7 +1106,10 @@ 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.",
"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..acde8313 100644
--- a/l10n/nl.json
+++ b/l10n/nl.json
@@ -1105,7 +1105,10 @@
"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.",
"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..b10e7cd1 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,20 @@ 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']]);
+ return $this->error(
+ code: 'MISSING_RECORDS_UNSUPPORTED',
+ status: Http::STATUS_UNPROCESSABLE_ENTITY,
+ details: ['accepted' => $this->importService->missingRecordsModes()]
+ );
}
// An unrecognised value is refused rather than read as true: true is the mode that overwrites.
@@ -293,6 +300,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 +402,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 +418,7 @@ 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/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/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/tests/Unit/Controller/CmdbImportControllerTest.php b/tests/Unit/Controller/CmdbImportControllerTest.php
index a27b7cfb..ca0964f8 100644
--- a/tests/Unit/Controller/CmdbImportControllerTest.php
+++ b/tests/Unit/Controller/CmdbImportControllerTest.php
@@ -114,7 +114,8 @@ private function controller(
if ($service === null) {
$service = $this->createMock(CmdbExportImportService::class);
$service->method('maxFileBytes')->willReturn(10485760);
- $service->method('supportsMissingRecords')->willReturnCallback(fn (string $mode): bool => $mode === 'keep');
+ $service->method('supportsMissingRecords')->willReturnCallback(fn (string $mode): bool => in_array($mode, ['keep', 'archive'], true));
+ $service->method('missingRecordsModes')->willReturn(['keep', 'archive']);
}
$logger = ($logger ?? $this->createMock(LoggerInterface::class));
@@ -157,7 +158,8 @@ protected function iniBytes(string $name): ?int {
private function service(): CmdbExportImportService|MockObject {
$service = $this->createMock(CmdbExportImportService::class);
$service->method('maxFileBytes')->willReturn(10485760);
- $service->method('supportsMissingRecords')->willReturnCallback(fn (string $mode): bool => $mode === 'keep');
+ $service->method('supportsMissingRecords')->willReturnCallback(fn (string $mode): bool => in_array($mode, ['keep', 'archive'], true));
+ $service->method('missingRecordsModes')->willReturn(['keep', 'archive']);
return $service;
}//end service()
@@ -371,9 +373,30 @@ public function testAReservedMissingRecordsValueIsRefused(): void {
$response = $this->controller(file: $this->file(path: $this->upload()), params: ['missingRecords' => $mode], service: $service)->import();
$this->assertSame(422, $response->getStatus(), $mode);
$this->assertSame('MISSING_RECORDS_UNSUPPORTED', $response->getData()['error'], $mode);
+ $this->assertEquals((object)['accepted' => ['keep', 'archive']], $response->getData()['details'], $mode);
+ $this->assertSame('Applications missing from the export can only be archived or kept.', $response->getData()['message'], $mode);
}
}//end testAReservedMissingRecordsValueIsRefused()
+ /**
+ * Without missingRecords the import archives; keep and archive are passed through as sent.
+ *
+ * @return void
+ *
+ * @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 testMissingRecordsDefaultsToArchive(): void {
+ foreach ([[[], 'archive'], [['missingRecords' => 'keep'], 'keep'], [['missingRecords' => 'archive'], 'archive']] as [$params, $expected]) {
+ $service = $this->service();
+ $service->expects($this->once())->method('import')
+ ->with($this->anything(), $this->callback(static fn (array $options): bool => $options['missingRecords'] === $expected))
+ ->willReturn(['success' => true]);
+
+ $response = $this->controller(file: $this->file(path: $this->upload()), params: array_merge(['municipalityName' => 'Gemeente Voorbeeldstad'], $params), service: $service)->import();
+ $this->assertSame(200, $response->getStatus(), $expected);
+ }
+ }//end testMissingRecordsDefaultsToArchive()
+
/**
* Without a municipality the answer is 422 MUNICIPALITY_REQUIRED and nothing is imported.
*
@@ -407,6 +430,7 @@ public static function serviceErrors(): array {
'schema' => [CmdbImportException::SCHEMA_OUTDATED, 503, ['schema' => 'module', 'missing' => ['externalKey']]],
'running' => [CmdbImportException::IMPORT_IN_PROGRESS, 409, []],
'ambiguous' => [CmdbImportException::MUNICIPALITY_AMBIGUOUS, 422, ['matches' => ['00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002']]],
+ 'archive' => [CmdbImportException::ARCHIVE_UNAVAILABLE, 503, []],
];
}//end serviceErrors()
@@ -421,6 +445,10 @@ public static function engineMessages(): array {
'schema' => [CmdbImportException::SCHEMA_OUTDATED, 'The stackiq register is out of date; import its configuration again.'],
'running' => [CmdbImportException::IMPORT_IN_PROGRESS, 'Another CMDB import is running; try again when it has finished.'],
'ambiguous' => [CmdbImportException::MUNICIPALITY_AMBIGUOUS, 'Several municipalities have this name; choose one from the list.'],
+ 'archive' => [
+ CmdbImportException::ARCHIVE_UNAVAILABLE,
+ 'Applications missing from the export cannot be archived: OpenRegister is missing or too old. Choose to keep them, or update OpenRegister.',
+ ],
];
}//end engineMessages()
@@ -533,6 +561,7 @@ public function testAValidUploadReturnsTheReport(): void {
'municipalityName' => 'Gemeente Voorbeeldstad',
'updateExisting' => false,
'publish' => true,
+ 'missingRecords' => 'keep',
'operationId' => 'cmdb-00000000-0000-0000-0000-000000000000',
'fileName' => 'export.xlsx',
]
@@ -567,6 +596,7 @@ public function testTheFieldsReachTheServiceAsSent(): void {
'municipalityName' => 'Gemeente Voorbeeldstad',
'updateExisting' => true,
'publish' => true,
+ 'missingRecords' => 'archive',
'operationId' => 'not-a-cmdb-id',
'fileName' => 'export.xlsx',
]
From f2c533d169d0b7742f6060de7fdd368fd3b74332 Mon Sep 17 00:00:00 2001
From: WilcoLouwerse
Date: Fri, 9 Oct 2026 15:52:04 +0200
Subject: [PATCH 06/18] feat(cmdb-import): offer the missing-records choice and
an Archived quick filter
The CMDB import section lets the admin archive or delete applications
missing from the export (the default) or keep them, with help text, and
shows the archived, unarchived, deleted and restored counts and outcomes.
A reconciliation entry has no row number and a deleted module no link, and
the progress line says when the import checks missing applications. The
Applications and Applications in use pages get an Archived quick filter
that lists the archive (_archived=true).
Co-Authored-By: Claude Opus 5.5
---
l10n/en.js | 11 +++
l10n/en.json | 11 +++
l10n/nl.js | 11 +++
l10n/nl.json | 11 +++
src/icons.js | 2 +
src/manifest.d/usages.json | 3 +-
src/manifest.json | 7 ++
src/utils/cmdbImport.js | 72 +++++++++++++++--
src/utils/cmdbImport.spec.js | 58 +++++++++++++-
.../settings/sections/CmdbImport.spec.js | 58 ++++++++++++++
src/views/settings/sections/CmdbImport.vue | 77 ++++++++++++++++++-
tests/vitest/cmdbArchiveQuickFilter.spec.js | 62 +++++++++++++++
12 files changed, 373 insertions(+), 10 deletions(-)
create mode 100644 tests/vitest/cmdbArchiveQuickFilter.spec.js
diff --git a/l10n/en.js b/l10n/en.js
index a5d73758..8e95ef02 100644
--- a/l10n/en.js
+++ b/l10n/en.js
@@ -1042,6 +1042,17 @@ OC.L10N.register(
"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 c14c8424..0d85cfba 100644
--- a/l10n/en.json
+++ b/l10n/en.json
@@ -1041,6 +1041,17 @@
"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 e0ce1d95..b0311833 100644
--- a/l10n/nl.js
+++ b/l10n/nl.js
@@ -1110,6 +1110,17 @@ OC.L10N.register(
"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 acde8313..92a16d73 100644
--- a/l10n/nl.json
+++ b/l10n/nl.json
@@ -1109,6 +1109,17 @@
"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/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