diff --git a/automation/remote_runner/server.py b/automation/remote_runner/server.py index 76f31164bc8b459d571f50c086f6497300cdd93c..7fefaab12fdaacb618c1a179535c5181f2da4f32 100644 --- a/automation/remote_runner/server.py +++ b/automation/remote_runner/server.py @@ -55,7 +55,7 @@ CASES = AUTOMATION.parent / "tests" / "cases" VERSION_FILE = AUTOMATION.parent / "VERSION" CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"} ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES", - "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS", "FPT_ALLOW_IMPORTS"} + "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS", "FPT_NAV_LINKS_LEARNED", "FPT_ALLOW_IMPORTS"} SESSION_STATE = "sign-in-state.json" # an attempt's signed-in session (assisted sign-in), in its job folder while it runs SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$") ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$") diff --git a/automation/scripts/check-gap-actions.ts b/automation/scripts/check-gap-actions.ts index 2cbed55e810e5ee613d16a86c628e99e2d46f914..71804ea88aae40096e1f6981a2d55d5d54c0fc1a 100644 --- a/automation/scripts/check-gap-actions.ts +++ b/automation/scripts/check-gap-actions.ts @@ -30,6 +30,10 @@ assert.deepEqual(invoiceProblems('FPT-1', inv({ InvoiceType: 'Credit memo' }), { assert.deepEqual(invoiceProblems('FPT-1', inv({ InvoiceType: 'CREDIT' }), { type: 'Credit memo' }), []); assert.match(invoiceProblems('FPT-1', inv({ InvoiceType: 'Standard' }), { type: 'Prepayment' })[0], /its type is "Standard", expected "Prepayment"/); assert.match(invoiceProblems('FPT-1', inv({}), { type: 'Standard' })[0], /its type is ""/); // a pod that returns no type is not a match +// a validated prepayment's status is "Unpaid" (then Available ...): it meets "Validated"; a standard invoice's "Unpaid" does not +assert.deepEqual(invoiceProblems('FPT-1', inv({ InvoiceType: 'Prepayment', ValidationStatus: 'Unpaid' }), { status: 'Validated' }), []); +assert.match(invoiceProblems('FPT-1', inv({ InvoiceType: 'Standard', ValidationStatus: 'Unpaid' }), { status: 'Validated' })[0], /expected "Validated"/); +assert.match(invoiceProblems('FPT-1', inv({ InvoiceType: 'Prepayment', ValidationStatus: 'Not validated' }), { status: 'Validated' })[0], /expected "Validated"/); assert.deepEqual(invoiceProblems('FPT-1', inv({ PaymentMethod: 'Electronic' }), { paymentMethod: 'electronic' }), []); assert.deepEqual(invoiceProblems('FPT-1', inv({ PaymentMethod: 'Electronic', PaymentMethodCode: 'EFT' }), { paymentMethod: 'EFT' }), []); assert.match(invoiceProblems('FPT-1', inv({ PaymentMethod: 'Check' }), { paymentMethod: 'Wire' })[0], /its payment method is "Check", expected "Wire"/); diff --git a/automation/scripts/check-nav.ts b/automation/scripts/check-nav.ts index 23c7e544272c8b7ff96ed2d2747bcaf241dff113..4d625cb8773013d1201625155679566f63909ed5 100644 --- a/automation/scripts/check-nav.ts +++ b/automation/scripts/check-nav.ts @@ -1,6 +1,6 @@ /* Checks the navigation-link parsing and matching (src/fusion/nav.ts) without a browser: `npx tsx scripts/check-nav.ts`. */ import assert from 'node:assert/strict'; -import { navLink, parseNavLinks } from '../src/fusion/nav'; +import { LEARNED_PATH, navLink, parseLearnedLinks, parseNavLinks } from '../src/fusion/nav'; const url = 'https://pod.fa.ocs.oraclecloud.com/fscmUI/faces/FuseOverview?fndGlobalItemNodeId=itemNode_procurement_purchase_orders'; const links = parseNavLinks(JSON.stringify({ 'Procurement > Purchase Orders': url, 'Payables > Invoices': 'http://x/fscmUI/a', 'nogroup': url, 'A > B': 5 })); @@ -14,4 +14,16 @@ assert.deepEqual(parseNavLinks(undefined), {}); assert.deepEqual(parseNavLinks('not json'), {}); assert.deepEqual(parseNavLinks('[1,2]'), {}); assert.deepEqual(parseNavLinks('null'), {}); +// learned links: relative, same shape as a work area's own address, anything else dropped +const path = '/fscmUI/faces/FndOverview?fndGlobalItemNodeId=itemNode_receivables_billing'; +const learned = parseLearnedLinks(JSON.stringify({ + 'Receivables > Billing': path, 'A > B': 'https://evil.example.com/fscmUI/faces/FndOverview?fndGlobalItemNodeId=itemNode_x', + 'C > D': '//evil.example.com/fscmUI/faces/FndOverview?fndGlobalItemNodeId=itemNode_x', 'E > F': '/fscmUI/faces/FndOverview?other=1', + 'G > H': '/fscmUI/faces/FndOverview?fndGlobalItemNodeId=itemNode_x&y=1', 'I > J': '/fscmUI/../x/faces/F?fndGlobalItemNodeId=itemNode_x', 'nogroup': path, 'K > L': 7 })); +assert.deepEqual(learned, { 'Receivables > Billing': path }); +assert.equal(navLink(learned, ' receivables ', 'BILLING'), path); // the same matching as a consultant's links +assert.ok(LEARNED_PATH.test(path) && !LEARNED_PATH.test(`https://x${path}`)); +assert.deepEqual(parseLearnedLinks(undefined), {}); +assert.deepEqual(parseLearnedLinks('not json'), {}); +assert.deepEqual(parseLearnedLinks('[1]'), {}); console.log('nav: all checks pass'); diff --git a/automation/scripts/check-refusal.ts b/automation/scripts/check-refusal.ts new file mode 100644 index 0000000000000000000000000000000000000000..66014d7f472063f27091902595114a4182dd1cf4 --- /dev/null +++ b/automation/scripts/check-refusal.ts @@ -0,0 +1,63 @@ +/* Checks the logic of a step's `refused` (src/fusion/refusal.ts) without a browser or a pod: `npx tsx scripts/check-refusal.ts` + * (coworker/tests/test_edge_cases.py runs it when tsx is installed). A refused step passes only when FUSION said no in the + * words expected; the runner's own failures (a locator timeout, a page that did not open) must never pass as a refusal. */ +import assert from 'node:assert/strict'; +import { expectRefusal, FusionRefused, refusalOf, refusalWords, refusedWith, ValueRefused } from '../src/fusion/refusal'; + +const fails = async (p: Promise, re: RegExp) => { await assert.rejects(p, re); }; + +(async () => { + // the words: alternatives, any case, any spacing, curly quotes + assert.deepEqual(refusalWords(' Negative | less than ZERO |'), ['negative', 'less than zero']); + assert.deepEqual(refusalWords(undefined), []); + assert.equal(refusedWith("The amount can’t be negative.", ["can't be negative"]), "can't be negative"); + assert.equal(refusedWith('Enter a value for Supplier', ['negative', 'supplier']), 'supplier'); + assert.equal(refusedWith('Something else', ['negative']), undefined); + + // what counts as Fusion's own words + assert.equal(refusalOf(new FusionRefused('Error: Enter a negative amount', 'saving: Fusion said Error: Enter a negative amount')), 'Error: Enter a negative amount'); + assert.equal(refusalOf(new ValueRefused('Fusion did not accept "5" in "Amount": must be negative', 'must be negative')), 'must be negative'); + assert.equal(refusalOf(new ValueRefused('"X" is not in the list (A, B)')), null); // a pod value Fusion does not list: the pod's data, not a refusal + assert.equal(refusalOf(new Error('locator.click: Timeout 30000ms exceeded')), null); // the runner's failure + assert.equal(refusalOf(new Error('Fusion said no')), null); // a plain Error is never taken for Fusion, whatever it says + assert.equal(refusalOf('Fusion said negative'), null); + + // 1. the action throws Fusion's message with the expected words: the step passes and says what Fusion said + let closed = 0; + const said = await expectRefusal('create_invoice', 'negative|less than zero', async () => { + throw new FusionRefused('Error: The amount must be less than zero for a credit memo.', 'Fusion did not save invoice X: Error: ...'); + }, async () => { closed++; }); + assert.match(said, /less than zero/); + assert.equal(closed, 1); // the page is left clean + + // 2. the action succeeds: Fusion took what it should refuse + await fails(expectRefusal('create_invoice', 'negative', async () => undefined), /Fusion took create_invoice that it should refuse/); + + // 3. a locator timeout (or any failure that is not Fusion's message): the step fails with that reason, never a pass + await fails(expectRefusal('create_invoice', 'negative', async () => { throw new Error('locator.click: Timeout 30000ms exceeded.\n call log: ...'); }), + /failed for another reason.*locator\.click: Timeout 30000ms exceeded/); + await fails(expectRefusal('create_invoice', 'negative', async () => { throw new Error('page.goto: net::ERR_CONNECTION_RESET'); }), /another reason.*ERR_CONNECTION_RESET/); + // ... even when its text mentions the expected words: only Fusion's own message counts + await fails(expectRefusal('create_invoice', 'negative', async () => { throw new Error('the amount is negative and the locator timed out'); }), /another reason/); + // a pod value Fusion does not list is not a refusal of the document + await fails(expectRefusal('create_invoice', 'supplier', async () => { throw new ValueRefused('"S" is not in the list (A, B)'); }), /another reason/); + await fails(expectRefusal('create_invoice', 'supplier', async () => { throw new ValueRefused('Fusion marked it invalid'); }), /another reason/); + + // 4. Fusion refused, but for another reason: the step fails and shows what Fusion said + let closedOther = 0; + await fails(expectRefusal('create_invoice', 'negative', async () => { throw new FusionRefused('Error: You must enter a supplier site.'); }, async () => { closedOther++; }), + /Fusion refused create_invoice, but not for the reason expected: it said "Error: You must enter a supplier site\."/); + assert.equal(closedOther, 1); + + // 5. a field message Fusion showed (ValueRefused with its words) counts like a window + assert.match(await expectRefusal('create_invoice', 'negative', async () => { throw new ValueRefused('Fusion did not accept "100" in "Amount"', 'Enter a negative amount.'); }), /negative/); + + // 6. a step without words is a mistake of the scenario, not a pass + await fails(expectRefusal('create_invoice', '', async () => { throw new FusionRefused('anything'); }), /refused needs the words/); + await fails(expectRefusal('create_invoice', ' | ', async () => undefined), /refused needs the words/); + + // 7. a failing clean-up of the page does not hide the refusal + assert.match(await expectRefusal('save', 'required', async () => { throw new FusionRefused('Supplier is required'); }, async () => { throw new Error('page closed'); }), /required/); + + console.log('check-refusal: ok'); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/automation/src/fusion/nav.ts b/automation/src/fusion/nav.ts index 364816111abdb7d1aef61ab463d6babf36941654..4bddf9586dba6aba31925ded38b6eef819f6f77b 100644 --- a/automation/src/fusion/nav.ts +++ b/automation/src/fusion/nav.ts @@ -19,3 +19,19 @@ export function navLink(links: Record, group: string, page: stri const hit = Object.keys(links).find((k) => key(k) === want); return hit ? links[hit] : null; } + +/** The shape of an address a run may learn and reuse: a page of a Fusion UI on the pod's own host and the id of the work + * area's menu entry, nothing else (seen live on 26D: "/fscmUI/faces/FndOverview?fndGlobalItemNodeId=itemNode_receivables_billing"). + * Relative on purpose: it can never name another host. The co-worker (platform/pods.py) holds the same rule. */ +export const LEARNED_PATH = /^\/\w+\/faces\/\w+\?fndGlobalItemNodeId=itemNode_\w+$/; + +/** The links earlier runs learned for this pod (FPT_NAV_LINKS_LEARNED, set by the co-worker), {"Group > Page": "/path?id"}; + * anything malformed or not of LEARNED_PATH is ignored, never an error. */ +export function parseLearnedLinks(raw: string | undefined): Record { + if (!raw) return {}; + try { + const o = JSON.parse(raw); + if (!o || typeof o !== 'object' || Array.isArray(o)) return {}; + return Object.fromEntries(Object.entries(o).filter(([k, v]) => k.includes('>') && typeof v === 'string' && LEARNED_PATH.test(v)) as [string, string][]); + } catch { return {}; } +} diff --git a/automation/src/fusion/refusal.ts b/automation/src/fusion/refusal.ts new file mode 100644 index 0000000000000000000000000000000000000000..20b3c72933a320d43e3842d1a8c557d6e7b218da --- /dev/null +++ b/automation/src/fusion/refusal.ts @@ -0,0 +1,74 @@ +/* + * Fusion's refusals, told apart from automation failures. Pure logic (no browser), so scripts/check-refusal.ts runs it + * without a pod. + * + * A negative scenario (a credit memo with a positive amount, a journal line with no account) passes when FUSION says no: + * its own message window or field message names the reason. It must never pass because the runner stumbled (a locator + * timeout, a page that did not open, a pod value Fusion does not list): that would report a working Fusion as proven. + * So the places that read Fusion's words throw FusionRefused (carrying only Fusion's text, `said`), and a step with + * `refused: ""` (see steps.ts) passes only on a FusionRefused whose text holds one of the words. + */ + +/** Fusion did not take a value in a field (not in this user's list, or not valid there): another one may be. `said` is the + * message Fusion itself showed for it ('' when the field was only marked invalid, or the value is not in the list). */ +export class ValueRefused extends Error { + constructor(message: string, readonly said = '') { super(message); this.name = 'ValueRefused'; } +} + +/** Fusion said no in its own words (a message window or note after a save or an action). `said` = Fusion's text alone, + * `message` = the same with the runner's context ("Fusion did not save invoice X: ..."). */ +export class FusionRefused extends Error { + constructor(readonly said: string, message?: string) { super(message ?? said); this.name = 'FusionRefused'; } +} + +/** Fusion's own words in a failure, or null when the failure is the runner's (a locator timeout, a navigation error, a + * value the pod does not list). A field Fusion marked invalid without saying why carries no words either. */ +export function refusalOf(e: unknown): string | null { + if (e instanceof FusionRefused) return e.said; + if (e instanceof ValueRefused && e.said.trim()) return e.said; + return null; +} + +const plain = (s: string) => s.toLowerCase().replace(/[‘’]/g, "'").replace(/\s+/g, ' ').trim(); + +/** The words a `refused` step expects: alternatives separated by "|", compared without regard to case or spacing. */ +export function refusalWords(spec: unknown): string[] { + return String(spec ?? '').split('|').map(plain).filter(Boolean); +} + +/** The first of `words` that Fusion's text holds, undefined when none. */ +export const refusedWith = (said: string, words: string[]): string | undefined => words.find((w) => plain(said).includes(w)); + +/** The failure's first line, and where in the business actions it happened (otherwise hidden here: "expect(locator) + * .toBeVisible() failed" alone does not say which field, seen live). */ +const firstLine = (e: unknown) => { + const where = /\b((?:ui|steps|rest|interfaces)\.ts:\d+)/.exec(String((e as Error)?.stack || ''))?.[1]; + return String((e as Error)?.message || e).split('\n')[0].slice(0, 300) + (where ? ` (at ${where})` : ''); +}; + +/** + * Run `run` (a business action) and require that Fusion refuses it. Resolves with Fusion's words when the action failed + * BECAUSE Fusion refused and its message holds one of the `spec` alternatives. Fails (throws) when + * - the action succeeded: Fusion took what it should refuse; + * - the action failed for a reason that is not Fusion's message: the step fails with that reason, never a pass; + * - Fusion refused, but said something else (the refusal may be for another reason than the one under test). + * `onRefused` runs after a refusal (the page is left clean: Fusion's message window closed); its own failure is ignored. + */ +export async function expectRefusal(what: string, spec: unknown, run: () => Promise, onRefused?: () => Promise): Promise { + const words = refusalWords(spec); + if (!words.length) throw new Error(`${what}: refused needs the words Fusion should say, for example refused: "negative|less than zero" (alternatives separated by |)`); + const shown = words.map((w) => `"${w}"`).join(' or '); + try { + await run(); + } catch (e) { + const said = refusalOf(e); + if (said === null) { + throw new Error(`${what} was expected to be refused by Fusion, but it failed for another reason, before or without Fusion's message: ${firstLine(e)}`); + } + if (onRefused) await Promise.resolve(onRefused()).catch(() => undefined); + const hit = refusedWith(said, words); + if (!hit) throw new Error(`Fusion refused ${what}, but not for the reason expected: it said "${said.slice(0, 300)}" (expected a message with ${shown})`); + return said; + } + throw new Error(`Fusion took ${what} that it should refuse (expected a message with ${shown})`); +} diff --git a/automation/src/fusion/rest.ts b/automation/src/fusion/rest.ts index 843413ae7ea39733fd4aa85d524bfaf10855474d..739a63014bace0879b0e733cc37cac67d4870aac 100644 --- a/automation/src/fusion/rest.ts +++ b/automation/src/fusion/rest.ts @@ -59,7 +59,7 @@ const q = (s: string) => s.replace(/'/g, "''"); /** What a step expects of an invoice in Fusion (business action expect_invoice). */ export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; type?: string; - paymentMethod?: string; approvalStatus?: string; validationStatus?: string; source?: string } + paymentMethod?: string; approvalStatus?: string; validationStatus?: string; source?: string; accountingStatus?: string } /** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */ const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled'); @@ -86,6 +86,13 @@ export function invoiceAmountProblems(type: string | undefined, amounts: number[ }); } +/** A prepayment's status after validation is its own word, not "Validated": Unpaid until it is paid, then Available, + * Partially applied, Fully applied (26D: a validated prepayment shows "Unpaid", on the page and in REST, seen live). */ +const PREPAYMENT_VALIDATED = ['unpaid', 'available', 'partially applied', 'fully applied', 'permanent']; +const prepaymentValidated = (inv: Invoice, want: string) => spelling(want) === 'validated' + && invoiceTypeKey(String(inv.InvoiceType ?? '')) === invoiceTypeKey('Prepayment') + && PREPAYMENT_VALIDATED.includes(spelling(String(inv.ValidationStatus ?? ''))); + /** Every way the invoice differs from what is expected, in words (empty: as expected). `amountAtLeast` is for the * invoice total when the pod adds tax on top of the lines: the total is then the amount plus that tax. */ export function invoiceProblems(number: string, inv: Invoice | null, want: InvoiceExpectation): string[] { @@ -93,7 +100,7 @@ export function invoiceProblems(number: string, inv: Invoice | null, want: Invoi const out: string[] = []; const amount = Number(inv.InvoiceAmount); if (want.status && spelling(String(inv.ValidationStatus ?? '')) !== spelling(want.status) - && !(spelling(want.status) === 'canceled' && inv.CanceledFlag)) { + && !(spelling(want.status) === 'canceled' && inv.CanceledFlag) && !prepaymentValidated(inv, want.status)) { out.push(`its status is "${inv.ValidationStatus ?? ''}", expected "${want.status}"`); } if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${inv.InvoiceAmount}, expected ${want.amount}`); @@ -120,6 +127,11 @@ export function invoiceProblems(number: string, inv: Invoice | null, want: Invoi if (got === undefined) out.push(`this pod's REST does not return the invoice's source, so "${want.source}" cannot be checked`); else if (spelling(String(got)) !== spelling(want.source)) out.push(`its source is "${got}", expected "${want.source}"`); } + if (want.accountingStatus) { // subledger accounting: Unaccounted, Draft, Accounted, Partially accounted (the invoices resource's AccountingStatus, seen live) + const got = invoiceAccountingStatus(inv); + if (!got) out.push(`this pod's REST does not return the invoice's accounting status, so "${want.accountingStatus}" cannot be checked`); + else if (codeKey(got) !== codeKey(want.accountingStatus)) out.push(`its accounting status is "${got}", expected "${want.accountingStatus}"`); + } if (want.validationStatus && validationKey(String(inv.ValidationStatus ?? '')) !== validationKey(want.validationStatus) && !(validationKey(want.validationStatus) === 'canceled' && inv.CanceledFlag)) { out.push(`its validation status is "${inv.ValidationStatus ?? ''}", expected "${want.validationStatus}"`); @@ -139,6 +151,10 @@ export const invoiceApprovalStatus = (inv: Invoice): string => String([inv.Appro * ("Never validated" in Oracle's own lookup): one status for a saved invoice that was not validated. */ const validationKey = (s: string) => { const k = codeKey(s); return k === 'never validated' ? 'not validated' : k; }; +/** The invoice's accounting status as the invoices resource returns it (attribute AccountingStatus, seen live on a 26D pod: Unaccounted + * for a new invoice, Draft once Account in Draft ran, Accounted after final accounting, Partially accounted): '' when the pod returns none. */ +export const invoiceAccountingStatus = (inv: Invoice): string => String(inv.AccountingStatus ?? '').trim(); + /** Whether the invoice's approval is under way (Initiated, or "In process" / "Pending" where a release says so): such an invoice * cannot be cancelled until the approval is withdrawn. */ export const invoiceInApproval = (inv: Invoice): boolean => /^(initiated|in process|in progress|pending|pending approval)$/.test(codeKey(invoiceApprovalStatus(inv))); @@ -313,7 +329,7 @@ export function journalProblems(name: string, b: JournalBatch | null, want: DocE * and releases differ several are read (every guess is listed in the report of the change that added them). */ export interface ArTransaction { CustomerTransactionId: number; TransactionNumber: string; BusinessUnit?: string; BillToCustomerName?: string; - TransactionType?: string; [k: string]: unknown } + TransactionType?: string; LinesAmount?: number; [k: string]: unknown } export interface ArReceipt { StandardReceiptId: number; ReceiptNumber: string; Amount?: number; [k: string]: unknown } const firstOf = (o: Record, keys: string[]) => keys.map((k) => o[k]).find((v) => v !== undefined && v !== null && v !== ''); @@ -326,8 +342,10 @@ export function transactionStatus(t: ArTransaction): string { return flag === undefined ? '' : (flag === true || /^(y|yes|true)$/i.test(String(flag)) ? 'Complete' : 'Incomplete'); } -/** A transaction's amount (entered, else total); NaN when it carries neither. */ -export const transactionAmount = (t: ArTransaction) => Number(firstOf(t, ['EnteredAmount', 'InvoiceAmount', 'TotalAmount', 'Amount']) ?? NaN); +/** A transaction's amount (entered, else total, else the sum of its lines); NaN when it carries none. Fusion 26D leaves every + * amount attribute of the header null while the transaction is Incomplete and fills EnteredAmount only on Complete (seen + * live: EnteredAmount null with a line of LineAmount 100), so rest.transaction() adds `LinesAmount`, the lines' sum. */ +export const transactionAmount = (t: ArTransaction) => Number(firstOf(t, ['EnteredAmount', 'InvoiceAmount', 'TotalAmount', 'Amount', 'LinesAmount']) ?? NaN); export const receiptAmount = (r: ArReceipt) => Number(firstOf(r, ['Amount', 'ReceiptAmount', 'EnteredAmount']) ?? NaN); @@ -468,7 +486,7 @@ export class FusionRest { } private async get(resource: string, query: string, extra: Record = {}): Promise { - const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100', ...extra }); + const params = new URLSearchParams({ ...(query ? { q: query } : {}), onlyData: 'true', limit: '100', ...extra }); // no query: every record const r = await this.call('GET', `${resource}?${params}`); if (r.status !== 200) throw new Error(`GET ${resource} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); return (JSON.parse(r.text).items || []) as T[]; @@ -543,6 +561,48 @@ export class FusionRest { return `${invoice}: approval ${invoiceApprovalStatus(inv) || 'not under way'}, nothing to withdraw`; } + /** The suppliers (with their sites) a business unit's invoices are paid to by `method`, best first: 26D's Pay in Full pays with + * the method of the invoice's supplier site, so a scenario that pays "by Check" needs a supplier the pod pays by check. Read from + * the business unit's newest invoices with that payment method (the method's name, then its code, whichever this release + * filters on; a release that refuses an attribute answers HTTP 400 and the next is tried), the run's own FPT- invoices left + * out; the pairs paid before (PaidStatus Paid) come first, then the most frequent. [] when the pod has no such invoice. With no + * `method` ('') the pairs are those of the business unit's paid invoices: the supplier and the site that BELONG together (the + * pod's discovered paid_supplier and paid_supplier_site are two independent most-frequent lists, and a site of another supplier + * is refused or leaves the field uneditable). */ + async suppliersPaidBy(method: string, businessUnit?: string): Promise<{ supplier: string; site: string; paid: boolean; count: number }[]> { + const bu = businessUnit ? `;BusinessUnit='${q(businessUnit)}'` : ''; + const same = (v: unknown) => spelling(String(v ?? '')) === spelling(method); + for (const attr of method ? ['PaymentMethod', 'PaymentMethodCode'] : ['PaidStatus']) { + let items: Invoice[]; + try { + const where = !method ? `PaidStatus='Paid'` : `${attr}='${q(attr === 'PaymentMethodCode' ? method.toUpperCase() : method)}'`; + // the newest invoices are mostly the runs' own FPT- ones (a pod's tests pile them up: 199 of 280 "Wire" invoices on the + // test pod were): pages are read until a page shows a pod invoice, at most 8 + items = []; + for (let page = 0; page < 8; page++) { + const got = await this.get('invoices', `${where}${bu}`, { orderBy: 'InvoiceId:desc', offset: String(page * 100) }); + items.push(...got); + if (got.length < 100 || items.some((i) => !/^FPT-/i.test(String(i.InvoiceNumber ?? '')))) break; + } + } catch (e) { + if (!/HTTP 400\b/.test(String((e as Error).message))) throw e; + continue; + } + const seen = new Map(); + for (const inv of items) { + if (/^FPT-/i.test(String(inv.InvoiceNumber ?? '')) || !inv.Supplier || (method && !(same(inv.PaymentMethod) || same(inv.PaymentMethodCode)))) continue; + const site = String(inv.SupplierSite ?? ''); + const k = `${inv.Supplier}\u0000${site}`; + const e = seen.get(k) ?? { supplier: inv.Supplier, site, paid: false, count: 0 }; + e.count++; + if (String(inv.PaidStatus ?? '').toLowerCase() === 'paid') e.paid = true; + seen.set(k, e); + } + if (seen.size) return [...seen.values()].sort((a, b) => Number(b.paid) - Number(a.paid) || b.count - a.count); + } + return []; + } + /** Clean-up of the test payment of an invoice (`invoice`; `number` = the payment's number when it is known): a payment that * is not voided is voided on the screens (REST has no void for it: NeedsScreen), because an invoice that is paid cannot be * cancelled. A paid invoice whose payment is not known is left for a person. */ @@ -589,11 +649,30 @@ export class FusionRest { return this.first('journalBatches', `BatchName='${q(name)}'`); } + /** The accounting periods the ledger's most recent posted journals are in, newest first (up to `max`): periods that took a + * posting lately are open for posting (the pod's test-data period can be a Future-Entry one, where Fusion lets a journal be + * entered but not posted). Empty when REST cannot say. */ + async postedPeriods(ledger: string, max = 2, scan = 60): Promise { + const found: string[] = []; + try { + const batches = await this.get<{ JeBatchId: number }>('journalBatches', "Status='P'", { orderBy: 'JeBatchId:desc', limit: String(scan), fields: 'JeBatchId' }); + for (const b of batches) { + const r = await this.call('GET', `journalBatches/${b.JeBatchId}/child/journalHeaders?${new URLSearchParams({ onlyData: 'true', fields: 'LedgerName,PeriodName', limit: '5' })}`); + if (r.status !== 200) continue; + for (const h of (JSON.parse(r.text).items || []) as { LedgerName?: string; PeriodName?: string }[]) { + if (h.LedgerName?.toLowerCase() === ledger.toLowerCase() && h.PeriodName && !found.includes(h.PeriodName)) found.push(h.PeriodName); + } + if (found.length >= max) break; + } + } catch { /* REST cannot say: the pod's own periods are used */ } + return found; + } + /** The journals of a batch (journalBatches child journalHeaders: their category, and on some pods their source); empty when * the pod refuses the child resource. */ async journalHeaders(batchId: number): Promise[]> { try { return await this.getAll(`journalBatches/${batchId}/child/journalHeaders`); } catch (e) { - if (/HTTP (400|404)/.test(String((e as Error).message))) return []; + if (/HTTP (400|404)\b/.test(String((e as Error).message))) return []; throw e; } } @@ -652,7 +731,7 @@ export class FusionRest { const v = rows[0]?.[attr]; if (v !== undefined && v !== null && String(v).trim()) return String(v).trim(); } catch (e) { - if (!/HTTP 400/.test(String((e as Error).message))) throw e; + if (!/HTTP 400\b/.test(String((e as Error).message))) throw e; } } return null; @@ -790,12 +869,44 @@ export class FusionRest { return done.join('; '); } - /** The transaction with this number, else the one carrying the test's tag in its customer order number (an imported one), Comments or Internal Notes. */ + /** The transaction with this number, else the one carrying the test's tag in its customer order number (an imported one), + * Comments, Internal Notes, or the Description of its line. The line's Description is where the tag is on 26D: the header's + * Comments came back null on a transaction saved with the tag typed in the screen's Comments (seen live), so clean-up never + * found such a transaction by Comments and left it Incomplete on the pod. With its lines' amount (`LinesAmount`). */ async transaction(numberOrTag: string): Promise { - return await this.first('receivablesInvoices', `TransactionNumber='${q(numberOrTag)}'`) + const t = await this.first('receivablesInvoices', `TransactionNumber='${q(numberOrTag)}'`) ?? await this.first('receivablesInvoices', `PurchaseOrder='${q(numberOrTag)}'`) // an imported one: its customer order number is the tag ?? await this.first('receivablesInvoices', `Comments LIKE '${q(numberOrTag)}%'`) - ?? await this.first('receivablesInvoices', `InternalNotes LIKE '${q(numberOrTag)}%'`); + ?? await this.first('receivablesInvoices', `InternalNotes LIKE '${q(numberOrTag)}%'`) + ?? await this.transactionByLine(numberOrTag); + return t ? this.withLines(t) : null; + } + + /** The transaction whose line's Description starts with the tag: REST cannot query a child, so the user's latest + * transactions are read with their lines (a test document is the latest thing its run made). */ + private async transactionByLine(tag: string): Promise { + if (!/^FPT-/i.test(tag)) return null; // a transaction number is never searched in the lines + try { + const rows = await this.get('receivablesInvoices', '', + { orderBy: 'CreationDate:desc', limit: '40', expand: 'receivablesInvoiceLines' }); + return rows.find((r) => (r.receivablesInvoiceLines ?? []).some((l) => String(l.Description ?? '').startsWith(tag))) ?? null; + } catch (e) { + if (/HTTP (400|404)/.test(String((e as Error).message))) return null; + throw e; + } + } + + /** The transaction with `LinesAmount`: its lines' amounts added (the header's amount is empty until Complete). */ + private async withLines(t: ArTransaction): Promise { + if (!t.CustomerTransactionId) return t; + try { + const lines = await this.get<{ LineAmount?: number }>(`receivablesInvoices/${t.CustomerTransactionId}/child/receivablesInvoiceLines`, ''); + const amounts = lines.map((l) => Number(l.LineAmount)).filter((n) => !Number.isNaN(n)); + return amounts.length ? { ...t, LinesAmount: Math.round(amounts.reduce((a, b) => a + b, 0) * 100) / 100 } : t; + } catch (e) { + if (/HTTP (400|404)/.test(String((e as Error).message))) return t; // a pod without the lines resource: the header says what it says + throw e; + } } /** The receipt with this number: the test's own tag. */ @@ -810,7 +921,15 @@ export class FusionRest { if (!t) return `${tag}: no transaction saved, nothing to clean up`; const status = transactionStatus(t); if (spelling(status) === 'incomplete') { - await this.remove(`receivablesInvoices/${t.CustomerTransactionId}`, `transaction ${t.TransactionNumber}`); + try { await this.remove(`receivablesInvoices/${t.CustomerTransactionId}`, `transaction ${t.TransactionNumber}`); } catch (e) { + // a business unit whose system options do not allow deleting transactions refuses it (seen live on 26D: HTTP 400 "You can't + // delete the transaction because the system options settings for this business unit don't allow transaction deletion. + // (AR-856746)"): no REST or screen delete exists then, the Incomplete transaction stays for a person + if (/AR-856746|don.t allow transaction deletion/i.test(String((e as Error).message))) { + throw new LeftForPerson(`transaction ${t.TransactionNumber} is Incomplete and Fusion does not let this business unit delete transactions (system option): delete it on Manage Transactions after allowing deletion, or leave it`); + } + throw e; + } if (await this.transaction(tag)) throw new Error(`transaction ${t.TransactionNumber}: Fusion accepted the delete but it is still there`); return `transaction ${t.TransactionNumber}: deleted by clean-up (never completed)`; } diff --git a/automation/src/fusion/steps.ts b/automation/src/fusion/steps.ts index fa6c6adc370d3f5fb15ebb38a6f6430bce2c2c9c..6b5b681befdcd6a2ddf1b65312aa48dd7e45d28d 100644 --- a/automation/src/fusion/steps.ts +++ b/automation/src/fusion/steps.ts @@ -5,8 +5,9 @@ import { approvalRef, expect, paymentRef, test, type DocKind, type FusionDocs } 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, podCandidates, podToday, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui'; +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 @@ -36,17 +37,33 @@ import { apDataSets, fusionDate, podCandidates, podToday, podValue, testNumber, * 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 } + 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 @@ -74,6 +91,7 @@ type Ctx = { ui: FusionUi; c: StepCase; saved: Record; uniques: 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 @@ -157,14 +175,48 @@ const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } /** 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[]): string[] => { - let first: string[] = []; - if (pays(ctx) && !ctx.chosen[`ap.${paid.replace('paid_', '')}`]) { try { first = podCandidates('ap', paid); } catch { /* not discovered yet */ } } +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 @@ -287,6 +339,26 @@ function amountValue(s: Step, ctx: Ctx): string { return amount; } +/** The parts a step leaves out (leave_out: a name, a list, or names separated by | or ,), per action: what Fusion must then refuse + * or hold back. Lower case; a part the action cannot leave out fails the step, so a typo never silently does nothing. */ +const LEAVE_OUT_OF: Record = { create_invoice: ['supplier', 'number', 'amount'], create_journal: ['account'], + create_transaction: ['customer', 'lines'] }; +function leaveOut(s: Step): string[] { + const raw = Array.isArray(s.leave_out) ? s.leave_out : s.leave_out ? String(s.leave_out).split(/[|,]/) : []; + const out = raw.map((x) => String(x).trim().toLowerCase()).filter(Boolean); + const can = LEAVE_OUT_OF[s.action]; + if (out.length && !can) throw new Error(`${s.action} does not take leave_out (only ${Object.keys(LEAVE_OUT_OF).join(', ')} do)`); + const bad = out.filter((x) => !can?.includes(x)); + if (bad.length) throw new Error(`${s.action} cannot leave out "${bad.join('", "')}" (it can leave out: ${can.join(', ')})`); + return out; +} + +/** The document a refused create_ step tries to make: noted so the refused step can check, once Fusion has said no, that it was + * not saved after all (it is already registered for clean-up, which then finds nothing to do). */ +function attempting(ctx: Ctx, s: Step, what: string, exists: () => Promise): void { + if (s.refused != null) ctx.attempt = { what, exists }; +} + /** Receivables: create_transaction and expect_transaction also take transaction_type (Invoice by default; Credit Memo, Debit * Memo or the pod's own type) and transaction_source (Manual or the pod's own source). */ export interface Step { transaction_type?: string; transaction_source?: string } @@ -360,12 +432,26 @@ const ACTIONS: Record Promise> = { await ctx.ui.settle(2000); await ACTIONS.confirm_if_asked({ action: 'confirm_if_asked' }, ctx); }, + /** Fusion does not let the user do something: the entry named by value (or any of several separated by |) of the menu named by + * field is greyed out or not listed on the page open now (a canceled invoice cannot be validated again). The step fails when + * the entry is usable, and when no such menu opens, so a screen that changed is never reported as Fusion refusing. For + * Invoice Actions, the Actions menu of a details panel is looked at when the page has no Invoice Actions. */ + expect_unavailable: async (s, ctx) => { + if (!s.field) throw new Error('expect_unavailable needs the menu as field'); + const entries = fill(s.value, ctx).split('|').map((x) => x.trim()).filter(Boolean); + if (!entries.length) throw new Error('expect_unavailable needs the entry (or entries separated by |) as value'); + const menu = fill(s.field, ctx).trim(); + const state = await ctx.ui.expectEntryUnavailable(menu.toLowerCase() === 'invoice actions' ? [menu, 'Actions'] : [menu], entries); + test.info().annotations.push({ type: 'unavailable', description: state }); + }, // Payables business actions /** Create and save a Payables invoice on its own screen (no open_task before it). value = the invoice amount (default * {{tv.amount}}); lines = the line amounts (default one line of the whole amount; the amount defaults to their sum); * name = what to remember the new FPT- number as (default invoice_number, used as {{saved.invoice_number}}); * invoice_type (default Standard; a credit or debit memo's amounts are negative) and payment_method as Fusion lists them. The - * number is registered for clean-up before the save, so the invoice is cancelled after the test, pass or fail. */ + * number is registered for clean-up before the save, so the invoice is cancelled after the test, pass or fail. leave_out + * (supplier, number, amount) leaves that header field empty; with `refused` the step expects Fusion to refuse the invoice + * (a credit memo with a positive amount, an invoice without a supplier) and then checks that it was not saved. */ create_invoice: async (s, ctx) => { const lines = (s.lines ?? []).map((l) => fill(l, ctx)); const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx) @@ -374,13 +460,18 @@ const ACTIONS: Record Promise> = { if (!amount) throw new Error('create_invoice needs an amount: value, lines, or the test value "amount"'); const invoiceType = s.invoice_type ? fill(s.invoice_type, ctx).trim() : undefined; const paymentMethod = s.payment_method ? fill(s.payment_method, ctx).trim() : undefined; + // the sign of a type's amounts is checked here before Fusion sees it, except on a refused step: there Fusion's own validation is the test const wrong = invoiceAmountProblems(invoiceType, (lines.length ? lines : [amount]).map((l, i) => amountOf(l, ctx, `line ${i + 1}`))); - if (wrong.length) throw new Error(`create_invoice invoice_type "${invoiceType || 'Standard'}": ${wrong.join('; ')}`); + if (wrong.length && s.refused == null) throw new Error(`create_invoice invoice_type "${invoiceType || 'Standard'}": ${wrong.join('; ')}`); + const leaving = leaveOut(s); if (ctx.c.canary) return createWithDataSets(ctx, { amount, lines, name: s.name || 'invoice_number', invoiceType, paymentMethod }); const number = ctx.track(testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, ''))); + attempting(ctx, s, `invoice ${number}`, async () => !!(await ctx.rest.invoiceByNumber(number))); + const byMethod = leaving.includes('supplier') ? undefined : await paidByMethod(ctx); const got = await ctx.ui.createInvoice({ businessUnit: apChoices(ctx, 'business_unit'), - supplier: paidFirst(ctx, 'paid_supplier', () => apChoices(ctx, 'supplier')), number, amount, - lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: paidFirst(ctx, 'paid_supplier_site', () => apSites(ctx)), invoiceType, paymentMethod }); + supplier: leaving.includes('supplier') ? [] : paidFirst(ctx, 'paid_supplier', () => apChoices(ctx, 'supplier'), byMethod?.suppliers), siteOf: byMethod?.siteOf, number, amount, + lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: paidFirst(ctx, 'paid_supplier_site', () => apSites(ctx), byMethod?.sites), invoiceType, paymentMethod, + leaveOut: leaving }); ctx.chosen['ap.business_unit'] = got.businessUnit; ctx.chosen['ap.supplier'] = got.supplier; ctx.saved[s.name || 'invoice_number'] = number; @@ -390,7 +481,8 @@ const ACTIONS: Record Promise> = { * (the pod may add tax on top); canceled = true or false; invoice_type = Standard, Credit memo, Debit memo or Prepayment; * payment_method = the method's name; approval_status = Not required, Required ...; validation_status = Validated, Not validated, * Needs revalidation (REST's ValidationStatus; a never validated invoice is Not validated); source = how it came in (External for - * an import, Manual Invoice Entry ...). With none of them, it checks that the invoice exists. */ + * an import, Manual Invoice Entry ...); accounting_status = Unaccounted, Draft, Accounted, Partially accounted (REST's AccountingStatus). + * With none of them, it checks that the invoice exists. */ expect_invoice: async (s, ctx) => { const number = invoiceNumber(s, ctx); const want: InvoiceExpectation = { @@ -403,6 +495,7 @@ const ACTIONS: Record Promise> = { approvalStatus: s.approval_status ? fill(s.approval_status, ctx) : undefined, validationStatus: s.validation_status ? fill(s.validation_status, ctx) : undefined, source: s.source ? fill(s.source, ctx).trim() : undefined, + accountingStatus: s.accounting_status ? fill(s.accounting_status, ctx) : undefined, }; // a scenario about approval on a pod whose invoices need none (its approval setup is off for this business unit): // not applicable here, reported as such and skipped, never a failure (seen on a 26D pod: "Not required") @@ -503,6 +596,24 @@ const ACTIONS: Record Promise> = { await restCheck(ctx, `initiate_approval ${invoice}`, () => untilRight(async () => invoiceProblems(invoice, await ctx.rest.invoiceByNumber(invoice), { approvalStatus: 'Initiated' }), `invoice ${invoice} after Approval > Initiate`, 120_000)); }, + /** Run subledger accounting on the validated invoice remembered as `name` (default invoice_number): Invoice Actions > Account in + * Draft (mode draft, the default) or Post to Ledger (mode final). Fusion must then show the invoice's AccountingStatus: Draft after + * Account in Draft (seen live), Accounted after final accounting. Draft accounting changes no ledger balance (it only makes the + * invoice's subledger journal entries, nothing goes to the General Ledger); final accounting transfers unposted journals of source + * Payables to the General Ledger, which only a person can remove, so it runs only where a scenario asks for it. An accounting rule + * that refuses the invoice fails the step in Fusion's words. Clean-up is unchanged: REST's Cancel Invoice cancels an invoice that has + * draft accounting (seen live: it stays Draft and the invoice shows Canceled), so no reversal is made first. */ + account_invoice: async (s, ctx) => { + const invoice = invoiceNumber(s, ctx); + const mode = fill(s.mode ?? 'draft', ctx).trim().toLowerCase(); + if (mode !== 'draft' && mode !== 'final') throw new Error(`account_invoice mode "${s.mode}": use draft (Account in Draft, the default) or final (Post to Ledger)`); + await restCheck(ctx, `account_invoice ${invoice}`, () => untilRight(async () => invoiceProblems(invoice, await ctx.rest.invoiceByNumber(invoice), { status: 'Validated', canceled: false }), + `invoice ${invoice} before it is accounted (only a validated invoice is)`, 30_000)); + const said = await ctx.ui.accountInvoice(invoice, mode); + const want = mode === 'final' ? 'Accounted' : 'Draft'; + await restCheck(ctx, `account_invoice ${invoice}`, () => untilRight(async () => invoiceProblems(invoice, await ctx.rest.invoiceByNumber(invoice), { accountingStatus: want }), + `invoice ${invoice} after ${mode === 'final' ? 'Post to Ledger' : 'Account in Draft'}${said.length ? ` (Fusion said: ${said.join(' | ').slice(0, 200)})` : ''}`, mode === 'final' ? 240_000 : 120_000)); + }, // Purchasing business actions /** Create a requisition of one noncatalog line on its own screen and submit it. value = the item's description * (after the test's tag); quantity (default the test value "quantity", else one) and price (default the test value @@ -640,11 +751,13 @@ const ACTIONS: Record Promise> = { const typeIs = s.transaction_type ? fill(s.transaction_type, ctx).trim() : undefined; const sourceIs = s.transaction_source ? fill(s.transaction_source, ctx).trim() : undefined; const wrong = transactionAmountProblems(typeIs, amountOf(amount, ctx, 'the amount')); - if (wrong.length) throw new Error(`create_transaction transaction_type "${typeIs || 'Invoice'}": ${wrong.join('; ')}`); + if (wrong.length && s.refused == null) throw new Error(`create_transaction transaction_type "${typeIs || 'Invoice'}": ${wrong.join('; ')}`); + const leaving = leaveOut(s); const tag = track(ctx, 'ar_transaction'); + attempting(ctx, s, `transaction ${tag}`, async () => !!(await ctx.rest.transaction(tag))); const got = await ctx.ui.createTransaction({ tag, description: 'Test transaction', amount, bu: choices(ctx, 'ar', 'business_unit'), source: choices(ctx, 'ar', 'transaction_source'), type: invoiceTypes(ctx), customer: choices(ctx, 'ar', 'customer'), - memo: choices(ctx, 'ar', 'memo_line'), typeIs, sourceIs }).catch((e: Error) => { + memo: choices(ctx, 'ar', 'memo_line'), typeIs, sourceIs, leaveOut: leaving }).catch((e: Error) => { // a type or source the scenario names and this pod does not have (no "Credit Memo" type on a 26D pod): the scenario // does not apply to this pod's setup — reported as not applicable and skipped, never a failure if (/the pod has no such transaction (type|source)/.test(String(e.message))) { @@ -670,13 +783,45 @@ const ACTIONS: Record Promise> = { * Incomplete. */ complete_transaction: async (s, ctx) => { const number = transactionNumber(s, ctx); - await ctx.ui.completeTransaction(number); + const said = await ctx.ui.completeTransaction(number); + // what Fusion showed after Complete is part of the failure when it kept the transaction Incomplete: its refusal in its words + const why = said.length ? ` (Fusion said: ${said.join(' | ').slice(0, 400)})` : ' (Fusion showed no message after Complete)'; await restCheck(ctx, `complete_transaction ${number}`, () => untilRight(async () => { const t = await ctx.rest.transaction(number); if (!t) return [`transaction ${number} is not in Fusion`]; - return /^incomplete$/i.test(transactionStatus(t)) ? [`transaction ${number} is still Incomplete`] : []; + return /^incomplete$/i.test(transactionStatus(t)) ? [`transaction ${number} is still Incomplete${why}`] : []; }, `transaction ${number} after Complete`, 120_000)); }, + /** Run subledger accounting on the completed transaction remembered as `name` (default transaction_number): Actions > Account in Draft + * (mode draft, the default) or Post to Ledger (mode final), then View Accounting must show the accounting Draft (Final) with its lines: + * Fusion's REST has no accounting status for a transaction, so the screen is the check. Draft accounting changes no ledger balance (it + * only makes the transaction's subledger journal entries); final accounting transfers unposted journals of source Receivables to the + * General Ledger, which only a person can remove, so it runs only where a scenario asks for it. Fusion's errors fail the step in its words. + * The transaction must be Complete first (REST is checked before). */ + account_transaction: async (s, ctx) => { + const number = transactionNumber(s, ctx); + const mode = fill(s.mode ?? 'draft', ctx).trim().toLowerCase(); + if (mode !== 'draft' && mode !== 'final') throw new Error(`account_transaction mode "${s.mode}": use draft (Account in Draft, the default) or final (Post to Ledger)`); + await restCheck(ctx, `account_transaction ${number}`, () => untilRight(async () => { + const t = await ctx.rest.transaction(number); + if (!t) return [`transaction ${number} is not in Fusion`]; + return /^complete$/i.test(transactionStatus(t)) ? [] : [`transaction ${number} is ${transactionStatus(t) || 'not complete'}: only a completed transaction is accounted`]; + }, `transaction ${number} before it is accounted`, 30_000)); + const got = await ctx.ui.accountTransaction(number, mode); + console.log(`[account_transaction] ${number}: ${got.said.join(' | ').slice(0, 200)}; View Accounting: status ${got.status}, ${got.lines} line(s)`); + }, + /** The Incomplete button of the completed transaction remembered as `name` (default transaction_number): Fusion must then show it + * Incomplete (REST). The way back after Account in Draft (seen live: allowed with draft accounting), so the test ends with an + * Incomplete transaction like every other Receivables test, not a completed one only a person can credit. */ + incomplete_transaction: async (s, ctx) => { + const number = transactionNumber(s, ctx); + await ctx.ui.incompleteTransaction(number); + await restCheck(ctx, `incomplete_transaction ${number}`, () => untilRight(async () => { + const t = await ctx.rest.transaction(number); + if (!t) return [`transaction ${number} is not in Fusion`]; + return /^incomplete$/i.test(transactionStatus(t)) ? [] : [`transaction ${number} is ${transactionStatus(t) || 'not Incomplete'}, expected Incomplete`]; + }, `transaction ${number} after Incomplete`, 120_000)); + }, /** Check the transaction in Fusion (REST): status (Incomplete, Complete ...: any case), amount = its exact amount, * amount_at_least = at least this (the pod may add tax), transaction_type and transaction_source as the pod names them. */ expect_transaction: async (s, ctx) => { @@ -694,6 +839,7 @@ const ACTIONS: Record Promise> = { const applyName = s.applies_to || 'transaction_number'; if (s.applies_to && !ctx.saved[applyName]) throw new Error(`create_receipt applies_to "${applyName}": no transaction is remembered under that name`); const tag = track(ctx, 'ar_receipt'); + attempting(ctx, s, `receipt ${tag}`, async () => !!(await ctx.rest.receipt(tag))); const got = await ctx.ui.createReceipt({ number: tag, amount, bu: choices(ctx, 'ar', 'business_unit'), customer: choices(ctx, 'ar', 'customer'), method: choices(ctx, 'ar', 'receipt_method'), applyTo: ctx.saved[applyName] }); for (const [k, v] of Object.entries(got)) if (v) ctx.chosen[`ar.${k}`] = v; @@ -802,7 +948,10 @@ const ACTIONS: Record Promise> = { /** Create and save a journal batch on its own screen: one debit and one credit of value (default {{tv.amount}}) on * the same account of the pod. category = the journal category (Adjustment, Accrual, Allocation, Reclass ... or a pod * value {{pod.gl.category}}; default the one Fusion fills); source = Manual, the only source a person enters (the - * subledger ones come from Create Accounting). name = what to remember the batch name as (default journal_batch). */ + * subledger ones come from Create Accounting). name = what to remember the batch name as (default journal_batch). + * credit_amount = the credit line's amount when it is not the debit's (an unbalanced journal); leave_out account = the credit + * line has no account. With `refused` the step expects Fusion to refuse the save (and the batch not to exist afterwards); a + * journal Fusion saves anyway is posted or refused by the steps that follow. */ create_journal: async (s, ctx) => { const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx) : ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : ''; @@ -811,10 +960,32 @@ const ACTIONS: Record Promise> = { const wanted = journalCategories(s, ctx); const source = s.source ? fill(s.source, ctx).trim() : ''; if (source && source.toLowerCase() !== 'manual') throw new Error(`create_journal source "${source}": a person enters only Manual journals; the others come from Create Accounting`); + const credit = s.credit_amount !== undefined && s.credit_amount !== '' ? fill(s.credit_amount, ctx) : undefined; + if (credit !== undefined) amountOf(credit, ctx, 'credit_amount'); + const leaving = leaveOut(s); const batch = track(ctx, 'gl_journal'); - const got = await ctx.ui.createJournal({ batch, amount, ledger: choices(ctx, 'gl', 'ledger'), + attempting(ctx, s, `journal batch ${batch}`, async () => !!(await ctx.rest.journalBatch(batch))); + // a scenario that posts the journal needs a period open for posting: the pod's test-data period may be a Future-Entry one (seen + // live: 06-27 lets a journal be saved and completed but Post stays disabled), so the periods the ledger's latest postings are in + // come first and the pod's own after them. A scenario that leaves the journal unposted keeps the pod's period. + const ledgers = choices(ctx, 'gl', 'ledger'); + const posts = ctx.c.steps.some((x) => x.action === 'post_journal'); + const open = posts && ledgers[0] ? await ctx.rest.postedPeriods(ledgers[0]) : []; + if (open.length) console.log(`[create_journal] the journal is posted later: period ${open.join(' or ')} (where ${ledgers[0]} posted lately) is tried before the pod's own`); + const got = await ctx.ui.createJournal({ batch, amount, creditAmount: credit, leaveOut: leaving, ledger: ledgers, category: wanted.names.length ? wanted.names : choices(ctx, 'gl', 'category'), categoryWanted: wanted.names.length > 0, - source: source ? 'Manual' : undefined, period: choices(ctx, 'gl', 'accounting_period'), account: choices(ctx, 'gl', 'account', ['ap', 'account']) }); + source: source ? 'Manual' : undefined, period: [...open, ...choices(ctx, 'gl', 'accounting_period')], account: choices(ctx, 'gl', 'account', ['ap', 'account']) }) + .catch((e: Error) => { + // a category the scenario names (Allocation) and this pod's Category list does not have: the scenario does not apply to + // this pod's setup, so it is reported as not applicable and skipped, never a failure. Not for the pod's own categories + // ({{pod.gl.category}}: those exist), nor a category Fusion refuses for another reason (that stays a failure). + if (!wanted.fromPod && String(e.message).startsWith(NO_SUCH_JOURNAL_CATEGORY)) { + const why = `Not applicable on this pod: ${String(e.message).split(':')[0]}`; + test.info().annotations.push({ type: 'not-applicable', description: why }); + test.skip(true, why); + } + throw e; + }); for (const [k, v] of Object.entries(got)) if (v && !(k === 'category' && wanted.names.length && !wanted.fromPod)) ctx.chosen[`gl.${k}`] = v; await restCheck(ctx, `create_journal ${batch}`, async () => { await untilFound(() => ctx.rest.journalBatch(batch), `journal batch ${batch} should be in Fusion after the save`); @@ -838,7 +1009,8 @@ const ACTIONS: Record Promise> = { } const status = journalStatus(b); if (!/^(unposted|selected for posting|posting in process|processing)?$/i.test(status)) { - throw new Error(`journal batch ${batch} did not post: its status is "${status}"`); + const why = String(b.ErrorMessage || '').trim(); + throw new Error(`journal batch ${batch} did not post: its status is "${status}"${why ? `: ${why}` : ''}${/period/i.test(why) ? ' (use an open period: Test data, GL accounting period)' : ''}`); } return [`journal batch ${batch} is still ${status || 'not posted'}`]; }, `journal batch ${batch} after Post`, 300_000)); @@ -864,10 +1036,9 @@ const ACTIONS: Record Promise> = { await restCheck(ctx, `reverse_journal ${batch}`, () => untilRight(async () => { const named = await ctx.rest.journalBatchesNamed(batch); if (named?.some((b) => b.BatchName !== batch)) return []; - const b = await ctx.rest.journalBatch(batch); - const flagged = b && Object.entries(b).some(([k, v]) => /revers/i.test(k) && v !== null && v !== '' - && !/^(n|no|false|not reversed)$/i.test(String(v))); - if (flagged) return []; + // the reversal is a batch of its own that Fusion names after this one (seen live: "Reverses -J "): it must + // exist. A reversal-looking field on the original batch (its reversal method, say) is not evidence of one. Only a pod that + // refuses the name search is left to Fusion's own confirmation if (named === null && said.some((t) => /revers|submitted|process/i.test(t))) return []; return [`no reversal of it is in Fusion yet${said.length ? ` (Fusion said: ${said.join(' | ').slice(0, 200)})` : ''}`]; }, `journal batch ${batch} reversal`, 180_000)); @@ -882,7 +1053,8 @@ const UI_BLOCKS: Record u invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] }, validate_invoice: { method: 'validateInvoice', args: (s, ctx) => { const n = ctx.saved[s.name || 'invoice_number']; // an imported invoice is not on the page yet: it is opened first - return [n && ctx.imported.has(n) ? n : undefined]; + // a step Fusion should refuse (Validate on a canceled invoice) is tried on the invoice opened afresh from Manage Invoices + return [n && (ctx.imported.has(n) || s.refused != null) ? n : undefined, s.refused != null]; } }, /** Find the invoice remembered as `name` (default invoice_number) on Manage Invoices: exactly it must be listed. */ find_invoice: { method: 'findInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] }, @@ -907,7 +1079,7 @@ const UI_BLOCKS: Record u export const supportedActions = () => [...Object.keys(ACTIONS), ...Object.keys(UI_BLOCKS)]; -async function runStep(s: Step, ctx: Ctx) { +async function runAction(s: Step, ctx: Ctx) { const direct = ACTIONS[s.action]; if (direct) return direct(s, ctx); const block = UI_BLOCKS[s.action]; @@ -916,6 +1088,39 @@ async function runStep(s: Step, ctx: Ctx) { await (fn as (...a: unknown[]) => Promise).apply(ctx.ui, block.args(s, ctx)); } +/** The document the refused step tried to make (noted by attempting), taken out of the context. */ +function takeAttempt(ctx: Ctx): Ctx['attempt'] { + const made = ctx.attempt; + ctx.attempt = undefined; + return made; +} + +/** A step with `refused`: the action must fail because Fusion refused it, in words that hold one of the step's (refusal.ts). Save + * reports what Fusion said instead of throwing, so what it said is the refusal. Afterwards Fusion's message window is closed, and a + * document the step tried to make must not exist in Fusion (a refusal that still saved it is a failure). */ +async function runRefused(s: Step, ctx: Ctx) { + ctx.attempt = undefined; + const run = s.action === 'save' + ? async () => { const said = await ctx.ui.save(); if (said.length) throw new FusionRefused(said.join(' | ').slice(0, 400)); } + : () => runAction(s, ctx); + const said = await expectRefusal(s.action, fill(s.refused, ctx), run, () => ctx.ui.closeDialogs()); + test.info().annotations.push({ type: 'refused', description: `${s.action}: Fusion said "${said.slice(0, 200)}"` }); + const made = takeAttempt(ctx); + if (made) { + await restCheck(ctx, `${s.action} refused: ${made.what} is not in Fusion`, async () => { + if (await made.exists()) throw new Error(`Fusion refused ${s.action} ("${said.slice(0, 120)}"), but ${made.what} exists in Fusion: it was saved anyway (the clean-up removes it)`); + }); + } +} + +async function runStep(s: Step, ctx: Ctx) { + // a canary proves the actions WORK on the pod: no step of it asks Fusion to refuse, leaves a part out or makes an odd document + if (ctx.c.canary && (s.refused != null || s.leave_out != null || s.credit_amount != null)) { + throw new Error(`${s.action}: a canary has no negative steps (refused, leave_out, credit_amount): it proves the actions work`); + } + return s.refused == null ? runAction(s, ctx) : runRefused(s, ctx); +} + /** The time a step of a scenario may take on a slow pod: a 26D screen step opens its task (one to three minutes for a work * area reached through the Navigator, seen live) and acts on it. A scenario gets at least the run's per-test limit and * this much per step, up to STEPS_CAP: a receivables scenario of six steps stopped at the flat ten minutes mid-way. */ diff --git a/automation/src/fusion/ui.ts b/automation/src/fusion/ui.ts index a6af7b8d6b3f87c16cc67029ae8c35775568abe4..e591799997e3b47047a87004d370c419cd008dc1 100644 --- a/automation/src/fusion/ui.ts +++ b/automation/src/fusion/ui.ts @@ -1,14 +1,19 @@ import * as fs from 'fs'; import { expect, test, type Locator, type Page } from '@playwright/test'; import { dateFormat, FALLBACK_FORMATS, formatDate, formatFromHint, inferDateFormat, parseDate, reformat, setDateFormat } from './dates'; -import { navLink, parseNavLinks } from './nav'; +import { navLink, parseLearnedLinks, parseNavLinks } from './nav'; import { parseHeals, pick, type HealHow, type HealKind, type HealRule } from './heal'; +import { FusionRefused, ValueRefused } from './refusal'; /** A text as a literal inside a regular expression. */ const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** The names of Receivables' complete control: 26D's Create Transaction completes with a "Complete and Close" button (its * Actions menu offers only Actions, View and Edit Distributions). */ +/** Where Receivables keeps the receipt tasks, in the order tried. On the 26D pod they are under the "Accounts Receivable" page (Create Receipt + * opens there in 19 s once the area is known); "Receipts" says the user has no such work area (a minute lost) and "Billing" waited out + * a 60 s click (five minutes lost), so these are tried last (seen live). */ +const RECEIPT_PAGES = ['Accounts Receivable', 'Receipts', 'Billing']; const COMPLETE_TRANSACTION = ['Complete', 'Complete Transaction', 'Complete and Close', 'Complete and Review', 'Complete and Create Another']; /** What a form field can be: what a user types into, picks from or ticks (never a button, link or heading). */ @@ -95,13 +100,38 @@ export function used(area: string, key: string, value: string, ok: boolean): voi try { fs.appendFileSync(f, JSON.stringify({ area: area.toUpperCase(), key, value, ok }) + '\n', 'utf-8'); } catch { /* best effort */ } } -/** Fusion did not take a value in a field (not in this user's list, or not valid there): another one may be. */ -export class ValueRefused extends Error {} +/** A work area's address this run learned by the menus (ok) or one learned earlier that no longer opens it (not ok), in the + * same file as the values (FPT_TESTDATA_USED, which every runner already sends back): the co-worker keeps the address for + * the pod as a learned navigation link, or removes it (platform/pods.py learn_nav_links). An address only, never a secret. */ +export function usedNav(workArea: string, path: string, ok: boolean): void { + const f = process.env.FPT_TESTDATA_USED; + if (!f) return; + try { fs.appendFileSync(f, JSON.stringify({ nav: workArea, path, ok }) + '\n', 'utf-8'); } catch { /* best effort */ } +} + +/** Fusion did not take a value in a field (not in this user's list, or not valid there): another one may be. When Fusion said + * why in a message, `said` holds its words (refusal.ts). */ +export { ValueRefused, FusionRefused }; + +/** A value that is not among the entries the field offers at all (a drop-down without it, a search that lists no rows): the pod + * does not have it, as opposed to a value Fusion refuses for another reason (not valid for this user or ledger). */ +export class ValueNotInList extends ValueRefused {} + +/** What createJournal's error says when the pod's Category list lacks the category a scenario asks for (steps.ts reports that as + * not applicable, never a failure): the pod has no such journal category. */ +export const NO_SUCH_JOURNAL_CATEGORY = 'the pod has no such journal category'; /** A field the screen does not show at all (as opposed to one it shows read-only or as fixed text): the only failure a * heal (heal.ts) may answer, by looking for the same field under another label. */ export class FieldMissing extends Error {} +/** A work area no menu offers this user (Fusion lists only what the user's roles grant, and an address of a work area + * the user may not open falls back to the home page without an error): retrying cannot help, the user's roles must. */ +export class WorkAreaUnavailable extends Error {} + +/** The role that grants a work area the test user is most likely to lack (named in the failure so the fix is plain). */ +const ROLE_OF_WORK_AREA: Record = { 'Purchase Orders': 'Buyer' }; + /** The run's approved heals (FPT_HEALS, set by the co-worker), parsed once per value. */ let healCache: { raw?: string; rules: HealRule[] } = { rules: [] }; const healRules = (): HealRule[] => { @@ -118,6 +148,19 @@ const navLinks = (): Record => { return navCache.links; }; +/** The links earlier runs learned for this pod (FPT_NAV_LINKS_LEARNED, set by the co-worker), parsed once per value. Apart + * from the consultant's (FPT_NAV_LINKS), which always win: a work area with one of those never uses or reports a learned one. */ +let learnedCache: { raw?: string; links: Record } = { links: {} }; +const learnedLinks = (): Record => { + const raw = process.env.FPT_NAV_LINKS_LEARNED; + if (raw !== learnedCache.raw) learnedCache = { raw, links: parseLearnedLinks(raw) }; + return learnedCache.links; +}; + +/** Work areas whose learned link did not open them in this worker: not tried again, and reported (usedNav) so the + * co-worker removes it. The menus are used instead, and the address they reach is learned afresh. */ +const droppedLearned = new Set(); + /** Work areas this test worker has reached ("Group > Page" -> its address: the page, "/fscmUI/faces/FndOverview" on 26D, * and the fndGlobalItemNodeId it carries): the next open goes straight there instead of the springboard or Navigator, * which on 26D took up to three minutes for a group the springboard does not show (Receivables, seen live). Kept per @@ -308,7 +351,7 @@ export class FusionUi { await this.answerOrganizationPrompt(); return; } catch (e) { - if (attempt >= 2) throw e; + if (attempt >= 2 || e instanceof WorkAreaUnavailable) throw e; } } } @@ -543,6 +586,7 @@ export class FusionUi { } if (await this.reopenWorkArea(group, pageName)) return; const shown = await this.openGroup(group).catch(() => [] as string[]); + let offered: string[] = []; // the work areas the group draws, for the failure's message if (shown.length) { // the group's work area entries are Fusion's "itemNode_..." elements; any visible target otherwise const item = this.page.locator('a[id^="itemNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(pageName)}\\s*$`) }).filter({ visible: true }).first(); @@ -553,6 +597,11 @@ export class FusionUi { this.reached(group, pageName); return; } + // the home page keeps an "itemNode_..." link for every work area the user may open, also those its group does not + // draw (they are hidden or beyond the group's apps): opened at its address, as reopenWorkArea does + if (await this.openFromNodeLinks(group, pageName)) return; + offered = await this.page.locator('a[id^="itemNode_"]').filter({ visible: true }).evaluateAll((els) => els + .map((e) => ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim()).filter(Boolean)).catch(() => [] as string[]); } await this.goHome(); await this.openNavigator(); @@ -562,39 +611,95 @@ export class FusionUi { const g = (await expand.count().catch(() => 0)) ? expand : await this.target(group); if (await g.isVisible().catch(() => false)) { await this.drawerClick(g); await this.settle(1500); } // expand the group const item = await this.target(pageName); - await item.waitFor({ state: 'visible', timeout: 30_000 }); + try { + await item.waitFor({ state: 'visible', timeout: 20_000 }); + } catch { + // not on the springboard, not among the node links, not in the Navigator: the user's roles do not grant it + const role = ROLE_OF_WORK_AREA[pageName]; + throw new WorkAreaUnavailable(`the test user has no access to ${group} > ${pageName}: no menu of this pod offers it to the user` + + (offered.length ? ` (its home page group shows only: ${offered.slice(0, 30).join(', ')})` : '') + + `. Give the user ${role ? `the ${role} role` : 'the role that grants this work area'}, or set another test user.`); + } await this.drawerClick(item); await this.settle(6000); this.reached(group, pageName); } - /** The work area is open: remembered as the current one, and its address's id for the next open (reopenWorkArea). */ + /** A work area whose "itemNode_..." link the home page holds but its group does not show: opened at its address + * (FndOverview?fndGlobalItemNodeId=). The link is found by its text, else by its + * id (itemNode__[New]_0, text empty until the group draws it). True when its page came. */ + private async openFromNodeLinks(group: string, pageName: string): Promise { + const nodes = await this.page.locator('a[id^="itemNode_"]').evaluateAll((els) => els.map((e) => ({ id: e.id, + text: ((e as HTMLElement).innerText || e.getAttribute('title') || e.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim() }))).catch(() => []); + const letters = (t: string) => t.toLowerCase().replace(/[^a-z0-9]/g, ''); + const want = letters(pageName); + const stem = (id: string) => letters(id.replace(/^itemNode_/, '').replace(/_\d+$/, '').replace(/New$/, '')); + const hits = nodes.filter((n) => letters(n.text) === want || stem(n.id).endsWith(want)); + // several (the same page in more groups): the one named for this group first + const hit = hits.find((n) => letters(n.id).includes(letters(group))) ?? hits[0]; + if (!hit) return false; + const { baseUrl } = fusionEnv(); + const address = `/fscmUI/faces/FndOverview?fndGlobalItemNodeId=${hit.id.replace(/_\d+$/, '')}`; + if (!(await this.openAddress(`${baseUrl}${address}`, pageName))) return false; + note('nav-link', `${group} > ${pageName} opened at the home page's link ${hit.id}`); + this.reached(group, pageName); + return true; + } + + /** The work area is open by the menus (not by a saved or learned address): remembered as the current one, and its + * address's id for the next open (reopenWorkArea). An address new to this worker and not already the pod's learned one + * is reported (usedNav) so later runs open the work area at once; never for a work area a consultant saved a link for. */ private reached(group: string, pageName: string) { this.workArea = `${group} > ${pageName}`; let url: URL | null = null; try { url = new URL(this.page.url()); } catch { return; } const id = url.searchParams.get('fndGlobalItemNodeId'); if (id && /^itemNode_\w+$/.test(id) && /^\/\w+\/faces\/\w+$/.test(url.pathname)) { - reachedWorkAreas.set(`${fusionEnv().baseUrl} | ${this.workArea}`, `${url.pathname}?fndGlobalItemNodeId=${id}`); + const address = `${url.pathname}?fndGlobalItemNodeId=${id}`; + const key = `${fusionEnv().baseUrl} | ${this.workArea}`; + const before = reachedWorkAreas.get(key); + reachedWorkAreas.set(key, address); + if (before !== address && navLink(learnedLinks(), group, pageName) !== address && !navLink(navLinks(), group, pageName)) { + droppedLearned.delete(key); + usedNav(this.workArea, address, true); + } } } - /** A work area this worker reached before, opened at its address; true when its page came (its title names it). A - * remembered address that no longer opens it is forgotten, and the menus are used. */ + /** A work area this worker reached before, or one the pod learned a link for, opened at its address; true when its page + * came (its title names it). A remembered address that no longer opens it is forgotten, and the menus are used; a + * learned one is also reported (usedNav) so the co-worker removes it, unless the page was Fusion's sign-in (the + * session, not the address, is then at fault). */ private async reopenWorkArea(group: string, pageName: string): Promise { const { baseUrl } = fusionEnv(); const key = `${baseUrl} | ${group} > ${pageName}`; - const address = reachedWorkAreas.get(key); + const learned = navLink(navLinks(), group, pageName) || droppedLearned.has(key) ? null : navLink(learnedLinks(), group, pageName); + const address = reachedWorkAreas.get(key) ?? learned; if (!address) return false; - await this.page.goto(`${baseUrl}${address}`, { waitUntil: 'domcontentloaded' }).catch(() => {}); + if (!(await this.openAddress(`${baseUrl}${address}`, pageName))) { + reachedWorkAreas.delete(key); + if (address === learned && !(await this.onSignInPage())) { + droppedLearned.add(key); + usedNav(`${group} > ${pageName}`, address, false); + note('nav-learned', `${group} > ${pageName}: the learned link did not open it, using the menus`); + } + return false; + } + this.workArea = `${group} > ${pageName}`; + return true; + } + + /** A work area opened at its address: true when its page came (its title names it). An address the user may not open + * (or that does not exist) lands on the home page without an error, so the title is what tells. */ + private async openAddress(url: string, pageName: string): Promise { + await this.page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {}); await this.settle(3000); const title = new RegExp(`(^|[-–:|]\\s*)${esc(pageName)}\\b`, 'i'); - const came = !(await this.onSignInPage()) + const signedOut = await this.onSignInPage(); + const came = !signedOut && await expect.poll(async () => title.test(await this.page.title()), { timeout: 30_000 }).toBe(true).then(() => true, () => false); - if (!came) { reachedWorkAreas.delete(key); return false; } - await this.closeDialogs(); - this.workArea = `${group} > ${pageName}`; - return true; + if (came) await this.closeDialogs(); + return came; } /** A click inside the open Navigator drawer: scrolled to its middle, and given to the element itself when a sticky @@ -666,8 +771,13 @@ export class FusionUi { // the visible one: Fusion pages keep hidden copies of many fields, and the first match is often one of those; and a // form control only: a section's collapse button can carry the name of a field in it ("Journal Batch" on 26D's // Create Journal), and typing into the button failed as "read-only" - return this.page.getByLabel(new RegExp(`^\\s*${label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s*\\(Required\\))?\\s*$`)) - .and(this.page.locator(FORM_CONTROL)).filter({ visible: true }).first(); + // "Label#idpart": a label that two fields of one page share (26D's Create Receipt names the customer's and the remittance + // bank's fields all "Name" and "Account"): the one whose id holds idpart (Oracle's own component ids, seen live: customerName, + // remittanceBankName) + const [text, idHint] = label.split('#'); + const byLabel = this.page.getByLabel(new RegExp(`^\\s*${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s*\\(Required\\))?\\s*$`)) + .and(this.page.locator(FORM_CONTROL)); + return (idHint ? byLabel.and(this.page.locator(`[id*="${idHint}" i]`)) : byLabel).filter({ visible: true }).first(); } /** Type a value (or choose it in a drop-down list) and leave the field, so Fusion runs its own logic (look-ups, @@ -730,14 +840,18 @@ export class FusionUi { * A supplier without a default site gets one chosen (ensureSupplierSite): a test of the defaulting itself checks * the site with expectFilled instead (AP-FUS-001, AP-FUS-011). */ async enterInvoiceHeader(h: { businessUnit: string | string[]; supplier: string | string[]; number: string; amount: string; date?: string; - site?: string[]; invoiceType?: string; paymentMethod?: string }) { + site?: string[]; siteOf?: Record; invoiceType?: string; paymentMethod?: string; leaveOut?: string[] }) { + // leaveOut (lower case: supplier, number, amount): a header field a negative scenario leaves empty, to see Fusion refuse the invoice + const out = (f: string) => !!h.leaveOut?.includes(f); const businessUnit = await this.putFirst('Business Unit', h.businessUnit, ['AP', 'business_unit']); - const supplier = await this.putFirst('Supplier', h.supplier, ['AP', 'supplier']); - const site = await this.ensureSupplierSite(supplier, h.site ?? []); + const supplier = out('supplier') ? '' : await this.putFirst('Supplier', h.supplier, ['AP', 'supplier']); + // the site that belongs to the supplier Fusion took (`siteOf`, from REST), else the pod's sites: a site of another supplier + // is refused, or the field stays uneditable and the click on it waits a minute. No supplier: no site to choose + const site = out('supplier') ? '' : await this.ensureSupplierSite(supplier, h.siteOf?.[supplier]?.length ? h.siteOf[supplier] : h.site ?? []); await this.chooseCurrencyIfEmpty(); if (h.invoiceType) await this.chooseInvoiceType(h.invoiceType); // before the amount: the type decides its sign - await this.put('Number', h.number); - await this.put('Amount', h.amount); + if (!out('number')) await this.put('Number', h.number); + if (!out('amount')) await this.put('Amount', h.amount); await this.put('Date', h.date || fusionDate()); if (h.paymentMethod) await this.choosePaymentMethod(h.paymentMethod); return { businessUnit, supplier, site }; @@ -828,12 +942,16 @@ export class FusionUi { * is given) charged to the pod's account, then Save. Fails with Fusion's own words when the save shows any message * or error, and waits until the invoice has a status (it exists in Fusion). `invoiceType` (a credit or debit memo has * negative amounts) and `paymentMethod` are set when given; Fusion's own defaults otherwise. Returns the values Fusion - * took. */ + * took. `leaveOut` (supplier, number, amount) leaves a header field empty, for a scenario that expects Fusion to refuse the + * invoice without it; the refusal is then a FusionRefused (refusal.ts) carrying Fusion's words. */ async createInvoice(h: { businessUnit: string | string[]; supplier: string | string[]; number: string; amount: string; - lines?: string[]; account: string; date?: string; site?: string[]; invoiceType?: string; paymentMethod?: string }) { + lines?: string[]; account: string; date?: string; site?: string[]; siteOf?: Record; invoiceType?: string; paymentMethod?: string; leaveOut?: string[] }) { await this.openTask('Payables', 'Invoices', 'Create Invoice'); const header = await this.enterInvoiceHeader(h); - const lines = h.lines?.length ? h.lines : [h.amount]; + // a header field left out (a negative scenario): no lines, straight to Save, where Fusion's refusal is the test. 26D + // keeps Lines collapsed and greyed until the header has its supplier and amount (seen live), so adding one would fail + // as the runner's, not Fusion's + const lines = h.leaveOut?.length ? [] : h.lines?.length ? h.lines : [h.amount]; let account = h.account; for (const [i, amount] of lines.entries()) account = await this.addLine(i + 1, { amount, account: h.account }); // 26D sets the invoice type back to Standard when a line's amount is entered (seen live): the type is put again before @@ -853,7 +971,7 @@ export class FusionUi { } const chosen = { ...header, account }; const said = await this.save(); - if (said.length) throw new Error(`Fusion did not save invoice ${h.number}: ${said[0].slice(0, 300)}`); + if (said.length) throw new FusionRefused(said[0].slice(0, 300), `Fusion did not save invoice ${h.number}: ${said[0].slice(0, 300)}`); await this.expectNoError(); await expect.poll(() => this.statusOnPage(h.number), { message: `invoice ${h.number} should be saved (Fusion shows its status)`, timeout: 60_000 }).not.toBe(''); @@ -933,7 +1051,7 @@ export class FusionUi { }, { timeout: 15_000 }).toBe(true).then(() => true, () => false); if (refused) { const hold = /supplier hold/i.test(refused) ? ': the supplier has a payment hold; set a supplier without one on the Test environments page (Test data, AP supplier)' : ''; - throw new Error(`Fusion did not pay invoice ${p.invoice}: ${refused.slice(0, 200)}${hold}`); + throw new FusionRefused(refused.slice(0, 200), `Fusion did not pay invoice ${p.invoice}: ${refused.slice(0, 200)}${hold}`); } if (!opened) throw new Error(`Pay in Full opened no window for invoice ${p.invoice}: the screen changed (verify Pay in Full on the pod)`); if (p.method) { // the window may offer the method; when it does not, the invoice's own method is what is paid with @@ -943,7 +1061,31 @@ export class FusionUi { await this.ensureFilled(['Bank Account', 'Disbursement Bank Account'], p.bank, ['AP', 'bank_account'], { required: false }); await this.ensureFilled(['Payment Process Profile'], p.profile, ['AP', 'payment_process_profile'], { required: false }); await this.ensureFilled(['Payment Document'], p.document, ['AP', 'payment_document'], { required: false }); - await this.answerWindow(['OK', 'Submit', 'Pay', 'Yes']); + // 26D draws the window as a popup selector, not as a role=dialog (seen live: getByRole('dialog') found none), so + // answerWindow, which looks in dialogs, never pressed Submit and the step went on as if the invoice had been paid. Its + // own Submit is pressed here; the dialog route stays for layouts that open Pay in Full as a dialog + const payWindow = this.page.locator('.AFPopupSelector').or(this.page.getByRole('dialog')).filter({ hasText: /Pay in Full:/i }) + .filter({ has: this.page.getByRole('button', { name: 'Submit', exact: true }) }).filter({ visible: true }); + const submit = payWindow.first().getByRole('button', { name: 'Submit', exact: true }); + if (await submit.isVisible().catch(() => false)) { await this.pressEnabled(submit, 'Submit in Pay in Full'); await this.settle(3000); } + else await this.answerWindow(['OK', 'Submit', 'Pay', 'Yes']); + // Fusion closes Pay in Full when it takes the payment; a window that stays open (a required field still empty, a refusal + // shown inside it) means nothing was paid. Its messages fail the step; the window is cancelled so the invoice can still be + // cancelled by the clean-up + if (await expect.poll(() => payWindow.count(), { timeout: 20_000 }).toBe(0).then(() => false, () => true)) { + const inside = (await payWindow.first().innerText().catch(() => '')).replace(/\s+/g, ' ').trim(); + const msgs = (await this.messages()).filter((m) => m.replace(/\s+/g, ' ').trim() !== inside && !/^\s*Pay in Full\b/i.test(m)); + const empty = [] as string[]; + for (const l of ['Bank Account', 'Payment Process Profile', 'Payment Document']) { + if (await this.field(l).isVisible().catch(() => false) && !(await this.value(l))) empty.push(l); + } + // its own Cancel (closeDialogs does not see this window: it is no role=dialog) + await payWindow.first().getByRole('button', { name: 'Cancel', exact: true }).click().catch(() => {}); + await this.settle(1500); + await this.closeDialogs(); + throw new Error(`Pay in Full did not pay invoice ${p.invoice}: its window stayed open after Submit` + + `${msgs.length ? `; Fusion said ${msgs.join(' | ').slice(0, 400)}` : ''}${empty.length ? `; still empty: ${empty.join(', ')} (set ap bank account / payment process profile on the Test environments page)` : ''}`); + } const said = await this.settleWindows(`paying invoice ${p.invoice}`); const named = /\bPayment\s+(?:Number\s+)?#?(\d[\w-]*)\b/i.exec(said.join(' ')); return { number: named?.[1] ?? '', said }; @@ -964,6 +1106,16 @@ export class FusionUi { await this.openResult([number]); await this.menuFirst(['Actions', 'Payment Actions'], ['Void Payment', 'Void'], `voiding payment ${number}`); await this.answerWindow(['OK', 'Void', 'Submit', 'Yes'], CANCEL_REASON); + // the Void Payment window (26D: Void Date, Accounting Date, Invoice Action, Submit / Cancel) closes once Fusion takes the + // void; one still open means nothing was voided, and the step must not pass on it + const voidWindow = this.page.locator('.AFPopupSelector').or(this.page.getByRole('dialog')).filter({ hasText: /Void Payment/i }) + .filter({ has: this.page.getByRole('button', { name: /^(Submit|OK|Void)$/ }) }).filter({ visible: true }); + if (await expect.poll(() => voidWindow.count(), { timeout: 20_000 }).toBe(0).then(() => false, () => true)) { + const msgs = (await this.messages()).filter((m) => !/^\s*Void Payment(?: |$)/i.test(m)); + await voidWindow.first().getByRole('button', { name: /^(Cancel|Close)$/ }).click().catch(() => {}); + await this.settle(1500); + throw new Error(`Void Payment did not void payment ${number}: its window stayed open${msgs.length ? `; Fusion said ${msgs.join(' | ').slice(0, 400)}` : ''}`); + } return this.settleWindows(`voiding payment ${number}`); } @@ -1035,6 +1187,29 @@ export class FusionUi { return this.settleWindows(`withdrawing the approval of invoice ${number}`); } + /** Business action account_invoice: subledger accounting on the validated invoice `number` (opened from Manage Invoices when it is + * not on the page; the Invoice Details panel's menu is "Actions"): Invoice Actions > Account in Draft (`mode` draft, the default) + * or Post to Ledger (`mode` final), Fusion's answers settled (an error fails the step in its words). + * DRAFT ACCOUNTING CHANGES NO LEDGER BALANCE: it only creates the invoice's subledger journal entries (status Draft, and the + * invoice's AccountingStatus says Draft); nothing is transferred to the General Ledger, so no journal of source Payables is made + * and no balance moves. Final (Post to Ledger) is the other way round: it creates final accounting and transfers it to the + * General Ledger as unposted journals of source Payables, which a person has to delete or post (from Oracle's documentation, NOT run + * live): a scenario that asks for it is one a client has agreed to. Fusion answers in a Confirmation ("The accounting has been completed.", with View Accounting and + * OK buttons, seen live for Account in Draft, ~13s after the menu entry; REST's AccountingStatus was Draft by then): settleWindows + * closes it with OK, so a later Cancel Invoice on the page is not covered by it (seen live: a Confirmation left open made the + * next click time out). A Confirmation that is not that sentence or that names an error is the failure. Returns what Fusion said. */ + async accountInvoice(number: string, mode: 'draft' | 'final' = 'draft'): Promise { + if (!(await this.invoiceOpen(number))) await this.openInvoice(number); + const entry = mode === 'final' ? 'Post to Ledger' : 'Account in Draft'; + const what = `accounting invoice ${number} (${entry})`; + await this.menuFirst(['Invoice Actions', 'Actions'], [entry], what); + const said = await this.settleWindows(what); + // a Confirmation that reports accounting errors ("completed with errors") is no success, whatever its heading says + const bad = said.find((t) => /\b(errors?|failed|failure|could not|cannot|can.t|not completed|not accounted)\b/i.test(t)); + if (bad) throw new Error(`${what}: Fusion said ${bad.slice(0, 400)}`); + return said; + } + /** A business unit without a default currency leaves Invoice Currency empty, and Fusion then refuses the lines ("the * invoice header is incomplete"). Choose the pod's own invoice currency (its records' most used); nothing to do when * Fusion filled it, or when the screen has no such list. */ @@ -1086,7 +1261,17 @@ export class FusionUi { await this.settle(); } await amount.click(); await amount.fill(line.amount); await amount.press('Tab'); await this.settle(1500); - return this.putLineAccount(row.getByRole('textbox', { name: 'Distribution Combination ID' }), line.account); + const account = row.getByRole('textbox', { name: 'Distribution Combination ID' }); + // a supplier with a default distribution set (seen live: ABC Consulting's "Contractor Expense (Single Distribution)") has the + // line's Distribution Combination disabled: Fusion distributes the line by the set, as it does for a clerk who keeps it. The + // click on the disabled field waited a minute and failed the step. Waited for a moment first: the field enables itself + // after the amount when the line has no set + if (!(await expect.poll(() => account.first().isEnabled().catch(() => false), { timeout: 4_000 }).toBe(true).then(() => true, () => false))) { + const set = await row.getByRole('textbox', { name: /^Distribution Set/ }).first().inputValue().catch(() => ''); + console.log(`[invoice line ${n}] Distribution Combination is disabled${set ? ` (distribution set "${set}")` : ''}: Fusion's own distribution kept`); + return line.account; + } + return this.putLineAccount(account, line.account); } /** The line's distribution combination. The pod's newest invoices can carry an account of another chart of accounts @@ -1199,8 +1384,11 @@ export class FusionUi { * once more if validating is what added the tax. A scenario that tests an amount mismatch uses invoiceAction. An * invoice already Validated needs nothing (Fusion would grey out Validate). `number` = an invoice that arrived through an import: * it is not on a page of this test yet, so it is opened from Manage Invoices first. */ - async validateInvoice(number?: string) { - if (number && !(await this.invoiceOpen(number))) await this.openInvoice(number); + async validateInvoice(number?: string, reopen = false) { + // `reopen`: the invoice is opened afresh even when its page is the one showing. The edit page a Cancel Invoice was done on keeps + // its state (seen live on 26D: Validate pressed there answered nothing, while the invoice opened again from Manage Invoices + // answers "You can't validate this invoice because it's been canceled."): a clerk opens the invoice again to try it + if (number && (reopen || !(await this.invoiceOpen(number)))) await this.openInvoice(number); if ((await this.statusOnPage()) === 'Validated') return; const balance = async () => { const t = await this.invoiceTotal(); @@ -1212,6 +1400,18 @@ export class FusionUi { await balance(); await this.invoiceAction('Validate'); await this.settle(3000); + // Fusion lists Validate even on a canceled invoice and answers it with an error window ("You can't validate this invoice because + // it's been canceled.", seen live on 26D, AP-FUS-054): its words are the result, said as Fusion's refusal + // (the error window can take a few seconds to show: looked for until the invoice shows Validated or a few seconds pass) + let refusal: string | undefined; + for (let i = 0; i < 8 && !(refusal = (await this.dialogs()).find((m) => /^\s*Error\b/.test(m))) && (await this.statusOnPage()) !== 'Validated'; i++) { + await this.page.waitForTimeout(1000); + } + if (refusal) { + const said = refusal.replace(/^\s*Error\s*/, '').replace(/\s*OK\s*$/, '').trim(); + await this.answerDialog('OK').catch(() => {}); + throw new FusionRefused(said.slice(0, 300), `Fusion did not validate the invoice: ${said.slice(0, 300)}`); + } if ((await this.statusOnPage()) !== 'Validated' && await balance()) { await this.invoiceAction('Validate'); await this.settle(3000); @@ -1237,12 +1437,19 @@ export class FusionUi { if (msgs.length) return msgs; await this.page.waitForTimeout(1000); } - return []; + // a refusal Fusion shows beside the field, with no message window ("Error: A value is required." under an Amount left empty: + // seen live, AP-FUS-053): the page's own error notes are Fusion's answer to the save + const inline = (await this.page.getByText(/^\s*Error:\s*\S/).filter({ visible: true }).allInnerTexts().catch(() => [] as string[])) + .map((t) => t.replace(/\s+/g, ' ').trim()).filter((t, i, all) => t && all.indexOf(t) === i); + return inline; } /** Run an entry of the Invoice Actions menu (Validate, Cancel Invoice, Manage Holds, ...). */ async invoiceAction(name: string) { - await this.menuAction('Invoice Actions', name); + // the edit page's menu is "Invoice Actions"; the Invoice Details panel a Manage Invoices result opens in has "Actions" + const full = await this.page.getByRole('button', { name: 'Invoice Actions', exact: true }).or(this.page.getByText('Invoice Actions', { exact: true })) + .filter({ visible: true }).count().catch(() => 0); + await this.menuAction(full ? 'Invoice Actions' : 'Actions', name); } /** Press the visible button named `name` (a scenario's click step). A button the screen does not show at all is looked @@ -1273,8 +1480,11 @@ export class FusionUi { } /** The choices a list field offers this user (up to `max`), read the way a user sees them: a drop-down's entries, or - * the rows a list of values shows on the down arrow. Read-only: the list is closed again and nothing is chosen. */ - async listChoices(label: string, max = 5): Promise { + * the rows a list of values shows on the down arrow. Read-only: the list is closed again and nothing is chosen, unless + * `pick`: the first choice is then clicked in the list, as a user picks it (what a field inside a window needs: typing a + * row's text there did not match, Fusion opened its "Search and Select" window; the row's first cell, the value Fusion + * keeps, is what the field then shows). Returns the choices read (the one picked first). */ + async listChoices(label: string, max = 5, pick = false): Promise { const f = this.field(label); if (!(await f.isVisible().catch(() => false))) return []; const select = (await f.evaluate((e) => e.tagName).catch(() => '')) === 'SELECT' ? f @@ -1288,33 +1498,78 @@ export class FusionUi { const items = () => this.page.locator('tr:visible, [role="option"]:visible, li:visible').evaluateAll((els) => els.map((e) => { const text = ((e as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim(); // a list of values' row ("Select Row" + the value's columns), a search-select's row (role row: the value itself), - // or an option; any other table row (a container of rows) is not a value - const first = e.tagName === 'TR' && /^Select Row/.test(text) + // an option, or a row of a combobox's drop-down popup (a plain row: the popup's id says "dropdownPopup" or + // "autosuggestpopup"; seen live on 26D Pay in Full: "BofA-2869 10271-17621-619" with no role and no Select Row cell: + // the value is the first cell, "BofA-2869", and the account number beside it only describes it); any other table + // row (a container of rows) is not a value + const popup = !!e.closest('[id*="dropdownPopup"], [id*="autosuggestpopup"]'); + const cell = () => Array.from(e.querySelectorAll('td')).map((td) => ((td as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim()).find((t) => t) || ''; + const first = e.tagName === 'TR' && popup && !e.querySelector('tr') ? cell() + : e.tagName === 'TR' && /^Select Row/.test(text) ? Array.from(e.querySelectorAll('td')).map((td) => ((td as HTMLElement).innerText || '').replace(/\s+/g, ' ').replace(/^\s*Select Row\s*/, '').trim()) .find((t) => t) || '' - : e.tagName === 'TR' ? (e.getAttribute('role') === 'row' ? text : '') : text; + : e.tagName === 'TR' ? (e.getAttribute('role') === 'row' || popup ? text : '') : text; return { text, value: first }; })).catch(() => [] as { text: string; value: string }[]); const before = new Set((await items()).map((i) => i.text)); + // the field inside a window (26D's Pay in Full, a create-and-edit popup): Escape would close the whole window, so the + // list is dismissed with a click on the window's own title bar instead + const win = this.windowOf(f); + const inWindow = (await win.count().catch(() => 0)) > 0; + // the user's recently used values come first, named "MRU Row " (an empty one: "... Empty Cell") + const read = async () => (await items()).filter((i) => !before.has(i.text) && i.value).map((i) => i.value.replace(/^MRU Row \d+\s*/i, '')) + .filter((v) => v.length <= 120 && !/^(All|Empty Cell|Search\.*|More\.*|Previous|Next.*|No results.*)$/i.test(v) && !/\d+-\d+ of \d+/.test(v)); // a list of values (its input is the field) opens on the down arrow; a search-select (a box wrapping its input, - // Ledger, Accounting Period) opens on a click on the box + // Ledger, Accounting Period) opens on a click on the box. A combobox list of values in a window did not open on the + // plain down arrow (seen live: Pay in Full's Bank Account, Payment Process Profile, Payment Document): it opens on + // Alt+Down, which is tried when the plain arrow showed nothing + let got: string[] = []; if ((await f.evaluate((e) => e.tagName).catch(() => '')) === 'INPUT') { if (!(await f.isEditable().catch(() => false))) return []; await f.click({ timeout: 5000 }).catch(() => {}); - await this.page.keyboard.press('ArrowDown').catch(() => {}); + for (const key of ['ArrowDown', 'Alt+ArrowDown']) { + await this.page.keyboard.press(key).catch(() => {}); + await this.settle(2500); + if ((got = await read()).length) break; + } } else { await f.click({ timeout: 5000 }).catch(() => {}); + await this.settle(2500); + got = await read(); + } + const uniqueOf = (v: string[]) => { const u = Array.from(new Set(v)); return u.filter((x) => !u.some((o) => o !== x && x.includes(o) && x.length > o.length + 2)); }; + const chosen = uniqueOf(got)[0]; + if (pick && chosen) { + // the leaf row of the open list whose first cell is the value (a container row repeats every row's text) + const row = this.page.locator('[id*="dropdownPopup"] tr:not(:has(tr)):visible, [id*="autosuggestpopup"] tr:not(:has(tr)):visible') + .filter({ hasText: chosen }).first(); + if (await row.isVisible().catch(() => false)) { + await row.click({ timeout: 5000 }).catch(() => {}); + await this.settle(2000); + return [chosen]; + } + } + if (inWindow) { + const title = win.locator('[id$="_ttxt"]').first(); + if (await title.isVisible().catch(() => false)) await title.click().catch(() => {}); + else { + const box = await win.boundingBox().catch(() => null); + if (box) await this.page.mouse.click(box.x + box.width / 2, box.y + 8).catch(() => {}); + } + } else { + await this.page.keyboard.press('Escape').catch(() => {}); + await this.settle(600); + await this.page.locator('body').click({ position: { x: 5, y: 5 } }).catch(() => {}); // a list still open covers the page } - await this.settle(2500); - // the user's recently used values come first, named "MRU Row " (an empty one: "... Empty Cell") - const got = (await items()).filter((i) => !before.has(i.text) && i.value).map((i) => i.value.replace(/^MRU Row \d+\s*/i, '')) - .filter((v) => v.length <= 120 && !/^(All|Empty Cell|Search\.*|More\.*|Previous|Next.*|No results.*)$/i.test(v) && !/\d+-\d+ of \d+/.test(v)); - await this.page.keyboard.press('Escape').catch(() => {}); await this.settle(600); - await this.page.locator('body').click({ position: { x: 5, y: 5 } }).catch(() => {}); // a list still open covers the page // a container entry repeats its entries' text: keep the single values - const uniq = Array.from(new Set(got)); - return uniq.filter((v) => !uniq.some((o) => o !== v && v.includes(o) && v.length > o.length + 2)).slice(0, max); + return uniqueOf(got).slice(0, max); + } + + /** The window (a dialog, or 26D's popup selector such as Pay in Full) a field is in: matches nothing for a field of the page. + * Escape and the page's own Cancel are not for such a field: either closes the whole window. */ + private windowOf(f: Locator): Locator { + return f.locator('xpath=ancestor::*[@role="dialog" or contains(@class,"AFPopupSelector")][1]'); } /** Run an entry of any menu of the page (the screen inventory lists them: "Actions", "Invoice Actions", ...). */ @@ -1342,6 +1597,38 @@ export class FusionUi { await this.settle(5000); } + /** Business action expect_unavailable: the entry (any of `entries`) of the first of `menus` the page shows is not usable + * now: Fusion greys it out (aria-disabled) or does not list it. The menu must open and list something, so a page that + * never opened it (or a menu with another name) fails the step instead of passing it; an entry that IS usable fails it, + * naming it. The menu is closed again and nothing is pressed. Returns what the menu showed, for the test's report. */ + async expectEntryUnavailable(menus: string[], entries: string[]): Promise { + let menu = ''; + for (const m of menus) { + const opener = this.page.getByRole('button', { name: m, exact: true }).or(this.page.getByText(m, { exact: true })).filter({ visible: true }).first(); + if (await opener.isVisible().catch(() => false)) { await opener.click(); menu = m; break; } + } + if (!menu) throw new Error(`the page shows no ${menus.map((m) => `"${m}"`).join(' or ')} menu to look at: cannot tell whether ${entries.join(' / ')} is available (verify the screen on the pod)`); + await this.settle(1500); + try { + const listed = await this.menuEntries(); + if (!listed.length) throw new Error(`the ${menu} menu opened and lists no entries: cannot tell whether ${entries.join(' / ')} is available`); + const usable: string[] = []; + const state: string[] = []; + for (const e of entries) { + const item = this.page.getByRole('menuitem', { name: new RegExp(`^\\s*${esc(e)}\\b`) }).filter({ visible: true }).first(); + if (!(await item.count().catch(() => 0))) { state.push(`${e}: not listed`); continue; } + const off = (await item.getAttribute('aria-disabled').catch(() => null)) === 'true' || await item.isDisabled().catch(() => false); + state.push(`${e}: ${off ? 'greyed out' : 'available'}`); + if (!off) usable.push(e); + } + if (usable.length) throw new Error(`Fusion offers ${usable.join(' / ')} in the ${menu} menu, but it should not (the menu lists: ${listed.join(', ').slice(0, 300)})`); + return `${menu} menu (${listed.join(', ').slice(0, 300)}): ${state.join('; ')}`; + } finally { + await this.page.keyboard.press('Escape').catch(() => {}); + await this.settle(500); + } + } + /** The entries of the menu open now. */ private async menuEntries(): Promise { return (await this.page.getByRole('menuitem').filter({ visible: true }).allInnerTexts().catch(() => [] as string[])) @@ -1371,7 +1658,7 @@ export class FusionUi { const said = await this.dialogs(); if (!said.length) return; await this.closeDialogs(); - throw new Error(`Fusion would not add a row to ${section}: ${said[0].slice(0, 300)}`); + throw new FusionRefused(said[0].slice(0, 300), `Fusion would not add a row to ${section}: ${said[0].slice(0, 300)}`); } /** A field of a table row by its column label; Fusion names row cells "