diff --git a/tests/e2e/spec-coverage/application-knowledge-base.spec.ts b/tests/e2e/spec-coverage/application-knowledge-base.spec.ts new file mode 100644 index 000000000..4621d6d90 --- /dev/null +++ b/tests/e2e/spec-coverage/application-knowledge-base.spec.ts @@ -0,0 +1,308 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Application knowledge base (the knowledge base change, tasks 1 and 2). + * + * Surfaces under test: + * src/manifest.json `ModuleDetail` widget `md-knowledge` (Knowledge + * articles, the library's CnCollectivesCard on OpenRegister's + * `collectives` leaf) next to `md-files` (Documentation), and the + * Collectives sidebar tab (CnCollectivesTab) that links, creates and + * unlinks pages; + * the src/manifest.d fragment of the change, page `KnowledgeBase` at + * /knowledge (a kb-search widget over OpenRegister's page search) and + * its menu entry `KnowledgeBaseMenu`, relocated under Applications by + * src/menu-layout.json. + * + * Seeds one application carrying this run's RUN_ID through the objects API. + * On an instance with Collectives it also makes a collective " + * Application knowledge" through the Collectives API and creates and links a + * page " Restore procedure" through OpenRegister's + * `.../collectives/new`. Afterwards it unlinks what it linked, deletes the + * collective (and its trash entry) and deletes the application. + * + * The suite runs on both kinds of instance (the Risks of the change): the Collectives + * scenarios skip without the app, and the set-up state scenario skips with it. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/insight-knowledge-base/specs/application-knowledge-base/spec.md#requirement-req-akb-001-the-application-detail-page-shall-show-the-knowledge-articles-linked-to-the-application + * @spec openspec/changes/insight-knowledge-base/specs/application-knowledge-base/spec.md#requirement-req-akb-002-an-application-owner-shall-link-an-existing-article-or-create-a-new-one-from-the-application-page + * @spec openspec/changes/insight-knowledge-base/specs/application-knowledge-base/spec.md#requirement-req-akb-003-the-knowledge-base-page-shall-search-the-articles-the-user-can-read-and-open-them-in-collectives + * @spec openspec/changes/insight-knowledge-base/specs/application-knowledge-base/spec.md#requirement-req-akb-004-without-the-collectives-app-the-knowledge-base-must-be-absent-not-broken + */ +import type { APIRequestContext, Page } from '@playwright/test' +import type { VoorzieningenConfig } from '../workflows/_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from '../workflows/_fixtures.ts' +import { appNav, gotoAppRoute } from './_helpers.ts' + +const OBJECTS = '/index.php/apps/openregister/api/objects' +const PAGE_SEARCH = '/index.php/apps/openregister/api/integrations/collectives/available' +const COLLECTIVES_OCS = '/ocs/v2.php/apps/collectives/api/v1.0/collectives' +const COLLECTIVES_API = '/index.php/apps/collectives/_api/collectives' + +const collectiveName = `${RUN_ID} Application knowledge` +const restoreTitle = `${RUN_ID} Restore procedure` +const onboardingTitle = `${RUN_ID} Onboarding new users` + +let api: APIRequestContext +let config: VoorzieningenConfig +let collectivesEnabled = false +let collectiveId = '' +let appId = '' + +// The tests share the seeded collective and its links: one worker, in order. +test.describe.configure({ mode: 'serial' }) + +interface LinkedPage { + id: string + title: string + url: string +} + +/** + * Whether a Nextcloud app is enabled on the instance. + * + * @param app The app id. + * @return True when it is enabled. + */ +async function appEnabled(app: string): Promise { + const res = await api.get('/ocs/v2.php/cloud/apps?filter=enabled&format=json') + if (!res.ok()) { + return false + } + const list: string[] = (await res.json())?.ocs?.data?.apps ?? [] + return list.includes(app) +} + +/** + * Create a collective through the Collectives API: the OCS API of current + * releases, else the older `_api` routes. + * + * @param name The collective's name. + * @return Its id. + */ +async function createCollective(name: string): Promise { + const ocs = await api.post(`${COLLECTIVES_OCS}?format=json`, { data: { name } }) + if (ocs.ok()) { + return String((await ocs.json())?.ocs?.data?.collective?.id ?? '') + } + const legacy = await api.post(COLLECTIVES_API, { data: { name } }) + expect(legacy.ok(), `create collective: ${legacy.status()} ${await legacy.text()}`).toBe(true) + return String((await legacy.json())?.data?.id ?? '') +} + +/** + * Delete a collective and empty it from the trash, with its team. + * + * @param id The collective's id. + * @return Nothing. + */ +async function deleteCollective(id: string): Promise { + const ocs = await api.delete(`${COLLECTIVES_OCS}/${id}?format=json`) + if (ocs.ok()) { + await api.delete(`${COLLECTIVES_OCS}/trash/${id}?circle=1&format=json`).catch(() => undefined) + return + } + await api.delete(`${COLLECTIVES_API}/${id}`).catch(() => undefined) + await api.delete(`${COLLECTIVES_API}/trash/${id}?circle=1`).catch(() => undefined) +} + +/** + * The Collectives pages linked to the seeded application. + * + * @return The linked pages. + */ +async function linkedPages(): Promise { + const res = await api.get(`${OBJECTS}/${config.register}/module/${appId}/integrations/collectives`) + if (!res.ok()) { + return [] + } + const body = await res.json() + const rows: Array> = Array.isArray(body) ? body : (body?.results ?? []) + return rows.map((row) => ({ + id: String(row.id ?? (row.data as { id?: unknown } | undefined)?.id ?? ''), + title: String(row.title ?? ''), + url: String(row.url ?? ''), + })) +} + +/** + * The pages whose title matches a term, across the caller's collectives. + * + * @param term The title term. + * @return The matching pages. + */ +async function searchPages(term: string): Promise { + const res = await api.get(`${PAGE_SEARCH}?search=${encodeURIComponent(term)}`) + if (!res.ok()) { + return [] + } + const rows: Array> = (await res.json())?.results ?? [] + return rows.map((row) => ({ id: String(row.id ?? ''), title: String(row.title ?? ''), url: String(row.url ?? '') })) +} + +/** + * Open the application page and its Collectives sidebar tab. + * + * @param page The page. + * @return Nothing. + */ +async function openCollectivesTab(page: Page): Promise { + await gotoAppRoute(page, `/modules/${appId}`) + await page.getByRole('tab', { name: 'Collectives' }).first().click({ timeout: 30000 }) +} + +/** + * The Knowledge articles card on the application page. + * + * @param page The page. + * @return The card. + */ +function knowledgeCard(page: Page) { + return page.locator('.cn-detail-card, [data-testid="cn-detail-widget-leaf-card"]').filter({ hasText: 'Knowledge articles' }).first() +} + +test.beforeAll(async () => { + api = await newApiContext() + config = await resolveConfig(api) + collectivesEnabled = await appEnabled('collectives') + appId = await createObject(api, config.register, 'module', { name: `${RUN_ID} application` }) + if (!collectivesEnabled) { + return + } + collectiveId = await createCollective(collectiveName) + expect(collectiveId, 'the collective has an id').not.toBe('') + const created = await api.post(`${OBJECTS}/${config.register}/module/${appId}/collectives/new`, { + data: { collectiveId: Number(collectiveId), title: restoreTitle }, + }) + expect(created.status(), await created.text()).toBeLessThan(300) +}) + +test.afterAll(async () => { + if (!api) return + if (appId !== '') { + for (const linked of await linkedPages()) { + await api.delete(`${OBJECTS}/${config.register}/module/${appId}/collectives/${linked.id}`).catch(() => undefined) + } + await deleteObject(api, config.register, 'module', appId) + } + if (collectiveId !== '') { + await deleteCollective(collectiveId) + } + await api.dispose() +}) + +// @e2e application-knowledge-base::an-information-manager-reads-the-articles-of-an-application +test('the application page lists its linked article with its collective, beside Documentation', async ({ page }) => { + test.skip(!collectivesEnabled, 'the Collectives app is not installed on this instance') + await gotoAppRoute(page, `/modules/${appId}`) + + const card = knowledgeCard(page) + await expect(card).toBeVisible({ timeout: 30000 }) + await expect(card.getByRole('link', { name: restoreTitle })).toBeVisible({ timeout: 30000 }) + await expect(card.getByText(collectiveName).first()).toBeVisible() + await expect(page.getByText('Documentation', { exact: true }).first()).toBeVisible() +}) + +// @e2e application-knowledge-base::an-application-owner-writes-a-new-article-for-an-application +test('creating an article from the application page makes the page in Collectives and lists it', async ({ page }) => { + test.skip(!collectivesEnabled, 'the Collectives app is not installed on this instance') + await openCollectivesTab(page) + + await page.getByRole('button', { name: 'Create new page' }).first().click() + const dialog = page.getByTestId('cn-collective-page-create') + await expect(dialog).toBeVisible({ timeout: 30000 }) + await dialog.getByLabel('Collective', { exact: true }).click() + await page.getByRole('option', { name: new RegExp(collectiveName) }).first().click() + await dialog.getByLabel('Page title').fill(onboardingTitle) + await dialog.getByRole('button', { name: 'Create page' }).click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + + await expect.poll(async () => (await searchPages(onboardingTitle)).map((found) => found.title), { timeout: 30000 }).toContain(onboardingTitle) + + await gotoAppRoute(page, `/modules/${appId}`) + await expect(knowledgeCard(page).getByRole('link', { name: onboardingTitle })).toBeVisible({ timeout: 30000 }) +}) + +// @e2e application-knowledge-base::unlinking-keeps-the-article +test('unlinking an article removes it from the panel and the page still opens in Collectives', async ({ page }) => { + test.skip(!collectivesEnabled, 'the Collectives app is not installed on this instance') + const linked = (await linkedPages()).find((found) => found.title === restoreTitle) + expect(linked, 'the seeded article is linked').toBeTruthy() + + await openCollectivesTab(page) + const row = page.locator('.cn-collectives-tab__row').filter({ hasText: restoreTitle }).first() + await expect(row).toBeVisible({ timeout: 30000 }) + await row.getByRole('button', { name: 'Actions' }).first().click() + await page.locator('.v-popper__popper--shown').last().getByRole('menuitem', { name: 'Unlink page' }).click() + await expect(page.locator('.cn-collectives-tab__row').filter({ hasText: restoreTitle })).toHaveCount(0, { timeout: 30000 }) + + await gotoAppRoute(page, `/modules/${appId}`) + await expect(knowledgeCard(page)).toBeVisible({ timeout: 30000 }) + await expect(knowledgeCard(page).getByRole('link', { name: restoreTitle })).toHaveCount(0) + + await page.goto(String(linked?.url), { waitUntil: 'domcontentloaded' }) + await expect(page).toHaveURL(/\/apps\/collectives\//) + await expect(page.getByText(restoreTitle).first()).toBeVisible({ timeout: 30000 }) +}) + +// @e2e application-knowledge-base::an-information-manager-finds-an-article-by-title +test('typing on the Knowledge base page lists the article and the result opens it in Collectives', async ({ page }) => { + test.skip(!collectivesEnabled, 'the Collectives app is not installed on this instance') + await gotoAppRoute(page, '/knowledge') + await expect(page.getByText('The search matches the titles of the articles', { exact: false }).first()).toBeVisible({ timeout: 30000 }) + + // The run's token keeps the match to this run's page in a shared dataset. + await page.getByLabel('Search the knowledge base').first().fill(`${RUN_ID} restore`) + const result = page.locator('.cn-kb-search-widget__results').getByRole('link', { name: restoreTitle }) + await expect(result).toBeVisible({ timeout: 30000 }) + await expect(result).toHaveAttribute('href', /\/apps\/collectives\//) + await expect(result).toHaveAttribute('target', '_blank') + + const opened = page.waitForEvent('popup') + await result.click() + const tab = await opened + await tab.waitForLoadState('domcontentloaded') + await expect(tab).toHaveURL(/\/apps\/collectives\//) + await expect(tab.getByText(restoreTitle).first()).toBeVisible({ timeout: 30000 }) + await tab.close() +}) + +// @e2e application-knowledge-base::the-entry-sits-under-applications +test('Knowledge base is a child of Applications in the menu, not a top-level entry', async ({ page }) => { + test.skip(!collectivesEnabled, 'the Collectives app is not installed on this instance') + await gotoAppRoute(page, '/') + const nav = appNav(page) + await nav.waitFor({ state: 'visible', timeout: 30000 }) + + const applications = nav.locator('li').filter({ has: page.getByRole('link', { name: 'Applications', exact: true }) }).first() + await expect(applications.getByRole('link', { name: 'Knowledge base', exact: true })).toHaveCount(1) + // Nested one list deeper than the top-level entries. + await expect(nav.locator('li li').filter({ has: page.getByRole('link', { name: 'Knowledge base', exact: true }) })).not.toHaveCount(0) + + const knowledge = nav.getByRole('link', { name: 'Knowledge base', exact: true }) + if (!(await knowledge.isVisible().catch(() => false))) { + await applications.getByRole('button', { name: 'Open menu' }).first().click() + } + await knowledge.click() + await expect(page).toHaveURL(/\/knowledge$/) +}) + +// @e2e application-knowledge-base::a-nextcloud-admin-without-collectives-sees-a-set-up-state +test('without Collectives the panel shows a set-up state naming it and the menu has no Knowledge base', async ({ page }) => { + test.skip(collectivesEnabled, 'the Collectives app is installed on this instance; this scenario needs an instance without it') + await gotoAppRoute(page, `/modules/${appId}`) + await expect(page.getByText('Collectives is not installed').first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByText('Documentation', { exact: true }).first()).toBeVisible() + + await expect(appNav(page).getByRole('link', { name: 'Knowledge base', exact: true })).toHaveCount(0) +}) diff --git a/tests/e2e/spec-coverage/claimed-usage.spec.ts b/tests/e2e/spec-coverage/claimed-usage.spec.ts new file mode 100644 index 000000000..002fe6790 --- /dev/null +++ b/tests/e2e/spec-coverage/claimed-usage.spec.ts @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * A supplier answers the usages claimed of its products + * (supplier-accepts-claimed-usage, tasks 2 and 3; REQ-010). + * + * Surfaces under test: + * src/components/organisations/ClaimedUsageList.vue "Claimed usage of our + * offering" on OrganisatieDetail, shown when the page's organisation is + * the user's active one, with Accept and Decline per claim and the + * DeclineClaimDialog confirmation; + * src/components/portfolio/ClaimAnswerNotice.vue the declined notice on + * the claiming organisation's usage page; + * `PUT /api/aanbod/claimed/{uuid}/accept`, refused for any active + * organisation that is not the usage's provider. + * + * Seeds, through the objects API, a supplier and two municipalities (each + * register organisation syncs to an OpenRegister organisation with the same + * uuid), two applications of the supplier with one version each, and three + * usages the municipalities register of them with the supplier as provider, + * all carrying this run's RUN_ID. The logged-in administrator joins the three + * organisations; the usages are created while a municipality is active, so + * that municipality owns them, and the supplier is made active to answer. + * Afterwards the seeded rows are deleted and the administrator's previous + * active organisation is restored. + * + * The change's scenarios carry no `@e2e` line; this file covers the three + * REQ-010 scenarios that tasks.md points at it. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/supplier-accepts-claimed-usage/specs/aanbod-listings/spec.md#requirement-a-supplier-answers-the-usages-claimed-of-its-products-req-010 + */ +import type { APIRequestContext } from '@playwright/test' +import type { VoorzieningenConfig } from '../workflows/_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from '../workflows/_fixtures.ts' +import { gotoAppRoute } from './_helpers.ts' + +const OR_API = '/index.php/apps/openregister/api' +const CLAIMED = '/index.php/apps/stackiq/api/aanbod/claimed' +const supplierName = `${RUN_ID} supplier` +const northName = `${RUN_ID} municipality north` +const eastName = `${RUN_ID} municipality east` + +let api: APIRequestContext +let config: VoorzieningenConfig +let previousActive = '' +const seeded: Array<[string, string]> = [] +const ids: Record = {} + +// The tests share the seeded claims and the active organisation: in order, in one worker. +test.describe.configure({ mode: 'serial' }) + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(api, config.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Wait until a register organisation has synced to an OpenRegister organisation. + * + * @param uuid The organisation's uuid. + * @return Nothing; throws when it never appears. + */ +async function awaitOrganisation(uuid: string): Promise { + for (let attempt = 0; attempt < 20; attempt++) { + const res = await api.get(`${OR_API}/organisations/${uuid}`) + if (res.ok()) return + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + throw new Error(`organisation ${uuid} did not sync to OpenRegister`) +} + +/** + * Make the administrator a member of an organisation; already being one is fine. + * + * @param uuid The organisation's uuid. + * @return Nothing. + */ +async function join(uuid: string): Promise { + const res = await api.post(`${OR_API}/organisations/${uuid}/join`, { data: {} }) + expect(res.ok() || res.status() === 409, `join ${uuid} returned ${res.status()}`).toBe(true) +} + +/** + * Make an organisation the administrator's active one. + * + * @param uuid The organisation's uuid. + * @return Nothing; throws when refused. + */ +async function setActive(uuid: string): Promise { + const res = await api.post(`${OR_API}/organisations/${uuid}/set-active`, { data: {} }) + expect(res.ok(), `set-active ${uuid} returned ${res.status()}`).toBe(true) +} + +/** + * Read one usage through the objects API. + * + * @param id The usage's id. + * @return The object. + */ +async function readUsage(id: string): Promise> { + const res = await api.get(`${OR_API}/objects/${config.register}/usage/${id}`) + expect(res.ok(), await res.text()).toBe(true) + return await res.json() +} + +test.beforeAll(async () => { + api = await newApiContext() + config = await resolveConfig(api) + + const me = await api.get('/index.php/apps/stackiq/api/me') + if (me.ok()) { + previousActive = (await me.json())?.organisations?.active?.uuid ?? '' + } + + ids.supplier = await seed('organization', { name: supplierName, type: 'Supplier', status: 'Active', contactsUid: `${RUN_ID}-supplier` }) + ids.north = await seed('organization', { name: northName, type: 'Municipality', status: 'Active', contactsUid: `${RUN_ID}-north` }) + ids.east = await seed('organization', { name: eastName, type: 'Municipality', status: 'Active', contactsUid: `${RUN_ID}-east` }) + for (const uuid of [ids.supplier, ids.north, ids.east]) { + await awaitOrganisation(uuid) + await join(uuid) + } + + await setActive(ids.supplier) + ids.suite = await seed('module', { name: `${RUN_ID} case suite`, provider: ids.supplier }) + ids.suiteVersion = await seed('moduleVersion', { module: ids.suite, version: '10.4', status: 'in use' }) + ids.finance = await seed('module', { name: `${RUN_ID} finance suite`, provider: ids.supplier }) + ids.financeVersion = await seed('moduleVersion', { module: ids.finance, version: '2026.1', status: 'in use' }) + + // Created while the municipality is active, so it owns the usage. + await setActive(ids.north) + ids.accepted = await seed('usage', { consumer: ids.north, provider: ids.supplier, module: ids.suite, moduleVersion: ids.suiteVersion, status: 'In production' }) + ids.refused = await seed('usage', { consumer: ids.north, provider: ids.supplier, module: ids.finance, moduleVersion: ids.financeVersion, status: 'In production' }) + await setActive(ids.east) + ids.declined = await seed('usage', { consumer: ids.east, provider: ids.supplier, module: ids.finance, moduleVersion: ids.financeVersion, status: 'In production' }) +}) + +test.afterAll(async () => { + if (!api) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(api, config.register, schema, id) + } + if (previousActive !== '') { + await api.post(`${OR_API}/organisations/${previousActive}/set-active`, { data: {} }) + } + await api.dispose() +}) + +// @e2e aanbod-listings::a-supplier-accepts-a-claim +test('a member of the supplier accepts a claim on its organisation page and the claim leaves the list', async ({ page }) => { + await setActive(ids.supplier) + await gotoAppRoute(page, `/organisaties/${ids.supplier}`) + + const list = page.getByTestId('claimed-usage-list') + await expect(list).toBeVisible({ timeout: 30000 }) + await expect(list).toContainText('Claimed usage of our offering') + const claim = list.getByTestId(`claim-${ids.accepted}`) + await expect(claim).toBeVisible({ timeout: 30000 }) + await expect(claim).toContainText(northName) + await expect(claim).toContainText(`${RUN_ID} case suite`) + await expect(claim).toContainText('10.4') + await expect(claim).toContainText(/\d{4}-\d{2}-\d{2}/) + + await list.getByTestId(`claim-accept-${ids.accepted}`).click() + await expect(list.getByTestId(`claim-${ids.accepted}`)).toHaveCount(0, { timeout: 30000 }) + + const usage = await readUsage(ids.accepted) + expect(usage.providerResponse).toBe('accepted') + expect(String(usage.providerResponseAt ?? '')).not.toBe('') + expect(String(usage.providerResponseBy ?? '')).not.toBe('') +}) + +// @e2e aanbod-listings::a-supplier-declines-a-claim +test('a declined claim stays the municipality\'s usage and its page says the supplier does not recognise it', async ({ page }) => { + await setActive(ids.supplier) + await gotoAppRoute(page, `/organisaties/${ids.supplier}`) + + const list = page.getByTestId('claimed-usage-list') + await expect(list.getByTestId(`claim-${ids.declined}`)).toBeVisible({ timeout: 30000 }) + await list.getByTestId(`claim-decline-${ids.declined}`).click() + const dialog = page.getByTestId('decline-claim-dialog') + await expect(dialog).toBeVisible({ timeout: 15000 }) + await expect(dialog).toContainText(eastName) + await page.getByTestId('decline-claim-confirm').click() + await expect(list.getByTestId(`claim-${ids.declined}`)).toHaveCount(0, { timeout: 30000 }) + + const usage = await readUsage(ids.declined) + expect(usage.providerResponse).toBe('declined') + expect((usage['@self'] as { organisation?: string } | undefined)?.organisation).toBe(ids.east) + + await setActive(ids.east) + await gotoAppRoute(page, `/gebruik/${ids.declined}`) + const notice = page.getByTestId('claim-declined-notice') + await expect(notice).toBeVisible({ timeout: 30000 }) + await expect(notice).toContainText('The supplier does not recognise this usage') + await expect(notice).toContainText(/\d{4}-\d{2}-\d{2}/) +}) + +// @e2e aanbod-listings::another-organisation-cannot-answer +test('accepting a claim with a municipality active is refused with 403 and nothing is written', async ({ page }) => { + await setActive(ids.north) + const res = await api.put(`${CLAIMED}/${ids.refused}/accept`) + expect(res.status(), await res.text()).toBe(403) + expect((await readUsage(ids.refused)).providerResponse ?? null).toBeNull() + + // Nor does the municipality's own page offer the supplier's list. + await gotoAppRoute(page, `/organisaties/${ids.supplier}`) + await expect(page.getByText(supplierName).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByTestId('claimed-usage-list')).toHaveCount(0) +}) diff --git a/tests/e2e/spec-coverage/publish-from-list.spec.ts b/tests/e2e/spec-coverage/publish-from-list.spec.ts new file mode 100644 index 000000000..586932172 --- /dev/null +++ b/tests/e2e/spec-coverage/publish-from-list.spec.ts @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Publish and lock from the list (publish-and-lock-from-the-list, task 1; + * REQ-ODP-010). + * + * Surface under test: the selection strip of `FacetedCatalogIndexView` on + * /modules (`selection-publish`, `selection-withdraw`, `selection-lock` next + * to the built-in Delete), which opens MassPublishObjects (one call per entry + * to `PUT /api/publication/{objectType}/{uuid}/publish`) and MassLockObjects + * (OpenRegister's lock, for the duration typed in seconds). The Published + * badge is `data-testid="publication-badge"` on the application's page. + * + * Seeds one supplier and six unpublished applications carrying this run's + * RUN_ID through the objects API (three to publish, three to lock), and + * removes exactly those rows afterwards, unlocking the locked ones first. + * The logged-in user is the instance admin, whom the publication endpoint's + * guard lets publish any entry, as it lets an aanbod-beheerder publish its own. + * + * The change's scenarios carry no `@e2e` line; this file covers the three + * REQ-ODP-010 scenarios that tasks.md points at it. REQ-ODP-011 is covered by + * tests/vitest/publicationAction.spec.js. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/publish-and-lock-from-the-list/specs/open-data-publishing/spec.md#requirement-selected-entries-are-published-withdrawn-or-locked-together-from-the-list-req-odp-010 + */ +import type { APIRequestContext, Page } from '@playwright/test' +import type { VoorzieningenConfig } from '../workflows/_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from '../workflows/_fixtures.ts' +import { gotoAppRoute } from './_helpers.ts' + +const OBJECTS = '/index.php/apps/openregister/api/objects' +const toPublish = [1, 2, 3].map((n) => `${RUN_ID} publish ${n}`) +const toLock = [1, 2, 3].map((n) => `${RUN_ID} lock ${n}`) + +let api: APIRequestContext +let config: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(api, config.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Read one application through the objects API. + * + * @param id The application's id. + * @return The object. + */ +async function readModule(id: string): Promise> { + const res = await api.get(`${OBJECTS}/${config.register}/module/${id}`) + expect(res.ok(), await res.text()).toBe(true) + return await res.json() +} + +/** + * Open Applications on this run's rows and tick the named ones. + * + * @param page The page. + * @param names The rows to select. + * @return Nothing. + */ +async function selectRows(page: Page, names: string[]): Promise { + await gotoAppRoute(page, `/modules?_search=${encodeURIComponent(RUN_ID)}`) + for (const name of names) { + const row = page.getByRole('row').filter({ hasText: name }) + await expect(row).toBeVisible({ timeout: 30000 }) + await row.getByRole('checkbox').first().check({ force: true }) + } +} + +test.beforeAll(async () => { + api = await newApiContext() + config = await resolveConfig(api) + ids.supplier = await seed('organization', { name: `${RUN_ID} supplier`, type: 'Supplier', status: 'Active', contactsUid: `${RUN_ID}-supplier` }) + for (const name of [...toPublish, ...toLock]) { + ids[name] = await seed('module', { name, provider: ids.supplier }) + } +}) + +test.afterAll(async () => { + if (!api) return + for (const name of toLock) { + await api.post(`${OBJECTS}/${config.register}/module/${ids[name]}/unlock`).catch(() => undefined) + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(api, config.register, schema, id) + } + await api.dispose() +}) + +// @e2e open-data-publishing::a-supplier-publishes-three-entries +test('publishing three selected applications from the strip gives each a publication date and the Published badge', async ({ page }) => { + await selectRows(page, toPublish) + await page.getByTestId('selection-publish').click() + + const dialog = page.getByRole('dialog').filter({ hasText: 'Publish 3 publications' }) + await expect(dialog).toBeVisible({ timeout: 15000 }) + for (const name of toPublish) { + await expect(dialog).toContainText(name) + } + await dialog.getByRole('button', { name: 'Publish', exact: true }).click() + await expect(dialog.getByText('Objects successfully published')).toBeVisible({ timeout: 30000 }) + await expect(dialog.getByTestId('mass-action-refused')).toHaveCount(0) + await dialog.getByRole('button', { name: 'Close' }).click() + await expect(dialog).toBeHidden({ timeout: 15000 }) + + const before = Date.now() + for (const name of toPublish) { + const published = String((await readModule(ids[name])).publicationDate ?? '') + expect(published, `${name} has a publication date`).not.toBe('') + // "Now": within the last ten minutes, allowing for clock skew. + expect(Math.abs(before - Date.parse(published))).toBeLessThan(10 * 60 * 1000) + + await gotoAppRoute(page, `/modules/${ids[name]}`) + await expect(page.getByTestId('publication-badge')).toHaveText('Published', { timeout: 30000 }) + } +}) + +// @e2e open-data-publishing::one-entry-belongs-to-someone-else +test.fixme('two own applications are published and the third, of another supplier, is listed as refused', async () => { + // Needs a non-admin aanbod-beheerder whose Nextcloud user value + // core/organisation is the owning supplier: PublicationController reads + // that value for its ownership guard, and no API this suite can call sets + // it. The refusal list itself is `data-testid="mass-action-refused"` in + // MassObjectDialog; tests/vitest/publicationActions.spec.js covers the + // split into succeeded and refused. +}) + +// @e2e open-data-publishing::locking-for-editing +test('locking three selected applications for an hour locks each of them', async ({ page }) => { + await selectRows(page, toLock) + await page.getByTestId('selection-lock').click() + + const dialog = page.getByRole('dialog').filter({ hasText: 'Lock 3 publications' }) + await expect(dialog).toBeVisible({ timeout: 15000 }) + await dialog.getByLabel('Duration in seconds (optional)').fill('3600') + await dialog.getByRole('button', { name: 'Lock', exact: true }).click() + await expect(dialog.getByText('Publications successfully locked')).toBeVisible({ timeout: 30000 }) + await dialog.getByRole('button', { name: 'Close' }).click() + await expect(dialog).toBeHidden({ timeout: 15000 }) + + // Another reader sees the lock on the object, with an expiry an hour out. + for (const name of toLock) { + const self = ((await readModule(ids[name]))['@self'] ?? {}) as { locked?: unknown } + expect(self.locked, `${name} is locked`).toBeTruthy() + const lock = self.locked as { expiration?: string, duration?: number } | true + if (typeof lock === 'object' && lock !== null) { + if (lock.duration !== undefined) { + expect(Number(lock.duration)).toBe(3600) + } + if (lock.expiration) { + expect(Date.parse(lock.expiration)).toBeGreaterThan(Date.now()) + } + } + } +}) diff --git a/tests/e2e/spec-coverage/record-reconciliation.spec.ts b/tests/e2e/spec-coverage/record-reconciliation.spec.ts new file mode 100644 index 000000000..bb117ebe9 --- /dev/null +++ b/tests/e2e/spec-coverage/record-reconciliation.spec.ts @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Record reconciliation (operations-record-reconciliation, tasks 4 and 5). + * + * Surfaces under test: + * src/views/FacetedCatalogIndexView.vue the Find duplicates button + * (`data-testid="find-duplicates"`) on /modules, shown when + * `GET /api/me` answers `mayFindDuplicates`, linking to OpenRegister's + * /duplicates page; + * src/components/merge/MergedRecordBanner.vue the `md-merged` widget on + * ModuleDetail, "Merged into " linking to the survivor. + * + * Seeds, through the objects API, one supplier and three applications + * carrying this run's RUN_ID: an original, a likely duplicate of it (same + * supplier and website, the name in another case), and a merged copy whose + * `recordStatus` is Merged and whose `mergedInto` is the original, the state + * CatalogueMergeRelinker leaves after OpenRegister's merge. Removes exactly + * those rows, and the regular user the access test makes, afterwards. + * + * The two scenarios that run on OpenRegister's Duplicate candidates page and + * its merge wizard are test.fixme: that page belongs to OpenRegister, so its + * register and schema pickers, pair rows and wizard buttons cannot be read + * from this repository. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/operations-record-reconciliation/specs/record-reconciliation/spec.md#requirement-req-rrc-001-applications-services-and-organisations-shall-declare-duplicate-rules-and-applications-and-services-shall-declare-how-they-merge + * @spec openspec/changes/operations-record-reconciliation/specs/record-reconciliation/spec.md#requirement-req-rrc-002-the-catalogue-pages-shall-lead-an-administrator-to-openregisters-duplicate-candidates + * @spec openspec/changes/operations-record-reconciliation/specs/record-reconciliation/spec.md#requirement-req-rrc-003-after-openregister-merges-two-applications-or-services-every-catalogue-reference-shall-point-at-the-survivor + * @spec openspec/changes/operations-record-reconciliation/specs/record-reconciliation/spec.md#requirement-req-rrc-004-merged-applications-and-services-shall-leave-the-lists-and-point-readers-to-the-survivor + */ +import type { APIRequestContext } from '@playwright/test' +import type { VoorzieningenConfig } from '../workflows/_fixtures.ts' + +import { expect, request as playwrightRequest, test } from '@playwright/test' +import { + BASE_URL, + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from '../workflows/_fixtures.ts' +import { APP_MAIN, dismissFirstRunWizard, gotoAppRoute, navClickTo } from './_helpers.ts' + +const original = `${RUN_ID} Example application` +const duplicate = `${RUN_ID} example Application` +const merged = `${RUN_ID} Example application copy` +const website = `https://www.example.org/${RUN_ID}` + +let api: APIRequestContext +let config: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(api, config.register, schema, data) + seeded.push([schema, id]) + return id +} + +test.beforeAll(async () => { + api = await newApiContext() + config = await resolveConfig(api) + ids.supplier = await seed('organization', { name: `${RUN_ID} supplier`, type: 'Supplier', status: 'Active', contactsUid: `${RUN_ID}-supplier` }) + ids.original = await seed('module', { name: original, provider: ids.supplier, website, recordStatus: 'Active' }) + ids.duplicate = await seed('module', { name: duplicate, provider: ids.supplier, website, recordStatus: 'Active' }) + ids.merged = await seed('module', { name: merged, provider: ids.supplier, website, recordStatus: 'Merged', mergedInto: ids.original }) +}) + +test.afterAll(async () => { + if (!api) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(api, config.register, schema, id) + } + await api.dispose() +}) + +// @e2e record-reconciliation::a-duplicate-application-appears-as-a-candidate +test.fixme('the two look-alike applications are listed as a pair on the Duplicate candidates page', async () => { + // Needs OpenRegister's /duplicates page: its register and schema pickers + // and its pair rows live in OpenRegister, not in this repository. The pair + // to look for is seeded above: `original` and `duplicate`, same supplier and + // website. +}) + +// @e2e record-reconciliation::a-functional-administrator-goes-to-the-candidates +test('Find duplicates on Applications opens OpenRegister\'s Duplicate candidates page', async ({ page }) => { + await navClickTo(page, 'Applications') + const find = page.getByTestId('find-duplicates') + await expect(find).toBeVisible({ timeout: 30000 }) + await expect(find).toHaveAttribute('href', /\/apps\/openregister\/duplicates$/) + await find.click() + await expect(page).toHaveURL(/\/apps\/openregister\/duplicates/, { timeout: 30000 }) +}) + +// @e2e record-reconciliation::a-regular-user-does-not-see-the-action +test('a user who is neither an admin nor a functional administrator gets no Find duplicates', async ({ browser }) => { + const userId = `recon-${RUN_ID}`.slice(0, 60) + const password = `Recon-${RUN_ID}-Pw!9` + const made = await api.post('/ocs/v2.php/cloud/users?format=json', { form: { userid: userId, password } }) + expect(made.ok(), await made.text()).toBe(true) + + const userApi = await playwrightRequest.newContext({ + baseURL: BASE_URL, + storageState: { cookies: [], origins: [] }, + httpCredentials: { username: userId, password, send: 'always' }, + extraHTTPHeaders: { 'OCS-APIREQUEST': 'true' }, + }) + const context = await browser.newContext({ baseURL: BASE_URL, storageState: { cookies: [], origins: [] } }) + try { + const me = await userApi.get('/index.php/apps/stackiq/api/me') + expect(me.status()).toBe(200) + expect((await me.json())?.mayFindDuplicates).not.toBe(true) + + const page = await context.newPage() + await page.goto('/index.php/login') + await page.locator('#user').fill(userId) + await page.locator('#password').fill(password) + await page.locator('[type="submit"]').first().click() + await page.waitForURL((url) => !url.pathname.includes('/login')) + await gotoAppRoute(page, '/modules') + if (await dismissFirstRunWizard(page)) { + await gotoAppRoute(page, '/modules') + } + // The toolbar has rendered: its Export menu sits next to where Find duplicates would be. + await expect(page.getByRole('button', { name: 'Export' }).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByTestId('find-duplicates')).toHaveCount(0) + await expect(page.getByText('Find duplicates', { exact: true })).toHaveCount(0) + } finally { + await context.close() + await userApi.dispose() + await api.delete(`/ocs/v2.php/cloud/users/${userId}?format=json`) + } +}) + +// @e2e record-reconciliation::usages-and-connections-follow-the-survivor +test.fixme('after a merge on OpenRegister\'s page the usage and the connection point at the original', async () => { + // Needs OpenRegister's merge wizard on the /duplicates page to merge the + // duplicate into the original; its markup is not in this repository, and + // OpenRegister's merge endpoint is not called anywhere in stackiq to copy + // from. The relinking is covered by + // tests/Unit/EventListener/CatalogueMergeRelinkerTest.php. +}) + +// @e2e record-reconciliation::a-reader-opens-an-old-link-to-a-merged-application +test('an old link to a merged application shows Merged into with a link to the original, and the list leaves it out', async ({ page }) => { + await gotoAppRoute(page, `/modules/${ids.merged}`) + const banner = page.getByTestId('merged-record-banner') + await expect(banner).toBeVisible({ timeout: 30000 }) + await expect(banner).toContainText('This entry was merged into another one.') + const link = banner.getByRole('link', { name: `Merged into ${original}` }) + await expect(link).toBeVisible({ timeout: 30000 }) + await link.click() + await expect(page).toHaveURL(new RegExp(`/modules/${ids.original}`)) + await expect(page.getByTestId('merged-record-banner')).toHaveCount(0) + + await gotoAppRoute(page, `/modules?_search=${encodeURIComponent(RUN_ID)}`) + const main = page.locator(APP_MAIN).first() + await expect(main.getByText(duplicate).first()).toBeVisible({ timeout: 30000 }) + await expect(main.getByText(merged)).toHaveCount(0) +}) diff --git a/tests/e2e/spec-coverage/supplier-facet.spec.ts b/tests/e2e/spec-coverage/supplier-facet.spec.ts new file mode 100644 index 000000000..6b096ad3f --- /dev/null +++ b/tests/e2e/spec-coverage/supplier-facet.spec.ts @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * The Supplier facet on the Applications and Services pages + * (the supplier facet change, task 3; REQ-SFC-002). + * + * Surface under test: `FacetedCatalogIndexView` on /modules and /diensten, + * whose CnFacetSidebar ("GEMMA filters") gains a Supplier group fed by the + * `supplier` bucket of `GET /api/facets/{schema}`; a choice is kept in the URL + * under `_gf_supplier` and in a saved facet view. + * + * Seeds, through the objects API, two supplier organisations, three + * applications (two of supplier A, one of supplier B) and two services (one + * per supplier), all carrying this run's RUN_ID, and removes exactly those + * rows and the saved view the test makes afterwards. + * + * Every visit opens the page with the run's token as the search + * (`?_search=`): the list then holds only this run's rows, and the facet + * counts are computed fresh rather than served from the TTL-only cache of the + * unparameterised request (see gemma-faceted-search.spec.ts), which may + * predate the seeded suppliers. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/insight-supplier-facet/specs/supplier-facet/spec.md#requirement-req-sfc-002-the-applications-and-services-pages-shall-offer-supplier-as-a-facet-that-narrows-the-list + */ +import type { APIRequestContext, Page } from '@playwright/test' +import type { VoorzieningenConfig } from '../workflows/_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from '../workflows/_fixtures.ts' +import { APP_MAIN, gotoAppRoute } from './_helpers.ts' + +const VIEWS = '/index.php/apps/openregister/api/views' +const supplierA = `${RUN_ID} supplier A` +const supplierB = `${RUN_ID} supplier B` +const appA1 = `${RUN_ID} application A one` +const appA2 = `${RUN_ID} application A two` +const appB = `${RUN_ID} application B` +const serviceA = `${RUN_ID} service A` +const serviceB = `${RUN_ID} service B` +const viewName = `${RUN_ID} supplier A services` + +let api: APIRequestContext +let config: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(api, config.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Escape a literal for use in a regular expression. + * + * @param text The literal. + * @return The escaped text. + */ +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** + * Open a faceted list with the run's token as the search. + * + * @param page The page. + * @param route The list route. + * @return Nothing. + */ +async function openList(page: Page, route: string): Promise { + await gotoAppRoute(page, `${route}?_search=${encodeURIComponent(RUN_ID)}`) + await expect(page.locator('.cn-facet-sidebar').first()).toBeVisible({ timeout: 30000 }) +} + +/** + * Choose a supplier in the Supplier facet. + * + * @param page The page. + * @param supplier The supplier's name. + * @return Nothing. + */ +async function chooseSupplier(page: Page, supplier: string): Promise { + const group = page.locator('.cn-facet-sidebar__group').filter({ hasText: 'Supplier' }).first() + await expect(group).toBeVisible({ timeout: 30000 }) + await group.getByLabel('Supplier', { exact: true }).click() + await page.getByRole('option', { name: new RegExp(escapeRegExp(supplier)) }).first().click() + await page.keyboard.press('Escape') +} + +test.beforeAll(async () => { + api = await newApiContext() + config = await resolveConfig(api) + ids.supplierA = await seed('organization', { name: supplierA, type: 'Supplier', status: 'Active', contactsUid: `${RUN_ID}-a` }) + ids.supplierB = await seed('organization', { name: supplierB, type: 'Supplier', status: 'Active', contactsUid: `${RUN_ID}-b` }) + ids.appA1 = await seed('module', { name: appA1, provider: ids.supplierA }) + ids.appA2 = await seed('module', { name: appA2, provider: ids.supplierA }) + ids.appB = await seed('module', { name: appB, provider: ids.supplierB }) + ids.serviceA = await seed('catalogService', { name: serviceA, provider: ids.supplierA, type: ['Application management'], modules: [ids.appA1] }) + ids.serviceB = await seed('catalogService', { name: serviceB, provider: ids.supplierB, type: ['Application management'], modules: [ids.appB] }) +}) + +test.afterAll(async () => { + if (!api) return + const views = await api.get(VIEWS) + if (views.ok()) { + const rows: Array<{ id?: unknown, uuid?: unknown, name?: unknown }> = (await views.json())?.results ?? [] + for (const view of rows.filter((row) => row.name === viewName)) { + await api.delete(`${VIEWS}/${String(view.id ?? view.uuid)}`).catch(() => undefined) + } + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(api, config.register, schema, id) + } + await api.dispose() +}) + +// @e2e supplier-facet::an-information-manager-narrows-applications-to-one-supplier +test('choosing a supplier on Applications leaves only its applications and puts _gf_supplier in the URL', async ({ page }) => { + await openList(page, '/modules') + const main = page.locator(APP_MAIN).first() + await expect(main.getByText(appB).first()).toBeVisible({ timeout: 30000 }) + + // The facet lists each supplier by name with its count, not by id. + const group = page.locator('.cn-facet-sidebar__group').filter({ hasText: 'Supplier' }).first() + await group.getByLabel('Supplier', { exact: true }).click() + await expect(page.getByRole('option', { name: new RegExp(escapeRegExp(supplierA)) }).first()).toContainText('2') + await expect(page.getByRole('option', { name: new RegExp(escapeRegExp(supplierB)) }).first()).toContainText('1') + await expect(page.getByRole('option', { name: new RegExp(ids.supplierA) })).toHaveCount(0) + await page.keyboard.press('Escape') + + await chooseSupplier(page, supplierA) + await expect(page).toHaveURL(/_gf_supplier/, { timeout: 30000 }) + await expect(main.getByText(appA1).first()).toBeVisible({ timeout: 30000 }) + await expect(main.getByText(appA2).first()).toBeVisible() + await expect(main.getByText(appB)).toHaveCount(0) + + // A reload restores the choice from the URL. + await page.reload({ waitUntil: 'domcontentloaded' }) + await expect(page.locator(APP_MAIN).first().getByText(appA1).first()).toBeVisible({ timeout: 30000 }) + await expect(page.locator(APP_MAIN).first().getByText(appB)).toHaveCount(0) +}) + +// @e2e supplier-facet::supplier-combines-with-a-gemma-facet +test.fixme('with a reference component chosen, the Supplier counts cover only its applications', async () => { + // Not seedable: a reference component reaches a module only as a link to an + // AMEF `element` object; the objects API drops bare strings in + // referenceComponents (see gemma-faceted-search.spec.ts), and this suite + // builds no element and relation fixtures. FacetServiceTest covers the + // disjunctive count. +}) + +// @e2e supplier-facet::a-saved-view-keeps-the-supplier +test('a saved Services view applied on a fresh page chooses the supplier again and narrows the list', async ({ page }) => { + await openList(page, '/diensten') + const main = page.locator(APP_MAIN).first() + await expect(main.getByText(serviceB).first()).toBeVisible({ timeout: 30000 }) + await chooseSupplier(page, supplierA) + await expect(page).toHaveURL(/_gf_supplier/, { timeout: 30000 }) + await expect(main.getByText(serviceB)).toHaveCount(0, { timeout: 30000 }) + + await page.getByRole('button', { name: 'Saved views' }).first().click() + await page.locator('.v-popper__popper--shown').last().getByRole('menuitem', { name: 'Save current filters as view' }).click() + const dialog = page.getByRole('dialog').filter({ hasText: 'Save as view' }) + await expect(dialog).toBeVisible({ timeout: 15000 }) + await dialog.getByLabel('View name').fill(viewName) + await dialog.getByRole('button', { name: 'Save view' }).click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + + // Fresh: no selection in the URL. + await gotoAppRoute(page, '/diensten') + await expect(page).not.toHaveURL(/_gf_supplier/) + await page.getByRole('button', { name: 'Saved views' }).first().click() + await page.locator('.v-popper__popper--shown').last().getByRole('menuitem', { name: viewName }).click() + + await expect(page).toHaveURL(/_gf_supplier/, { timeout: 30000 }) + const group = page.locator('.cn-facet-sidebar__group').filter({ hasText: 'Supplier' }).first() + await expect(group).toContainText(supplierA, { timeout: 30000 }) + const list = page.locator(APP_MAIN).first() + await expect(list.getByText(serviceA).first()).toBeVisible({ timeout: 30000 }) + await expect(list.getByText(serviceB)).toHaveCount(0) +}) diff --git a/tests/e2e/workflows/application-components.spec.ts b/tests/e2e/workflows/application-components.spec.ts new file mode 100644 index 000000000..96670d958 --- /dev/null +++ b/tests/e2e/workflows/application-components.spec.ts @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Application components (landscape-application-components): a supplier adds + * a component from the Components section of its application's page and the + * component names the application it is part of, and a buyer reads the + * components of an application while the Applications list shows whole + * applications until "All, including components" is picked. + * + * Seeds a supplier organisation, two applications and two components of the + * second one carrying this run's RUN_ID through the objects API (the call the + * Add form makes). Removes exactly those rows and the component the first test + * adds through the form afterwards. Setup and teardown use the API; every + * assertion is made on the rendered page. + * + * The scenario marked `@e2e exclude` (a cycle is refused) is covered by + * tests/Unit/Service/ModuleComponentGuardTest.php and + * tests/Unit/EventListener/ModuleComponentListenerTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/landscape-application-components/specs/application-components/spec.md#requirement-req-acm-001-an-application-can-name-the-application-it-is-a-component-of + * @spec openspec/changes/landscape-application-components/specs/application-components/spec.md#requirement-req-acm-002-the-application-page-lists-its-components + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + findAll, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const supplier = `${RUN_ID} component supplier` +// Names are chosen so none is a substring of another: a text match on the +// application never also matches one of its components. +const records = `${RUN_ID} records suite` +const addedComponent = `${RUN_ID} citizen portal` +const caseSuite = `${RUN_ID} case suite` +const casePortal = `${RUN_ID} case portal` +const documentStore = `${RUN_ID} document store` + +test.describe.configure({ mode: 'serial' }) + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * The titled card of a list widget on a detail page. + * + * @param page The page. + * @param title The card's title. + * @return The card. + */ +function catalogCard(page: Page, title: string): Locator { + return page + .locator('.cn-detail-page__catalog-card') + .filter({ has: page.getByText(title, { exact: true }) }) + .first() +} + +/** + * Click a list card's Add: the title-row button in the board look, else the + * item in the card's Actions menu. Returns the create dialog. + * + * @param page The page. + * @param card The card. + * @param label The Add label. + * @return The dialog. + */ +async function addFromCard(page: Page, card: Locator, label: string): Promise { + const button = card.getByTestId('cn-detail-widget-catalog-add') + if (await button.count()) { + await button.first().click() + } else { + await card.getByRole('button', { name: 'Actions' }).first().click() + await page.locator('.v-popper__popper--shown').last().getByRole('menuitem', { name: label }).first().click() + } + const dialog = page.locator('[role="dialog"], .modal-container').first() + await dialog.waitFor({ state: 'visible', timeout: 15000 }) + return dialog +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + ids.supplier = await seed('organization', { + name: supplier, + type: 'Supplier', + status: 'Active', + contactsUid: `${RUN_ID}-component-supplier`, + }) + ids.records = await seed('module', { name: records, provider: ids.supplier }) + ids.caseSuite = await seed('module', { name: caseSuite, provider: ids.supplier }) + ids.casePortal = await seed('module', { name: casePortal, provider: ids.supplier, partOf: ids.caseSuite }) + ids.documentStore = await seed('module', { name: documentStore, provider: ids.supplier, partOf: ids.caseSuite }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + // The component the first test added through the form; a component goes + // before the application it is part of. + for (const row of await findAll(apiCtx, cfg.register, 'module', addedComponent)) { + const id = String((row as { id?: string }).id ?? (row as { '@self'?: { id?: string } })['@self']?.id ?? '') + if (id && JSON.stringify(row).includes(RUN_ID)) { + await deleteObject(apiCtx, cfg.register, 'module', id) + } + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e application-components::a-supplier-records-a-component +test('a component added from the application page names that application as Part of', async ({ + page, +}) => { + await gotoAppRoute(page, `/modules/${ids.records}`) + await dismissSupportDialog(page) + const components = catalogCard(page, 'Components') + await expect(components).toBeVisible({ timeout: 30000 }) + + // The create form seeds Part of from the list's filter. + const dialog = await addFromCard(page, components, 'Add component') + await dialog.getByLabel('Name', { exact: true }).first().fill(addedComponent) + await dialog.getByRole('button', { name: /save|create/i }).last().click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + + const row = components.getByRole('row').filter({ hasText: addedComponent }) + await expect(row).toBeVisible({ timeout: 30000 }) + await row.getByText(addedComponent).first().click() + await expect(page).toHaveURL(/\/modules\/[0-9a-f-]{36}/, { timeout: 30000 }) + await expect(page).not.toHaveURL(new RegExp(`/modules/${ids.records}`)) + await dismissSupportDialog(page) + await expect(page.getByText(addedComponent).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByText('Part of', { exact: true }).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByText(records, { exact: true }).first()).toBeVisible({ timeout: 30000 }) +}) + +// @e2e application-components::a-buyer-reads-what-an-application-is-made-of +test('the application page lists both components and the list hides them until All, including components', async ({ + page, +}) => { + await gotoAppRoute(page, `/modules/${ids.caseSuite}`) + await dismissSupportDialog(page) + const components = catalogCard(page, 'Components') + await expect(components).toBeVisible({ timeout: 30000 }) + await expect(components.getByRole('row').filter({ hasText: casePortal })).toBeVisible({ timeout: 30000 }) + await expect(components.getByRole('row').filter({ hasText: documentStore })).toBeVisible({ timeout: 30000 }) + + await gotoAppRoute(page, `/modules?_search=${encodeURIComponent(RUN_ID)}`) + await dismissSupportDialog(page) + // The list opens on Whole applications. + await expect(page.getByRole('row').filter({ hasText: caseSuite })).toBeVisible({ timeout: 30000 }) + await expect(page.getByRole('row').filter({ hasText: casePortal })).toHaveCount(0) + await expect(page.getByRole('row').filter({ hasText: documentStore })).toHaveCount(0) + + await page.getByRole('tab', { name: 'All, including components', exact: true }).click() + await expect(page.getByRole('row').filter({ hasText: casePortal })).toBeVisible({ timeout: 30000 }) + await expect(page.getByRole('row').filter({ hasText: documentStore })).toBeVisible({ timeout: 30000 }) + await expect(page.getByRole('row').filter({ hasText: caseSuite })).toBeVisible() +}) diff --git a/tests/e2e/workflows/application-interfaces.spec.ts b/tests/e2e/workflows/application-interfaces.spec.ts new file mode 100644 index 000000000..219c33095 --- /dev/null +++ b/tests/e2e/workflows/application-interfaces.spec.ts @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * APIs an application offers (connections-api-catalogue): a supplier adds a + * REST API from the APIs section of its application's page and finds it on + * the APIs list, and an architect reads both APIs of an application with + * their style and status. + * + * Seeds a supplier organisation, two applications and two APIs of the second + * application carrying this run's RUN_ID through the objects API (the call the + * Add form makes). Removes exactly those rows and the API the first test adds + * through the form afterwards. Setup and teardown use the API; every assertion + * is made on the rendered page. + * + * The scenario marked `@e2e exclude` (a connection naming its API) is covered + * by tests/Unit/Settings/ApplicationInterfaceFragmentTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/connections-api-catalogue/specs/application-interfaces/spec.md#requirement-req-aif-001-a-user-can-record-an-api-that-an-application-offers + * @spec openspec/changes/connections-api-catalogue/specs/application-interfaces/spec.md#requirement-req-aif-002-the-application-page-lists-its-apis + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + findAll, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const supplier = `${RUN_ID} API supplier` +const appX = `${RUN_ID} case application` +const appY = `${RUN_ID} messaging application` +const addedApi = `${RUN_ID} cases API` +const restApi = `${RUN_ID} records API` +const eventApi = `${RUN_ID} records events` + +test.describe.configure({ mode: 'serial' }) + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * The titled card of a list widget on a detail page. + * + * @param page The page. + * @param title The card's title. + * @return The card. + */ +function catalogCard(page: Page, title: string): Locator { + return page + .locator('.cn-detail-page__catalog-card') + .filter({ has: page.getByText(title, { exact: true }) }) + .first() +} + +/** + * Click a list card's Add: the title-row button in the board look, else the + * item in the card's Actions menu. Returns the create dialog. + * + * @param page The page. + * @param card The card. + * @param label The Add label. + * @return The dialog. + */ +async function addFromCard(page: Page, card: Locator, label: string): Promise { + const button = card.getByTestId('cn-detail-widget-catalog-add') + if (await button.count()) { + await button.first().click() + } else { + await card.getByRole('button', { name: 'Actions' }).first().click() + await page.locator('.v-popper__popper--shown').last().getByRole('menuitem', { name: label }).first().click() + } + const dialog = page.locator('[role="dialog"], .modal-container').first() + await dialog.waitFor({ state: 'visible', timeout: 15000 }) + return dialog +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + ids.supplier = await seed('organization', { + name: supplier, + type: 'Supplier', + status: 'Active', + contactsUid: `${RUN_ID}-api-supplier`, + }) + ids.x = await seed('module', { name: appX, provider: ids.supplier }) + ids.y = await seed('module', { name: appY, provider: ids.supplier }) + ids.rest = await seed('applicationInterface', { + name: restApi, + module: ids.y, + style: 'REST', + version: '2.0', + status: 'in use', + }) + ids.event = await seed('applicationInterface', { + name: eventApi, + module: ids.y, + style: 'event or message', + version: '1.0', + status: 'in development', + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + // The API the first test added through the form. + for (const row of await findAll(apiCtx, cfg.register, 'applicationInterface', addedApi)) { + const id = String((row as { id?: string }).id ?? (row as { '@self'?: { id?: string } })['@self']?.id ?? '') + if (id && JSON.stringify(row).includes(RUN_ID)) { + await deleteObject(apiCtx, cfg.register, 'applicationInterface', id) + } + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e application-interfaces::a-supplier-adds-a-rest-api-to-its-application +test('an API added from the application page is listed there and on the APIs list', async ({ + page, +}) => { + await gotoAppRoute(page, `/modules/${ids.x}`) + await dismissSupportDialog(page) + const apis = catalogCard(page, 'APIs') + await expect(apis).toBeVisible({ timeout: 30000 }) + + const dialog = await addFromCard(page, apis, 'Add API') + await dialog.getByLabel('Name', { exact: true }).first().fill(addedApi) + await dialog.getByLabel('Style', { exact: true }).first().click() + await page.getByRole('option', { name: 'REST', exact: true }).first().click() + await dialog.getByLabel('Version', { exact: true }).first().fill('1.2') + await dialog.getByLabel('Specification', { exact: true }).first().fill('https://example.org/openapi.yaml') + await dialog.getByRole('button', { name: /save|create/i }).last().click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + + const row = apis.getByRole('row').filter({ hasText: addedApi }) + await expect(row).toBeVisible({ timeout: 30000 }) + await expect(row).toContainText('REST') + await expect(row).toContainText('1.2') + + await gotoAppRoute(page, '/apis') + await dismissSupportDialog(page) + const search = page.getByRole('main').getByRole('textbox', { name: /search/i }).first() + if (await search.count()) { + await search.fill(addedApi) + } + const listed = page.getByRole('row').filter({ hasText: addedApi }) + await expect(listed).toBeVisible({ timeout: 30000 }) + await expect(listed).toContainText('REST') + await expect(listed).toContainText(appX) +}) + +// @e2e application-interfaces::an-architect-checks-what-an-application-offers +test('the application page lists its REST and event APIs with style and status', async ({ + page, +}) => { + await gotoAppRoute(page, `/modules/${ids.y}`) + await dismissSupportDialog(page) + const apis = catalogCard(page, 'APIs') + await expect(apis).toBeVisible({ timeout: 30000 }) + + const rest = apis.getByRole('row').filter({ hasText: restApi }) + await expect(rest).toBeVisible({ timeout: 30000 }) + await expect(rest).toContainText('REST') + await expect(rest).toContainText('in use') + + const event = apis.getByRole('row').filter({ hasText: eventApi }) + await expect(event).toBeVisible({ timeout: 30000 }) + await expect(event).toContainText('event or message') + await expect(event).toContainText('in development') + + // Each row opens the API's own page. + await rest.getByText(restApi).first().click() + await expect(page).toHaveURL(new RegExp(`/apis/${ids.rest}`), { timeout: 30000 }) + await expect(page.getByText(restApi).first()).toBeVisible({ timeout: 30000 }) +}) diff --git a/tests/e2e/workflows/architecture-assistant-views.spec.ts b/tests/e2e/workflows/architecture-assistant-views.spec.ts new file mode 100644 index 000000000..05e73509d --- /dev/null +++ b/tests/e2e/workflows/architecture-assistant-views.spec.ts @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Assistant-drafted views: a draft written through the `stackiq.draftView` + * MCP tool hands back its editor link and is listed as a draft on the Views + * page, the editor names who the draft was made for (also after a person + * moves a node and saves), and a fresh draft without positions is laid out + * when it first opens and is found under the origin assistant in the Views + * sidebar. + * + * Seeds three AMEF elements carrying this run's RUN_ID in the register the app + * maps (`/api/amef/config`) through the objects API, and drafts views through + * OpenRegister's MCP endpoint as the suite's admin (the call Hermiq makes in a + * logged-in user's session). Removes exactly the seeded elements, the drafted + * views and the relations those drafts created afterwards. + * + * The scenarios marked `@e2e exclude` in the change's spec are covered by + * tests/Unit/Service/ArchitectureViewDraftServiceTest.php, + * tests/Unit/Mcp/StackiqToolProviderDraftToolsTest.php, + * tests/Unit/Service/ViewServiceDrawnViewTest.php and + * tests/Unit/Service/ArchiMateExportServiceDrawnFilterTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/architecture-assistant-drafted-views/specs/architecture-assistant-views/spec.md#requirement-req-aav-002-stackiq-shall-offer-a-create-tool-that-writes-a-draft-view-from-elements-and-relations + * @spec openspec/changes/architecture-assistant-drafted-views/specs/architecture-assistant-views/spec.md#requirement-req-aav-003-every-object-the-draft-tool-writes-shall-carry-the-assistant-mark-in-the-same-write + * @spec openspec/changes/architecture-assistant-drafted-views/specs/architecture-assistant-views/spec.md#requirement-req-aav-004-a-drafted-view-shall-be-laid-out-when-it-is-first-opened + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + findAll, + NC_ADMIN_USER, + newApiContext, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +interface DraftResult { + uuid: string + url: string + created: { elements: number, relations: number } +} + +const OR = '/index.php/apps/openregister/api/objects' +const MCP = '/index.php/apps/openregister/api/mcp' + +let apiCtx: APIRequestContext +let register = '' +const seeded: Array<[string, string]> = [] +const drafted: string[] = [] +const ids: Record = {} +const caseSystem = `${RUN_ID} case system` +const documentStore = `${RUN_ID} document store` +const caseRegister = `${RUN_ID} case register` + +/** + * Create a row in the AMEF register and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Read a JSON-RPC answer, sent as plain JSON or as a server-sent event. + * + * @param raw The response body. + * @return The JSON-RPC message. + */ +function rpcMessage(raw: string): Record { + const trimmed = raw.trim() + if (trimmed.startsWith('{')) { + return JSON.parse(trimmed) + } + const data = trimmed.split('\n').filter((line) => line.startsWith('data:')).pop() ?? '' + return JSON.parse(data.slice('data:'.length).trim()) +} + +/** + * Call one tool on OpenRegister's MCP endpoint as the admin. + * + * @param name The tool name. + * @param args The tool arguments. + * @return The tool's result payload. + */ +async function callTool(name: string, args: Record): Promise> { + const accept = { Accept: 'application/json, text/event-stream' } + const init = await apiCtx.post(MCP, { + headers: accept, + data: { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'e2e', version: '1.0.0' } }, + }, + }) + expect(init.ok(), `MCP initialize: HTTP ${init.status()}`).toBe(true) + const session = init.headers()['mcp-session-id'] + const headers: Record = session ? { ...accept, 'Mcp-Session-Id': session } : accept + const res = await apiCtx.post(MCP, { + headers, + data: { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name, arguments: args } }, + }) + expect(res.ok(), `MCP ${name}: HTTP ${res.status()}`).toBe(true) + const message = rpcMessage(await res.text()) + expect(message.error, `MCP ${name}: ${JSON.stringify(message.error)}`).toBeUndefined() + const result = message.result ?? {} + expect(result.isError, `MCP ${name} returned an error: ${JSON.stringify(result.content)}`).not.toBe(true) + if (result.structuredContent) { + return result.structuredContent + } + const text = (result.content ?? []).find((part: { type?: string }) => part.type === 'text')?.text + return text ? JSON.parse(text) : result +} + +/** + * Draft a view through `stackiq.draftView` and remember it for cleanup. + * + * @param name The view name. + * @param elements The element uuids, each with its key. + * @param relations The Flow relations, as source and target keys. + * @return The draft result. + */ +async function draft(name: string, elements: Array<[string, string]>, relations: Array<[string, string]>): Promise { + const result = (await callTool('stackiq.draftView', { + name, + description: `${RUN_ID} drafted in the e2e run`, + elements: elements.map(([key, uuid]) => ({ key, uuid })), + relations: relations.map(([source, target]) => ({ source, target, type: 'Flow' })), + })) as DraftResult + expect(result.uuid, 'the draft names its view').toBeTruthy() + drafted.push(result.uuid) + return result +} + +/** + * Read one view as the admin. + * + * @param id The view's uuid. + * @return The view. + */ +async function readView(id: string): Promise> { + const res = await apiCtx.get(`${OR}/${register}/view/${id}`) + expect(res.ok(), `view ${id}: HTTP ${res.status()}`).toBe(true) + return res.json() +} + +/** + * Open a view in the editor and wait for it to settle. + * + * @param page The page. + * @param id The view's uuid. + * @return The editor. + */ +async function openEditor(page: Page, id: string): Promise { + await gotoAppRoute(page, `/views/${id}`) + await dismissSupportDialog(page) + const editor = page.getByTestId('architecture-view-editor') + await expect(editor).toBeVisible({ timeout: 30000 }) + return editor +} + +test.describe.configure({ mode: 'serial' }) + +test.beforeAll(async () => { + apiCtx = await newApiContext() + const res = await apiCtx.get('/index.php/apps/stackiq/api/amef/config') + expect(res.ok(), `amef/config returned ${res.status()}`).toBe(true) + const config = (await res.json())?.config ?? {} + register = String(config.register ?? config.register_id ?? '') + expect(register, 'stackiq maps an AMEF register').not.toBe('') + + ids.caseSystem = await seed('element', { + identifier: `id-${RUN_ID}-case-system`, + name: caseSystem, + type: 'ApplicationComponent', + origin: 'drawn', + }) + ids.documentStore = await seed('element', { + identifier: `id-${RUN_ID}-document-store`, + name: documentStore, + type: 'ApplicationComponent', + origin: 'drawn', + }) + ids.caseRegister = await seed('element', { + identifier: `id-${RUN_ID}-case-register`, + name: caseRegister, + type: 'ApplicationComponent', + origin: 'drawn', + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const id of drafted) { + const res = await apiCtx.get(`${OR}/${register}/view/${id}`) + const view = res.ok() ? await res.json() : {} + for (const connection of view.connections ?? []) { + const identifier = String(connection.modelRelationshipId ?? '') + if (!identifier) continue + const found = await apiCtx.get(`${OR}/${register}/relation`, { params: { _limit: 5, identifier } }) + const relation = found.ok() ? ((await found.json()).results ?? [])[0] : null + const relationId = String(relation?.id ?? relation?.['@self']?.id ?? '') + if (relationId && relation?.origin === 'assistant') { + await deleteObject(apiCtx, register, 'relation', relationId) + } + } + await deleteObject(apiCtx, register, 'view', id) + } + for (const row of await findAll(apiCtx, register, 'view', RUN_ID)) { + const id = String(row.id ?? (row as { '@self'?: { id?: string } })['@self']?.id ?? '') + if (id && !drafted.includes(id)) { + await deleteObject(apiCtx, register, 'view', id) + } + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e architecture-assistant-views::an-assistant-drafts-a-view-and-hands-back-a-link +test('a draftView call hands back the editor link and the Views page lists the draft', async ({ page }) => { + const name = `${RUN_ID} assistant link draft` + const result = await draft( + name, + [['a', ids.caseSystem], ['b', ids.documentStore]], + [['a', 'b']], + ) + expect(result.url).toBe(`/apps/stackiq/views/${result.uuid}`) + + await gotoAppRoute(page, `/views?_search=${encodeURIComponent(RUN_ID)}`) + await dismissSupportDialog(page) + const row = page.getByRole('row').filter({ hasText: name }) + await expect(row).toBeVisible({ timeout: 30000 }) + await expect(row).toContainText(/draft/i) +}) + +// @e2e architecture-assistant-views::a-reviewer-sees-who-the-draft-was-made-for +test('the editor names who the draft was made for, also after a node is moved and saved', async ({ page }) => { + const result = await draft( + `${RUN_ID} assistant reviewed draft`, + [['a', ids.caseSystem], ['b', ids.documentStore]], + [['a', 'b']], + ) + const editor = await openEditor(page, result.uuid) + const notice = page.getByTestId('view-editor-draft-notice') + await expect(notice).toContainText('Drafted by an assistant for', { timeout: 30000 }) + await expect(notice).toContainText(NC_ADMIN_USER) + const draftedAt = new Date(String((await readView(result.uuid)).draftedAt)) + expect(Number.isNaN(draftedAt.getTime()), 'the view carries draftedAt').toBe(false) + await expect(notice).toContainText(/\d/) + + const node = editor.locator('.vue-flow__node').filter({ hasText: caseSystem }) + await expect(node).toBeVisible({ timeout: 30000 }) + const box = await node.boundingBox() + expect(box, 'the node has a box on the canvas').not.toBeNull() + const x = (box?.x ?? 0) + (box?.width ?? 0) / 2 + const y = (box?.y ?? 0) + (box?.height ?? 0) / 2 + await page.mouse.move(x, y) + await page.mouse.down() + await page.mouse.move(x + 120, y + 60, { steps: 8 }) + await page.mouse.up() + + await editor.getByRole('button', { name: 'Save', exact: true }).click() + await expect(page.getByText('The view is saved.')).toBeVisible({ timeout: 30000 }) + await expect(notice).toContainText('Drafted by an assistant for') + await expect(notice).toContainText(NC_ADMIN_USER) + + const stored = await readView(result.uuid) + expect(stored.origin).toBe('assistant') + expect(stored.draftedFor).toBe(NC_ADMIN_USER) + + await page.reload() + await expect(page.getByTestId('view-editor-draft-notice')).toContainText('Drafted by an assistant for', { timeout: 30000 }) +}) + +// @e2e architecture-assistant-views::an-application-owner-opens-a-fresh-draft +test('a fresh draft is laid out on open and is listed under the origin assistant', async ({ page }) => { + const name = `${RUN_ID} assistant fresh draft` + const result = await draft( + name, + [['a', ids.caseSystem], ['b', ids.documentStore], ['c', ids.caseRegister]], + [['a', 'b'], ['b', 'c']], + ) + const editor = await openEditor(page, result.uuid) + const nodes = editor.locator('.vue-flow__node') + await expect(nodes).toHaveCount(3, { timeout: 30000 }) + await expect(editor.locator('.vue-flow__edge')).toHaveCount(2) + const points = new Set() + for (const node of await nodes.all()) { + const box = await node.boundingBox() + expect(box, 'each node has a box on the canvas').not.toBeNull() + points.add(`${Math.round(box?.x ?? 0)},${Math.round(box?.y ?? 0)}`) + } + expect(points.size, 'the three nodes sit at distinct positions').toBe(3) + + await gotoAppRoute(page, `/views?_search=${encodeURIComponent(RUN_ID)}`) + await dismissSupportDialog(page) + await page.getByLabel('Origin', { exact: true }).first().click() + await page.getByRole('option', { name: /assistant/i }).first().click() + await expect(page.getByRole('row').filter({ hasText: name })).toBeVisible({ timeout: 30000 }) +}) diff --git a/tests/e2e/workflows/architecture-decisions.spec.ts b/tests/e2e/workflows/architecture-decisions.spec.ts new file mode 100644 index 000000000..d2bd1375d --- /dev/null +++ b/tests/e2e/workflows/architecture-decisions.spec.ts @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Architecture decisions: recording a decision with a rejected alternative, + * a second person accepting it through the declared lifecycle, and the + * decisions about an application in use listed on its usage page. + * + * Seeds an organisation, an application, a usage and two architecture + * decisions carrying this run's RUN_ID through the objects API, and creates a + * reviewer account for the run (the review guard needs a reviewer other than + * the author). Removes exactly those rows, the decision the record test + * creates and the account afterwards. The guard and the notification rules + * are covered by tests/Unit/Lifecycle/ArchitectureDecisionReviewGuardTest.php + * and tests/Unit/Settings/ArchitectureDecisionRegisterShapeTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/architecture-decision-register/specs/architecture-decision-register/spec.md#requirement-req-adreg-001-an-information-manager-shall-record-an-architecture-decision-with-its-context-options-and-consequences + * @spec openspec/changes/architecture-decision-register/specs/architecture-decision-register/spec.md#requirement-req-adreg-002-a-decision-shall-be-reviewed-by-a-second-person-through-a-declared-lifecycle + * @spec openspec/changes/architecture-decision-register/specs/architecture-decision-register/spec.md#requirement-req-adreg-004-a-decision-shall-link-to-the-applications-and-elements-it-affects-and-to-board-decisions + */ +import type { APIRequestContext, Browser, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, request as playwrightRequest, test } from '@playwright/test' +import { randomBytes } from 'node:crypto' +import { BASE_URL } from '../base-url.ts' +import { + createObject, + deleteObject, + findAll, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute, openCreateDialog } from './_ui.ts' + +const OR = '/index.php/apps/openregister/api/objects' +const SCHEMA = 'architectureDecision' +const reviewer = `adr-${RUN_ID}`.slice(0, 60) +const password = `Ad-${randomBytes(18).toString('hex')}-Pw1!` + +let apiCtx: APIRequestContext +let reviewerCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const organisation = `${RUN_ID} municipality` +const application = `${RUN_ID} case application` +const inReview = `${RUN_ID} one archive for all records` +const accepted = `${RUN_ID} one case system for all domains` + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Move a decision to another status through a direct edit, as one account. + * + * @param ctx The account's API context. + * @param id The decision. + * @param status The status to reach. + * @return Resolves once the status is stored. + */ +async function moveTo(ctx: APIRequestContext, id: string, status: string): Promise { + const res = await ctx.patch(`${OR}/${cfg.register}/${SCHEMA}/${id}`, { data: { status } }) + expect(res.ok(), `${status}: HTTP ${res.status()} ${await res.text()}`).toBe(true) +} + +/** + * The id of an object, whether given as a row or as an object. + * + * @param row The row. + * @return The id, or an empty string. + */ +function idOf(row: Record): string { + return String(row.id ?? (row as { '@self'?: { id?: string } })['@self']?.id ?? '') +} + +/** + * A browser page logged in as the reviewer, from an empty storage state. + * + * @param browser The browser. + * @return The logged-in page. + */ +async function reviewerPage(browser: Browser): Promise { + const context = await browser.newContext({ baseURL: BASE_URL, storageState: { cookies: [], origins: [] } }) + const page = await context.newPage() + await page.goto('/index.php/login', { timeout: 60000 }) + const user = page.locator('input[autocomplete="username"], input[name="user"], input[id="user"]') + await user.waitFor({ state: 'visible', timeout: 45000 }) + await user.fill(reviewer) + await page.locator('input[autocomplete="current-password"], input[type="password"], input[name="password"]').fill(password) + await page.locator('button[type="submit"], input[type="submit"]').first().click() + await page.waitForFunction(() => !window.location.pathname.includes('/login'), { timeout: 30000 }) + return page +} + +test.describe.configure({ mode: 'serial' }) + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + const made = await apiCtx.post('/ocs/v2.php/cloud/users?format=json', { + data: { userid: reviewer, password, groups: ['admin'] }, + }) + expect(made.ok(), `reviewer account: HTTP ${made.status()}`).toBe(true) + reviewerCtx = await playwrightRequest.newContext({ + baseURL: BASE_URL, + storageState: { cookies: [], origins: [] }, + httpCredentials: { username: reviewer, password, send: 'always' }, + extraHTTPHeaders: { 'OCS-APIREQUEST': 'true' }, + }) + + ids.org = await seed('organization', { name: organisation, type: 'Municipality' }) + ids.module = await seed('module', { name: application }) + ids.usage = await seed('usage', { + consumer: ids.org, + module: ids.module, + status: 'In production', + startDateInProduction: '2022-01-01', + }) + // The author (the admin) submits; the guard needs a reviewer other than the author. + ids.inReview = await seed(SCHEMA, { + title: inReview, + context: `${RUN_ID} records are archived per department.`, + decision: 'All records go to one archive.', + category: 'data', + impact: 'medium', + reviewer, + status: 'in review', + }) + // Accepting is the reviewer's, so the reviewer moves it from in review to accepted. + ids.accepted = await seed(SCHEMA, { + title: accepted, + context: `${RUN_ID} three domains each run their own case system.`, + decision: 'One case system, domain by domain.', + category: 'application', + impact: 'high', + reviewer, + applications: [ids.usage], + }) + await moveTo(apiCtx, ids.accepted, 'in review') + await moveTo(reviewerCtx, ids.accepted, 'accepted') +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const row of await findAll(apiCtx, cfg.register, SCHEMA, RUN_ID)) { + const id = idOf(row) + if (id && !seeded.some(([, seededId]) => seededId === id)) { + await deleteObject(apiCtx, cfg.register, SCHEMA, id) + } + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await reviewerCtx?.dispose() + await apiCtx.delete(`/ocs/v2.php/cloud/users/${encodeURIComponent(reviewer)}?format=json`).catch(() => undefined) + await apiCtx.dispose() +}) + +// @e2e architecture-decision-register::an-information-manager-records-a-decision +// The Add form has no editor for an alternative with its reason: `alternatives` is an array of objects without `x-widget: sub-objects`, so CnFormDialog renders it as a tag box. +test.fixme('a recorded decision is listed as draft and its page shows the rejected alternative', async ({ page }) => { + const title = `${RUN_ID} new integrations only through APIs` + await gotoAppRoute(page, '/architectuurbesluiten') + await dismissSupportDialog(page) + + const dialog = await openCreateDialog(page, /Add/) + await dialog.getByLabel('Title').fill(title) + await dialog.getByLabel('Context').fill('File exchange over FTP cannot be traced.') + await dialog.getByLabel('Decision').fill('A new integration uses a documented API.') + await dialog.getByLabel('Category').click() + await page.getByRole('option', { name: 'Integration', exact: true }).click() + await dialog.getByLabel('Impact').click() + await page.getByRole('option', { name: 'Medium', exact: true }).click() + await dialog.getByLabel('Reviewer').fill(reviewer) + await dialog.getByLabel('Alternatives').fill('File transfer') + await dialog.getByLabel('Reason rejected').fill('Transfers cannot be traced.') + await dialog.getByRole('button', { name: /Save|Create/ }).last().click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + + const row = page.getByRole('row').filter({ hasText: title }) + await expect(row).toContainText(/draft/i, { timeout: 30000 }) + await row.click() + await expect(page).toHaveURL(/\/architectuurbesluiten\//) + await expect(page.getByText('File transfer').first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByText('Transfers cannot be traced.').first()).toBeVisible() +}) + +// @e2e architecture-decision-register::a-reviewer-accepts-a-decision +test('the reviewer applies Accept and the History tab shows the transition', async ({ browser }) => { + const page = await reviewerPage(browser) + try { + await gotoAppRoute(page, `/architectuurbesluiten/${ids.inReview}`) + await dismissSupportDialog(page) + await expect(page.getByText(inReview).first()).toBeVisible({ timeout: 30000 }) + + await page.getByTestId('cn-lifecycle-action-accept').click() + await expect(page.getByTestId('cn-lifecycle-actions-error')).toHaveCount(0) + await expect(page.getByText('Accepted', { exact: true }).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByTestId('cn-lifecycle-action-accept')).toHaveCount(0) + + const res = await apiCtx.get(`${OR}/${cfg.register}/${SCHEMA}/${ids.inReview}`) + expect((await res.json()).status).toBe('accepted') + + await page.getByRole('tab', { name: 'History' }).click() + await expect(page.getByRole('tabpanel').filter({ hasText: /accepted/i }).first()).toBeVisible({ timeout: 30000 }) + } finally { + await page.context().close() + } +}) + +// @e2e architecture-decision-register::an-application-owner-sees-the-decisions-about-their-application +test('the usage page lists the accepted decision about it and opens the decision page', async ({ page }) => { + await gotoAppRoute(page, `/gebruik/${ids.usage}`) + await dismissSupportDialog(page) + await expect(page.getByText('Architecture decisions').first()).toBeVisible({ timeout: 30000 }) + const row = page.getByRole('row').filter({ hasText: accepted }) + await expect(row).toBeVisible({ timeout: 30000 }) + await expect(row).toContainText(/accepted/i) + await expect(page.getByRole('row').filter({ hasText: inReview })).toHaveCount(0) + + await row.click() + await expect(page).toHaveURL(new RegExp(`/architectuurbesluiten/${ids.accepted}`), { timeout: 30000 }) + await expect(page.getByText(accepted).first()).toBeVisible({ timeout: 30000 }) +}) diff --git a/tests/e2e/workflows/architecture-view-export.spec.ts b/tests/e2e/workflows/architecture-view-export.spec.ts new file mode 100644 index 000000000..ec93161a3 --- /dev/null +++ b/tests/e2e/workflows/architecture-view-export.spec.ts @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Architecture view export: a drawn view downloaded as an SVG image from the + * view page's Export menu, and the Word and PowerPoint actions disabled with + * the reason on an instance without filinq while Download SVG still works. + * + * Seeds one drawn view with three nodes in the AMEF register the app maps + * (`/api/amef/config`), carrying this run's RUN_ID, through the objects API, + * and removes exactly that view afterwards. The SVG rendering rules, the + * filinq gateway and the document route are covered by + * tests/Unit/Service/ViewImageServiceTest.php, + * tests/Unit/Controller/ViewControllerImageTest.php, + * tests/Unit/Service/ViewDocumentGatewayTest.php, + * tests/Unit/Controller/ViewControllerDocumentTest.php and + * tests/vitest/viewExport.spec.js. + * + * Both tests are fixme: the Export menu (src/services/viewExport.js) is not + * mounted in ArchitectureViewEditor.vue yet (task 4 of the change). + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/architecture-views-to-office-documents/specs/architecture-view-office-export/spec.md#requirement-req-avo-001-stackiq-shall-draw-a-view-as-a-standalone-svg-from-its-stored-geometry + * @spec openspec/changes/architecture-views-to-office-documents/specs/architecture-view-office-export/spec.md#requirement-req-avo-003-the-document-actions-shall-say-why-they-are-unavailable-when-filinq-cannot-take-the-request + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' + +import { expect, test } from '@playwright/test' +import { readFile } from 'node:fs/promises' +import { + createObject, + deleteObject, + newApiContext, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let register = '' +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const viewName = `${RUN_ID} case handling today` +const nodeNames = [`${RUN_ID} case system`, `${RUN_ID} document store`, `${RUN_ID} case register`] + +/** + * Create a row in the AMEF register and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Open a view and its Export menu. + * + * @param page The page. + * @param id The view's uuid. + * @return The editor. + */ +async function openExportMenu(page: Page, id: string): Promise { + await gotoAppRoute(page, `/views/${id}`) + await dismissSupportDialog(page) + const editor = page.getByTestId('architecture-view-editor') + await expect(editor).toBeVisible({ timeout: 30000 }) + await editor.getByRole('button', { name: 'Export', exact: true }).click() + return editor +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + const res = await apiCtx.get('/index.php/apps/stackiq/api/amef/config') + expect(res.ok(), `amef/config returned ${res.status()}`).toBe(true) + const config = (await res.json())?.config ?? {} + register = String(config.register ?? config.register_id ?? '') + expect(register, 'stackiq maps an AMEF register').not.toBe('') + + const nodes = nodeNames.map((name, index) => ({ + viewNodeId: `id-${RUN_ID}-node-${index}`, + parent: null, + elementRef: `id-${RUN_ID}-element-${index}`, + x: 40 + index * 200, + y: 80, + width: 120, + height: 55, + name, + type: 'ApplicationComponent', + })) + ids.view = await seed('view', { + identifier: `id-${RUN_ID}-export-view`, + name: viewName, + origin: 'drawn', + status: 'draft', + nodes, + connections: [ + { + viewRelationshipId: `id-${RUN_ID}-conn-0`, + modelRelationshipId: `id-${RUN_ID}-rel-0`, + sourceId: nodes[0].viewNodeId, + targetId: nodes[1].viewNodeId, + type: 'Flow', + bendpoints: [], + }, + ], + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e architecture-view-office-export::an-application-owner-downloads-a-view-as-svg +// The Export menu is not mounted in ArchitectureViewEditor.vue; src/services/viewExport.js holds its actions only. +test.fixme('Export, then Download SVG, gives an SVG file named after the view holding its nodes', async ({ page }) => { + await openExportMenu(page, ids.view) + const downloading = page.waitForEvent('download') + await page.getByRole('menuitem', { name: 'Download SVG' }).click() + const download = await downloading + expect(download.suggestedFilename()).toMatch(/\.svg$/) + expect(download.suggestedFilename()).toContain(RUN_ID) + + const path = await download.path() + const svg = await readFile(String(path), 'utf8') + expect(svg).toContain(' { + await openExportMenu(page, ids.view) + const word = page.getByRole('menuitem', { name: 'Create Word document' }) + const slide = page.getByRole('menuitem', { name: 'Create PowerPoint slide' }) + await expect(word).toBeDisabled() + await expect(slide).toBeDisabled() + await expect(page.getByText('Word and PowerPoint need the document app filinq').first()).toBeVisible() + await expect(page.getByRole('menuitem', { name: 'Download SVG' })).toBeEnabled() +}) diff --git a/tests/e2e/workflows/ask-the-catalogue.spec.ts b/tests/e2e/workflows/ask-the-catalogue.spec.ts new file mode 100644 index 000000000..6a8fb798b --- /dev/null +++ b/tests/e2e/workflows/ask-the-catalogue.spec.ts @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Ask the catalogue (the assistant answers and action trail change, task 2): a + * user opens Ask from the menu, asks which applications a supplier offers and + * reads the reply with its linked Sources; a question no entry matches reads + * "No catalogue entries matched this question." and leaves the assistant out. + * + * Seeds one supplier and three published applications of that supplier, all + * carrying this run's RUN_ID, through the objects API, and removes exactly + * those rows afterwards. Both tests need hermiq: `POST /api/ask` answers 503 + * before it searches when hermiq is absent, so they skip on an instance + * without it. The reply itself comes from the assistant, so the test holds + * the Sources list (the entries the reply cites, linked by stackiq) to the + * three applications, and checks the reply names them as a soft assertion. + * + * The excluded scenarios (an unreadable entry is never sent, hermiq missing) + * are covered by tests/Unit/Service/AskServiceTest.php and + * tests/Unit/Controller/AskControllerTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/insight-assistant-answers-and-action-trail/specs/assistant-insight/spec.md#requirement-req-ask-001-an-answer-lists-the-catalogue-entries-it-used + * @spec openspec/changes/insight-assistant-answers-and-action-trail/specs/assistant-insight/spec.md#requirement-req-ask-002-the-ask-panel-is-only-offered-when-hermiq-is-installed + */ +import type { APIRequestContext, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, navClickTo } from './_ui.ts' + +const ASK_PATH = '/apps/stackiq/api/ask' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +let hermiqEnabled = false +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const supplierName = `${RUN_ID} supplier` +const applications = [ + `${RUN_ID} application one`, + `${RUN_ID} application two`, + `${RUN_ID} application three`, +] + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Whether a Nextcloud app is enabled on the instance. + * + * @param app The app id. + * @return True when it is enabled. + */ +async function appEnabled(app: string): Promise { + const res = await apiCtx.get('/ocs/v2.php/cloud/apps?filter=enabled&format=json') + if (!res.ok()) { + return false + } + const list: string[] = (await res.json())?.ocs?.data?.apps ?? [] + return list.includes(app) +} + +/** + * Open Ask through its menu entry and submit a question. + * + * @param page The page. + * @param question The question. + * @return The JSON `POST /api/ask` answered with. + */ +async function ask(page: Page, question: string): Promise> { + await navClickTo(page, 'Ask the catalogue') + await dismissSupportDialog(page) + await expect(page.getByRole('heading', { name: 'Ask the catalogue' }).first()).toBeVisible({ timeout: 30000 }) + await page.getByLabel('Your question').first().fill(question) + const answered = page.waitForResponse((res) => res.url().includes(ASK_PATH) && res.request().method() === 'POST', { timeout: 120000 }) + await page.getByTestId('ask-submit').click() + const response = await answered + expect(response.status(), await response.text()).toBe(200) + return await response.json() +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + hermiqEnabled = await appEnabled('hermiq') + ids.supplier = await seed('organization', { + name: supplierName, + type: 'Supplier', + status: 'Active', + contactsUid: `${RUN_ID}-supplier`, + }) + const now = new Date().toISOString() + for (const [index, name] of applications.entries()) { + ids[`app${index}`] = await seed('module', { + name, + shortDescription: `${name} is offered by ${supplierName}`, + provider: ids.supplier, + publicationDate: now, + }) + } +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e assistant-insight::a-user-asks-which-applications-a-supplier-offers +test('asking which applications a supplier offers lists its three applications as linked Sources', async ({ page }) => { + test.skip(!hermiqEnabled, 'hermiq is not installed on this instance; POST /api/ask answers 503 without it') + test.setTimeout(180000) + + const body = await ask(page, `Which applications does ${supplierName} offer?`) + expect(Array.isArray(body.searched) && body.searched.length > 0, 'the catalogue search found the seeded entries').toBe(true) + + const answer = page.getByTestId('ask-answer') + await expect(answer).toBeVisible({ timeout: 30000 }) + const sources = page.getByTestId('ask-sources') + await expect(sources).toBeVisible() + for (const [index, name] of applications.entries()) { + const link = sources.getByRole('link', { name, exact: true }) + await expect(link).toBeVisible() + await expect(link).toHaveAttribute('href', new RegExp(`/modules/${ids[`app${index}`]}$`)) + // The wording of the reply is the assistant's; the names should be in it. + await expect.soft(answer.locator('.ask-reply')).toContainText(name) + } + + await sources.getByRole('link', { name: applications[0], exact: true }).click() + await expect(page).toHaveURL(new RegExp(`/modules/${ids.app0}`)) + await expect(page.getByText(applications[0]).first()).toBeVisible({ timeout: 30000 }) +}) + +// @e2e assistant-insight::nothing-matched +test('a question no entry matches says so and the assistant is not asked', async ({ page }) => { + test.skip(!hermiqEnabled, 'hermiq is not installed on this instance; POST /api/ask answers 503 without it') + + const body = await ask(page, `${RUN_ID} qqzx no catalogue entry holds this text`) + // No entry searched means AskService returned before calling hermiq's converse. + expect(body.searched).toEqual([]) + expect(body.sources).toEqual([]) + expect(body.reply).toBe('') + + await expect(page.getByTestId('ask-empty')).toHaveText('No catalogue entries matched this question.') + await expect(page.getByTestId('ask-answer')).toHaveCount(0) +}) diff --git a/tests/e2e/workflows/assistant-actions.spec.ts b/tests/e2e/workflows/assistant-actions.spec.ts new file mode 100644 index 000000000..629ca1b8a --- /dev/null +++ b/tests/e2e/workflows/assistant-actions.spec.ts @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Assistant actions (the assistant answers and action trail change, task 3): an + * administrator opens Assistant actions, filters on one stackiq tool and reads + * the row of an assistant's call with when, user, tool and the linked record, + * and the record link opens the contract page. + * + * Seeds one organisation, one application, a usage of it and a contract on + * that usage, all carrying this run's RUN_ID, through the objects API, and + * removes exactly those rows afterwards. + * + * The audit row itself is answered in the browser (page.route on + * OpenRegister's `GET /api/audit-trails`): an `mcp.` audit record is written + * only when an assistant calls a stackiq tool over MCP, which a test cannot + * start, and stackiq keeps no copy it could seed. The answered row points at + * the seeded contract, so the schema lookup and the record link run against + * the live instance. The test also checks the page asks OpenRegister for the + * `mcp.` action prefix, the `stackiq.` tool prefix and the chosen tool, so the + * filtering stays server side. + * + * The excluded scenario (a user sees only their own assistant's actions) is + * OpenRegister's audit-trail rule; tests/vitest/assistantActions.spec.js + * covers that stackiq adds no wider read. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/insight-assistant-answers-and-action-trail/specs/assistant-insight/spec.md#requirement-req-ask-003-assistant-actions-on-catalogue-records-are-listed + */ +import type { APIRequestContext, Route } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + NC_ADMIN_USER, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, navClickTo } from './_ui.ts' + +const AUDIT_TRAILS = '/apps/openregister/api/audit-trails' +const TOOL = 'stackiq.submitContractApproval' +const OTHER_TOOL = 'stackiq.module.get' +const WHEN = '2026-10-06T10:15:00+00:00' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +let contractSchemaId = '' +let moduleSchemaId = '' +const contractNumber = `${RUN_ID}-2025-0042` + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * The numeric schema id OpenRegister stores on an object. + * + * @param schema The schema slug. + * @param id The object's id. + * @return The schema id. + */ +async function schemaIdOf(schema: string, id: string): Promise { + const res = await apiCtx.get(`/index.php/apps/openregister/api/objects/${cfg.register}/${schema}/${id}`) + expect(res.ok(), await res.text()).toBe(true) + const body = await res.json() + return String(body?.['@self']?.schema ?? '') +} + +/** + * One audit row as OpenRegister's list returns it. + * + * @param id The row id. + * @param toolId The tool. + * @param schema The schema id of the record. + * @param objectUuid The record. + * @return The row. + */ +function auditRow(id: string, toolId: string, schema: string, objectUuid: string): Record { + return { + id, + created: WHEN, + action: 'mcp.tools/call', + userName: NC_ADMIN_USER, + toolId, + schema, + objectUuid, + resultSummary: { isError: false }, + } +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + ids.org = await seed('organization', { + name: `${RUN_ID} municipality`, + type: 'Municipality', + status: 'Active', + contactsUid: `${RUN_ID}-municipality`, + }) + ids.app = await seed('module', { name: `${RUN_ID} application` }) + ids.usage = await seed('usage', { module: ids.app, consumer: ids.org, status: 'In production' }) + ids.contract = await seed('catalogContract', { + contractNumber, + contractType: 'Licence', + status: 'Active', + startDate: '2026-01-01', + endDate: '2027-12-31', + usage: ids.usage, + }) + contractSchemaId = await schemaIdOf('catalogContract', ids.contract) + moduleSchemaId = await schemaIdOf('module', ids.app) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e assistant-insight::an-administrator-reviews-what-an-assistant-changed +test('filtering on the submit tool leaves one row whose record link opens the contract', async ({ page }) => { + const asked: URLSearchParams[] = [] + await page.route(`**${AUDIT_TRAILS}*`, async (route: Route) => { + const params = new URL(route.request().url()).searchParams + asked.push(params) + const rows = [auditRow(`${RUN_ID}-1`, TOOL, contractSchemaId, ids.contract)] + if (!params.has('tool')) { + rows.push(auditRow(`${RUN_ID}-2`, OTHER_TOOL, moduleSchemaId, ids.app)) + } + await route.fulfill({ json: { results: rows.filter((row) => !params.has('tool') || row.toolId === params.get('tool')), nextCursor: null } }) + }) + + await navClickTo(page, 'Assistant actions') + await dismissSupportDialog(page) + await expect(page.getByRole('heading', { name: 'Assistant actions' }).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByTestId('aa-row')).toHaveCount(2, { timeout: 30000 }) + + await page.getByLabel('Tool', { exact: true }).fill('submitContractApproval') + await page.getByTestId('aa-apply').click() + + const rows = page.getByTestId('aa-row') + await expect(rows).toHaveCount(1, { timeout: 30000 }) + const last = asked[asked.length - 1] + expect(last.get('actionPrefix')).toBe('mcp.') + expect(last.get('toolPrefix')).toBe('stackiq.') + expect(last.get('tool')).toBe(TOOL) + + // The page prints the date in the browser's locale; read it the same way. + const when = await page.evaluate((iso) => new Date(iso).toLocaleString(), WHEN) + const row = rows.first() + await expect(row).toContainText(when) + await expect(row).toContainText('2026') + await expect(row).toContainText(NC_ADMIN_USER) + await expect(row).toContainText(TOOL) + await expect(row).toContainText('Succeeded') + + const record = row.getByRole('link', { name: ids.contract }) + await expect(record).toBeVisible({ timeout: 30000 }) + await record.click() + await expect(page).toHaveURL(new RegExp(`/contracten/${ids.contract}`)) + await expect(page.getByText(contractNumber).first()).toBeVisible({ timeout: 30000 }) +}) diff --git a/tests/e2e/workflows/bulk-actions.spec.ts b/tests/e2e/workflows/bulk-actions.spec.ts new file mode 100644 index 000000000..7cee5d8c7 --- /dev/null +++ b/tests/e2e/workflows/bulk-actions.spec.ts @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Bulk delete on the Applications page: three selected applications are + * deleted in one action, after a confirmation that lists how many go. + * + * Seeds three applications carrying this run's RUN_ID through the objects + * API, ticks their rows on /modules, chooses "Delete selected" in the + * selection strip and confirms in the mass-delete dialog. Afterwards the + * seeded rows are deleted again; a row the test already removed answers 404, + * which the cleanup ignores. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/capability-rows-the-code-does-not-yet-meet/specs/open-data-publishing/spec.md#requirement-selected-entries-are-deleted-together-from-the-list-req-clr-011 + */ +import type { APIRequestContext, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const apps = [ + `${RUN_ID} application one`, + `${RUN_ID} application two`, + `${RUN_ID} application three`, +] + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * Tick a list row's checkbox by the text it shows. + * + * @param page The page. + * @param text The row's text. + * @return Nothing. + */ +async function selectRow(page: Page, text: string): Promise { + const row = page.getByRole('row').filter({ hasText: text }) + await expect(row).toBeVisible({ timeout: 30000 }) + await row.getByRole('checkbox').first().check({ force: true }) +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + for (const name of apps) { + await seed('module', { name }) + } +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e open-data-publishing::an-information-manager-deletes-three-entries-at-once +test('three selected applications are deleted together after a confirmation that lists them', async ({ + page, +}) => { + await gotoAppRoute(page, `/modules?_search=${encodeURIComponent(RUN_ID)}`) + await dismissSupportDialog(page) + for (const name of apps) { + await selectRow(page, name) + } + + const strip = page.getByTestId('cn-selection-strip') + await expect(strip).toContainText('3 selected') + await strip.getByRole('button', { name: 'Delete selected' }).click() + + const review = page.locator('[data-testid-modal="cn-mass-delete-dialog"]') + await expect(review).toBeVisible({ timeout: 30000 }) + await expect(review.locator('.cn-mass-delete__item')).toHaveCount(3) + for (const name of apps) { + await expect(review).toContainText(name) + } + await page.getByTestId('cn-mass-delete-dialog-confirm').click() + + for (const name of apps) { + await expect(page.getByRole('row').filter({ hasText: name })).toHaveCount(0, { timeout: 30000 }) + } + + // The rows stay gone after a fresh load, so the delete reached the server. + await gotoAppRoute(page, `/modules?_search=${encodeURIComponent(RUN_ID)}`) + await dismissSupportDialog(page) + for (const name of apps) { + await expect(page.getByRole('row').filter({ hasText: name })).toHaveCount(0, { timeout: 30000 }) + } +}) diff --git a/tests/e2e/workflows/connection-suggestions.spec.ts b/tests/e2e/workflows/connection-suggestions.spec.ts new file mode 100644 index 000000000..b20a79a8c --- /dev/null +++ b/tests/e2e/workflows/connection-suggestions.spec.ts @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Suggested connections (connections-derived-dependencies): a municipality's + * new usage gets the known connection to an application it already uses + * suggested and accepts it, and a usage of a new version of an application + * gets the connections of the earlier version suggested as carried over. + * + * Seeds a municipality carrying this run's RUN_ID (it syncs to an OpenRegister + * organisation with the same uuid), makes the logged-in administrator a member + * with that municipality active, because the suggestion endpoints answer only + * the organisation that owns the usage, and seeds the applications, versions, + * a national provision, the connections and the usages through the objects + * API. Setup and teardown use the API; every assertion is made on the rendered + * page. Afterwards the seeded rows are deleted and the administrator's previous + * active organisation is restored. + * + * The scenarios marked `@e2e exclude` are covered by + * tests/Unit/Service/ConnectionSuggestionServiceTest.php and + * tests/Unit/Controller/ConnectionSuggestionControllerTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/connections-derived-dependencies/specs/derived-connections/spec.md#requirement-req-dcn-001-stackiq-suggests-the-known-connections-of-an-application-inside-the-organisations-landscape + * @spec openspec/changes/connections-derived-dependencies/specs/derived-connections/spec.md#requirement-req-dcn-002-a-replacing-usage-is-offered-the-connections-of-the-usage-it-replaces + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +interface AmefConfig { + register: string + element_schema: string +} + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +let amef: AmefConfig +const seeded: Array<[string, string, string]> = [] +const ids: Record = {} +let previousActive = '' +const OR_API = '/index.php/apps/openregister/api' +const municipality = `${RUN_ID} suggesting municipality` +const appX = `${RUN_ID} intake application` +const appY = `${RUN_ID} archive application` +const linkXY = `${RUN_ID} intake to archive` +const appV = `${RUN_ID} permits application` +const appW = `${RUN_ID} payments application` +const provision = `${RUN_ID} national register` +const linkVW = `${RUN_ID} permits to payments` +const linkVNational = `${RUN_ID} permits to national register` + +test.describe.configure({ mode: 'serial' }) + +/** + * Create a row and remember it for cleanup. + * + * @param register The register id. + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(register: string, schema: string, data: Record): Promise { + const id = await createObject(apiCtx, register, schema, data) + seeded.push([register, schema, id]) + return id +} + +/** + * Read the AMEF register mapping, where the national provisions live. + * + * @param ctx An admin API context. + * @return The register and the element schema. + */ +async function resolveAmefConfig(ctx: APIRequestContext): Promise { + const res = await ctx.get('/index.php/apps/stackiq/api/amef/config') + expect(res.ok(), `amef/config returned ${res.status()}`).toBe(true) + const config = (await res.json())?.config ?? {} + const register = String(config.register ?? config.register_id ?? '') + expect(register, 'stackiq has no AMEF register mapping').not.toBe('') + return { register, element_schema: String(config.element_schema || 'element') } +} + +/** + * Wait until a register organisation has synced to an OpenRegister organisation. + * + * @param uuid The organisation's uuid. + * @return Nothing; throws when it never appears. + */ +async function awaitOrganisation(uuid: string): Promise { + for (let attempt = 0; attempt < 20; attempt++) { + const res = await apiCtx.get(`${OR_API}/organisations/${uuid}`) + if (res.ok()) return + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + throw new Error(`organisation ${uuid} did not sync to OpenRegister`) +} + +/** + * The Suggested connections panel of a usage page. + * + * @param page The page. + * @return The panel. + */ +function suggestionsPanel(page: Page): Locator { + return page.locator('.connection-suggestions').first() +} + +/** + * One suggestion in the panel, by the connection's name. + * + * @param page The page. + * @param name The connection's name. + * @return The suggestion's list item. + */ +function suggestion(page: Page, name: string): Locator { + return suggestionsPanel(page).locator('li', { hasText: name }) +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + amef = await resolveAmefConfig(apiCtx) + const reg = cfg.register + const published = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() + + const me = await apiCtx.get('/index.php/apps/stackiq/api/me') + if (me.ok()) { + previousActive = (await me.json())?.organisations?.active?.uuid ?? '' + } + + ids.org = await seed(reg, 'organization', { + name: municipality, + type: 'Municipality', + status: 'Active', + contactsUid: `${RUN_ID}-suggesting-municipality`, + }) + await awaitOrganisation(ids.org) + const join = await apiCtx.post(`${OR_API}/organisations/${ids.org}/join`, { data: {} }) + if (!join.ok() && join.status() !== 409) { + console.warn(`join ${ids.org} returned ${join.status()}`) + } + const active = await apiCtx.post(`${OR_API}/organisations/${ids.org}/set-active`, { data: {} }) + expect(active.ok(), `set-active returned ${active.status()}`).toBe(true) + + // Shared landscape: a published connection X-Y, the municipality uses Y, + // and the usage of X is what it records now. + ids.x = await seed(reg, 'module', { name: appX }) + ids.y = await seed(reg, 'module', { name: appY }) + ids.linkXY = await seed(reg, 'connection', { + name: linkXY, + moduleA: ids.x, + moduleB: ids.y, + type: 'api', + dataExchangeDirection: 'AtoB', + status: 'in use', + publicationDate: published, + }) + ids.usageY = await seed(reg, 'usage', { consumer: ids.org, module: ids.y, status: 'In production' }) + ids.usageX = await seed(reg, 'usage', { consumer: ids.org, module: ids.x, status: 'In production' }) + + // Carry-over: a usage of V at version 1 with connections to W and to a + // national provision, and a usage of V at version 2. + ids.v = await seed(reg, 'module', { name: appV }) + ids.w = await seed(reg, 'module', { name: appW }) + ids.v1 = await seed(reg, 'moduleVersion', { module: ids.v, version: '1', status: 'in use' }) + ids.v2 = await seed(reg, 'moduleVersion', { module: ids.v, version: '2', status: 'in use' }) + ids.provision = await seed(amef.register, amef.element_schema, { + identifier: `id-${RUN_ID}-national-register`, + type: 'ApplicationComponent', + name: provision, + gemmaType: 'Buitengemeentelijke voorziening', + properties: [], + }) + ids.linkVW = await seed(reg, 'connection', { + name: linkVW, + moduleA: ids.v, + moduleB: ids.w, + type: 'api', + dataExchangeDirection: 'AtoB', + status: 'in use', + publicationDate: published, + }) + ids.linkVNational = await seed(reg, 'connection', { + name: linkVNational, + moduleA: ids.v, + nonMunicipalProvision: ids.provision, + type: 'digikoppeling', + dataExchangeDirection: 'AtoB', + status: 'in use', + publicationDate: published, + }) + ids.usageV1 = await seed(reg, 'usage', { + consumer: ids.org, + module: ids.v, + moduleVersion: ids.v1, + status: 'In production', + koppelingen: [ids.linkVW, ids.linkVNational], + }) + ids.usageV2 = await seed(reg, 'usage', { + consumer: ids.org, + module: ids.v, + moduleVersion: ids.v2, + status: 'Planned', + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [register, schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, register, schema, id) + } + if (previousActive !== '') { + await apiCtx.post(`${OR_API}/organisations/${previousActive}/set-active`, { data: {} }) + } + await apiCtx.dispose() +}) + +// @e2e derived-connections::a-municipality-gets-its-connections-suggested +test('the usage of X is offered the connection to Y and accepting adds it to the usage', async ({ + page, +}) => { + await gotoAppRoute(page, `/gebruik/${ids.usageX}`) + await dismissSupportDialog(page) + await expect(page.getByText('Suggested connections').first()).toBeVisible({ timeout: 30000 }) + const item = suggestion(page, linkXY) + await expect(item).toBeVisible({ timeout: 30000 }) + await expect(item).toContainText('Both applications are in your landscape') + + await item.getByRole('button', { name: `Accept ${linkXY}` }).click() + await expect(page.getByText('Connections added: 1').first()).toBeVisible({ timeout: 30000 }) + await expect(suggestion(page, linkXY)).toHaveCount(0) + + // After a reload it is one of the usage's connections, no longer a suggestion. + await page.reload() + await dismissSupportDialog(page) + await expect(page.getByText('Suggested connections').first()).toBeVisible({ timeout: 30000 }) + await expect(suggestionsPanel(page).locator('li').first().or(suggestionsPanel(page).getByText(/No suggestions/))).toBeVisible({ timeout: 30000 }) + await expect(suggestion(page, linkXY)).toHaveCount(0) + await expect(page.getByText(linkXY).first()).toBeVisible({ timeout: 30000 }) +}) + +// @e2e derived-connections::a-new-version-keeps-its-connections +test('the usage of version 2 is offered both connections of version 1 as carried over', async ({ + page, +}) => { + await gotoAppRoute(page, `/gebruik/${ids.usageV2}`) + await dismissSupportDialog(page) + await expect(page.getByText('Suggested connections').first()).toBeVisible({ timeout: 30000 }) + for (const name of [linkVW, linkVNational]) { + const item = suggestion(page, name) + await expect(item).toBeVisible({ timeout: 30000 }) + await expect(item).toContainText('Carried over from another version') + } +}) diff --git a/tests/e2e/workflows/contracts.spec.ts b/tests/e2e/workflows/contracts.spec.ts new file mode 100644 index 000000000..151419579 --- /dev/null +++ b/tests/e2e/workflows/contracts.spec.ts @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * A contract's supplier: the contract page shows the supplier of the service + * the contract is for, linking to that supplier's organisation page. + * + * Seeds a supplier organisation, a service it provides and a contract for + * that service, all carrying this run's RUN_ID, through the objects API, and + * removes exactly those rows afterwards. + * + * The contract page (ContractDetail in src/manifest.json) has no supplier + * field: catalogContract points at its service only, and the "Service & + * usage" related widget (ct-related) declares no source that reads the + * service's provider. The scenario is therefore marked fixme until the page + * shows the supplier. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/capability-rows-the-code-does-not-yet-meet/specs/vendor-product-master-data/spec.md#requirement-a-contract-shows-its-supplier-through-the-service-it-is-for-req-clr-014 + */ +import type { APIRequestContext } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const supplier = `${RUN_ID} supplier` +const service = `${RUN_ID} hosting service` + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + ids.supplier = await seed('organization', { name: supplier, type: 'Supplier' }) + ids.service = await seed('catalogService', { + name: service, + provider: ids.supplier, + }) + ids.contract = await seed('catalogContract', { + contractNumber: `${RUN_ID}-1`, + contractType: 'SLA', + status: 'Active', + startDate: '2026-01-01', + cost: 5000, + costPeriod: 'Annually', + service: ids.service, + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e vendor-product-master-data::a-contract-manager-reads-a-contract-s-supplier +// fixme: the contract page shows no supplier; neither ct-data nor ct-related reads the service's provider. +test.fixme('the contract page shows the supplier of its service, linking to the organisation page', async ({ + page, +}) => { + await gotoAppRoute(page, `/contracten/${ids.contract}`) + await dismissSupportDialog(page) + await expect(page.getByText(service).first()).toBeVisible({ timeout: 30000 }) + + const link = page.getByRole('link', { name: supplier }).first() + await expect(link).toBeVisible({ timeout: 30000 }) + await link.click() + await expect(page).toHaveURL(new RegExp(`/organisaties/${ids.supplier}`), { timeout: 30000 }) + await expect(page.getByText(supplier).first()).toBeVisible({ timeout: 30000 }) +}) diff --git a/tests/e2e/workflows/federation-settings.spec.ts b/tests/e2e/workflows/federation-settings.spec.ts new file mode 100644 index 000000000..7e89b28ff --- /dev/null +++ b/tests/e2e/workflows/federation-settings.spec.ts @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Federation settings: an admin removes a peer catalogue in the Catalog + * federation section of the app's admin settings + * (src/views/settings/sections/FederationSettings.vue). + * + * Seeds one peer whose host carries this run's RUN_ID through the admin + * federation API (the call the "Add peer" button makes), removes it through + * the rendered "Remove peer" button, and checks the peer list the pull reads + * no longer holds it. Afterwards the peer is removed again if a failed run + * left it behind. + * + * Switching federation on and showing the registration status (task 21) is + * not built: the section only tells the admin to enable federation in the + * app configuration. That test is marked fixme. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/capability-rows-the-code-does-not-yet-meet/specs/federated-catalog-sync/spec.md#requirement-an-admin-removes-a-peer-catalogue-req-clr-015 + */ +import type { APIRequestContext, Page } from '@playwright/test' + +import { expect, test } from '@playwright/test' +import { newApiContext, RUN_ID } from './_fixtures.ts' +import { dismissSupportDialog } from './_ui.ts' + +const FEDERATION_API = '/index.php/apps/stackiq/api/federation' +const peerUrl = `https://${RUN_ID}.catalog.example.org` + +let apiCtx: APIRequestContext + +/** + * The peer URLs the federation status lists; a pull reads exactly these. + * + * @return The subscribed peer URLs. + */ +async function subscribedPeers(): Promise { + const res = await apiCtx.get(`${FEDERATION_API}/status`) + expect(res.ok()).toBe(true) + const body = await res.json() + const peers: Array<{ url?: string }> = Array.isArray(body?.peers) ? body.peers : [] + return peers.map((peer) => String(peer.url ?? '')) +} + +/** + * Open the app's admin settings and wait for the federation section. + * + * @param page The page. + * @return Nothing. + */ +async function gotoFederationSettings(page: Page): Promise { + await page.goto('/settings/admin/stackiq', { waitUntil: 'domcontentloaded' }) + await dismissSupportDialog(page) + await expect(page.getByRole('heading', { name: 'Catalog federation' }).first()).toBeVisible({ + timeout: 30000, + }) + await expect(page.getByRole('heading', { name: 'Subscribed peers' }).first()).toBeVisible({ + timeout: 30000, + }) +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + const res = await apiCtx.post(`${FEDERATION_API}/peers`, { data: { peerUrl } }) + if (!res.ok()) { + throw new Error(`add peer ${peerUrl} returned ${res.status()}: ${await res.text()}`) + } +}) + +test.afterAll(async () => { + if (!apiCtx) return + if ((await subscribedPeers()).includes(peerUrl)) { + await apiCtx.delete(`${FEDERATION_API}/peers`, { data: { peerUrl } }) + } + await apiCtx.dispose() +}) + +// @e2e federated-catalog-sync::an-admin-removes-a-peer +test('an admin removes a peer and it is gone from the list and from the next pull', async ({ + page, +}) => { + await gotoFederationSettings(page) + const peer = page.locator('li', { hasText: peerUrl }) + await expect(peer).toBeVisible({ timeout: 30000 }) + await peer.getByRole('button', { name: 'Remove peer' }).click() + await expect(page.getByText('Peer removed').first()).toBeVisible({ timeout: 30000 }) + await expect(peer).toHaveCount(0, { timeout: 30000 }) + + // The list stays without the peer after a fresh load. + await gotoFederationSettings(page) + await expect(page.locator('li', { hasText: peerUrl })).toHaveCount(0) + + // The pull iterates the subscribed peers the status lists, so a peer + // missing there is not read by the next pull. + expect(await subscribedPeers()).not.toContain(peerUrl) +}) + +// Task 21 is not built: FederationSettings.vue has no control to switch federation on and shows no registration status. +test.fixme('an admin switches federation on and the section shows the registration status', async ({ + page, +}) => { + await gotoFederationSettings(page) +}) diff --git a/tests/e2e/workflows/owner-attestation.spec.ts b/tests/e2e/workflows/owner-attestation.spec.ts new file mode 100644 index 000000000..b30d49894 --- /dev/null +++ b/tests/e2e/workflows/owner-attestation.spec.ts @@ -0,0 +1,377 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Confirmation rounds (landscape-owner-attestation): an information manager + * starts a round over a municipality's applications in use, the owner confirms + * an entry from My confirmation requests, and the round page shows an overdue + * request with its owner. + * + * Seeds two municipalities carrying this run's RUN_ID, a contact person whose + * contactsUid is the logged-in administrator (so the owner resolves to that + * Nextcloud user), five applications and usages for the first municipality, + * four of them with that owner, and one owned usage for the second, through the + * objects API. The administrator becomes a member of the first municipality + * with it active, so the Start round dialog offers it. The overdue round is + * started through the round endpoint with yesterday as deadline, and its + * pending request is then set to overdue, which is what the daily + * AttestationOverdueJob does (covered by + * tests/Unit/BackgroundJob/AttestationOverdueJobTest.php); a browser test + * cannot run a background job. Afterwards the seeded rows, the rounds and + * their requests are deleted and the administrator's previous active + * organisation is restored. + * + * The scenarios marked `@e2e exclude` are covered by + * tests/Unit/Settings/OwnerAttestationFragmentTest.php and + * tests/Unit/EventListener/AttestationCorrectionListenerTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/landscape-owner-attestation/specs/owner-attestation/spec.md#requirement-req-oat-001-an-information-manager-starts-a-confirmation-round-for-a-scope + * @spec openspec/changes/landscape-owner-attestation/specs/owner-attestation/spec.md#requirement-req-oat-003-an-owner-confirms-or-corrects-each-entry + * @spec openspec/changes/landscape-owner-attestation/specs/owner-attestation/spec.md#requirement-req-oat-004-the-round-shows-who-answered-and-who-is-overdue + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + findAll, + NC_ADMIN_USER, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const rounds: string[] = [] +const ids: Record = {} +const usageIds: string[] = [] +let previousActive = '' +const OR_API = '/index.php/apps/openregister/api' +const municipality = `${RUN_ID} confirming municipality` +const lateMunicipality = `${RUN_ID} late municipality` +const ownedApps = [1, 2, 3, 4].map((n) => `${RUN_ID} owned application ${n}`) +const ownerlessApp = `${RUN_ID} ownerless application` +const lateApp = `${RUN_ID} late application` +const roundName = `${RUN_ID} quarterly round` +const lateRoundName = `${RUN_ID} late round` + +test.describe.configure({ mode: 'serial' }) + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * The id of an object row. + * + * @param row The row. + * @return The id, or an empty string. + */ +function idOf(row: Record): string { + return String((row as { id?: string }).id ?? (row as { '@self'?: { id?: string } })['@self']?.id ?? '') +} + +/** + * A date as YYYY-MM-DD, some days from today. + * + * @param days Days from today; negative for the past. + * @return The date. + */ +function isoDay(days: number): string { + return new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10) +} + +/** + * Escape a literal for use in a regular expression. + * + * @param text The literal. + * @return The escaped text. + */ +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** + * A request is labelled by its entry's name, or by the entry's id when the + * usage carries no name of its own. + * + * @param name The application's name. + * @param usageId The usage's id. + * @return A pattern matching either. + */ +function entryLabel(name: string, usageId: string): RegExp { + return new RegExp(`${escapeRegExp(name)}|${usageId}`) +} + +/** + * The titled card of a list widget on a detail page. + * + * @param page The page. + * @param title The card's title. + * @return The card. + */ +function catalogCard(page: Page, title: string): Locator { + return page + .locator('.cn-detail-page__catalog-card') + .filter({ has: page.getByText(title, { exact: true }) }) + .first() +} + +/** + * Wait until a register organisation has synced to an OpenRegister organisation. + * + * @param uuid The organisation's uuid. + * @return Nothing; throws when it never appears. + */ +async function awaitOrganisation(uuid: string): Promise { + for (let attempt = 0; attempt < 20; attempt++) { + const res = await apiCtx.get(`${OR_API}/organisations/${uuid}`) + if (res.ok()) return + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + throw new Error(`organisation ${uuid} did not sync to OpenRegister`) +} + +/** + * The requests of a round. + * + * @param roundId The round's id. + * @return The request rows. + */ +async function requestsOf(roundId: string): Promise>> { + const res = await apiCtx.get( + `${OR_API}/objects/${cfg.register}/attestationRequest?round=${encodeURIComponent(roundId)}&_limit=200`, + ) + if (!res.ok()) return [] + const body = await res.json() + const list = body?.results ?? body ?? [] + return Array.isArray(list) ? list : [] +} + +/** + * The round page of a round found by its name on the Confirmation rounds list. + * + * @param page The page. + * @param name The round's name. + * @return Nothing. + */ +async function openRound(page: Page, name: string): Promise { + await gotoAppRoute(page, '/confirmation-rounds') + await dismissSupportDialog(page) + const row = page.getByRole('row').filter({ hasText: name }) + await expect(row).toBeVisible({ timeout: 30000 }) + await row.getByText(name).first().click() + await expect(page).toHaveURL(/\/confirmation-rounds\/[^/]+$/, { timeout: 30000 }) + await dismissSupportDialog(page) +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + + const me = await apiCtx.get('/index.php/apps/stackiq/api/me') + if (me.ok()) { + previousActive = (await me.json())?.organisations?.active?.uuid ?? '' + } + + ids.org = await seed('organization', { + name: municipality, + type: 'Municipality', + status: 'Active', + contactsUid: `${RUN_ID}-confirming-municipality`, + }) + ids.lateOrg = await seed('organization', { + name: lateMunicipality, + type: 'Municipality', + status: 'Active', + contactsUid: `${RUN_ID}-late-municipality`, + }) + await awaitOrganisation(ids.org) + const join = await apiCtx.post(`${OR_API}/organisations/${ids.org}/join`, { data: {} }) + if (!join.ok() && join.status() !== 409) { + console.warn(`join ${ids.org} returned ${join.status()}`) + } + const active = await apiCtx.post(`${OR_API}/organisations/${ids.org}/set-active`, { data: {} }) + expect(active.ok(), `set-active returned ${active.status()}`).toBe(true) + + // The owner: a contact person whose contactsUid is the administrator's + // system address book entry, so it resolves to that Nextcloud user. + ids.owner = await seed('contactPerson', { + contactsUid: NC_ADMIN_USER, + role: `${RUN_ID} application owner`, + organization: ids.org, + }) + + for (const name of ownedApps) { + const module = await seed('module', { name }) + usageIds.push(await seed('usage', { + consumer: ids.org, + module, + status: 'In production', + businessOwner: ids.owner, + })) + } + const ownerlessModule = await seed('module', { name: ownerlessApp }) + ids.ownerlessUsage = await seed('usage', { consumer: ids.org, module: ownerlessModule, status: 'In production' }) + + const lateModule = await seed('module', { name: lateApp }) + ids.lateUsage = await seed('usage', { + consumer: ids.lateOrg, + module: lateModule, + status: 'In production', + businessOwner: ids.owner, + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const row of await findAll(apiCtx, cfg.register, 'attestationRound', RUN_ID)) { + const id = idOf(row) + if (id && JSON.stringify(row).includes(RUN_ID) && !rounds.includes(id)) { + rounds.push(id) + } + } + for (const roundId of rounds) { + for (const request of await requestsOf(roundId)) { + const id = idOf(request) + if (id) { + await deleteObject(apiCtx, cfg.register, 'attestationRequest', id) + } + } + await deleteObject(apiCtx, cfg.register, 'attestationRound', roundId) + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + if (previousActive !== '') { + await apiCtx.post(`${OR_API}/organisations/${previousActive}/set-active`, { data: {} }) + } + await apiCtx.dispose() +}) + +// @e2e owner-attestation::a-round-over-the-applications-in-use +test('a round over the applications in use sends four requests and names the usage without an owner', async ({ + page, +}) => { + await gotoAppRoute(page, '/confirmation-rounds') + await dismissSupportDialog(page) + await page.getByRole('button', { name: 'Start round' }).first().click() + const dialog = page.getByRole('dialog').filter({ hasText: 'Start confirmation round' }) + await expect(dialog).toBeVisible({ timeout: 30000 }) + + await dialog.getByLabel('Name', { exact: true }).first().fill(roundName) + await dialog.getByRole('combobox', { name: 'Organisation' }).fill(municipality) + await page.locator('.vs__dropdown-option', { hasText: municipality }).first().click() + await dialog.getByRole('combobox', { name: 'Entries to confirm' }).click() + await page.getByRole('option', { name: 'Applications in use', exact: true }).first().click() + await dialog.getByLabel('Deadline', { exact: true }).first().fill(isoDay(14)) + await dialog.getByRole('button', { name: 'Start round', exact: true }).click() + + await expect(dialog).toContainText('Requests sent: 4', { timeout: 30000 }) + const ownerless = dialog.locator('section').filter({ has: page.getByRole('heading', { name: 'Entries without an owner' }) }) + await expect(ownerless).toContainText(entryLabel(ownerlessApp, ids.ownerlessUsage)) + for (const [index, name] of ownedApps.entries()) { + await expect(ownerless).not.toContainText(entryLabel(name, usageIds[index])) + } + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + + await openRound(page, roundName) + const pending = catalogCard(page, 'Pending') + await expect(pending).toBeVisible({ timeout: 30000 }) + await expect(pending.getByRole('row').filter({ hasText: NC_ADMIN_USER })).toHaveCount(4, { timeout: 30000 }) + await expect(page.getByText('Entries without an owner').first()).toBeVisible() +}) + +// @e2e owner-attestation::confirming-from-the-list +test('confirming a request from My confirmation requests marks it confirmed and dates the usage', async ({ + page, +}) => { + const label = entryLabel(ownedApps[0], usageIds[0]) + await gotoAppRoute(page, '/my-confirmations') + await dismissSupportDialog(page) + const row = page.getByRole('row').filter({ hasText: label }).first() + await expect(row).toBeVisible({ timeout: 30000 }) + await row.getByRole('button', { name: 'Actions' }).first().click() + await page.locator('.v-popper__popper--shown').last().getByRole('menuitem', { name: 'Confirm', exact: true }).first().click() + // The list shows pending requests only, so the confirmed one leaves it. + await expect(page.getByRole('row').filter({ hasText: label })).toHaveCount(0, { timeout: 30000 }) + + await openRound(page, roundName) + const confirmed = catalogCard(page, 'Confirmed') + await expect(confirmed.getByRole('row').filter({ hasText: label })).toBeVisible({ timeout: 30000 }) + await expect(catalogCard(page, 'Pending').getByRole('row').filter({ hasText: label })).toHaveCount(0) + + await gotoAppRoute(page, `/gebruik/${usageIds[0]}`) + await dismissSupportDialog(page) + const today = new Date() + const day = String(today.getDate()) + const month = String(today.getMonth() + 1) + const year = String(today.getFullYear()) + const pad = (value: string) => value.padStart(2, '0') + const formats = [ + `${year}-${pad(month)}-${pad(day)}`, + `${pad(day)}-${pad(month)}-${year}`, + `${day}-${month}-${year}`, + `${month}/${day}/${year}`, + `${pad(day)}/${pad(month)}/${year}`, + `${day}/${month}/${year}`, + today.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }), + today.toLocaleDateString('en-GB', { year: 'numeric', month: 'short', day: 'numeric' }), + today.toLocaleDateString('en-GB', { year: 'numeric', month: 'long', day: 'numeric' }), + today.toLocaleDateString('nl-NL', { year: 'numeric', month: 'long', day: 'numeric' }), + ] + const lastConfirmed = page.getByText('Last confirmed', { exact: true }).first() + await expect(lastConfirmed).toBeVisible({ timeout: 30000 }) + await expect(lastConfirmed.locator('xpath=..')).toContainText(new RegExp(formats.map(escapeRegExp).join('|')), { timeout: 30000 }) +}) + +// @e2e owner-attestation::following-up-overdue-owners +test('a round past its deadline shows its one overdue request with the owner', async ({ + page, +}) => { + const started = await apiCtx.post('/index.php/apps/stackiq/api/attestation-rounds', { + data: { + organisation: ids.lateOrg, + scopeSchema: 'usage', + deadline: isoDay(-1), + name: lateRoundName, + }, + }) + expect(started.ok(), `starting the round returned ${started.status()}`).toBe(true) + const roundId = String((await started.json())?.round?.id ?? '') + expect(roundId, 'the round endpoint returned no round id').not.toBe('') + rounds.push(roundId) + + // What the daily overdue job does with a pending request past its deadline. + const requests = await requestsOf(roundId) + expect(requests).toHaveLength(1) + const moved = await apiCtx.patch( + `${OR_API}/objects/${cfg.register}/attestationRequest/${idOf(requests[0])}`, + { data: { status: 'overdue' } }, + ) + expect(moved.ok(), `marking the request overdue returned ${moved.status()}`).toBe(true) + + await openRound(page, lateRoundName) + const overdue = catalogCard(page, 'Overdue') + await expect(overdue).toBeVisible({ timeout: 30000 }) + const rows = overdue.getByRole('row').filter({ hasText: NC_ADMIN_USER }) + await expect(rows).toHaveCount(1, { timeout: 30000 }) + await expect(rows.first()).toContainText(entryLabel(lateApp, ids.lateUsage)) + await expect(catalogCard(page, 'Pending').getByRole('row').filter({ hasText: NC_ADMIN_USER })).toHaveCount(0) +}) diff --git a/tests/e2e/workflows/portfolio-report.spec.ts b/tests/e2e/workflows/portfolio-report.spec.ts new file mode 100644 index 000000000..83382808a --- /dev/null +++ b/tests/e2e/workflows/portfolio-report.spec.ts @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Portfolio report: a usage's row shows its yearly cost from its contracts + * next to its business value and risk score. + * + * Seeds an organisation, an application, a usage scored business value 4, + * technical fit 3 and risk 2, and a contract of 10,000 euro a year on that + * usage, all carrying this run's RUN_ID, through the objects API, and removes + * exactly those rows afterwards. The row shows the scores as + * "value / fit / risk" and the cost in nl-NL euro formatting. The CSV columns + * are covered by tests/Unit/Service/PortfolioReportServiceTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/capability-rows-the-code-does-not-yet-meet/specs/application-value-assessment/spec.md#requirement-the-portfolio-report-shows-each-usage-s-yearly-cost-beside-its-value-and-risk-scores-req-clr-016 + */ +import type { APIRequestContext } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute } from './_ui.ts' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const organisation = `${RUN_ID} municipality` +const application = `${RUN_ID} case application` + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + ids.org = await seed('organization', { name: organisation, type: 'Municipality' }) + ids.module = await seed('module', { name: application }) + ids.usage = await seed('usage', { + consumer: ids.org, + module: ids.module, + status: 'In production', + timeClassification: 'Invest', + businessValue: 4, + technicalFit: 3, + riskScore: 2, + scoredOn: '2026-10-01', + }) + await seed('catalogContract', { + usage: ids.usage, + contractNumber: `${RUN_ID}-1`, + contractType: 'Licence', + startDate: '2026-01-01', + cost: 10000, + costPeriod: 'Annually', + status: 'Active', + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e application-value-assessment::an-information-manager-compares-cost-with-value +test('a usage row shows 10,000 euro a year beside business value 4 and risk 2', async ({ + page, +}) => { + await gotoAppRoute(page, '/portfolio-report') + await dismissSupportDialog(page) + await page.getByLabel('Organisation').first().click() + await page.locator('.vs__dropdown-option', { hasText: organisation }).first().click() + + const row = page.getByTestId('pr-row').filter({ hasText: application }) + await expect(row).toBeVisible({ timeout: 30000 }) + // Business value / technical fit / risk score. + await expect(row).toContainText('4 / 3 / 2') + await expect(row).toContainText('10.000') +}) diff --git a/tests/e2e/workflows/process-mapping.spec.ts b/tests/e2e/workflows/process-mapping.spec.ts new file mode 100644 index 000000000..3e246c398 --- /dev/null +++ b/tests/e2e/workflows/process-mapping.spec.ts @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. +/** + * Business process mapping: a process recorded with three ordered steps, the + * steps an application in use supports listed on its usage page, a step + * marked as not compliant, the steps drawn as a read-only flow, and a process + * taken into use through its lifecycle. + * + * Seeds an organisation, an application, a usage, two processes and four + * steps carrying this run's RUN_ID through the objects API (the call the Add + * forms make), and removes exactly those rows and the process and steps the + * record test creates afterwards. The flow mapping and the hidden-usage count + * are covered by tests/vitest/processStepFlow.spec.js and + * tests/vitest/processStepUsages.spec.js, the schema rules by + * tests/Unit/Settings/ProcessMappingRegisterShapeTest.php. + * + * Written from the change's scenarios; not yet run against a live instance. + * + * @spec openspec/changes/architecture-process-mapping/specs/business-process-mapping/spec.md#requirement-req-bpm-001-a-municipal-information-manager-shall-record-a-business-process-with-ordered-steps + * @spec openspec/changes/architecture-process-mapping/specs/business-process-mapping/spec.md#requirement-req-bpm-002-a-step-shall-name-the-applications-in-use-that-support-it + * @spec openspec/changes/architecture-process-mapping/specs/business-process-mapping/spec.md#requirement-req-bpm-003-a-step-shall-carry-a-risk-level-and-a-compliance-check + * @spec openspec/changes/architecture-process-mapping/specs/business-process-mapping/spec.md#requirement-req-bpm-004-the-process-page-shall-show-the-steps-as-a-read-only-flow + * @spec openspec/changes/architecture-process-mapping/specs/business-process-mapping/spec.md#requirement-req-bpm-005-a-process-shall-move-through-a-declared-lifecycle-and-may-follow-a-gemma-reference-process + */ +import type { APIRequestContext, Locator, Page } from '@playwright/test' +import type { VoorzieningenConfig } from './_fixtures.ts' + +import { expect, test } from '@playwright/test' +import { + createObject, + deleteObject, + findAll, + newApiContext, + resolveConfig, + RUN_ID, +} from './_fixtures.ts' +import { dismissSupportDialog, gotoAppRoute, openCreateDialog } from './_ui.ts' + +const OR = '/index.php/apps/openregister/api/objects' + +let apiCtx: APIRequestContext +let cfg: VoorzieningenConfig +const seeded: Array<[string, string]> = [] +const ids: Record = {} +const organisation = `${RUN_ID} municipality` +const application = `${RUN_ID} service desk application` +const permitProcess = `${RUN_ID} handling an application` +const draftProcess = `${RUN_ID} handling a request` +const intake = `${RUN_ID} intake` +const review = `${RUN_ID} check requirements` +const decide = `${RUN_ID} decide` +const archive = `${RUN_ID} archive the file` + +/** + * Create a row and remember it for cleanup. + * + * @param schema The schema slug. + * @param data The object. + * @return The new id. + */ +async function seed(schema: string, data: Record): Promise { + const id = await createObject(apiCtx, cfg.register, schema, data) + seeded.push([schema, id]) + return id +} + +/** + * The id of an object, whether given as a row or as an object. + * + * @param row The row. + * @return The id, or an empty string. + */ +function idOf(row: Record): string { + return String(row.id ?? (row as { '@self'?: { id?: string } })['@self']?.id ?? '') +} + +/** + * Pick an option in a select of an open form, named by its label. + * + * @param page The page. + * @param dialog The form dialog. + * @param label The field label. + * @param option The option text. + * @return Resolves once picked. + */ +async function pick(page: Page, dialog: Locator, label: string, option: RegExp): Promise { + await dialog.getByLabel(label, { exact: true }).first().click() + await page.getByRole('option', { name: option }).first().click() +} + +/** + * The open form dialog. + * + * @param page The page. + * @return The dialog, once visible. + */ +async function openDialog(page: Page): Promise { + const dialog = page.locator('[role="dialog"], .modal-container').first() + await dialog.waitFor({ state: 'visible', timeout: 15000 }) + return dialog +} + +test.beforeAll(async () => { + apiCtx = await newApiContext() + cfg = await resolveConfig(apiCtx) + ids.org = await seed('organization', { name: organisation, type: 'Municipality' }) + ids.module = await seed('module', { name: application }) + ids.usage = await seed('usage', { + consumer: ids.org, + module: ids.module, + status: 'In production', + startDateInProduction: '2022-01-01', + }) + ids.permit = await seed('process', { name: permitProcess, status: 'active', tags: [RUN_ID] }) + ids.intake = await seed('processStep', { + process: ids.permit, + name: intake, + stepType: 'event', + position: 1, + usages: [ids.usage], + riskLevel: 'low', + complianceCheck: 'compliant', + }) + ids.review = await seed('processStep', { + process: ids.permit, + name: review, + stepType: 'task', + position: 2, + usages: [], + riskLevel: 'medium', + complianceCheck: 'not checked', + }) + ids.decide = await seed('processStep', { + process: ids.permit, + name: decide, + stepType: 'decision', + position: 3, + usages: [], + riskLevel: 'high', + complianceCheck: 'not compliant', + complianceNote: `${RUN_ID} the decision is not archived on time.`, + }) + ids.draft = await seed('process', { name: draftProcess, status: 'draft' }) + ids.archive = await seed('processStep', { + process: ids.draft, + name: archive, + stepType: 'task', + position: 1, + riskLevel: 'not assessed', + complianceCheck: 'not checked', + }) +}) + +test.afterAll(async () => { + if (!apiCtx) return + for (const schema of ['processStep', 'process']) { + for (const row of await findAll(apiCtx, cfg.register, schema, RUN_ID)) { + const id = idOf(row) + if (id && !seeded.some(([, seededId]) => seededId === id)) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + } + } + for (const [schema, id] of seeded.reverse()) { + await deleteObject(apiCtx, cfg.register, schema, id) + } + await apiCtx.dispose() +}) + +// @e2e business-process-mapping::an-information-manager-adds-a-process-with-three-steps +test('a new process with three steps lists them in position order and reads draft', async ({ page }) => { + const name = `${RUN_ID} handling a report` + const steps = [`${RUN_ID} register`, `${RUN_ID} assess`, `${RUN_ID} complete`] + await gotoAppRoute(page, '/processen') + await dismissSupportDialog(page) + + const create = await openCreateDialog(page, /Add/) + await create.getByLabel('Name', { exact: true }).fill(name) + await create.getByRole('button', { name: /Save|Create/ }).last().click() + await expect(create).toBeHidden({ timeout: 30000 }) + + await page.getByRole('row').filter({ hasText: name }).first().click() + await expect(page).toHaveURL(/\/processen\//, { timeout: 30000 }) + + for (const [index, step] of steps.entries()) { + await page.getByRole('button', { name: 'Add step', exact: true }).first().click() + const dialog = await openDialog(page) + await dialog.getByLabel('Name', { exact: true }).fill(step) + await dialog.getByLabel('Position', { exact: true }).fill(String(index + 1)) + await dialog.getByRole('button', { name: /Save|Create/ }).last().click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + await expect(page.getByRole('row').filter({ hasText: step })).toBeVisible({ timeout: 30000 }) + } + + const listed = (await page.getByRole('row').filter({ hasText: `${RUN_ID} ` }).allInnerTexts()) + .map((text) => steps.findIndex((step) => text.includes(step))) + .filter((index) => index >= 0) + expect(listed).toEqual([0, 1, 2]) + + await gotoAppRoute(page, `/processen?_search=${encodeURIComponent(name)}`) + const row = page.getByRole('row').filter({ hasText: name }) + await expect(row).toContainText(/draft/i, { timeout: 30000 }) +}) + +// @e2e business-process-mapping::an-application-owner-sees-which-process-steps-their-application-supports +test('the usage page lists the step it supports with its process and opens the step page', async ({ page }) => { + await gotoAppRoute(page, `/gebruik/${ids.usage}`) + await dismissSupportDialog(page) + await expect(page.getByText('Process steps this application supports').first()).toBeVisible({ timeout: 30000 }) + const row = page.getByRole('row').filter({ hasText: intake }) + await expect(row).toBeVisible({ timeout: 30000 }) + await expect(row).toContainText(permitProcess, { timeout: 30000 }) + await expect(page.getByRole('row').filter({ hasText: review })).toHaveCount(0) + + await row.click() + await expect(page).toHaveURL(new RegExp(`/processtappen/${ids.intake}`), { timeout: 30000 }) + await expect(page.getByTestId('process-step-usages')).toContainText(application, { timeout: 30000 }) +}) + +// @e2e business-process-mapping::an-information-manager-marks-a-step-as-not-compliant +test('a step edited to high risk and not compliant shows both on the process page', async ({ page }) => { + const note = `${RUN_ID} the requirements are not checked against the regulation.` + await gotoAppRoute(page, `/processtappen/${ids.review}`) + await dismissSupportDialog(page) + await expect(page.getByText(review).first()).toBeVisible({ timeout: 30000 }) + + await page.getByRole('button', { name: 'Edit', exact: true }).first().click() + const dialog = await openDialog(page) + await pick(page, dialog, 'Risk level', /^high$/i) + await pick(page, dialog, 'Compliance check', /^not compliant$/i) + await dialog.getByLabel('Compliance note', { exact: true }).fill(note) + await dialog.getByRole('button', { name: /save/i }).last().click() + await expect(dialog).toBeHidden({ timeout: 30000 }) + await expect(page.getByText(note).first()).toBeVisible({ timeout: 30000 }) + + const res = await apiCtx.get(`${OR}/${cfg.register}/processStep/${ids.review}`) + expect(await res.json()).toMatchObject({ riskLevel: 'high', complianceCheck: 'not compliant', complianceNote: note }) + + await gotoAppRoute(page, `/processen/${ids.permit}`) + const row = page.getByRole('row').filter({ hasText: review }) + await expect(row).toContainText(/high/i, { timeout: 30000 }) + await expect(row).toContainText(/not compliant/i) +}) + +// @e2e business-process-mapping::a-reader-sees-the-flow-of-a-process +test('the process page draws three steps in position order and marks the decision step', async ({ page }) => { + await gotoAppRoute(page, `/processen/${ids.permit}`) + await dismissSupportDialog(page) + const flow = page.getByTestId('process-step-flow') + await expect(flow.locator('.vue-flow__node')).toHaveCount(3, { timeout: 30000 }) + await expect(flow.locator('.vue-flow__edge')).toHaveCount(2) + + const node = flow.locator('.vue-flow__node').filter({ hasText: decide }) + await expect(node).toContainText('Risk: High') + await expect(node).toContainText('Compliance: Not compliant') + await expect(node).toContainText('Needs attention') + await expect(node.locator('.process-step-flow__node--attention')).toHaveCount(1) + await expect(flow.locator('.vue-flow__node').filter({ hasText: intake })).not.toContainText('Needs attention') +}) + +// @e2e business-process-mapping::an-owner-activates-a-process +test('applying Activate makes the process active and the History tab shows it', async ({ page }) => { + await gotoAppRoute(page, `/processen/${ids.draft}`) + await dismissSupportDialog(page) + await expect(page.getByText(draftProcess).first()).toBeVisible({ timeout: 30000 }) + + await page.getByTestId('cn-lifecycle-action-activate').click() + await expect(page.getByTestId('cn-lifecycle-actions-error')).toHaveCount(0) + await expect(page.getByText('Active', { exact: true }).first()).toBeVisible({ timeout: 30000 }) + await expect(page.getByTestId('cn-lifecycle-action-activate')).toHaveCount(0) + + const res = await apiCtx.get(`${OR}/${cfg.register}/process/${ids.draft}`) + expect((await res.json()).status).toBe('active') + + await page.getByRole('tab', { name: 'History' }).click() + await expect(page.getByRole('tabpanel').filter({ hasText: /active/i }).first()).toBeVisible({ timeout: 30000 }) +})