import * as fs from 'fs'; import * as path from 'path'; import YAML from 'yaml'; import { approvalRef, expect, paymentRef, test, type DocKind, type FusionDocs } from './fixtures'; import { activeHolds, closeAction, invoiceAmountProblems, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, orderCloseable, orderReceivable, orderStatus, paymentProblems, paymentTypeKey, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation, type PaymentExpectation } from './rest'; import { invoiceApprovalStatus, transactionAmountProblems, type TransactionExpectation } from './rest'; import { expectRefusal, FusionRefused } from './refusal'; import { apInvoiceFiles, arTransactionFiles, fbdiDate, importBody, importsAllowed, IMPORTS_REFUSED } from './interfaces'; import { apDataSets, fusionDate, NO_SUCH_JOURNAL_CATEGORY, podCandidates, podToday, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui'; /* * Step runner: executes a scenario written as plain steps in tests/cases/.yaml (runner: steps), with no * hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright * runs them the same way every time. Unknown actions fail the step with a clear message, never guess. * * Step fields: action, field, value, expected (shown in the report and the live view). * Values may use {{pod..}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}}, * {{tv.}} and {{saved.}} (a value remembered by an earlier `remember` step). * * Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not * break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice, * expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario * per area (tests/cases/CANARY-.yaml) runs each of them once before a run, to prove they still work on the pod. * Purchasing: create_requisition, expect_requisition, cancel_requisition, create_purchase_order, submit_purchase_order, * find_purchase_order, expect_purchase_order, cancel_purchase_order (extra fields quantity, price). General Ledger: * create_journal, post_journal, find_journal, expect_journal, reverse_journal (extra field posted). Receivables: * create_transaction, complete_transaction, find_transaction, expect_transaction, create_receipt, find_receipt, * expect_receipt (extra field applies_to: the transaction a receipt is applied to). Receiving: create_receipt_for_order and * expect_receipt_of_order (extra fields applies_to: the order, and quantity), close_purchase_order (value: how). create_invoice and expect_invoice also * take invoice_type (Standard, Credit memo, Debit memo, Prepayment) and payment_method (the pod's: Check, Electronic, Wire); * expect_invoice also checks approval_status (Not required, Required ...) and validation_status (Validated, Not validated, * Needs revalidation). * Payments (scenario-only, never in a canary): create_payment (a quick payment of a validated invoice: applies_to = the invoice's * remembered name, payment_method, payment_type Quick; name = what to remember the payment number as, payment_number), * find_payment, expect_payment (status, amount, amount_at_least, payment_method, payment_type), void_payment. A payment the * test leaves is voided by the clean-up, before the invoice is cancelled. * initiate_approval (scenario-only: name = the invoice's remembered name) sends a validated invoice for approval (Invoice Actions > * Approval > Initiate) and checks Fusion shows the approval Initiated; the clean-up withdraws it before the invoice is cancelled. * Subledger accounting (scenario-only, never in a canary; the General Ledger's journals of source Payables and Receivables come from it): * account_invoice (a validated invoice: Invoice Actions > Account in Draft, or Post to Ledger with mode final; expect_invoice then checks * accounting_status Draft / Accounted) and account_transaction (a completed transaction: Actions > Account in Draft or Post to Ledger, * checked in View Accounting, since REST has no accounting status for a transaction), with incomplete_transaction to take a completed * transaction back to Incomplete. Draft accounting changes no ledger balance; the invoice clean-up (cancel) is unchanged by it. * Interfaces (scenario-only, never in a canary; they write through Fusion's ERP Integration REST service, so they need REST and the pod's * "allow imports" setting, FPT_ALLOW_IMPORTS=1): import_payables_invoice (a FBDI file through Payables invoice import; source = the * invoice source, External by default) and import_receivables_transaction (a FBDI file through AutoInvoice; transaction_source = an import * source of the pod, transaction_type). Each remembers the number of the document the import created (name), checked by expect_invoice * (source) or expect_transaction (transaction_source) like any other; the clean-up cancels an imported invoice, an imported * transaction that is complete is listed for a person to credit. * * Negative scenarios: `refused: ""` on a step says Fusion must say no to it. The step passes only when the action failed * BECAUSE Fusion refused (its message window, error note or field message holds one of the |-separated words, any case); it fails * when Fusion takes the action ("Fusion took X that it should refuse"), when the action fails for the runner's own reason (a locator * timeout, a page that did not open), or when Fusion refuses with other words (refusal.ts). The runner's own pre-checks (the sign * of an invoice or transaction amount) are not made on a refused step, so Fusion's validation is what is tested. A document the * refused step tried to make is registered for clean-up before the save, as always, and must not exist in Fusion afterwards. * Fields: leave_out (create_invoice: supplier, number, amount; create_journal: account = the credit line's; create_transaction: * customer, lines) leaves that part empty; credit_amount (create_journal) makes the credit differ from the debit (unbalanced). * expect_unavailable (field = menu, value = entry, or entries separated by |): Fusion greys the entry out or does not list it. */ export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[]; lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean; quantity?: string | number; price?: string | number; posted?: boolean; applies_to?: string; invoice_type?: string; payment_method?: string; category?: string; source?: string; payment_type?: string; approval_status?: string; validation_status?: string; accounting_status?: string; mode?: string; refused?: string; leave_out?: string | string[]; credit_amount?: string | number } export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record; canary?: boolean } // a canary (tests/cases/CANARY-.yaml): create_invoice tries the pod's data sets in turn const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases'); /** * The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds * that id (the co-worker's staging folder for drafts), else from the script library tests/cases/. */ export function stepCaseFile(id: string, dir?: string): string { for (const d of [dir, process.env.FPT_STEPS_DIR]) { if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`); } return path.join(CASES_DIR, `${id}.yaml`); } export function loadStepCase(id: string, dir?: string): StepCase { const f = stepCaseFile(id, dir); const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase; if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`); return c; } type Ctx = { ui: FusionUi; c: StepCase; saved: Record; uniques: Record; track: (n: string) => string; imported: Set; // the invoices an import made (import_payables_invoice): validate_invoice opens them from Manage Invoices first chosen: Record; // the pod value Fusion accepted, per "area.key", used again for the rest of the test orderTags: Record; // the test's tag of each purchase order made, by its number (its receipt names it for clean-up) attempt?: { what: string; exists: () => Promise }; // a document a refused create_ step tried to make: it must not exist afterwards rest: FusionRest; // Fusion REST, for the business actions that check what the screens did docs: FusionDocs }; // Purchasing and General Ledger test documents, cleaned up after the test function fill(raw: unknown, ctx: Ctx): string { return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => { const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key); if (pod) return ctx.chosen[`${pod[1]}.${pod[2]}`.toLowerCase()] ?? podValue(pod[1], pod[2]); // the pod's own test data if (key === 'today') return fusionDate(); if (key.startsWith('unique:')) { const t = key.slice(7); return (ctx.uniques[t] ??= testNumber(t)); } if (key.startsWith('tv.')) return String(ctx.c.test_values?.[key.slice(3)] ?? ''); if (key.startsWith('saved.')) return ctx.saved[key.slice(6)] ?? ''; throw new Error(`unknown placeholder {{${key}}}`); }); } /** Enter a value. A value that is exactly one pod test data placeholder ({{pod.ap.business_unit}}) is tried with each * value the pod has for it, in order, until Fusion accepts one (a business unit this user may use, a source that * exists on this pod): the first that works is kept for the rest of the test and remembered for the next run. */ async function putValue(s: Step, ctx: Ctx, put: (v: string) => Promise): Promise { const ref = /^\s*\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}\s*$/i.exec(String(s.value ?? '')); const key = ref ? `${ref[1]}.${ref[2]}`.toLowerCase() : ''; if (!ref || ctx.chosen[key]) return put(fill(s.value, ctx)); const tried: string[] = []; for (const v of podCandidates(ref[1], ref[2])) { try { await put(v); ctx.chosen[key] = v; used(ref[1], ref[2], v, true); return; } catch (e) { if (!(e instanceof ValueRefused)) throw e; used(ref[1], ref[2], v, false); tried.push(v); } } throw new Error(`Fusion accepted none of the ${tried.length} value(s) this pod has for ${ref[2].replace(/_/g, ' ')} in ` + `"${s.field}" (${tried.join(', ')}): this test user is not offered any of them; set one it may use on the Test environments page`); } /** The invoice a business action works on: the number create_invoice (or a `remember` step) stored under the step's * `name`, "invoice_number" when it names none. */ function invoiceNumber(s: Step, ctx: Ctx): string { const name = s.name || 'invoice_number'; const n = ctx.saved[name]; if (!n) throw new Error(`${s.action} needs an invoice: no invoice number is remembered as "${name}" (create_invoice or remember it first)`); return n; } /** A number a step gives (an amount), filled in from its placeholders. */ function amountOf(raw: string | number, ctx: Ctx, what: string): number { const v = Number(fill(raw, ctx).replace(/,/g, '')); if (!Number.isFinite(v)) throw new Error(`${what} must be a number, got "${fill(raw, ctx)}"`); return v; } /** Ask Fusion (REST) until `problems` comes back empty: REST can lag a few seconds behind what the screen saved. Fails * with the last problems in words. */ async function untilRight(problems: () => Promise, what: string, timeoutMs = 60_000) { const end = Date.now() + timeoutMs; for (;;) { const p = await problems(); if (!p.length) return; if (Date.now() > end) throw new Error(`${what}: ${p.join('; ')}`); await new Promise((r) => setTimeout(r, 3000)); } } /** A business action's check through Fusion REST. On a pod with assisted sign-in there is no password for REST: the * check is skipped with a note on the test (the screen steps before it already ran and stand). */ async function restCheck(ctx: Ctx, what: string, fn: () => Promise): Promise { if (ctx.rest.available) return fn(); test.info().annotations.push({ type: REST_SKIPPED, description: `${what}: ${NO_REST_WHY}` }); } /** The pod values to try for an AP test data key: the one Fusion already took in this test, else the pod's candidates. */ const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chosen[`ap.${key}`]] : podCandidates('ap', key); /** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */ const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } }; /** A scenario that pays its invoice: the suppliers the pod pays (paid_supplier, from its paid invoices) come first, then * the usual ones. The latest invoices' supplier can carry a payment hold, and Fusion then refuses Pay in Full (seen live). */ const pays = (ctx: Ctx) => ctx.c.steps.some((s) => s.action === 'create_payment'); const paidFirst = (ctx: Ctx, paid: string, usual: () => string[], lead: string[] = []): string[] => { let first: string[] = [...lead]; if (pays(ctx) && !ctx.chosen[`ap.${paid.replace('paid_', '')}`]) { try { first = [...first, ...podCandidates('ap', paid)]; } catch { /* not discovered yet */ } } let rest: string[] = []; try { rest = usual(); } catch (e) { if (!first.length) throw e; } return [...first, ...rest].filter((v, i, all) => all.indexOf(v) === i); }; /** The method a scenario pays by: its create_payment step's payment_method ('' when no step names one). */ const payMethod = (ctx: Ctx): string => { const step = ctx.c.steps.find((s) => s.action === 'create_payment' && s.payment_method); return step ? fill(step.payment_method!, ctx).trim() : ''; }; /** The suppliers a paying scenario's invoice goes to, each with the site that belongs to it (so the supplier and its site are * chosen as a PAIR: the discovered paid_supplier and paid_supplier_site are independent most-frequent lists, and a site of another * supplier is refused or leaves Supplier Site uneditable, seen live as a 60 s click timeout). A scenario that pays by a method (AP-FUS-020 * Electronic, 021 Check, 022 Wire) needs a supplier site the pod pays by that method: * 26D's Pay in Full pays with the invoice's own method, the supplier site's. The suppliers and sites of the business unit's newest * invoices of that method come first (rest.suppliersPaidBy: those paid before, then the most frequent); a scenario that names no * method gets the business unit's paid pairs. Null when the scenario does not pay, the test already chose its supplier, there is no * REST, or REST could not answer (the usual order then stands); fails in words when REST answers that no invoice of the business * unit uses the method. */ async function paidByMethod(ctx: Ctx): Promise<{ suppliers: string[]; sites: string[]; siteOf: Record } | null> { const method = payMethod(ctx); if (!pays(ctx) || !ctx.rest.available || ctx.chosen['ap.supplier']) return null; const units = apChoices(ctx, 'business_unit'); let answered = false; for (const bu of units) { let found; try { found = await ctx.rest.suppliersPaidBy(method, bu); } catch (e) { console.log(`[create_invoice] suppliers paid by ${method} in ${bu}: not read (${errorText(e)})`); continue; } answered = true; if (!found.length) continue; console.log(`[create_invoice] pays${method ? ` by ${method}` : ''}: suppliers the pod pays in ${bu}: ${found.slice(0, 4).map((f) => `${f.supplier} / ${f.site}${f.paid ? ' (paid)' : ''}`).join(', ')}`); const siteOf: Record = {}; for (const f of found) if (f.site) (siteOf[f.supplier] ??= []).push(f.site); return { suppliers: found.map((f) => f.supplier), sites: found.map((f) => f.site).filter(Boolean), siteOf }; } if (answered && method) throw new Error(`no supplier in ${units.join(' / ') || 'the business unit'} is paid by ${method}: this scenario pays by ${method}, and 26D's Pay in Full pays with the supplier site's own method; set a supplier (and site) the pod pays by ${method} on the Test environments page (Test data, AP supplier)`); return null; } const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200); /** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an * invoice. A shared pod's sampled data can be whoever used it last (a supplier without a default site, an account of * another ledger); the set that works is recorded as accepted (FPT_TESTDATA_USED), so the co-worker learns it and the * run's other scenarios and the next run try it first. When no set validates, the first set that saved is kept, so * the canary's own validate_invoice step shows what is broken; when none saves, create_invoice fails with each reason. */ async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[]; name: string; invoiceType?: string; paymentMethod?: string }) { const sets = apDataSets(); const why: string[] = []; let saved: ApDataSet | null = null; let last = false; // the invoice the last set saved is the one on the page const create = async (set: ApDataSet, k: number) => { const number = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`)); const got = await ctx.ui.createInvoice({ businessUnit: set.businessUnit, supplier: set.supplier, site: set.site, number, amount: h.amount, lines: h.lines, account: set.account, invoiceType: h.invoiceType, paymentMethod: h.paymentMethod }); ctx.saved[h.name] = number; return got; }; for (const [k, set] of sets.entries()) { const label = `${set.businessUnit} / ${set.supplier}`; last = false; let got; try { got = await create(set, k); } catch (e) { why.push(`${label}: ${errorText(e)}`); continue; } saved ??= set; last = true; try { await ctx.ui.validateInvoice(); await ctx.ui.expectStatus('Validated', ctx.saved[h.name]); } catch (e) { why.push(`${label}: saved but did not validate (${errorText(e)})`); continue; } for (const [key, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site], ['account', got.account]]) { if (v) { used('AP', key, v, true); ctx.chosen[`ap.${key}`] = v; } } if (k) console.log(`[canary] Payables data set ${k + 1} of ${sets.length} works (${label}); tried: ${why.join(' | ')}`); return; } if (!saved) throw new Error(`create_invoice failed with each of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`); console.log(`[canary] no Payables data set validates: ${why.join(' | ')}`); if (!last) await create(saved, sets.length); } /** The pod's values to try for one test data key, the one Fusion already took in this test first; none when the pod * has no such test data (Fusion's own default is then kept, or its list's first choice taken). `also` = keys of other * areas tried after it: a journal's account may be the Payables one, which belongs to a ledger of the same pod. */ function choices(ctx: Ctx, area: string, key: string, ...also: [string, string][]): string[] { const out: string[] = []; for (const [a, k] of [[area, key] as [string, string], ...also]) { const took = ctx.chosen[`${a}.${k}`.toLowerCase()]; if (took) { out.push(took); continue; } try { out.push(...podCandidates(a, k)); } catch { /* the pod has no such test data */ } } return out.filter((v, i, all) => v && all.indexOf(v) === i); } /** A journal step's category: a name Fusion lists (Adjustment, Accrual, Allocation, Reclass ...) or a pod placeholder * ({{pod.gl.category}}), which gives the pod's candidates in turn. Empty: the category Fusion defaults. */ function journalCategories(s: Step, ctx: Ctx): { names: string[]; fromPod: boolean } { const raw = String(s.category ?? '').trim(); const ref = /^\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}$/i.exec(raw); if (ref) return { names: choices(ctx, ref[1].toLowerCase(), ref[2].toLowerCase()), fromPod: true }; return { names: raw ? [fill(raw, ctx).trim()] : [], fromPod: false }; } /** A new test reference for a document of this scenario (FPT--