diff --git a/automation/remote_runner/server.py b/automation/remote_runner/server.py index 4316ddc2c06bdceed0f43e08d7b731777a09d301..cd75a48b5f54d0b420723f760e06cd2512e837ea 100644 --- a/automation/remote_runner/server.py +++ b/automation/remote_runner/server.py @@ -55,7 +55,7 @@ CASES = AUTOMATION.parent / "tests" / "cases" VERSION_FILE = AUTOMATION.parent / "VERSION" CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"} ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES", - "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS"} + "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS"} SESSION_STATE = "sign-in-state.json" # an attempt's signed-in session (assisted sign-in), in its job folder while it runs SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$") ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$") diff --git a/automation/scripts/check-nav.ts b/automation/scripts/check-nav.ts new file mode 100644 index 0000000000000000000000000000000000000000..23c7e544272c8b7ff96ed2d2747bcaf241dff113 --- /dev/null +++ b/automation/scripts/check-nav.ts @@ -0,0 +1,17 @@ +/* Checks the navigation-link parsing and matching (src/fusion/nav.ts) without a browser: `npx tsx scripts/check-nav.ts`. */ +import assert from 'node:assert/strict'; +import { navLink, parseNavLinks } from '../src/fusion/nav'; + +const url = 'https://pod.fa.ocs.oraclecloud.com/fscmUI/faces/FuseOverview?fndGlobalItemNodeId=itemNode_procurement_purchase_orders'; +const links = parseNavLinks(JSON.stringify({ 'Procurement > Purchase Orders': url, 'Payables > Invoices': 'http://x/fscmUI/a', 'nogroup': url, 'A > B': 5 })); +assert.deepEqual(Object.keys(links), ['Procurement > Purchase Orders']); // http, no "A > B" form and non-strings dropped +assert.equal(navLink(links, 'Procurement', 'Purchase Orders'), url); +assert.equal(navLink(links, ' procurement ', 'PURCHASE orders'), url); // case and spacing do not matter +assert.equal(navLink(links, 'Procurement', 'Purchase Order'), null); // no guessing +assert.equal(navLink(links, 'Payables', 'Invoices'), null); +// bad input is ignored +assert.deepEqual(parseNavLinks(undefined), {}); +assert.deepEqual(parseNavLinks('not json'), {}); +assert.deepEqual(parseNavLinks('[1,2]'), {}); +assert.deepEqual(parseNavLinks('null'), {}); +console.log('nav: all checks pass'); diff --git a/automation/src/fusion/fixtures.ts b/automation/src/fusion/fixtures.ts index 8dcdfa6a3cfeb18bb193ff608d5a0b2f3f0c5e5a..97fb56ca18cd8c94361c2cac52aad90302162434 100644 --- a/automation/src/fusion/fixtures.ts +++ b/automation/src/fusion/fixtures.ts @@ -17,19 +17,54 @@ export interface ApInvoices { /** The Purchasing, General Ledger and Receivables test documents a test creates, by the reference registered BEFORE the save (the * test's FPT- tag in a requisition's or an order's Description, a journal batch's name, a transaction's Comments, a receipt's number): Fusion gives a requisition * or an order its number only when it is saved. */ -export type DocKind = 'po_requisition' | 'po_order' | 'po_receipt' | 'gl_journal' | 'ar_transaction' | 'ar_receipt'; +export type DocKind = 'po_requisition' | 'po_order' | 'po_receipt' | 'gl_journal' | 'ar_transaction' | 'ar_receipt' | 'ap_payment' | 'ap_approval'; +/** A test payment is registered as "-PAY" (kind ap_payment) before the invoice is paid; its own number is + * noted once Fusion has made it, so clean-up voids that payment before the invoice is cancelled. */ +export const paymentRef = (invoice: string) => `${invoice}-PAY`; +/** An invoice a test sends for approval is registered as "-APR" (kind ap_approval) before it is sent: the clean-up + * withdraws the approval on the screens before the invoice is cancelled (Fusion does not cancel one in approval). */ +export const approvalRef = (invoice: string) => `${invoice}-APR`; export interface FusionDocs { /** Register a test document BEFORE saving it, so it is cleaned up even if the test fails half-way. A receipt of an order * names that order's tag (`order`): the order is left for a person too while its receipt is. */ track(kind: DocKind, ref: string, order?: string): string; + /** The number of the payment registered as `ref` (kind ap_payment), once Fusion made it. */ + payment(ref: string, number: string): void; +} + +/** Clean-up of an invoice sent for approval: the approval is withdrawn on the screens when it is under way. Fusion not offering the + * withdraw, or not showing the approval withdrawn, is no failure of the test: it is left for a person, with what to do. */ +async function cleanApproval(rest: FusionRest, ui: FusionUi, ref: string): Promise { + const invoice = ref.replace(/-APR$/, ''); + const todo = 'withdraw the approval on Payables > Invoices > Manage Invoices (Invoice Actions > Approval > Withdraw), then cancel the invoice'; + try { + return await rest.cleanApproval(invoice); + } catch (e) { + if (!(e instanceof NeedsScreen)) throw e; + try { + await ui.withdrawApproval(invoice); + } catch (w) { + throw new LeftForPerson(`invoice ${invoice} is in approval and Fusion's screens did not withdraw it (${String((w as Error).message || w).split('\n')[0].slice(0, 200)}): ${todo}`); + } + for (let i = 0; i < 12; i++) { // the withdrawal is a workflow: it takes a moment to show + try { + return `${await rest.cleanApproval(invoice)} (on the screens: ${e.message})`; + } catch (x) { + if (!(x instanceof NeedsScreen)) throw x; + await new Promise((r) => setTimeout(r, 5_000)); + } + } + throw new LeftForPerson(`invoice ${invoice} is still in approval after Withdraw: ${todo}`); + } } /** Clean-up of one test document over REST (rest.ts): a requisition or order cancelled or deleted, a journal deleted * while unposted, an incomplete transaction deleted (a completed one or a receipt is left for a person). What REST cannot do (a submitted requisition, an order pending approval) is done on the screens * with the business action's own steps, then REST is asked again. */ -async function cleanDoc(rest: FusionRest, ui: FusionUi, kind: DocKind, ref: string, received = false): Promise { +async function cleanDoc(rest: FusionRest, ui: FusionUi, kind: DocKind, ref: string, received = false, payment = ''): Promise { + if (kind === 'ap_approval') return cleanApproval(rest, ui, ref); const clean = () => (kind === 'po_requisition' ? rest.cleanRequisition(ref) : kind === 'po_order' ? rest.cleanPurchaseOrder(ref, received) - : kind === 'po_receipt' ? rest.cleanPoReceipt(ref) + : kind === 'po_receipt' ? rest.cleanPoReceipt(ref) : kind === 'ap_payment' ? rest.cleanPayment(ref.replace(/-PAY$/, ''), payment || undefined) : kind === 'ar_transaction' ? rest.cleanTransaction(ref) : kind === 'ar_receipt' ? rest.cleanReceipt(ref) : rest.cleanJournal(ref)); try { return await clean(); @@ -37,6 +72,7 @@ async function cleanDoc(rest: FusionRest, ui: FusionUi, kind: DocKind, ref: stri if (!(e instanceof NeedsScreen)) throw e; if (kind === 'po_requisition') await ui.cancelRequisition(ref); else if (kind === 'po_order') await ui.cancelPurchaseOrder(ref); + else if (kind === 'ap_payment' && payment) await ui.voidPayment(payment); else throw e; return `${await clean()} (on the screens: ${e.message})`; } @@ -94,7 +130,12 @@ export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; fusi const done = await rest.cancelIfPresent(n, d.businessUnit, d.supplier); testInfo.annotations.push({ type: 'cleanup', description: done }); ledger({ kind: 'ap_invoice', number: n, cleaned: done }); - } catch (e) { errors.push(String((e as Error).message || e)); } + } catch (e) { + if (e instanceof LeftForPerson) { // an invoice still in approval: not a failure of the test, the run's test data lists it + testInfo.annotations.push({ type: 'cleanup', description: `left for a person: ${e.message}` }); + ledger({ kind: 'ap_invoice', number: n, left: e.message }); + } else errors.push(String((e as Error).message || e)); + } } if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`); }, @@ -102,11 +143,16 @@ export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; fusi // it is torn down before the page (it depends on `fusion`). fusionDocs: async ({ fusion }, use, testInfo) => { const docs: [DocKind, string, string?][] = []; + const payments: Record = {}; // payment number by the ref it was registered under await use({ + payment: (ref, number) => { + payments[ref] = number; + ledger({ kind: 'ap_payment', number: ref, payment: number }); + }, track: (kind, ref, order) => { if (!docs.some(([k, r]) => k === kind && r === ref)) { ledger({ kind, number: ref, by: kind === 'gl_journal' ? 'name' : kind === 'ar_receipt' ? 'receipt number' : kind === 'ar_transaction' ? 'comments' - : kind === 'po_receipt' ? 'packing slip' : 'description', order, test: testInfo.title }); + : kind === 'po_receipt' ? 'packing slip' : kind === 'ap_payment' || kind === 'ap_approval' ? 'invoice number' : 'description', order, test: testInfo.title }); docs.push([kind, ref, order]); } return ref; @@ -123,7 +169,7 @@ export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; fusi // the newest first: an order made from a requisition goes before the requisition, a receipt before its order for (const [kind, ref, order] of [...docs].reverse()) { try { - const done = await cleanDoc(rest, fusion, kind, ref, received.has(ref)); + const done = await cleanDoc(rest, fusion, kind, ref, received.has(ref), payments[ref]); testInfo.annotations.push({ type: 'cleanup', description: done }); ledger({ kind, number: ref, cleaned: done }); } catch (e) { diff --git a/automation/src/fusion/nav.ts b/automation/src/fusion/nav.ts new file mode 100644 index 0000000000000000000000000000000000000000..364816111abdb7d1aef61ab463d6babf36941654 --- /dev/null +++ b/automation/src/fusion/nav.ts @@ -0,0 +1,21 @@ +/** Per-pod navigation links (FPT_NAV_LINKS, set by the co-worker): the address of a work area a consultant opened by hand, + * for pods whose menus do not show it to the test user. Pure, so a script can check it without a browser. */ + +const key = (s: string) => s.split('>').map((p) => p.replace(/\s+/g, ' ').trim().toLowerCase()).join('>'); + +/** The run's links, {"Group > Page": address}; anything malformed is ignored, never an error. */ +export function parseNavLinks(raw: string | undefined): Record { + if (!raw) return {}; + try { + const o = JSON.parse(raw); + if (!o || typeof o !== 'object' || Array.isArray(o)) return {}; + return Object.fromEntries(Object.entries(o).filter(([k, v]) => k.includes('>') && typeof v === 'string' && /^https:\/\//i.test(v)) as [string, string][]); + } catch { return {}; } +} + +/** The address saved for "group > page" (case and spacing do not matter), or null. */ +export function navLink(links: Record, group: string, page: string): string | null { + const want = key(`${group} > ${page}`); + const hit = Object.keys(links).find((k) => key(k) === want); + return hit ? links[hit] : null; +} diff --git a/automation/src/fusion/rest.ts b/automation/src/fusion/rest.ts index ff50ab5ced9372d40a58a20f876e327ea25259ff..989834947f01babef3531cfa884cb8ecb1e0ee30 100644 --- a/automation/src/fusion/rest.ts +++ b/automation/src/fusion/rest.ts @@ -58,7 +58,7 @@ const q = (s: string) => s.replace(/'/g, "''"); /** What a step expects of an invoice in Fusion (business action expect_invoice). */ export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; type?: string; - paymentMethod?: string } + paymentMethod?: string; approvalStatus?: string; validationStatus?: string } /** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */ const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled'); @@ -109,12 +109,80 @@ export function invoiceProblems(number: string, inv: Invoice | null, want: Invoi out.push(`its payment method is "${has[0] ?? ''}", expected "${want.paymentMethod}"`); } } + if (want.approvalStatus) { // "Not required" / "Required" ...: where this pod's REST returns the approval status + const got = invoiceApprovalStatus(inv); + if (!got) out.push(`this pod's REST does not return the invoice's approval status, so "${want.approvalStatus}" cannot be checked`); + else if (codeKey(got) !== codeKey(want.approvalStatus)) out.push(`its approval status is "${got}", expected "${want.approvalStatus}"`); + } + if (want.validationStatus && validationKey(String(inv.ValidationStatus ?? '')) !== validationKey(want.validationStatus) + && !(validationKey(want.validationStatus) === 'canceled' && inv.CanceledFlag)) { + out.push(`its validation status is "${inv.ValidationStatus ?? ''}", expected "${want.validationStatus}"`); + } return out; } +/** A status in the words of a code or a meaning: "NOT REQUIRED", "Not_required" and "not required" are one status. */ +const codeKey = (s: string) => spelling(String(s ?? '').replace(/_/g, ' ')); + +/** The invoice's approval status as this pod's REST returns it ("Not required", "Required", "Approved" ...): the first of the + * attributes releases use for it that holds a value ('' when the pod exposes none: it then cannot be checked). */ +export const invoiceApprovalStatus = (inv: Invoice): string => String([inv.ApprovalStatus, inv.WFapprovalStatus, inv.ApprovalStatusMeaning] + .find((v) => v !== undefined && v !== null && v !== '') ?? '').trim(); + +/** What a validation status is called by the client ("Not validated") and by REST on an invoice nobody validated yet + * ("Never validated" in Oracle's own lookup): one status for a saved invoice that was not validated. */ +const validationKey = (s: string) => { const k = codeKey(s); return k === 'never validated' ? 'not validated' : k; }; + +/** Whether the invoice's approval is under way (Initiated, or "In process" / "Pending" where a release says so): such an invoice + * cannot be cancelled until the approval is withdrawn. */ +export const invoiceInApproval = (inv: Invoice): boolean => /^(initiated|in process|in progress|pending|pending approval)$/.test(codeKey(invoiceApprovalStatus(inv))); + +/** Whether the invoice has been paid, wholly or in part (its payment status): a paid invoice cannot be cancelled until its + * payment is voided. */ +export const invoiceIsPaid = (inv: Invoice): boolean => /^(paid|partially paid|y|p)$/.test(codeKey(String(inv.PaymentStatus ?? inv.PaymentStatusCode ?? ''))); + /** The holds still on the invoice: a released hold carries the name of its release. */ export const activeHolds = (holds: InvoiceHold[]) => holds.filter((h) => !h.ReleaseName); +/* + * Payables payments (payablesPayments): a quick payment of one test invoice (create_payment), checked and voided by its + * payment number. Attribute names are the documented ones of 11.13.18.05 as far as known; where releases differ several are + * read, and every guess is listed in the report of the change that added them (verify them on the pod). + */ +export interface Payment { PaymentId: number; PaymentNumber: number | string; PaymentAmount?: number; PaymentMethod?: string; PaymentMethodCode?: string; + PaymentType?: string; PaymentStatus?: string; [k: string]: unknown } +export interface PaymentExpectation { status?: string; amount?: number; amountAtLeast?: number; method?: string; type?: string } + +/** A payment's status in words ("Negotiable", "Voided" ...; the code when a pod returns only that). */ +export const paymentStatus = (p: Payment) => String(p.PaymentStatus || p.PaymentStatusCode || p.Status || '').trim(); + +/** A payment type as the step and REST both mean it: "Quick", "QUICK" and "Quick payment" are one type; Payment Process Request + * is also written "PPR" or "Payment Process Requests". */ +export function paymentTypeKey(t: string): string { + const s = codeKey(String(t ?? '')); + return /^quick( payments?)?$/.test(s) ? 'quick' : /^manual( payments?)?$/.test(s) ? 'manual' : /^refunds?$/.test(s) ? 'refund' + : /^(ppr|payment process requests?)$/.test(s) ? 'payment process request' : s; +} + +/** The payment's amount (NaN when it carries none). */ +export const paymentAmount = (p: Payment) => Number(firstOf(p, ['PaymentAmount', 'Amount', 'PaidAmount']) ?? NaN); + +/** Every way a payment differs from what is expected, in words (empty: as expected). */ +export function paymentProblems(ref: string, p: Payment | null, want: PaymentExpectation): string[] { + if (!p) return [`payment ${ref} is not in Fusion`]; + const out = docProblems(`payment ${ref}`, paymentStatus(p), paymentAmount(p), undefined, want); + const typeGot = String(p.PaymentType ?? p.PaymentTypeCode ?? '').trim(); + if (want.type && paymentTypeKey(typeGot) !== paymentTypeKey(want.type)) out.push(`payment ${ref}: its type is "${typeGot}", expected "${want.type}"`); + if (want.method) { // the method's name or its code, whichever this release returns + const has = [p.PaymentMethod, p.PaymentMethodCode, p.PaymentMethodName].filter((v) => v !== undefined && v !== null && v !== '').map(String); + if (!has.some((m) => spelling(m) === spelling(want.method!))) out.push(`payment ${ref}: its payment method is "${has[0] ?? ''}", expected "${want.method}"`); + } + return out; +} + +/** A payment that is out of the way: voided (or stopped by the bank, which a clean-up cannot undo but leaves nothing to void). */ +export const paymentVoided = (p: Payment) => statusKey(paymentStatus(p)) === 'voided'; + /* * Purchasing and General Ledger. Every test document carries the test's own FPT- tag where Fusion keeps a free text * (a requisition's and an order's Description, a journal batch's name): the number Fusion gives a requisition or an @@ -129,7 +197,8 @@ export interface JournalBatch { JeBatchId: number; BatchName: string; Status?: s /** What a step expects of a requisition, an order or a journal batch (expect_requisition, expect_purchase_order, * expect_journal). */ -export interface DocExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; posted?: boolean } +export interface DocExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; posted?: boolean; + category?: string; source?: string } /** A requisition's status in words (DocumentStatus; the code when a pod returns only that). */ export const requisitionStatus = (r: Requisition) => String(r.DocumentStatus || r.DocumentStatusCode || '').trim(); @@ -204,9 +273,31 @@ export function purchaseOrderProblems(number: string, o: PurchaseOrder | null, w return docProblems(`purchase order ${number}`, orderStatus(o), orderAmount(o), undefined, want); } -export function journalProblems(name: string, b: JournalBatch | null, want: DocExpectation): string[] { +/** The attributes a pod may keep a journal's category and source in (journalHeaders carries the category, a batch or its + * journals the source); the names are those of usage.py's GL read. */ +const JOURNAL_CATEGORY_ATTRS = ['JournalCategory', 'UserJeCategoryName', 'CategoryName', 'Category']; +const JOURNAL_SOURCE_ATTRS = ['JournalSource', 'UserJeSourceName', 'SourceName', 'Source']; + +/** A journal's category or source as Fusion shows it: the first of `attrs` that holds a value on the batch or on one of its + * journals; '' when the pod returns none of them. */ +export function journalAttribute(b: JournalBatch, headers: Record[], attrs: string[]): string { + for (const row of [b as Record, ...headers]) { + const v = attrs.map((k) => row[k]).find((x) => x !== undefined && x !== null && String(x).trim() !== ''); + if (v !== undefined) return String(v).trim(); + } + return ''; +} + +export function journalProblems(name: string, b: JournalBatch | null, want: DocExpectation, headers: Record[] = []): string[] { if (!b) return [`journal batch ${name} is not in Fusion`]; - return docProblems(`journal batch ${name}`, journalStatus(b), NaN, journalPosted(b), want); + const out = docProblems(`journal batch ${name}`, journalStatus(b), NaN, journalPosted(b), want); + for (const [what, wanted, attrs] of [['category', want.category, JOURNAL_CATEGORY_ATTRS], ['source', want.source, JOURNAL_SOURCE_ATTRS]] as const) { + if (!wanted) continue; + const shown = journalAttribute(b, headers, [...attrs]); + if (!shown) out.push(`journal batch ${name}: Fusion's REST gives no ${what} for it (cannot check it is "${wanted}")`); + else if (spelling(shown) !== spelling(wanted)) out.push(`journal batch ${name}: its ${what} is "${shown}", expected "${wanted}"`); + } + return out; } /* @@ -247,9 +338,36 @@ export function receiptState(r: ArReceipt): string { return open < 0.005 ? 'Applied' : open >= total - 0.005 ? 'Unapplied' : 'Partially applied'; } -export function transactionProblems(number: string, t: ArTransaction | null, want: DocExpectation): string[] { +/** What a step expects of a transaction: the document's own expectations, its type (Invoice, Credit Memo, Debit Memo or the + * pod's own) and its source (Manual or the pod's own). */ +export interface TransactionExpectation extends DocExpectation { type?: string; source?: string } + +/** A transaction type or source as the step and REST both mean it: case and spacing do not matter ("Credit memo" is the + * pod's "Credit Memo"; a "_" or "-" is a space). */ +export function transactionNameKey(t: string): string { + return String(t ?? '').trim().toLowerCase().replace(/[_-]+/g, ' ').replace(/\s+/g, ' '); +} + +/** The sign Fusion enforces on a transaction's line amount by its type: a credit memo is entered negative, an invoice and a + * debit memo positive. A type of the pod's own (a PA invoice, a client's) has no rule here. Words for what is wrong + * (empty: right); no type is an invoice. */ +export function transactionAmountProblems(type: string | undefined, amount: number): string[] { + const kind = transactionNameKey(type || 'invoice'); + if (kind === 'credit memo' && !(amount < 0)) return [`the amount (${amount}): a credit memo is entered with a negative amount`]; + if ((kind === 'invoice' || kind === 'debit memo') && amount < 0) return [`the amount (${amount}): ${kind === 'invoice' ? 'an invoice' : 'a debit memo'} has a positive amount (a negative one is a credit memo)`]; + return []; +} + +export function transactionProblems(number: string, t: ArTransaction | null, want: TransactionExpectation): string[] { if (!t) return [`transaction ${number} is not in Fusion`]; - return docProblems(`transaction ${number}`, transactionStatus(t), transactionAmount(t), undefined, want); + const out = docProblems(`transaction ${number}`, transactionStatus(t), transactionAmount(t), undefined, want); + if (want.type && transactionNameKey(String(t.TransactionType ?? '')) !== transactionNameKey(want.type)) { + out.push(`transaction ${number}: its type is "${t.TransactionType ?? ''}", expected "${want.type}"`); + } + if (want.source && transactionNameKey(String(t.TransactionSource ?? t.BatchSource ?? '')) !== transactionNameKey(want.source)) { + out.push(`transaction ${number}: its source is "${t.TransactionSource ?? t.BatchSource ?? ''}", expected "${want.source}"`); + } + return out; } export function receiptProblems(number: string, r: ArReceipt | null, want: DocExpectation): string[] { @@ -343,8 +461,8 @@ export class FusionRest { return { status: res.status, text: await res.text() }; } - private async get(resource: string, query: string): Promise { - const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100' }); + private async get(resource: string, query: string, extra: Record = {}): Promise { + const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100', ...extra }); const r = await this.call('GET', `${resource}?${params}`); if (r.status !== 200) throw new Error(`GET ${resource} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); return (JSON.parse(r.text).items || []) as T[]; @@ -368,6 +486,24 @@ export class FusionRest { return this.get('invoiceHolds', `InvoiceNumber='${q(number)}'`); } + /** The payment with this number (payablesPayments; the number is numeric on some releases, text on others). */ + async payment(number: string): Promise { + return await this.first('payablesPayments', `PaymentNumber=${q(number)}`) ?? await this.first('payablesPayments', `PaymentNumber='${q(number)}'`); + } + + /** The newest payments to a payee (a supplier), newest first: how the payment a step just made is found when Fusion does not + * name its number. A pod that does not have the attribute answers HTTP 400: the next one is tried; none: []. */ + async recentPayments(supplier: string): Promise { + for (const attr of ['Payee', 'PayeeName', 'SupplierName', 'Supplier']) { + try { + return await this.get('payablesPayments', `${attr}='${q(supplier)}'`, { orderBy: 'PaymentId:desc' }); + } catch (e) { + if (!/HTTP 400\b/.test(String((e as Error).message))) throw e; + } + } + return []; + } + /** Run an invoice action (validateInvoice, cancelInvoice, ...) the way Fusion's REST service offers it. */ async invoiceAction(action: string, body: Record): Promise { const r = await this.call('POST', `invoices/action/${action}`, body, 'application/vnd.oracle.adf.action+json'); @@ -381,12 +517,42 @@ export class FusionRest { const inv = await this.invoice(number, supplier) ?? await this.invoiceByNumber(number); if (!inv) return `${number}: not saved, nothing to clean up`; if (inv.CanceledFlag) return `${number}: already cancelled`; + if (invoiceInApproval(inv)) { // only the screens withdraw an approval (cleanApproval does it before this); one left stays for a person + throw new LeftForPerson(`invoice ${number} is in approval (${invoiceApprovalStatus(inv)}) and Fusion does not cancel it: withdraw the approval on Payables > Invoices > Manage Invoices ` + + '(Invoice Actions > Approval > Withdraw), then cancel the invoice'); + } await this.invoiceAction('cancelInvoice', { InvoiceNumber: number, BusinessUnit: inv.BusinessUnit || businessUnit, Supplier: inv.Supplier || supplier }); const after = await this.invoice(number, inv.Supplier || supplier); if (!after?.CanceledFlag) throw new Error(`${number}: cancelInvoice reported success but the invoice is not cancelled`); return `${number}: cancelled by clean-up`; } + /** Clean-up of the approval of an invoice a test sent for approval (`invoice`): one under way is withdrawn on the screens (REST has + * no withdraw for it: NeedsScreen), because Fusion does not cancel an invoice while its approval is under way. */ + async cleanApproval(invoice: string): Promise { + const inv = await this.invoiceByNumber(invoice); + if (!inv) return `${invoice}: not in Fusion, no approval to withdraw`; + if (inv.CanceledFlag) return `${invoice}: already cancelled, no approval to withdraw`; + if (invoiceInApproval(inv)) throw new NeedsScreen(`invoice ${invoice} is in approval (${invoiceApprovalStatus(inv)}): its approval is withdrawn on Manage Invoices (Invoice Actions > Approval > Withdraw)`); + return `${invoice}: approval ${invoiceApprovalStatus(inv) || 'not under way'}, nothing to withdraw`; + } + + /** Clean-up of the test payment of an invoice (`invoice`; `number` = the payment's number when it is known): a payment that + * is not voided is voided on the screens (REST has no void for it: NeedsScreen), because an invoice that is paid cannot be + * cancelled. A paid invoice whose payment is not known is left for a person. */ + async cleanPayment(invoice: string, number?: string): Promise { + if (number) { + const p = await this.payment(number); + if (!p) return `payment ${number}: not in Fusion, nothing to clean up`; + if (paymentVoided(p)) return `payment ${number}: already voided`; + throw new NeedsScreen(`payment ${number} is ${paymentStatus(p) || 'not voided'}: it is voided on Manage Payments (Actions > Void Payment)`); + } + const inv = await this.invoiceByNumber(invoice); + if (!inv || !invoiceIsPaid(inv)) return `${invoice}: no payment made, nothing to clean up`; + throw new LeftForPerson(`invoice ${invoice} is ${inv.PaymentStatus}, and the number of its payment is not known: void the payment on ` + + 'Payables > Payments > Manage Payments (Actions > Void Payment), then cancel the invoice'); + } + /** The first item of a resource matching `query`, or null. A query the resource refuses (an attribute this pod does not * have: HTTP 400) answers null, so the caller's next way of finding it is tried. */ private async first(resource: string, query: string): Promise { @@ -417,6 +583,15 @@ export class FusionRest { return this.first('journalBatches', `BatchName='${q(name)}'`); } + /** The journals of a batch (journalBatches child journalHeaders: their category, and on some pods their source); empty when + * the pod refuses the child resource. */ + async journalHeaders(batchId: number): Promise[]> { + try { return await this.getAll(`journalBatches/${batchId}/child/journalHeaders`); } catch (e) { + if (/HTTP (400|404)/.test(String((e as Error).message))) return []; + throw e; + } + } + /** The batches whose name holds the test's batch name: the batch itself and the reversal Fusion makes of it (Fusion * names a reversal after the batch it reverses). Null when this pod refuses the LIKE query. */ async journalBatchesNamed(name: string): Promise { diff --git a/automation/src/fusion/steps.ts b/automation/src/fusion/steps.ts index 24b7486cf19a31fbd54d5ddeb7d46c1f708a0c93..40c386f93b1b42eab916c4326bcb1a485acd69fd 100644 --- a/automation/src/fusion/steps.ts +++ b/automation/src/fusion/steps.ts @@ -1,9 +1,10 @@ import * as fs from 'fs'; import * as path from 'path'; import YAML from 'yaml'; -import { expect, test, type DocKind, type FusionDocs } from './fixtures'; +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, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation } from './rest'; + orderReceivable, orderStatus, paymentProblems, paymentTypeKey, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation, type PaymentExpectation } from './rest'; +import { transactionAmountProblems, type TransactionExpectation } from './rest'; import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui'; /* @@ -25,11 +26,20 @@ import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, Valu * 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). + * 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. */ 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 } + 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 } export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record; canary?: boolean } // a canary (tests/cases/CANARY-.yaml): create_invoice tries the pod's data sets in turn @@ -190,6 +200,15 @@ function choices(ctx: Ctx, area: string, key: string, ...also: [string, string][ 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--