Astra 0598704: 26D AP/AR/GL fixes verified live, payments, subledger accounting, edge cases, learned navigation, consultant step import (059870495533)
2d71dc3 verified Download automation/src/fusion/steps.ts from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 87.3 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/automation/src/fusion/steps.ts
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/automation/src/fusion/steps.ts
-
curl -L -o steps.ts https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/automation/src/fusion/steps.ts
87.3 kB
import * as fs from 'fs';
import * as path from 'path';
import YAML from 'yaml';
import { approvalRef, expect, paymentRef, test, type DocKind, type FusionDocs } from './fixtures';
import { activeHolds, closeAction, invoiceAmountProblems, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, orderCloseable,
orderReceivable, orderStatus, paymentProblems, paymentTypeKey, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation, type PaymentExpectation } from './rest';
import { invoiceApprovalStatus, transactionAmountProblems, type TransactionExpectation } from './rest';
import { expectRefusal, FusionRefused } from './refusal';
import { apInvoiceFiles, arTransactionFiles, fbdiDate, importBody, importsAllowed, IMPORTS_REFUSED } from './interfaces';
import { apDataSets, fusionDate, NO_SUCH_JOURNAL_CATEGORY, podCandidates, podToday, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui';
/*
* Step runner: executes a scenario written as plain steps in tests/cases/<ID>.yaml (runner: steps), with no
* hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright
* runs them the same way every time. Unknown actions fail the step with a clear message, never guess.
*
* Step fields: action, field, value, expected (shown in the report and the live view).
* Values may use {{pod.<area>.<key>}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}},
* {{tv.<test_values key>}} and {{saved.<name>}} (a value remembered by an earlier `remember` step).
*
* Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not
* break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice,
* expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario
* per area (tests/cases/CANARY-<AREA>.yaml) runs each of them once before a run, to prove they still work on the pod.
* Purchasing: create_requisition, expect_requisition, cancel_requisition, create_purchase_order, submit_purchase_order,
* find_purchase_order, expect_purchase_order, cancel_purchase_order (extra fields quantity, price). General Ledger:
* create_journal, post_journal, find_journal, expect_journal, reverse_journal (extra field posted). Receivables:
* create_transaction, complete_transaction, find_transaction, expect_transaction, create_receipt, find_receipt,
* expect_receipt (extra field applies_to: the transaction a receipt is applied to). Receiving: create_receipt_for_order and
* expect_receipt_of_order (extra fields applies_to: the order, and quantity), close_purchase_order (value: how). create_invoice and expect_invoice also
* take invoice_type (Standard, Credit memo, Debit memo, Prepayment) and payment_method (the pod's: Check, Electronic, Wire);
* expect_invoice also checks approval_status (Not required, Required ...) and validation_status (Validated, Not validated,
* Needs revalidation).
* Payments (scenario-only, never in a canary): create_payment (a quick payment of a validated invoice: applies_to = the invoice's
* remembered name, payment_method, payment_type Quick; name = what to remember the payment number as, payment_number),
* find_payment, expect_payment (status, amount, amount_at_least, payment_method, payment_type), void_payment. A payment the
* test leaves is voided by the clean-up, before the invoice is cancelled.
* initiate_approval (scenario-only: name = the invoice's remembered name) sends a validated invoice for approval (Invoice Actions >
* Approval > Initiate) and checks Fusion shows the approval Initiated; the clean-up withdraws it before the invoice is cancelled.
* Subledger accounting (scenario-only, never in a canary; the General Ledger's journals of source Payables and Receivables come from it):
* account_invoice (a validated invoice: Invoice Actions > Account in Draft, or Post to Ledger with mode final; expect_invoice then checks
* accounting_status Draft / Accounted) and account_transaction (a completed transaction: Actions > Account in Draft or Post to Ledger,
* checked in View Accounting, since REST has no accounting status for a transaction), with incomplete_transaction to take a completed
* transaction back to Incomplete. Draft accounting changes no ledger balance; the invoice clean-up (cancel) is unchanged by it.
* Interfaces (scenario-only, never in a canary; they write through Fusion's ERP Integration REST service, so they need REST and the pod's
* "allow imports" setting, FPT_ALLOW_IMPORTS=1): import_payables_invoice (a FBDI file through Payables invoice import; source = the
* invoice source, External by default) and import_receivables_transaction (a FBDI file through AutoInvoice; transaction_source = an import
* source of the pod, transaction_type). Each remembers the number of the document the import created (name), checked by expect_invoice
* (source) or expect_transaction (transaction_source) like any other; the clean-up cancels an imported invoice, an imported
* transaction that is complete is listed for a person to credit.
*
* Negative scenarios: `refused: "<words>"` on a step says Fusion must say no to it. The step passes only when the action failed
* BECAUSE Fusion refused (its message window, error note or field message holds one of the |-separated words, any case); it fails
* when Fusion takes the action ("Fusion took X that it should refuse"), when the action fails for the runner's own reason (a locator
* timeout, a page that did not open), or when Fusion refuses with other words (refusal.ts). The runner's own pre-checks (the sign
* of an invoice or transaction amount) are not made on a refused step, so Fusion's validation is what is tested. A document the
* refused step tried to make is registered for clean-up before the save, as always, and must not exist in Fusion afterwards.
* Fields: leave_out (create_invoice: supplier, number, amount; create_journal: account = the credit line's; create_transaction:
* customer, lines) leaves that part empty; credit_amount (create_journal) makes the credit differ from the debit (unbalanced).
* expect_unavailable (field = menu, value = entry, or entries separated by |): Fusion greys the entry out or does not list it.
*/
export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[];
lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean;
quantity?: string | number; price?: string | number; posted?: boolean; applies_to?: string; invoice_type?: string; payment_method?: string;
category?: string; source?: string; payment_type?: string; approval_status?: string; validation_status?: string; accounting_status?: string; mode?: string;
refused?: string; leave_out?: string | string[]; credit_amount?: string | number }
export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record<string, unknown>;
canary?: boolean } // a canary (tests/cases/CANARY-<AREA>.yaml): create_invoice tries the pod's data sets in turn
const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases');
/**
* The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds
* that id (the co-worker's staging folder for drafts), else from the script library tests/cases/.
*/
export function stepCaseFile(id: string, dir?: string): string {
for (const d of [dir, process.env.FPT_STEPS_DIR]) {
if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`);
}
return path.join(CASES_DIR, `${id}.yaml`);
}
export function loadStepCase(id: string, dir?: string): StepCase {
const f = stepCaseFile(id, dir);
const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase;
if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`);
return c;
}
type Ctx = { ui: FusionUi; c: StepCase; saved: Record<string, string>; uniques: Record<string, string>; track: (n: string) => string;
imported: Set<string>; // the invoices an import made (import_payables_invoice): validate_invoice opens them from Manage Invoices first
chosen: Record<string, string>; // the pod value Fusion accepted, per "area.key", used again for the rest of the test
orderTags: Record<string, string>; // the test's tag of each purchase order made, by its number (its receipt names it for clean-up)
attempt?: { what: string; exists: () => Promise<boolean> }; // a document a refused create_ step tried to make: it must not exist afterwards
rest: FusionRest; // Fusion REST, for the business actions that check what the screens did
docs: FusionDocs }; // Purchasing and General Ledger test documents, cleaned up after the test
function fill(raw: unknown, ctx: Ctx): string {
return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => {
const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key);
if (pod) return ctx.chosen[`${pod[1]}.${pod[2]}`.toLowerCase()] ?? podValue(pod[1], pod[2]); // the pod's own test data
if (key === 'today') return fusionDate();
if (key.startsWith('unique:')) { const t = key.slice(7); return (ctx.uniques[t] ??= testNumber(t)); }
if (key.startsWith('tv.')) return String(ctx.c.test_values?.[key.slice(3)] ?? '');
if (key.startsWith('saved.')) return ctx.saved[key.slice(6)] ?? '';
throw new Error(`unknown placeholder {{${key}}}`);
});
}
/** Enter a value. A value that is exactly one pod test data placeholder ({{pod.ap.business_unit}}) is tried with each
* value the pod has for it, in order, until Fusion accepts one (a business unit this user may use, a source that
* exists on this pod): the first that works is kept for the rest of the test and remembered for the next run. */
async function putValue(s: Step, ctx: Ctx, put: (v: string) => Promise<void>): Promise<void> {
const ref = /^\s*\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}\s*$/i.exec(String(s.value ?? ''));
const key = ref ? `${ref[1]}.${ref[2]}`.toLowerCase() : '';
if (!ref || ctx.chosen[key]) return put(fill(s.value, ctx));
const tried: string[] = [];
for (const v of podCandidates(ref[1], ref[2])) {
try {
await put(v);
ctx.chosen[key] = v;
used(ref[1], ref[2], v, true);
return;
} catch (e) {
if (!(e instanceof ValueRefused)) throw e;
used(ref[1], ref[2], v, false);
tried.push(v);
}
}
throw new Error(`Fusion accepted none of the ${tried.length} value(s) this pod has for ${ref[2].replace(/_/g, ' ')} in ` +
`"${s.field}" (${tried.join(', ')}): this test user is not offered any of them; set one it may use on the Test environments page`);
}
/** The invoice a business action works on: the number create_invoice (or a `remember` step) stored under the step's
* `name`, "invoice_number" when it names none. */
function invoiceNumber(s: Step, ctx: Ctx): string {
const name = s.name || 'invoice_number';
const n = ctx.saved[name];
if (!n) throw new Error(`${s.action} needs an invoice: no invoice number is remembered as "${name}" (create_invoice or remember it first)`);
return n;
}
/** A number a step gives (an amount), filled in from its placeholders. */
function amountOf(raw: string | number, ctx: Ctx, what: string): number {
const v = Number(fill(raw, ctx).replace(/,/g, ''));
if (!Number.isFinite(v)) throw new Error(`${what} must be a number, got "${fill(raw, ctx)}"`);
return v;
}
/** Ask Fusion (REST) until `problems` comes back empty: REST can lag a few seconds behind what the screen saved. Fails
* with the last problems in words. */
async function untilRight(problems: () => Promise<string[]>, what: string, timeoutMs = 60_000) {
const end = Date.now() + timeoutMs;
for (;;) {
const p = await problems();
if (!p.length) return;
if (Date.now() > end) throw new Error(`${what}: ${p.join('; ')}`);
await new Promise((r) => setTimeout(r, 3000));
}
}
/** A business action's check through Fusion REST. On a pod with assisted sign-in there is no password for REST: the
* check is skipped with a note on the test (the screen steps before it already ran and stand). */
async function restCheck(ctx: Ctx, what: string, fn: () => Promise<void>): Promise<void> {
if (ctx.rest.available) return fn();
test.info().annotations.push({ type: REST_SKIPPED, description: `${what}: ${NO_REST_WHY}` });
}
/** The pod values to try for an AP test data key: the one Fusion already took in this test, else the pod's candidates. */
const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chosen[`ap.${key}`]] : podCandidates('ap', key);
/** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */
const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } };
/** A scenario that pays its invoice: the suppliers the pod pays (paid_supplier, from its paid invoices) come first, then
* the usual ones. The latest invoices' supplier can carry a payment hold, and Fusion then refuses Pay in Full (seen live). */
const pays = (ctx: Ctx) => ctx.c.steps.some((s) => s.action === 'create_payment');
const paidFirst = (ctx: Ctx, paid: string, usual: () => string[], lead: string[] = []): string[] => {
let first: string[] = [...lead];
if (pays(ctx) && !ctx.chosen[`ap.${paid.replace('paid_', '')}`]) { try { first = [...first, ...podCandidates('ap', paid)]; } catch { /* not discovered yet */ } }
let rest: string[] = [];
try { rest = usual(); } catch (e) { if (!first.length) throw e; }
return [...first, ...rest].filter((v, i, all) => all.indexOf(v) === i);
};
/** The method a scenario pays by: its create_payment step's payment_method ('' when no step names one). */
const payMethod = (ctx: Ctx): string => {
const step = ctx.c.steps.find((s) => s.action === 'create_payment' && s.payment_method);
return step ? fill(step.payment_method!, ctx).trim() : '';
};
/** The suppliers a paying scenario's invoice goes to, each with the site that belongs to it (so the supplier and its site are
* chosen as a PAIR: the discovered paid_supplier and paid_supplier_site are independent most-frequent lists, and a site of another
* supplier is refused or leaves Supplier Site uneditable, seen live as a 60 s click timeout). A scenario that pays by a method (AP-FUS-020
* Electronic, 021 Check, 022 Wire) needs a supplier site the pod pays by that method:
* 26D's Pay in Full pays with the invoice's own method, the supplier site's. The suppliers and sites of the business unit's newest
* invoices of that method come first (rest.suppliersPaidBy: those paid before, then the most frequent); a scenario that names no
* method gets the business unit's paid pairs. Null when the scenario does not pay, the test already chose its supplier, there is no
* REST, or REST could not answer (the usual order then stands); fails in words when REST answers that no invoice of the business
* unit uses the method. */
async function paidByMethod(ctx: Ctx): Promise<{ suppliers: string[]; sites: string[]; siteOf: Record<string, string[]> } | 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<string, string[]> = {};
for (const f of found) if (f.site) (siteOf[f.supplier] ??= []).push(f.site);
return { suppliers: found.map((f) => f.supplier), sites: found.map((f) => f.site).filter(Boolean), siteOf };
}
if (answered && method) throw new Error(`no supplier in ${units.join(' / ') || 'the business unit'} is paid by ${method}: this scenario pays by ${method}, and 26D's Pay in Full pays with the supplier site's own method; set a supplier (and site) the pod pays by ${method} on the Test environments page (Test data, AP supplier)`);
return null;
}
const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200);
/** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an
* invoice. A shared pod's sampled data can be whoever used it last (a supplier without a default site, an account of
* another ledger); the set that works is recorded as accepted (FPT_TESTDATA_USED), so the co-worker learns it and the
* run's other scenarios and the next run try it first. When no set validates, the first set that saved is kept, so
* the canary's own validate_invoice step shows what is broken; when none saves, create_invoice fails with each reason. */
async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[]; name: string; invoiceType?: string; paymentMethod?: string }) {
const sets = apDataSets();
const why: string[] = [];
let saved: ApDataSet | null = null;
let last = false; // the invoice the last set saved is the one on the page
const create = async (set: ApDataSet, k: number) => {
const number = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`));
const got = await ctx.ui.createInvoice({ businessUnit: set.businessUnit, supplier: set.supplier, site: set.site, number,
amount: h.amount, lines: h.lines, account: set.account, invoiceType: h.invoiceType, paymentMethod: h.paymentMethod });
ctx.saved[h.name] = number;
return got;
};
for (const [k, set] of sets.entries()) {
const label = `${set.businessUnit} / ${set.supplier}`;
last = false;
let got;
try { got = await create(set, k); } catch (e) { why.push(`${label}: ${errorText(e)}`); continue; }
saved ??= set;
last = true;
try {
await ctx.ui.validateInvoice();
await ctx.ui.expectStatus('Validated', ctx.saved[h.name]);
} catch (e) { why.push(`${label}: saved but did not validate (${errorText(e)})`); continue; }
for (const [key, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site], ['account', got.account]]) {
if (v) { used('AP', key, v, true); ctx.chosen[`ap.${key}`] = v; }
}
if (k) console.log(`[canary] Payables data set ${k + 1} of ${sets.length} works (${label}); tried: ${why.join(' | ')}`);
return;
}
if (!saved) throw new Error(`create_invoice failed with each of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`);
console.log(`[canary] no Payables data set validates: ${why.join(' | ')}`);
if (!last) await create(saved, sets.length);
}
/** The pod's values to try for one test data key, the one Fusion already took in this test first; none when the pod
* has no such test data (Fusion's own default is then kept, or its list's first choice taken). `also` = keys of other
* areas tried after it: a journal's account may be the Payables one, which belongs to a ledger of the same pod. */
function choices(ctx: Ctx, area: string, key: string, ...also: [string, string][]): string[] {
const out: string[] = [];
for (const [a, k] of [[area, key] as [string, string], ...also]) {
const took = ctx.chosen[`${a}.${k}`.toLowerCase()];
if (took) { out.push(took); continue; }
try { out.push(...podCandidates(a, k)); } catch { /* the pod has no such test data */ }
}
return out.filter((v, i, all) => v && all.indexOf(v) === i);
}
/** A journal step's category: a name Fusion lists (Adjustment, Accrual, Allocation, Reclass ...) or a pod placeholder
* ({{pod.gl.category}}), which gives the pod's candidates in turn. Empty: the category Fusion defaults. */
function journalCategories(s: Step, ctx: Ctx): { names: string[]; fromPod: boolean } {
const raw = String(s.category ?? '').trim();
const ref = /^\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}$/i.exec(raw);
if (ref) return { names: choices(ctx, ref[1].toLowerCase(), ref[2].toLowerCase()), fromPod: true };
return { names: raw ? [fill(raw, ctx).trim()] : [], fromPod: false };
}
/** A new test reference for a document of this scenario (FPT-<id>-<time>): what clean-up registers before the save. */
const docTag = (ctx: Ctx, kind = '') => testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, '') + kind);
/** The document a business action works on: what its create action (or a `remember` step) stored under the step's
* `name`, `fallback` when it names none. */
function docRef(s: Step, ctx: Ctx, fallback: string, noun: string, creator: string): string {
const name = s.name || fallback;
const n = ctx.saved[name];
if (!n) throw new Error(`${s.action} needs ${noun}: nothing is remembered as "${name}" (${creator} or remember it first)`);
return n;
}
const paymentNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'payment_number', 'a payment', 'create_payment');
const requisitionNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'requisition_number', 'a requisition', 'create_requisition');
const orderNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'order_number', 'a purchase order', 'create_purchase_order');
const journalBatch = (s: Step, ctx: Ctx) => docRef(s, ctx, 'journal_batch', 'a journal', 'create_journal');
const transactionNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'transaction_number', 'a transaction', 'create_transaction');
const receiptNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'receipt_number', 'a receipt', 'create_receipt');
/** A line's quantity and price: the step's own, else the test values "quantity" (default one) and "price" (else
* "amount"). */
function linePrice(s: Step, ctx: Ctx): { quantity: string; price: string } {
const tv = ctx.c.test_values ?? {};
const given = (v: unknown) => v !== undefined && v !== '';
const quantity = given(s.quantity) ? fill(s.quantity, ctx) : given(tv.quantity) ? fill('{{tv.quantity}}', ctx) : '1';
const price = given(s.price) ? fill(s.price, ctx) : given(tv.price) ? fill('{{tv.price}}', ctx) : given(tv.amount) ? fill('{{tv.amount}}', ctx) : '';
if (!price) throw new Error(`${s.action} needs a price: price, or the test value "price" (or "amount")`);
amountOf(quantity, ctx, 'quantity');
amountOf(price, ctx, 'price');
return { quantity, price };
}
/** What an expect_ step of Purchasing, General Ledger or Receivables asks of its document. */
const expectation = (s: Step, ctx: Ctx): DocExpectation => ({
status: s.status ? fill(s.status, ctx) : undefined,
amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined,
amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined,
canceled: s.canceled,
posted: s.posted,
});
/** Ask Fusion (REST) until `find` answers something: a document just saved can take a few seconds to show. */
async function untilFound<T>(find: () => Promise<T | null | undefined>, what: string, timeoutMs = 60_000): Promise<T> {
const end = Date.now() + timeoutMs;
for (;;) {
const v = await find();
if (v) return v;
if (Date.now() > end) throw new Error(what);
await new Promise((r) => setTimeout(r, 3000));
}
}
/** A step's amount: its value, else the test value "amount". */
function amountValue(s: Step, ctx: Ctx): string {
const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx) : ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : '';
if (!amount) throw new Error(`${s.action} needs an amount: value, or the test value "amount"`);
amountOf(amount, ctx, 'the amount');
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<string, string[]> = { 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<boolean>): 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 }
/** The transaction types to try for an invoice: Invoice first, then the pod's own that are not another class's (the pod's
* latest transactions may be credit memos); the one Fusion already took in this test alone. */
function invoiceTypes(ctx: Ctx): string[] {
if (ctx.chosen['ar.transaction_type']) return [ctx.chosen['ar.transaction_type']];
return ['Invoice', ...choices(ctx, 'ar', 'transaction_type').filter((t) => !/credit|debit|chargeback|deposit|guarantee/i.test(t))]
.filter((v, i, all) => all.indexOf(v) === i);
}
/** A new test document registered for clean-up BEFORE its save (its tag), so it is cleaned up even if the step fails. */
const track = (ctx: Ctx, kind: DocKind) => ctx.docs.track(kind, docTag(ctx, kind === 'ar_receipt' ? 'R' : '')); // R: a receipt and its transaction never share a tag
/** An interface id for a FBDI header row (links its lines; unique in the interface table): the clock, one per attempt. */
const interfaceId = (attempt: number) => Number(String(Date.now()).slice(-12)) * 10 + attempt;
/** The document an import should have created, asked for until it shows (REST can lag the job by a few seconds); null when it never does. */
async function findAfterImport<T>(find: () => Promise<T | null | undefined>): Promise<T | null> {
try { return await untilFound(find, 'not found', 60_000); } catch { return null; }
}
/** An import step on a pod without REST (assisted sign-in): nothing is sent, the test says so, and the name still holds a reference so
* the steps after it (their REST checks are skipped too) do not fail for want of a document. */
function importSkipped(ctx: Ctx, action: string, name: string): void {
ctx.saved[name] = docTag(ctx);
test.info().annotations.push({ type: REST_SKIPPED, description: `${action}: not run: an import is sent through Fusion REST, and this pod uses assisted sign-in (no password for REST)` });
}
/** The proven actions. Optional ones call a FusionUi method only if that building block exists. */
const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
sign_in: async (_s, { ui }) => ui.signIn(),
open_task: async (s, ctx) => {
await ctx.ui.openPath(fill(s.value, ctx)); // "Group > Page > Task", or "Group > Action" for a quick action
},
enter: async (s, ctx) => {
if (!s.field) throw new Error('enter needs a field');
if (s.field === 'Number') ctx.track(fill(s.value, ctx)); // a saved test invoice is cancelled after the test, pass or fail
await putValue(s, ctx, (v) => ctx.ui.put(s.field!, v));
},
expect_filled: async (s, ctx) => { for (const f of s.fields ?? (s.field ? [s.field] : [])) await ctx.ui.expectFilled(f); },
expect_value: async (s, ctx) => {
if (!s.field) throw new Error('expect_value needs a field');
await expect.poll(() => ctx.ui.value(s.field!), { message: `${s.field} should be "${fill(s.value, ctx)}"`, timeout: 30_000 }).toBe(fill(s.value, ctx));
},
remember: async (s, ctx) => { if (!s.field || !s.name) throw new Error('remember needs field and name'); ctx.saved[s.name] = await ctx.ui.value(s.field); },
click: async (s, ctx) => {
const name = fill(s.value, ctx);
await ctx.ui.pressButton(name);
},
confirm_if_asked: async (_s, ctx) => {
const yes = ctx.ui.page.getByRole('button', { name: /^(Yes|OK)$/ });
if (await yes.count()) { await yes.first().click(); await ctx.ui.settle(); }
},
// any screen: tables, menus, messages, searches and statuses (the AI writes these for every business area)
add_row: async (s, ctx) => { if (!s.field) throw new Error('add_row needs the table section as field'); await ctx.ui.addRow(s.field); },
enter_in_row: async (s, ctx) => {
if (!s.field) throw new Error('enter_in_row needs a field');
await putValue(s, ctx, (v) => ctx.ui.putInRow(s.field!, v));
},
menu_action: async (s, ctx) => {
if (!s.field) throw new Error('menu_action needs the menu as field');
await ctx.ui.menuAction(s.field, fill(s.value, ctx));
},
expect_no_error: async (_s, ctx) => ctx.ui.expectNoError(),
expect_message: async (s, ctx) => ctx.ui.expectMessage(fill(s.value, ctx)),
expect_results: async (_s, ctx) => ctx.ui.expectResults(),
cancel_without_saving: async (_s, ctx) => {
await ctx.ui.page.getByRole('button', { name: 'Cancel', exact: true }).first().click();
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. 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)
: lines.length ? lines.reduce((sum, l, i) => sum + amountOf(l, ctx, `line ${i + 1}`), 0).toFixed(2)
: ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : '';
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 && 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: 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;
},
/** Check the invoice in Fusion (REST) by its number. status = the status it must have (Validated, Needs revalidation,
* Canceled ...: matched without regard to case); amount = its exact amount; amount_at_least = at least this amount
* (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 ...); 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 = {
status: s.status ? fill(s.status, ctx) : undefined,
amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined,
amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined,
canceled: s.canceled,
type: s.invoice_type ? fill(s.invoice_type, ctx) : undefined,
paymentMethod: s.payment_method ? fill(s.payment_method, ctx) : undefined,
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")
if (want.approvalStatus && /^(required|initiated)$/i.test(want.approvalStatus.trim()) && ctx.rest.available) {
const inv = await ctx.rest.invoiceByNumber(number).catch(() => null);
if (inv && /^not\s*required$/i.test(invoiceApprovalStatus(inv))) {
const why = `Not applicable on this pod: invoice approval is not required for this business unit (Fusion says "Not required"), so "${want.approvalStatus}" cannot occur`;
test.info().annotations.push({ type: 'not-applicable', description: why });
test.skip(true, why);
}
}
await restCheck(ctx, `expect_invoice ${number}`, () =>
untilRight(async () => invoiceProblems(number, await ctx.rest.invoiceByNumber(number), want), `invoice ${number} in Fusion`));
},
/** The invoice carries a hold that is not released: value = the hold's name as Fusion lists it (any case). */
expect_hold: async (s, ctx) => {
const number = invoiceNumber(s, ctx);
const name = fill(s.value, ctx).trim().toLowerCase();
if (!name) throw new Error('expect_hold needs the hold name as value');
await restCheck(ctx, `expect_hold ${number}`, () => untilRight(async () => {
const holds = activeHolds(await ctx.rest.holds(number));
return holds.some((h) => String(h.HoldName || '').trim().toLowerCase() === name) ? []
: [`no "${fill(s.value, ctx)}" hold (holds: ${holds.map((h) => h.HoldName).join(', ') || 'none'})`];
}, `invoice ${number}`));
},
/** The invoice carries no hold that is not released (the holds list: 26D no longer returns ActiveHoldFlag). */
expect_no_holds: async (s, ctx) => {
const number = invoiceNumber(s, ctx);
await restCheck(ctx, `expect_no_holds ${number}`, () => untilRight(async () => {
const holds = activeHolds(await ctx.rest.holds(number));
return holds.length ? [`it is on hold: ${holds.map((h) => h.HoldName).join(', ')}`] : [];
}, `invoice ${number}`, 20_000));
},
// Payments of invoices (not in the canary: a payment is a scenario's, and clean-up voids it)
/** Pay the validated invoice remembered as applies_to (default invoice_number) in full with a quick payment: Invoice Actions >
* Pay in Full. payment_method = the method the payment is made with (when Fusion's window offers it; else the invoice's own
* stays); payment_type is Quick (the only one created). The pod's bank account, payment document and payment process profile
* are the test data ap.bank_account, ap.payment_document and ap.payment_process_profile when set, else Fusion's defaults or the
* first choice of its lists. The payment is registered for clean-up before it is made (the clean-up voids it, then the
* invoice is cancelled). name = what to remember its number as (default payment_number). */
create_payment: async (s, ctx) => {
const invoice = invoiceNumber({ ...s, name: s.applies_to }, ctx);
const type = s.payment_type ? fill(s.payment_type, ctx).trim() : 'Quick';
if (paymentTypeKey(type) !== 'quick') {
throw new Error(`create_payment payment_type "${type}": only a Quick payment (Pay in Full on the invoice) is created; a ${type} payment can only be checked (expect_payment)`);
}
const method = s.payment_method ? fill(s.payment_method, ctx).trim() : undefined;
const supplier = ctx.chosen['ap.supplier'] ?? '';
await restCheck(ctx, `create_payment ${invoice}`, () => untilRight(async () => invoiceProblems(invoice, await ctx.rest.invoiceByNumber(invoice), { status: 'Validated', canceled: false }),
`invoice ${invoice} before it is paid (only a validated invoice is paid)`, 30_000));
const before = new Set<number>(ctx.rest.available && supplier ? (await ctx.rest.recentPayments(supplier)).map((p) => p.PaymentId) : []);
const ref = ctx.docs.track('ap_payment', paymentRef(invoice));
const got = await ctx.ui.createPayment({ invoice, method, bank: choices(ctx, 'ap', 'bank_account'), document: choices(ctx, 'ap', 'payment_document'),
profile: choices(ctx, 'ap', 'payment_process_profile') });
let number = got.number;
if (ctx.rest.available) { // the payment Fusion named, else the newest payment to the supplier that was not there before
const fresh = async () => (await ctx.rest.recentPayments(supplier)).find((p) => !before.has(p.PaymentId)) ?? null;
const p = await untilFound(async () => (number ? await ctx.rest.payment(number) : null) ?? (supplier ? await fresh() : null),
`a payment of invoice ${invoice} should be in Fusion after Pay in Full${number ? ` (Fusion named ${number})` : ''}`);
number = String(p.PaymentNumber);
}
if (!number) throw new Error(`invoice ${invoice} was paid, but Fusion did not name the payment's number and this run has no Fusion REST to find it: void the payment on Payments > Manage Payments`);
ctx.docs.payment(ref, number);
ctx.saved[s.name || 'payment_number'] = number;
},
/** Check the payment in Fusion (REST): status (Negotiable, Voided ...: any case), amount = its exact amount, amount_at_least =
* at least this, payment_method = the method's name, payment_type = Quick, Manual, Refund or Payment Process Request. */
expect_payment: async (s, ctx) => {
const number = paymentNumber(s, ctx);
const want: PaymentExpectation = {
status: s.status ? fill(s.status, ctx) : undefined,
amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined,
amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined,
method: s.payment_method ? fill(s.payment_method, ctx) : undefined,
type: s.payment_type ? fill(s.payment_type, ctx) : undefined,
};
await restCheck(ctx, `expect_payment ${number}`, () =>
untilRight(async () => paymentProblems(number, await ctx.rest.payment(number), want), `payment ${number} in Fusion`));
},
/** Void the payment remembered as `name` (default payment_number): Actions > Void Payment on Manage Payments; Fusion must
* then show it Voided. The invoice is unpaid again, and clean-up cancels it as usual. */
void_payment: async (s, ctx) => {
const number = paymentNumber(s, ctx);
await ctx.ui.voidPayment(number);
await restCheck(ctx, `void_payment ${number}`, () =>
untilRight(async () => paymentProblems(number, await ctx.rest.payment(number), { status: 'Voided' }), `payment ${number} after Void Payment`, 120_000));
},
/** Send the validated invoice for approval: Invoice Actions > Approval > Initiate (name = the invoice's remembered name, default
* invoice_number). Fusion must then show the invoice's approval Initiated. A pod whose invoice approval is not set up offers no
* such entry (or says so): the step then fails with that message, it never pretends. The invoice is registered for clean-up before
* it is sent (the clean-up withdraws the approval, then cancels the invoice; one it cannot withdraw is listed in left-on-pod). */
initiate_approval: async (s, ctx) => {
const invoice = invoiceNumber(s, ctx);
await restCheck(ctx, `initiate_approval ${invoice}`, () => untilRight(async () => invoiceProblems(invoice, await ctx.rest.invoiceByNumber(invoice), { status: 'Validated', canceled: false }),
`invoice ${invoice} before it is sent for approval (only a validated invoice is)`, 30_000));
ctx.docs.track('ap_approval', approvalRef(invoice));
await ctx.ui.initiateApproval(invoice);
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
* "price", else "amount"); name = what to remember its number as (default requisition_number). */
create_requisition: async (s, ctx) => {
const { quantity, price } = linePrice(s, ctx);
const tag = track(ctx, 'po_requisition');
const said = await ctx.ui.createRequisition({ description: `${tag} ${fill(s.value, ctx).trim() || 'Test item'}`, quantity, price,
bu: choices(ctx, 'po', 'requisitioning_bu'), category: choices(ctx, 'po', 'category'), uom: choices(ctx, 'po', 'uom'),
account: choices(ctx, 'po', 'charge_account', ['gl', 'account'], ['ap', 'account']) });
// its number: Fusion's confirmation names it, else REST finds the requisition by the tag in its description
const m = /\bRequisition\s+([A-Za-z0-9][\w-]*)\s+(?:was|has been)\s+submitted/i.exec(said.join(' '));
if (!ctx.rest.available && m) { // assisted sign-in: Fusion's own confirmation names it
ctx.saved[s.name || 'requisition_number'] = m[1];
return restCheck(ctx, `requisition ${m[1]} in Fusion`, async () => {});
}
const r = await untilFound(async () => (m ? await ctx.rest.requisition(m[1]) : null) ?? ctx.rest.requisition(tag),
`requisition ${m?.[1] ?? tag} should be in Fusion after the submit`);
ctx.saved[s.name || 'requisition_number'] = r.Requisition;
},
/** Check the requisition in Fusion (REST): status (Incomplete, Pending approval, Approved, Rejected, Canceled ...:
* any case), canceled = true or false. With neither, that it exists. */
expect_requisition: async (s, ctx) => {
const number = requisitionNumber(s, ctx);
const want = expectation(s, ctx);
await restCheck(ctx, `expect_requisition ${number}`, () =>
untilRight(async () => requisitionProblems(number, await ctx.rest.requisition(number), want), `requisition ${number} in Fusion`));
},
/** Create a purchase order of one goods line on its own screen and save it (not submitted). value = the line's
* description (after the test's tag); quantity, price as for create_requisition; name = what to remember its number
* as (default order_number). */
create_purchase_order: async (s, ctx) => {
const { quantity, price } = linePrice(s, ctx);
const supplier = choices(ctx, 'po', 'supplier');
if (!supplier.length) podValue('po', 'supplier'); // fails saying where to set it
const tag = track(ctx, 'po_order');
const got = await ctx.ui.createPurchaseOrder({ description: `${tag} ${fill(s.value, ctx).trim() || 'Test item'}`, quantity, price,
bu: choices(ctx, 'po', 'business_unit'), supplier, site: choices(ctx, 'po', 'supplier_site'), category: choices(ctx, 'po', 'category'),
uom: choices(ctx, 'po', 'uom') });
for (const [k, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site]]) if (v) ctx.chosen[`po.${k}`] = v;
const shown = await ctx.ui.orderNumberOnPage();
if (!ctx.rest.available && shown) { // assisted sign-in: the number Fusion shows on the order
ctx.saved[s.name || 'order_number'] = shown;
ctx.orderTags[shown] = tag;
return restCheck(ctx, `purchase order ${shown} in Fusion`, async () => {});
}
const o = await untilFound(async () => (await ctx.rest.purchaseOrder(tag)) ?? (shown ? ctx.rest.purchaseOrder(shown) : null),
`purchase order ${shown || tag} should be in Fusion after the save`);
ctx.saved[s.name || 'order_number'] = o.OrderNumber;
ctx.orderTags[o.OrderNumber] = tag;
},
/** Submit the order (opened from Manage Orders when it is not on the page): Fusion must take it out of Incomplete
* (Pending Approval, or Open where no approval is needed). */
submit_purchase_order: async (s, ctx) => {
const number = orderNumber(s, ctx);
await ctx.ui.submitPurchaseOrder(number);
await restCheck(ctx, `submit_purchase_order ${number}`, () => untilRight(async () => {
const o = await ctx.rest.purchaseOrder(number);
if (!o) return [`purchase order ${number} is not in Fusion`];
return /^incomplete$/i.test(String(o.Status || o.StatusCode || '')) ? [`purchase order ${number} is still Incomplete`] : [];
}, `purchase order ${number} after Submit`, 120_000));
},
/** Check the order in Fusion (REST): status (Open, Pending Approval, Incomplete, Canceled ...: any case), amount =
* its exact total, amount_at_least = at least this (the pod may add tax), canceled = true or false. */
expect_purchase_order: async (s, ctx) => {
const number = orderNumber(s, ctx);
const want = expectation(s, ctx);
await restCheck(ctx, `expect_purchase_order ${number}`, () =>
untilRight(async () => purchaseOrderProblems(number, await ctx.rest.purchaseOrder(number), want), `purchase order ${number} in Fusion`));
},
// Closing and receiving purchase orders (not in the canary: only a person can undo them)
/** Close the order remembered as name (default order_number) from its Actions menu: value = Close for Receiving, Close for
* Invoicing, Close or Finally Close. The order must be approved first (the step waits for it); Fusion must then show the
* matching status. A closed order cannot be cancelled: clean-up leaves it for a person, listed in the run's test data. */
close_purchase_order: async (s, ctx) => {
const number = orderNumber(s, ctx);
const how = fill(s.value, ctx).trim();
const action = closeAction(how);
if (!action) throw new Error(`close_purchase_order value "${how}" is not a way to close an order (Close for Receiving, Close for Invoicing, Close, Finally Close)`);
await restCheck(ctx, `close_purchase_order ${number}`, () => untilRight(async () => {
const o = await ctx.rest.purchaseOrder(number);
if (!o) return [`purchase order ${number} is not in Fusion`];
const status = orderStatus(o);
return orderCloseable(status) ? [] : [`purchase order ${number} is ${status || 'not approved'}: only an approved (Open) order can be closed`];
}, `purchase order ${number} before it is closed`, 120_000));
await ctx.ui.closePurchaseOrder(number, how, action.direct);
await restCheck(ctx, `close_purchase_order ${number}`, () =>
untilRight(async () => purchaseOrderProblems(number, await ctx.rest.purchaseOrder(number), { status: action.status }), `purchase order ${number} after ${how}`, 120_000));
},
/** Receive the line of the order remembered as applies_to (default order_number): the whole open quantity, or `quantity`.
* The order must be approved (Open) first: the step waits for that, and says so when it does not happen (an approval
* rule of the pod). The test's tag goes into the receipt's packing slip and is registered for clean-up before the save;
* clean-up leaves the receipt (and its order) for a person, listed in the run's test data. name = what to remember the
* receipt number as (default po_receipt_number). */
create_receipt_for_order: async (s, ctx) => {
const order = orderNumber({ ...s, name: s.applies_to }, ctx);
const quantity = s.quantity !== undefined && s.quantity !== '' ? fill(s.quantity, ctx) : undefined;
if (quantity !== undefined) amountOf(quantity, ctx, 'quantity');
await restCheck(ctx, `create_receipt_for_order ${order}`, () => untilRight(async () => {
const o = await ctx.rest.purchaseOrder(order);
if (!o) return [`purchase order ${order} is not in Fusion`];
const status = orderStatus(o);
return orderReceivable(status) ? [] : [`purchase order ${order} is ${status || 'not approved'}: only an approved (Open) order can be received`];
}, `purchase order ${order} before it is received`, 120_000));
const tag = testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, '').slice(-8) + 'R'); // at most 24 characters: a packing slip holds 25
ctx.docs.track('po_receipt', tag, ctx.orderTags[order]);
const got = await ctx.ui.createReceiptForOrder({ order, tag, quantity });
const key = got.receiptNumber || tag;
await restCheck(ctx, `create_receipt_for_order ${key}`, async () => {
await untilFound(async () => (await ctx.rest.poReceipt(key)).receipt ?? (await ctx.rest.poReceipt(tag)).receipt
?? (((await ctx.rest.orderReceivedQuantity(order)) ?? 0) > 0 ? { ReceiptNumber: key } : null),
`receipt ${key} (packing slip ${tag}) should be in Fusion after the save`);
});
ctx.saved[s.name || 'po_receipt_number'] = key;
},
/** Check the receipt in Fusion (REST): it exists and, with quantity, the quantity received on the order (the receipt's
* own lines, else the order's schedules). applies_to = the order (default order_number). */
expect_receipt_of_order: async (s, ctx) => {
const ref = docRef(s, ctx, 'po_receipt_number', 'a receipt of a purchase order', 'create_receipt_for_order');
const order = ctx.saved[s.applies_to || 'order_number'];
const want = { quantity: s.quantity !== undefined && s.quantity !== '' ? amountOf(s.quantity, ctx, 'quantity') : undefined };
await restCheck(ctx, `expect_receipt_of_order ${ref}`, () => untilRight(async () => {
const { receipt } = await ctx.rest.poReceipt(ref);
const onOrder = order && (want.quantity !== undefined || !receipt) ? (await ctx.rest.orderReceivedQuantity(order)) ?? undefined : undefined;
return poReceiptProblems(ref, receipt, onOrder, want);
}, `receipt ${ref} in Fusion`));
},
// Receivables business actions
/** Create and save (Incomplete) a transaction on its own screen: an Invoice of one line of value (default {{tv.amount}}),
* the pod's business unit, source and customer. transaction_type (Invoice by default; a credit memo's amount is negative) and
* transaction_source (Manual) are set when given, the pod's defaults otherwise. name = what to remember its number as (default
* transaction_number). */
create_transaction: async (s, ctx) => {
const amount = amountValue(s, ctx);
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 && 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, 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))) {
const why = `Not applicable on this pod: ${String(e.message).split(' (')[0].replace(/^Fusion does not take/, 'Fusion has no')}`;
test.info().annotations.push({ type: 'not-applicable', description: why });
test.skip(true, why);
}
throw e;
});
for (const [k, v] of Object.entries(got)) { // a type or source the step asked for is not what the next transaction of the test starts from
if (v && !(k === 'transaction_type' && typeIs) && !(k === 'transaction_source' && sourceIs)) ctx.chosen[`ar.${k}`] = v;
}
const shown = await ctx.ui.transactionNumberOnPage();
if (!ctx.rest.available && shown) { // assisted sign-in: the number Fusion shows on the transaction
ctx.saved[s.name || 'transaction_number'] = shown;
return restCheck(ctx, `transaction ${shown} in Fusion`, async () => {});
}
const t = await untilFound(async () => (await ctx.rest.transaction(tag)) ?? (shown ? ctx.rest.transaction(shown) : null),
`transaction ${shown || tag} should be in Fusion after the save`);
ctx.saved[s.name || 'transaction_number'] = t.TransactionNumber;
},
/** Complete the transaction (opened from Manage Transactions when it is not on the page): Fusion must take it out of
* Incomplete. */
complete_transaction: async (s, ctx) => {
const number = transactionNumber(s, ctx);
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${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) => {
const number = transactionNumber(s, ctx);
const want: TransactionExpectation = { ...expectation(s, ctx), type: s.transaction_type ? fill(s.transaction_type, ctx).trim() : undefined,
source: s.transaction_source ? fill(s.transaction_source, ctx).trim() : undefined };
await restCheck(ctx, `expect_transaction ${number}`, () =>
untilRight(async () => transactionProblems(number, await ctx.rest.transaction(number), want), `transaction ${number} in Fusion`));
},
/** Create and save a standard receipt of value (default {{tv.amount}}) for the customer of the transaction, numbered with
* the test's tag, and apply it to the transaction remembered as applies_to (default transaction_number; none
* remembered: left unapplied). name = what to remember its number as (default receipt_number). */
create_receipt: async (s, ctx) => {
const amount = amountValue(s, ctx);
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;
await restCheck(ctx, `create_receipt ${tag}`, async () => {
await untilFound(() => ctx.rest.receipt(tag), `receipt ${tag} should be in Fusion after the save`);
});
ctx.saved[s.name || 'receipt_number'] = tag;
},
/** Check the receipt in Fusion (REST): status = its state (Applied, Unapplied, Partially applied, Reversed), amount =
* its exact amount. */
expect_receipt: async (s, ctx) => {
const number = receiptNumber(s, ctx);
const want = expectation(s, ctx);
await restCheck(ctx, `expect_receipt ${number}`, () =>
untilRight(async () => receiptProblems(number, await ctx.rest.receipt(number), want), `receipt ${number} in Fusion`));
},
// Interfaces: documents that arrive through an import, made the way the client's integrations make them
/** Import a Payables invoice through Payables Standard Invoice Import: a FBDI file of one standard invoice of value (default {{tv.amount}})
* with one Item line is uploaded through Fusion's ERP Integration REST service and its import job run, then the step waits for the job
* and finds the invoice by its FPT- number. source = the invoice source (default External); the pod's business unit, supplier, site,
* account and currency. name = what to remember the number as (default invoice_number). Registered for clean-up before the upload,
* so the invoice is cancelled after the test like a screen one. Needs the pod's "allow imports" setting; on a pod with assisted sign-in
* (no REST) it is skipped with a note. */
import_payables_invoice: async (s, ctx) => {
const amount = amountValue(s, ctx);
const source = s.source ? fill(s.source, ctx).trim() : 'External';
const name = s.name || 'invoice_number';
if (!ctx.rest.available) return importSkipped(ctx, s.action, name);
if (!importsAllowed()) throw new Error(`import_payables_invoice: ${IMPORTS_REFUSED}`);
const currency = choices(ctx, 'ap', 'currency')[0];
if (!currency) throw new Error('import_payables_invoice needs the invoice currency: the pod has no Payables test data "currency"; set it on the Test environments page');
const sets = apDataSets();
const why: string[] = [];
for (const [k, set] of sets.entries()) {
const tag = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`)); // a tag per attempt: rows of one never meet the next import
const files = apInvoiceFiles({ tag, interfaceId: interfaceId(k), businessUnit: set.businessUnit, supplier: set.supplier, site: set.site[0], account: set.account,
source, amount, currency, date: fbdiDate(podToday()) });
const job = await ctx.rest.importBulkData(importBody('payables_invoice', tag, files,
{ 'Business Unit': set.businessUnit, Source: source, 'Import Set': tag, Purge: 'Y', 'Summarize Report': 'N' }));
await ctx.rest.waitForJob(job, `import_payables_invoice ${tag}`); // a job that errors is not a data problem: it stops the step
if (await findAfterImport(() => ctx.rest.invoiceByNumber(tag))) {
ctx.chosen['ap.business_unit'] = set.businessUnit;
ctx.chosen['ap.supplier'] = set.supplier;
used('AP', 'business_unit', set.businessUnit, true);
used('AP', 'supplier', set.supplier, true);
ctx.saved[name] = tag;
ctx.imported.add(tag);
return;
}
why.push(`${set.businessUnit} / ${set.supplier}: the import job succeeded but invoice ${tag} is not in Fusion (the interface rejected it: see Payables > Invoices > Review Import Results)`);
}
throw new Error(`import_payables_invoice: no invoice was imported with any of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`);
},
/** Import a Receivables transaction through AutoInvoice: a FBDI file of one invoice of one line of value (default {{tv.amount}}) is
* uploaded through Fusion's ERP Integration REST service and its import job run, then the step waits for the job and finds the
* transaction by its FPT- tag. transaction_source = the pod's import source (when not given: the pod's sources that are not Manual,
* in turn); transaction_type (Invoice by default); the pod's business unit, customer, currency and memo line. name = what to remember
* its number as (default transaction_number). Registered for clean-up before the upload: an Incomplete transaction is deleted, a
* completed one (what AutoInvoice usually makes) is listed for a person to credit. Needs the pod's "allow imports" setting; on a pod
* with assisted sign-in (no REST) it is skipped with a note. */
import_receivables_transaction: async (s, ctx) => {
const amount = amountValue(s, ctx);
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(`import_receivables_transaction transaction_type "${typeIs || 'Invoice'}": ${wrong.join('; ')}`);
const name = s.name || 'transaction_number';
if (!ctx.rest.available) return importSkipped(ctx, s.action, name);
if (!importsAllowed()) throw new Error(`import_receivables_transaction: ${IMPORTS_REFUSED}`);
const currency = choices(ctx, 'ar', 'currency')[0];
if (!currency) throw new Error('import_receivables_transaction needs the currency: the pod has no Receivables test data "currency"; set it on the Test environments page');
const sources = sourceIs ? [sourceIs] : choices(ctx, 'ar', 'transaction_source').filter((v) => !/^manual$/i.test(v)).slice(0, 3);
if (!sources.length) throw new Error('import_receivables_transaction needs an import source: give transaction_source, or the pod needs a Receivables test data "transaction_source" other than Manual');
const bus = choices(ctx, 'ar', 'business_unit');
const customers = choices(ctx, 'ar', 'customer');
if (!bus.length || !customers.length) throw new Error("import_receivables_transaction needs the pod's Receivables business unit and customer test data: set them on the Test environments page");
const memo = choices(ctx, 'ar', 'memo_line')[0];
const why: string[] = [];
for (const [k, source] of sources.entries()) {
const bu = bus[Math.min(k, bus.length - 1)];
const customer = customers[Math.min(k, customers.length - 1)];
const account = await ctx.rest.customerAccountNumber(customer);
if (!account) throw new Error("import_receivables_transaction: the customer's account number could not be read through REST (receivablesInvoices has none of "
+ 'BillToCustomerNumber, BillToAccountNumber, CustomerAccountNumber on this pod); AutoInvoice needs it');
const tag = ctx.docs.track('ar_transaction', docTag(ctx, k ? String(k) : '')); // before the upload: cleaned up (or listed) even if the step fails
const files = arTransactionFiles({ tag, businessUnit: bu, source, type: typeIs ?? invoiceTypes(ctx)[0], customerAccount: account, amount, currency,
date: fbdiDate(podToday()), memoLine: memo });
const job = await ctx.rest.importBulkData(importBody('receivables_transaction', tag, files,
{ 'Business Unit': bu, 'Transaction Source': source, 'From Transaction Number': tag, 'To Transaction Number': tag }));
await ctx.rest.waitForJob(job, `import_receivables_transaction ${tag}`);
const found = await findAfterImport(() => ctx.rest.transaction(tag));
if (found) {
ctx.chosen['ar.business_unit'] = bu;
ctx.chosen['ar.customer'] = customer;
used('AR', 'business_unit', bu, true);
used('AR', 'customer', customer, true);
used('AR', 'transaction_source', source, true);
ctx.saved[name] = found.TransactionNumber;
return;
}
why.push(`${source}: the import job succeeded but transaction ${tag} is not in Fusion (AutoInvoice rejected the line: see Receivables > Billing > Review AutoInvoice Results)`);
}
throw new Error(`import_receivables_transaction: no transaction was imported with any of the ${sources.length} source(s) tried: ${why.join(' | ')}`);
},
// General Ledger business actions
/** 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).
* 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) : '';
if (!amount) throw new Error('create_journal needs an amount: value, or the test value "amount"');
amountOf(amount, ctx, 'the journal amount');
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');
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: [...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`);
});
ctx.saved[s.name || 'journal_batch'] = batch;
},
/** Post the journal batch (opened from Manage Journals when it is not on the page). Posting runs as a process: the
* step waits until REST shows the batch posted, or sent for approval (then expect_journal posted: true fails, which
* says so); a posting error fails it at once. */
post_journal: async (s, ctx) => {
const batch = journalBatch(s, ctx);
await ctx.ui.postJournal(batch);
await restCheck(ctx, `post_journal ${batch}`, () => untilRight(async () => {
const b = await ctx.rest.journalBatch(batch);
if (!b) return [`journal batch ${batch} is not in Fusion`];
if (journalPosted(b)) return [];
const approval = String(b.ApprovalStatusMeaning || b.ApprovalStatus || '').trim();
if (/in process|pending|waiting|progress/i.test(approval)) {
console.log(`[post_journal] ${batch} went for approval (${approval}): it posts once approved`);
return [];
}
const status = journalStatus(b);
if (!/^(unposted|selected for posting|posting in process|processing)?$/i.test(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));
},
/** Check the journal batch in Fusion (REST): status (Posted, Unposted ...: any case), posted = true or false, category
* (as Fusion names it: the batch's journal), source (Manual). */
expect_journal: async (s, ctx) => {
const batch = journalBatch(s, ctx);
const want = { ...expectation(s, ctx), category: s.category ? fill(s.category, ctx).trim() : undefined,
source: s.source ? fill(s.source, ctx).trim() : undefined };
await restCheck(ctx, `expect_journal ${batch}`, () => untilRight(async () => {
const b = await ctx.rest.journalBatch(batch);
const headers = b && (want.category || want.source) ? await ctx.rest.journalHeaders(b.JeBatchId) : [];
return journalProblems(batch, b, want, headers);
}, `journal batch ${batch} in Fusion`));
},
/** Reverse the posted journal batch (opened from Manage Journals when it is not on the page). Fusion's reversal is a
* batch it names after this one: the step waits until REST shows it (or the batch says it is reversed; on a pod that
* refuses the name search, Fusion's own confirmation of the reversal). */
reverse_journal: async (s, ctx) => {
const batch = journalBatch(s, ctx);
const said = await ctx.ui.reverseJournal(batch);
await restCheck(ctx, `reverse_journal ${batch}`, () => untilRight(async () => {
const named = await ctx.rest.journalBatchesNamed(batch);
if (named?.some((b) => b.BatchName !== batch)) return [];
// the reversal is a batch of its own that Fusion names after this one (seen live: "Reverses <batch>-J <date> <id>"): 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));
},
};
/** Building blocks that live on FusionUi (added module by module): action name -> method name and argument fields. */
const UI_BLOCKS: Record<string, { method: string; args: (s: Step, ctx: Ctx) => unknown[] }> = {
add_line: { method: 'addLine', args: (s, ctx) => [Number((s as { line?: number }).line ?? 1),
{ amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },
save: { method: 'save', args: () => [] },
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
// 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)] },
/** Invoice Actions > Cancel Invoice on the invoice remembered as `name`, confirmed: it must then show Canceled. */
cancel_invoice: { method: 'cancelInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },
expect_status: { method: 'expectStatusText', args: (s, ctx) => [fill(s.value, ctx)] },
/** Find the payment remembered as `name` (default payment_number) on Manage Payments: exactly it must be listed. */
find_payment: { method: 'findPayment', args: (s, ctx) => [paymentNumber(s, ctx)] },
/** Cancel the requisition remembered as `name` (default requisition_number), or withdraw it while pending approval. */
cancel_requisition: { method: 'cancelRequisition', args: (s, ctx) => [requisitionNumber(s, ctx)] },
/** Find the order remembered as `name` (default order_number) on Manage Orders: exactly it must be listed. */
find_purchase_order: { method: 'findPurchaseOrder', args: (s, ctx) => [orderNumber(s, ctx)] },
/** Cancel the order remembered as `name` (withdrawn and deleted while pending approval): Canceled or gone after. */
cancel_purchase_order: { method: 'cancelPurchaseOrder', args: (s, ctx) => [orderNumber(s, ctx)] },
/** Find the journal batch remembered as `name` (default journal_batch) on Manage Journals: exactly it is listed. */
find_journal: { method: 'findJournal', args: (s, ctx) => [journalBatch(s, ctx)] },
/** Find the transaction remembered as `name` (default transaction_number) on Manage Transactions: exactly it is listed. */
find_transaction: { method: 'findTransaction', args: (s, ctx) => [transactionNumber(s, ctx)] },
/** Find the receipt remembered as `name` (default receipt_number) on Manage Receipts: exactly it is listed. */
find_receipt: { method: 'findReceipt', args: (s, ctx) => [receiptNumber(s, ctx)] },
};
export const supportedActions = () => [...Object.keys(ACTIONS), ...Object.keys(UI_BLOCKS)];
async function runAction(s: Step, ctx: Ctx) {
const direct = ACTIONS[s.action];
if (direct) return direct(s, ctx);
const block = UI_BLOCKS[s.action];
const fn = block && (ctx.ui as unknown as Record<string, unknown>)[block.method];
if (typeof fn !== 'function') throw new Error(`step action "${s.action}" is not supported yet (known: ${supportedActions().join(', ')})`);
await (fn as (...a: unknown[]) => Promise<void>).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. */
const STEP_BUDGET = 150_000;
const STEPS_CAP = 1_800_000;
/** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts, or
* from a staged draft's entry (opts.dir = the staging folder holding its YAML). */
export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {
const c = loadStepCase(id, opts.dir);
test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices, fusionDocs }) => {
test.setTimeout(Math.max(test.info().timeout, Math.min(STEPS_CAP, c.steps.length * STEP_BUDGET)));
const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, imported: new Set(), chosen: {}, orderTags: {}, rest: apInvoices.rest, docs: fusionDocs };
for (const [i, s] of c.steps.entries()) {
const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;
await test.step(s.expected ? `${label} (expect: ${s.expected})` : label, () => runStep(s, ctx));
}
});
}
import * as fs from 'fs';
import * as path from 'path';
import YAML from 'yaml';
import { approvalRef, expect, paymentRef, test, type DocKind, type FusionDocs } from './fixtures';
import { activeHolds, closeAction, invoiceAmountProblems, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, orderCloseable,
orderReceivable, orderStatus, paymentProblems, paymentTypeKey, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation, type PaymentExpectation } from './rest';
import { invoiceApprovalStatus, transactionAmountProblems, type TransactionExpectation } from './rest';
import { expectRefusal, FusionRefused } from './refusal';
import { apInvoiceFiles, arTransactionFiles, fbdiDate, importBody, importsAllowed, IMPORTS_REFUSED } from './interfaces';
import { apDataSets, fusionDate, NO_SUCH_JOURNAL_CATEGORY, podCandidates, podToday, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui';
/*
* Step runner: executes a scenario written as plain steps in tests/cases/<ID>.yaml (runner: steps), with no
* hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright
* runs them the same way every time. Unknown actions fail the step with a clear message, never guess.
*
* Step fields: action, field, value, expected (shown in the report and the live view).
* Values may use {{pod.<area>.<key>}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}},
* {{tv.<test_values key>}} and {{saved.<name>}} (a value remembered by an earlier `remember` step).
*
* Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not
* break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice,
* expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario
* per area (tests/cases/CANARY-<AREA>.yaml) runs each of them once before a run, to prove they still work on the pod.
* Purchasing: create_requisition, expect_requisition, cancel_requisition, create_purchase_order, submit_purchase_order,
* find_purchase_order, expect_purchase_order, cancel_purchase_order (extra fields quantity, price). General Ledger:
* create_journal, post_journal, find_journal, expect_journal, reverse_journal (extra field posted). Receivables:
* create_transaction, complete_transaction, find_transaction, expect_transaction, create_receipt, find_receipt,
* expect_receipt (extra field applies_to: the transaction a receipt is applied to). Receiving: create_receipt_for_order and
* expect_receipt_of_order (extra fields applies_to: the order, and quantity), close_purchase_order (value: how). create_invoice and expect_invoice also
* take invoice_type (Standard, Credit memo, Debit memo, Prepayment) and payment_method (the pod's: Check, Electronic, Wire);
* expect_invoice also checks approval_status (Not required, Required ...) and validation_status (Validated, Not validated,
* Needs revalidation).
* Payments (scenario-only, never in a canary): create_payment (a quick payment of a validated invoice: applies_to = the invoice's
* remembered name, payment_method, payment_type Quick; name = what to remember the payment number as, payment_number),
* find_payment, expect_payment (status, amount, amount_at_least, payment_method, payment_type), void_payment. A payment the
* test leaves is voided by the clean-up, before the invoice is cancelled.
* initiate_approval (scenario-only: name = the invoice's remembered name) sends a validated invoice for approval (Invoice Actions >
* Approval > Initiate) and checks Fusion shows the approval Initiated; the clean-up withdraws it before the invoice is cancelled.
* Subledger accounting (scenario-only, never in a canary; the General Ledger's journals of source Payables and Receivables come from it):
* account_invoice (a validated invoice: Invoice Actions > Account in Draft, or Post to Ledger with mode final; expect_invoice then checks
* accounting_status Draft / Accounted) and account_transaction (a completed transaction: Actions > Account in Draft or Post to Ledger,
* checked in View Accounting, since REST has no accounting status for a transaction), with incomplete_transaction to take a completed
* transaction back to Incomplete. Draft accounting changes no ledger balance; the invoice clean-up (cancel) is unchanged by it.
* Interfaces (scenario-only, never in a canary; they write through Fusion's ERP Integration REST service, so they need REST and the pod's
* "allow imports" setting, FPT_ALLOW_IMPORTS=1): import_payables_invoice (a FBDI file through Payables invoice import; source = the
* invoice source, External by default) and import_receivables_transaction (a FBDI file through AutoInvoice; transaction_source = an import
* source of the pod, transaction_type). Each remembers the number of the document the import created (name), checked by expect_invoice
* (source) or expect_transaction (transaction_source) like any other; the clean-up cancels an imported invoice, an imported
* transaction that is complete is listed for a person to credit.
*
* Negative scenarios: `refused: "<words>"` on a step says Fusion must say no to it. The step passes only when the action failed
* BECAUSE Fusion refused (its message window, error note or field message holds one of the |-separated words, any case); it fails
* when Fusion takes the action ("Fusion took X that it should refuse"), when the action fails for the runner's own reason (a locator
* timeout, a page that did not open), or when Fusion refuses with other words (refusal.ts). The runner's own pre-checks (the sign
* of an invoice or transaction amount) are not made on a refused step, so Fusion's validation is what is tested. A document the
* refused step tried to make is registered for clean-up before the save, as always, and must not exist in Fusion afterwards.
* Fields: leave_out (create_invoice: supplier, number, amount; create_journal: account = the credit line's; create_transaction:
* customer, lines) leaves that part empty; credit_amount (create_journal) makes the credit differ from the debit (unbalanced).
* expect_unavailable (field = menu, value = entry, or entries separated by |): Fusion greys the entry out or does not list it.
*/
export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[];
lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean;
quantity?: string | number; price?: string | number; posted?: boolean; applies_to?: string; invoice_type?: string; payment_method?: string;
category?: string; source?: string; payment_type?: string; approval_status?: string; validation_status?: string; accounting_status?: string; mode?: string;
refused?: string; leave_out?: string | string[]; credit_amount?: string | number }
export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record<string, unknown>;
canary?: boolean } // a canary (tests/cases/CANARY-<AREA>.yaml): create_invoice tries the pod's data sets in turn
const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases');
/**
* The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds
* that id (the co-worker's staging folder for drafts), else from the script library tests/cases/.
*/
export function stepCaseFile(id: string, dir?: string): string {
for (const d of [dir, process.env.FPT_STEPS_DIR]) {
if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`);
}
return path.join(CASES_DIR, `${id}.yaml`);
}
export function loadStepCase(id: string, dir?: string): StepCase {
const f = stepCaseFile(id, dir);
const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase;
if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`);
return c;
}
type Ctx = { ui: FusionUi; c: StepCase; saved: Record<string, string>; uniques: Record<string, string>; track: (n: string) => string;
imported: Set<string>; // the invoices an import made (import_payables_invoice): validate_invoice opens them from Manage Invoices first
chosen: Record<string, string>; // the pod value Fusion accepted, per "area.key", used again for the rest of the test
orderTags: Record<string, string>; // the test's tag of each purchase order made, by its number (its receipt names it for clean-up)
attempt?: { what: string; exists: () => Promise<boolean> }; // a document a refused create_ step tried to make: it must not exist afterwards
rest: FusionRest; // Fusion REST, for the business actions that check what the screens did
docs: FusionDocs }; // Purchasing and General Ledger test documents, cleaned up after the test
function fill(raw: unknown, ctx: Ctx): string {
return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => {
const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key);