import { APIRequestContext, expect } from '@playwright/test'; import type { O2CPersona } from './modules/o2c/labels'; import type { R2RPersona } from './modules/r2r/labels'; import type { A2RPersona } from './modules/a2r/labels'; import type { EXPPersona } from './modules/exp/labels'; import type { SCMPersona } from './modules/scm/labels'; import type { P2MPersona } from './modules/p2m/labels'; import type { PPMPersona } from './modules/ppm/labels'; import type { SCPPersona } from './modules/scp/labels'; import type { HCMPersona } from './modules/hcm/labels'; import type { CXPersona } from './modules/cx/labels'; /** P2P personas plus each module pack's own (gl_accountant / integration_user are shared across packs). */ export type Persona = O2CPersona | R2RPersona | A2RPersona | EXPPersona | SCMPersona | P2MPersona | PPMPersona | SCPPersona | HCMPersona | CXPersona | 'requester' | 'approver_l1' | 'approver_l2' | 'buyer' | 'po_approver' | 'po_approver_l2' | 'receiver' | 'ap_specialist' | 'ap_supervisor' | 'invoice_approver' | 'payments_user' | 'gl_accountant' | 'supplier_admin' | 'integration_user' | 'read_only' | 'contract_author' | 'contract_author_bu2' | 'legal_reviewer' | 'category_manager' | 'supplier_user_a'; /** Seeded synthetic master data in the MOCK app (after /api/test/reset). Never pod values. */ export const MOCK = { bu: 'US1', otherBu: 'UK1', location: 'MOCK-HQ-DOCK', supplier: 'Acme Office Supplies (MOCK)', withholdingSupplier: 'Withholding Services (MOCK)', foreignSupplier: 'Euro Parts GmbH (MOCK)', catalogItem: 'MOCK-PAPER-A4', agreementItem: 'MOCK-TONER-AGR', bypassAgreementItem: 'MOCK-PENS-AGR', agreement: 'BPA-M001', bypassAgreement: 'BPA-M002', account: '01-000-6100-0000', altAccount: '01-000-6200-0000', disabledAccount: '01-000-9999-0000', distributionSet: 'ZZ_P2P_DIST_60_40', bank: 'MOCK-BANK-MAIN', lowBank: 'MOCK-BANK-LOW', isoPpp: 'MOCK ISO20022 PPP', checkPpp: 'MOCK CHECK PPP', excludedSource: 'MOCK_EDI', restBase: '/fscmRestApi/resources/11.13.18.05', }; let n = 0; /** * Authorization-denied check (QA review 9 Oct 2026): the call must be refused as an authorization failure, i.e. HTTP 403 or 401 * with a denial message. 5xx, 404 or a validation 400/409 do NOT count as "refused". Pod responses may word the message differently. */ export function expectDenied(r: { status: number; body: any }, what: string, message: RegExp = /not authori[sz]ed|cannot|segregation of duties|forbidden|denied|no access/i) { expect([401, 403], `${what}: authorization denial (got ${r.status}: ${JSON.stringify(r.body)})`).toContain(r.status); expect(String(r.body?.message ?? r.body?.detail ?? r.body ?? ''), `${what}: denial message`).toMatch(message); } /** Unique synthetic identifiers per run (S4: isolated data). */ export function unique(prefix: string) { n += 1; return `${prefix}-${Date.now().toString(36).toUpperCase()}-${n}`; } /** Client for the MOCK app's internal /api (data recipes) and its Fusion-style REST facade (assertions). */ export class MockApi { constructor(private request: APIRequestContext) {} async reset() { const r = await this.request.post('/api/test/reset'); expect(r.ok(), 'mock reset').toBeTruthy(); } async setConfig(patch: Record) { await this.ok('read_only', 'PATCH', '/test/config', patch); } async seed(): Promise<{ otherBuReq: string; otherBuPo: string }> { return this.ok('read_only', 'GET', '/test/seed'); } async call(as: Persona, method: string, path: string, data?: unknown, base = '/api') { const r = await this.request.fetch(`${base}${path}`, { method, data, headers: { 'X-Mock-Role': as } }); const text = await r.text(); let body: any = text; try { body = JSON.parse(text); } catch { /* not JSON */ } return { status: r.status(), body }; } async ok(as: Persona, method: string, path: string, data?: unknown) { const res = await this.call(as, method, path, data); expect(res.status, `${method} ${path} as ${as}: ${JSON.stringify(res.body)}`).toBeLessThan(300); return res.body; } /** Fusion-style REST facade call (MOCK.restBase). */ rest(as: Persona, method: string, path: string, data?: unknown) { return this.call(as, method, path, data, MOCK.restBase); } async restOne(as: Persona, resource: string, field: string, value: string) { const r = await this.rest(as, 'GET', `/${resource}?q=${encodeURIComponent(`${field}='${value}'`)}`); expect(r.status).toBe(200); return r.body as { items: any[]; count: number }; } async supplierId(name = MOCK.supplier): Promise { const { items } = await this.ok('read_only', 'GET', '/suppliers'); const s = items.find((x: any) => x.name === name); expect(s, `seeded supplier ${name}`).toBeTruthy(); return s.id; } /** Approve every open approval task on a document, in routing order (recipe helper). */ async approveAll(docId: string, kind: 'requisitions' | 'purchaseOrders' | 'invoices') { for (let i = 0; i < 5; i++) { const { items } = await this.ok('read_only', 'GET', '/tasks'); const t = items.find((x: any) => x.docId === docId && x.status === 'OPEN' && x.kind === 'APPROVAL'); if (!t) return; await this.ok(t.assignee, 'POST', `/${kind}/${docId}/approve`, {}); } } // ---- data recipes (mock equivalents of tests/data-recipes/DR-*) ---- async submittedRequisition(o: { itemCode?: string; quantity?: number; as?: Persona } = {}) { const r = await this.ok(o.as ?? 'requester', 'POST', '/requisitions', { bu: MOCK.bu, description: unique('Synthetic req'), deliverToLocation: MOCK.location, lines: [{ itemCode: o.itemCode ?? MOCK.catalogItem, quantity: o.quantity ?? 10 }] }); return this.ok(o.as ?? 'requester', 'POST', `/requisitions/${r.id}/submit`); } /** DR-REQ-001: approved requisition line not on any PO. */ async approvedRequisition(o: { itemCode?: string; quantity?: number } = {}) { const r = await this.submittedRequisition(o); await this.approveAll(r.id, 'requisitions'); return this.ok('read_only', 'GET', `/requisitions/${r.id}`); } /** DR-PO-001/002/006: open (approved) PO for the seeded supplier. */ async openPo(o: { matchType?: '2-WAY' | '3-WAY'; quantity?: number; unitPrice?: number } = {}) { const po = await this.ok('buyer', 'POST', '/purchaseOrders', { bu: MOCK.bu, supplierId: await this.supplierId(), matchType: o.matchType ?? '3-WAY', lines: [{ description: 'A4 copy paper, box (MOCK)', quantity: o.quantity ?? 10, unitPrice: o.unitPrice ?? 25 }] }); await this.ok('buyer', 'POST', `/purchaseOrders/${po.id}/submit`); await this.approveAll(po.id, 'purchaseOrders'); const out = await this.ok('read_only', 'GET', `/purchaseOrders/${po.id}`); expect(out.status).toBe('OPEN'); return out; } async receive(poId: string, quantity: number) { return this.ok('receiver', 'POST', '/receipts', { poId, lines: [{ lineNum: 1, quantity }] }); } /** DR-RCV-001 / DR-PO-006: open 3-way PO received in full or partially. */ async receivedPo(o: { quantity?: number; unitPrice?: number; received?: number } = {}) { const po = await this.openPo({ matchType: '3-WAY', quantity: o.quantity, unitPrice: o.unitPrice }); await this.receive(po.id, o.received ?? po.lines[0].quantity); return po; } async poInvoice(poId: string, o: { quantity: number; unitPrice: number; validate?: boolean; number?: string; amount?: number }) { const inv = await this.ok('ap_specialist', 'POST', '/invoices', { poId, invoiceNumber: o.number ?? unique('INV'), amount: o.amount, lines: [{ poLineNum: 1, quantity: o.quantity, unitPrice: o.unitPrice }] }); return o.validate === false ? inv : this.ok('ap_specialist', 'POST', `/invoices/${inv.id}/validate`); } /** DR-INV-002: non-PO invoice using the 60/40 distribution set. */ async nonPoInvoice(o: { amount?: number; validate?: boolean; source?: string; supplier?: string } = {}) { const inv = await this.ok('ap_specialist', 'POST', '/invoices', { supplierId: await this.supplierId(o.supplier), invoiceNumber: unique('INV'), amount: o.amount ?? 500, distributionSet: MOCK.distributionSet, source: o.source }); return o.validate === false ? inv : this.ok('ap_specialist', 'POST', `/invoices/${inv.id}/validate`); } /** DR-INV-001: validated 3-way matched invoice 10 x 25.00, no holds. */ async validatedInvoice() { const po = await this.receivedPo(); return this.poInvoice(po.id, { quantity: 10, unitPrice: 25 }); } /** DR-INV-003: invoice on price hold (26.26 vs 25.00 at 5% tolerance). */ async heldInvoice() { const po = await this.receivedPo(); const inv = await this.poInvoice(po.id, { quantity: 10, unitPrice: 26.26 }); expect(inv.holds.map((h: any) => h.code)).toEqual(['PRICE']); return inv; } }