diff --git a/automation/scripts/check-gap-actions.ts b/automation/scripts/check-gap-actions.ts new file mode 100644 index 0000000000000000000000000000000000000000..2cbed55e810e5ee613d16a86c628e99e2d46f914 --- /dev/null +++ b/automation/scripts/check-gap-actions.ts @@ -0,0 +1,82 @@ +/* Checks the pure REST expectation logic of the gap actions (src/fusion/rest.ts) without a browser or a pod: + * `npx tsx scripts/check-gap-actions.ts` (coworker/tests/test_gap_actions.py runs it when tsx is installed). */ +import assert from 'node:assert/strict'; +import { closeAction, invoiceAmountProblems, invoiceProblems, invoiceTypeKey, orderCloseable, orderReceivable, orderStatus, poReceiptProblems, purchaseOrderProblems, receiptLineQuantity, receiptQueries, + scheduleReceivedQuantity, type Invoice } from '../src/fusion/rest'; + +const inv = (o: Record) => ({ InvoiceId: 1, InvoiceNumber: 'FPT-1', InvoiceAmount: 100, ValidationStatus: 'Validated', CanceledFlag: false, + BusinessUnit: 'BU', Supplier: 'S', ...o }) as Invoice; + +// invoice types: the meaning, the code and the spelling Fusion uses are one type +assert.equal(invoiceTypeKey('Credit memo'), 'credit memo'); +assert.equal(invoiceTypeKey('CREDIT'), 'credit memo'); +assert.equal(invoiceTypeKey('credit_memo'), 'credit memo'); +assert.equal(invoiceTypeKey(' Debit Memo '), 'debit memo'); +assert.equal(invoiceTypeKey('Standard'), 'standard'); +assert.equal(invoiceTypeKey('PREPAYMENT'), 'prepayment'); +// the sign Fusion enforces by type +assert.deepEqual(invoiceAmountProblems(undefined, [100]), []); +assert.deepEqual(invoiceAmountProblems('Standard', [0]), []); +assert.deepEqual(invoiceAmountProblems('Credit memo', [-50]), []); +assert.deepEqual(invoiceAmountProblems('Debit memo', [-5, -10]), []); +assert.deepEqual(invoiceAmountProblems('Prepayment', [20]), []); +assert.match(invoiceAmountProblems('Credit memo', [50])[0], /a credit memo is entered with a negative amount/); +assert.equal(invoiceAmountProblems('Debit memo', [-5, 5]).length, 1); +assert.match(invoiceAmountProblems('Debit memo', [-5, 5])[0], /line 2 \(5\)/); +assert.match(invoiceAmountProblems('Standard', [-1])[0], /positive amount/); +assert.match(invoiceAmountProblems('Prepayment', [0])[0], /more than zero/); +// expect_invoice by type and payment method +assert.deepEqual(invoiceProblems('FPT-1', inv({ InvoiceType: 'Credit memo' }), { type: 'Credit Memo' }), []); +assert.deepEqual(invoiceProblems('FPT-1', inv({ InvoiceType: 'CREDIT' }), { type: 'Credit memo' }), []); +assert.match(invoiceProblems('FPT-1', inv({ InvoiceType: 'Standard' }), { type: 'Prepayment' })[0], /its type is "Standard", expected "Prepayment"/); +assert.match(invoiceProblems('FPT-1', inv({}), { type: 'Standard' })[0], /its type is ""/); // a pod that returns no type is not a match +assert.deepEqual(invoiceProblems('FPT-1', inv({ PaymentMethod: 'Electronic' }), { paymentMethod: 'electronic' }), []); +assert.deepEqual(invoiceProblems('FPT-1', inv({ PaymentMethod: 'Electronic', PaymentMethodCode: 'EFT' }), { paymentMethod: 'EFT' }), []); +assert.match(invoiceProblems('FPT-1', inv({ PaymentMethod: 'Check' }), { paymentMethod: 'Wire' })[0], /its payment method is "Check", expected "Wire"/); +assert.match(invoiceProblems('FPT-1', inv({}), { paymentMethod: 'Wire' })[0], /its payment method is ""/); +assert.deepEqual(invoiceProblems('FPT-1', inv({ InvoiceType: 'Debit memo', InvoiceAmount: -40, PaymentMethod: 'Wire' }), + { type: 'debit memo', paymentMethod: 'Wire', amount: -40, status: 'validated' }), []); +// receipts of purchase orders +assert.equal(orderReceivable('Open'), true); +assert.equal(orderReceivable('closed for invoicing'), true); +assert.equal(orderReceivable('Pending Approval'), false); +assert.equal(orderReceivable('Closed for Receiving'), false); +assert.equal(orderReceivable(''), false); +assert.equal(receiptLineQuantity({ lines: [{ Quantity: 2 }, { Quantity: '3' }] }), 5); +assert.equal(receiptLineQuantity({ Quantity: 4 }), 4); +assert.ok(Number.isNaN(receiptLineQuantity({ ReceiptNumber: '1' }))); +assert.ok(Number.isNaN(receiptLineQuantity({ lines: [{ Other: 1 }] }))); +assert.equal(scheduleReceivedQuantity([{ ReceivedQuantity: 1 }, { ReceivedQuantity: 2.5 }]), 3.5); +assert.ok(Number.isNaN(scheduleReceivedQuantity([{ Quantity: 9 }]))); // the ordered quantity is not the received one +assert.deepEqual(receiptQueries("FPT-O'1R"), ["ReceiptNumber='FPT-O''1R'", "PackingSlip='FPT-O''1R'", "Comments LIKE 'FPT-O''1R%'", "ShipmentNumber='FPT-O''1R'"]); +assert.deepEqual(poReceiptProblems('R1', { ReceiptNumber: 'R1' }, undefined, {}), []); +assert.deepEqual(poReceiptProblems('R1', null, undefined, {}), ['receipt R1 is not in Fusion']); +assert.deepEqual(poReceiptProblems('R1', null, 0, {}), ['receipt R1 is not in Fusion']); +assert.deepEqual(poReceiptProblems('R1', null, 3, {}), []); // its order shows the received quantity +assert.deepEqual(poReceiptProblems('R1', { lines: [{ Quantity: 3 }] }, undefined, { quantity: 3 }), []); +assert.match(poReceiptProblems('R1', { lines: [{ Quantity: 3 }] }, 9, { quantity: 4 })[0], /the quantity received is 3, expected 4/); +assert.deepEqual(poReceiptProblems('R1', { ReceiptNumber: 'R1' }, 4, { quantity: 4 }), []); // no quantity on the receipt: the order's +assert.match(poReceiptProblems('R1', { ReceiptNumber: 'R1' }, undefined, { quantity: 4 })[0], /does not give the received quantity/); +// closing purchase orders +assert.equal(closeAction('Close for Receiving')?.status, 'Closed for Receiving'); +assert.equal(closeAction(' close for invoicing ')?.status, 'Closed for Invoicing'); +assert.equal(closeAction('CLOSE')?.status, 'Closed'); +assert.equal(closeAction('Finally Close')?.status, 'Finally Closed'); +assert.deepEqual(closeAction('Close for Receiving')?.direct, ['Close for Receiving', 'Close Receiving']); +assert.equal(closeAction('Reopen'), null); +assert.equal(orderCloseable('Open'), true); +assert.equal(orderCloseable('Closed for Receiving'), true); +assert.equal(orderCloseable('CLOSED_FOR_INVOICING'), true); +for (const s of ['Pending Approval', 'Incomplete', 'Canceled', 'Finally Closed', '']) assert.equal(orderCloseable(s), false, s); +assert.equal(orderStatus({ POHeaderId: 1, OrderNumber: '1', Status: 'Open' }), 'Open'); +assert.equal(orderStatus({ POHeaderId: 1, OrderNumber: '1', StatusCode: 'OPEN' }), 'OPEN'); +assert.equal(orderStatus({ POHeaderId: 1, OrderNumber: '1', Status: 'Open', ClosureStatus: 'Closed for Receiving' }), 'Closed for Receiving'); +assert.equal(orderStatus({ POHeaderId: 1, OrderNumber: '1', Status: 'Open', ClosureStatus: 'Open' }), 'Open'); +assert.equal(orderStatus({ POHeaderId: 1, OrderNumber: '1', Status: 'Pending Approval', ClosureStatus: 'Closed' }), 'Pending Approval'); // closure counts on an open or closed order only +const po = (o: Record) => ({ POHeaderId: 1, OrderNumber: 'PO1', ...o }); +assert.deepEqual(purchaseOrderProblems('PO1', po({ Status: 'Closed for Receiving' }), { status: 'closed for receiving' }), []); +assert.deepEqual(purchaseOrderProblems('PO1', po({ Status: 'CLOSED_FOR_RECEIVING' }), { status: 'Closed for Receiving' }), []); +assert.deepEqual(purchaseOrderProblems('PO1', po({ Status: 'Open', CloseStatus: 'Finally Closed' }), { status: 'Finally Closed' }), []); +assert.match(purchaseOrderProblems('PO1', po({ Status: 'Open' }), { status: 'Closed for Receiving' })[0], /its status is "Open", expected "Closed for Receiving"/); +assert.match(purchaseOrderProblems('PO1', po({ Status: 'Closed for Invoicing' }), { status: 'Closed' })[0], /expected "Closed"/); // not the same status +console.log('check-gap-actions: ok'); diff --git a/automation/src/fusion/fixtures.ts b/automation/src/fusion/fixtures.ts index a58e27b9848a4e3dc8c5107e804e06c2fb05683a..8dcdfa6a3cfeb18bb193ff608d5a0b2f3f0c5e5a 100644 --- a/automation/src/fusion/fixtures.ts +++ b/automation/src/fusion/fixtures.ts @@ -1,7 +1,7 @@ import { appendFileSync } from 'node:fs'; import { test as base, expect } from '@playwright/test'; import { beginLiveStatus, liveViewDir, startLiveView } from '../live-view'; -import { FusionRest, NeedsScreen, NO_REST_WHY, REST_SKIPPED } from './rest'; +import { FusionRest, LeftForPerson, NeedsScreen, NO_REST_WHY, REST_SKIPPED } from './rest'; import { apData, assistedSignIn, FusionUi, markSignInExpired, SIGN_IN_EXPIRED, signInExpiredReason } from './ui'; /** Payables test invoices of one test: REST for checks, and every number registered here is cancelled afterwards. */ @@ -14,20 +14,23 @@ export interface ApInvoices { check(what: string, fn: () => Promise): Promise; } -/** The Purchasing and General Ledger 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): Fusion gives a requisition +/** 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' | 'gl_journal'; +export type DocKind = 'po_requisition' | 'po_order' | 'po_receipt' | 'gl_journal' | 'ar_transaction' | 'ar_receipt'; export interface FusionDocs { - /** Register a test document BEFORE saving it, so it is cleaned up even if the test fails half-way. */ - track(kind: DocKind, ref: string): string; + /** 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; } /** Clean-up of one test document over REST (rest.ts): a requisition or order cancelled or deleted, a journal deleted - * while unposted. What REST cannot do (a submitted requisition, an order pending approval) is done on the screens + * 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): Promise { - const clean = () => (kind === 'po_requisition' ? rest.cleanRequisition(ref) : kind === 'po_order' ? rest.cleanPurchaseOrder(ref) : rest.cleanJournal(ref)); +async function cleanDoc(rest: FusionRest, ui: FusionUi, kind: DocKind, ref: string, received = false): Promise { + const clean = () => (kind === 'po_requisition' ? rest.cleanRequisition(ref) : kind === 'po_order' ? rest.cleanPurchaseOrder(ref, received) + : kind === 'po_receipt' ? rest.cleanPoReceipt(ref) + : kind === 'ar_transaction' ? rest.cleanTransaction(ref) : kind === 'ar_receipt' ? rest.cleanReceipt(ref) : rest.cleanJournal(ref)); try { return await clean(); } catch (e) { @@ -98,26 +101,38 @@ export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; fusi // The same for requisitions, orders and journals. It uses the test's own browser for what REST cannot clean up, so // it is torn down before the page (it depends on `fusion`). fusionDocs: async ({ fusion }, use, testInfo) => { - const docs: [DocKind, string][] = []; + const docs: [DocKind, string, string?][] = []; await use({ - track: (kind, ref) => { + track: (kind, ref, order) => { if (!docs.some(([k, r]) => k === kind && r === ref)) { - ledger({ kind, number: ref, by: kind === 'gl_journal' ? 'name' : 'description', test: testInfo.title }); - docs.push([kind, 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 }); + docs.push([kind, ref, order]); } return ref; }, }); if (!docs.length) return; const rest = new FusionRest(); + if (!rest.available) { // assisted sign-in, no REST: the ledger keeps them listed, a person cleans them up + for (const [, ref] of docs) testInfo.annotations.push({ type: 'cleanup', description: `${ref}: not cleaned up (no Fusion REST on this pod); clean it up by hand` }); + return; + } const errors: string[] = []; - // the newest first: an order made from a requisition goes before the requisition - for (const [kind, ref] of [...docs].reverse()) { + const received = new Set(); // orders whose receipt a person has to undo: Fusion does not cancel them + // 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); + const done = await cleanDoc(rest, fusion, kind, ref, received.has(ref)); testInfo.annotations.push({ type: 'cleanup', description: done }); ledger({ kind, number: ref, cleaned: done }); - } catch (e) { errors.push(String((e as Error).message || e).split('\n')[0]); } + } catch (e) { + if (e instanceof LeftForPerson) { // not a failure of the test: the run's test data lists it with what to do + if (kind === 'po_receipt' && order) received.add(order); + testInfo.annotations.push({ type: 'cleanup', description: `left for a person: ${e.message}` }); + ledger({ kind, number: ref, left: e.message }); + } else errors.push(String((e as Error).message || e).split('\n')[0]); + } } if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`); }, diff --git a/automation/src/fusion/rest.ts b/automation/src/fusion/rest.ts index ce8f575cd14ee5dda2cb11f635b5c450a5530ac4..ff50ab5ced9372d40a58a20f876e327ea25259ff 100644 --- a/automation/src/fusion/rest.ts +++ b/automation/src/fusion/rest.ts @@ -57,11 +57,34 @@ export interface InvoiceHold { HoldId: number; HoldName: string; HoldReason?: st 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 } +export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; type?: string; + paymentMethod?: 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'); +/** An invoice type as the step and REST both mean it: "Credit memo", "Credit Memo", "CREDIT" and "credit_memo" are one type + * (Fusion's REST returns the type's meaning or its code, by release). */ +export function invoiceTypeKey(t: string): string { + const s = spelling(String(t ?? '').replace(/[_-]+/g, ' ')); + return /^credit( memo)?$/.test(s) ? 'credit memo' : /^debit( memo)?$/.test(s) ? 'debit memo' : s; +} + +/** The sign Fusion enforces on an invoice's amount by its type: a credit or debit memo is entered negative, a standard + * invoice and a prepayment positive (a prepayment more than zero). Words for what is wrong (empty: right); no type + * given is a standard invoice. Checked before the screen is opened, so a wrong step fails in a sentence, not in Fusion. */ +export function invoiceAmountProblems(type: string | undefined, amounts: number[]): string[] { + const kind = invoiceTypeKey(type || 'standard'); + const negative = kind === 'credit memo' || kind === 'debit memo'; + return amounts.flatMap((a, i) => { + const what = amounts.length > 1 ? `line ${i + 1} (${a})` : `the amount (${a})`; + if (negative && !(a < 0)) return [`${what}: a ${kind} is entered with a negative amount`]; + if (!negative && a < 0) return [`${what}: a ${kind} invoice has a positive amount (a negative one is a credit or debit memo)`]; + if (kind === 'prepayment' && a === 0) return [`${what}: a prepayment is for more than zero`]; + return []; + }); +} + /** Every way the invoice differs from what is expected, in words (empty: as expected). `amountAtLeast` is for the * invoice total when the pod adds tax on top of the lines: the total is then the amount plus that tax. */ export function invoiceProblems(number: string, inv: Invoice | null, want: InvoiceExpectation): string[] { @@ -77,6 +100,15 @@ export function invoiceProblems(number: string, inv: Invoice | null, want: Invoi out.push(`its amount is ${inv.InvoiceAmount}, expected at least ${want.amountAtLeast}`); } if (want.canceled !== undefined && !!inv.CanceledFlag !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled'); + if (want.type && invoiceTypeKey(String(inv.InvoiceType ?? '')) !== invoiceTypeKey(want.type)) { + out.push(`its type is "${inv.InvoiceType ?? ''}", expected "${want.type}"`); + } + if (want.paymentMethod) { // the method's name or its code, whichever this release returns + const has = [inv.PaymentMethod, inv.PaymentMethodCode].filter((v) => v !== undefined && v !== null && v !== '').map(String); + if (!has.some((m) => spelling(m) === spelling(want.paymentMethod!))) { + out.push(`its payment method is "${has[0] ?? ''}", expected "${want.paymentMethod}"`); + } + } return out; } @@ -102,8 +134,30 @@ export interface DocExpectation { status?: string; amount?: number; amountAtLeas /** 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(); -/** An order's status in words ("Open", "Pending Approval", "Incomplete", "Canceled", ...). */ -export const orderStatus = (o: PurchaseOrder) => String(o.Status || o.StatusCode || '').trim(); +/** The attributes a pod may keep an order's closure in, apart from its status (Open, Closed for Receiving, ...): read when the + * status says only Open or Closed. Guesses (a release may fold the closure into Status itself): verify on the pod. */ +const CLOSURE_ATTRS = ['ClosureStatus', 'CloseStatus', 'ClosedStatus', 'ClosureStatusCode']; + +/** An order's status in words ("Open", "Pending Approval", "Incomplete", "Canceled", "Closed for Receiving", ...). */ +export function orderStatus(o: PurchaseOrder): string { + const base = String(o.Status || o.StatusCode || '').trim(); + const closure = String(CLOSURE_ATTRS.map((k) => o[k]).find((v) => v !== undefined && v !== null && v !== '') ?? '').trim(); + return closure && /^(open|closed)$/i.test(base) && !/^open$/i.test(closure) ? closure : base; +} + +/** What close_purchase_order closes an order as (its value, any case), the entries of the Actions menu that do it directly, + * and the status Fusion then shows. null: not a way to close an order. */ +export const CLOSE_ACTIONS: Record = { + 'close for receiving': { status: 'Closed for Receiving', direct: ['Close for Receiving', 'Close Receiving'] }, + 'close for invoicing': { status: 'Closed for Invoicing', direct: ['Close for Invoicing', 'Close Invoicing'] }, + close: { status: 'Closed', direct: ['Close', 'Close Order', 'Close Purchase Order'] }, + 'finally close': { status: 'Finally Closed', direct: ['Finally Close', 'Finally Close Order'] }, +}; +export const closeAction = (how: string) => CLOSE_ACTIONS[spelling(how)] ?? null; + +/** An order that can be closed (any way): approved, or already closed one way and now closed another. Not pending approval, + * not incomplete, not canceled, not finally closed. */ +export const orderCloseable = (status: string) => ['open', 'closed for receiving', 'closed for invoicing', 'closed'].includes(statusKey(status)); /** An order's amount: its total, or the ordered amount on pods that return only that. NaN when it carries neither. */ export const orderAmount = (o: PurchaseOrder) => Number(['Total', 'Ordered', 'TotalAmount', 'Amount'].map((k) => o[k]) @@ -120,6 +174,9 @@ export function journalStatus(b: JournalBatch): string { export const journalPosted = (b: JournalBatch) => String(b.Status || '').trim().toUpperCase() === 'P' || spelling(journalStatus(b)) === 'posted'; +/** A status as the screen and REST both mean it: also "CLOSED_FOR_RECEIVING" (a code) is "Closed for Receiving". */ +const statusKey = (s: string) => spelling(String(s ?? '').replace(/_/g, ' ')); + /** A requisition or order that is out of the way: cancelled, or (a requisition) withdrawn. */ const canceledStatus = (s: string) => /^(canceled|withdrawn)$/.test(spelling(s)); @@ -127,7 +184,7 @@ const canceledStatus = (s: string) => /^(canceled|withdrawn)$/.test(spelling(s)) function docProblems(what: string, status: string, amount: number, posted: boolean | undefined, want: DocExpectation): string[] { const out: string[] = []; const shown = (n: number) => (Number.isNaN(n) ? 'not given by Fusion' : String(n)); - if (want.status && spelling(status) !== spelling(want.status)) out.push(`its status is "${status}", expected "${want.status}"`); + if (want.status && statusKey(status) !== statusKey(want.status)) out.push(`its status is "${status}", expected "${want.status}"`); if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${shown(amount)}, expected ${want.amount}`); if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) { out.push(`its amount is ${shown(amount)}, expected at least ${want.amountAtLeast}`); @@ -152,6 +209,106 @@ export function journalProblems(name: string, b: JournalBatch | null, want: DocE return docProblems(`journal batch ${name}`, journalStatus(b), NaN, journalPosted(b), want); } +/* + * Receivables (Order-to-Cash): receivablesInvoices (transactions) and standardReceipts. A transaction is numbered by + * Fusion on save, so it carries the test's FPT- tag in its Comments and is found by it; a receipt's number is typed by + * the test, so the tag IS its number. Attribute names are the documented ones of 11.13.18.05 as far as known; where pods + * and releases differ several are read (every guess is listed in the report of the change that added them). + */ +export interface ArTransaction { CustomerTransactionId: number; TransactionNumber: string; BusinessUnit?: string; BillToCustomerName?: string; + TransactionType?: string; [k: string]: unknown } +export interface ArReceipt { StandardReceiptId: number; ReceiptNumber: string; Amount?: number; [k: string]: unknown } + +const firstOf = (o: Record, keys: string[]) => keys.map((k) => o[k]).find((v) => v !== undefined && v !== null && v !== ''); + +/** A transaction's status in words ("Incomplete", "Complete", ...): its status attribute, else its complete flag. */ +export function transactionStatus(t: ArTransaction): string { + const said = firstOf(t, ['InvoiceStatus', 'TransactionStatus', 'Status', 'StatusMeaning']); + if (said !== undefined) return String(said).trim(); + const flag = firstOf(t, ['CompleteFlag', 'Complete']); + return flag === undefined ? '' : (flag === true || /^(y|yes|true)$/i.test(String(flag)) ? 'Complete' : 'Incomplete'); +} + +/** A transaction's amount (entered, else total); NaN when it carries neither. */ +export const transactionAmount = (t: ArTransaction) => Number(firstOf(t, ['EnteredAmount', 'InvoiceAmount', 'TotalAmount', 'Amount']) ?? NaN); + +export const receiptAmount = (r: ArReceipt) => Number(firstOf(r, ['Amount', 'ReceiptAmount', 'EnteredAmount']) ?? NaN); + +/** A receipt's application state in words: "Applied", "Unapplied", "Partially applied" (or "Reversed" when it is). The + * state or status attribute says it when it can; else the unapplied amount against the receipt's amount. */ +export function receiptState(r: ArReceipt): string { + for (const k of ['State', 'ReceiptState', 'StatusMeaning', 'Status', 'ReceiptStatus']) { + const v = String(r[k] ?? '').trim(); + if (/revers|applied|unidentified/i.test(v)) return v; + } + const open = Number(firstOf(r, ['UnappliedAmount', 'UnappliedAmt']) ?? NaN); + const total = receiptAmount(r); + if (Number.isNaN(open) || Number.isNaN(total)) return String(firstOf(r, ['State', 'Status', 'ReceiptStatus']) ?? '').trim(); + return open < 0.005 ? 'Applied' : open >= total - 0.005 ? 'Unapplied' : 'Partially applied'; +} + +export function transactionProblems(number: string, t: ArTransaction | null, want: DocExpectation): string[] { + if (!t) return [`transaction ${number} is not in Fusion`]; + return docProblems(`transaction ${number}`, transactionStatus(t), transactionAmount(t), undefined, want); +} + +export function receiptProblems(number: string, r: ArReceipt | null, want: DocExpectation): string[] { + if (!r) return [`receipt ${number} is not in Fusion`]; + return docProblems(`receipt ${number}`, receiptState(r), receiptAmount(r), undefined, want); +} + +/* + * Receipts of purchase orders (Receiving): a receipt carries the test's FPT- tag as its packing slip, so it is found by it + * (and by the number Fusion gives it). Which resource and attribute a pod answers is not the same on every release: + * receivingReceiptRequests and receivingReceiptTransactions are asked with several attributes in turn (a pod that does not + * have one answers HTTP 400 or 404, which is not an error), and the order's own received quantity (its schedules) is the + * other witness. Every guess is listed in the report of the change that added them. + */ +export interface PoReceipt { ReceiptNumber?: string; [k: string]: unknown } +export interface ReceiptOfOrderExpectation { quantity?: number } + +export const RECEIPT_RESOURCES = ['receivingReceiptRequests', 'receivingReceiptTransactions']; +/** The queries that find a receipt by what the test knows: its number, its packing slip (the tag), a comment or shipment number. */ +export const receiptQueries = (v: string) => [`ReceiptNumber='${q(v)}'`, `PackingSlip='${q(v)}'`, `Comments LIKE '${q(v)}%'`, `ShipmentNumber='${q(v)}'`]; + +/** An order that can be received: approved (Open), or already closed for invoicing; not pending approval, not closed for receiving. */ +export const orderReceivable = (status: string) => ['open', 'closed for invoicing'].includes(statusKey(status)); + +function sumOf(rows: Record[], keys: string[]): number { + let total = 0; + let seen = false; + for (const r of rows) { + const v = firstOf(r, keys); + if (v !== undefined && !Number.isNaN(Number(v))) { total += Number(v); seen = true; } + } + return seen ? total : NaN; +} + +/** The quantity a receipt record carries: its lines' quantities when it holds them, else its own. NaN when it says none. */ +export function receiptLineQuantity(r: PoReceipt): number { + const keys = ['Quantity', 'ReceivedQuantity', 'QuantityReceived']; + return Array.isArray(r.lines) ? sumOf(r.lines as Record[], keys) : Number(firstOf(r, keys) ?? NaN); +} + +/** The quantity received on an order, from its schedules. NaN when they say none. */ +export const scheduleReceivedQuantity = (schedules: Record[]) => sumOf(schedules, ['ReceivedQuantity', 'QuantityReceived', 'Received']); + +/** Every way a receipt differs from what is expected, in words. `onOrder` = the quantity received on its order (the other + * witness: a pod whose receipt resources this user cannot read still shows the order's received quantity). */ +export function poReceiptProblems(ref: string, r: PoReceipt | null, onOrder: number | undefined, want: ReceiptOfOrderExpectation): string[] { + const onOrderSeen = onOrder !== undefined && !Number.isNaN(onOrder) && onOrder > 0; + if (!r && !onOrderSeen) return [`receipt ${ref} is not in Fusion`]; + if (want.quantity === undefined) return []; + const own = r ? receiptLineQuantity(r) : NaN; + const got = !Number.isNaN(own) ? own : onOrder ?? NaN; + if (Number.isNaN(got)) return [`receipt ${ref}: Fusion does not give the received quantity (expected ${want.quantity})`]; + return Math.abs(got - want.quantity) < 0.0005 ? [] : [`receipt ${ref}: the quantity received is ${got}, expected ${want.quantity}`]; +} + +/** Clean-up that only a person can do (a completed transaction needs a credit memo, an applied receipt a reversal): + * the test is not failed for it; the document stays in the run's test-data list with what to do. */ +export class LeftForPerson extends Error {} + /** Clean-up that REST cannot do (a submitted requisition: Fusion's REST service offers no cancel for it): the fixture * does it on the screens instead, then asks REST again. */ export class NeedsScreen extends Error {} @@ -274,6 +431,70 @@ export class FusionRest { if (r.status < 200 || r.status >= 300) throw new Error(`${what}: Fusion refused the delete (HTTP ${r.status} ${r.text.slice(0, 200)})`); } + /** A first item, or why none: a pod that does not have the resource or the attribute answers HTTP 400 or 404 (`refused`). */ + private async tryFirst(resource: string, query: string): Promise<{ item: T | null; refused: boolean }> { + try { return { item: (await this.get(resource, query))[0] || null, refused: false }; } catch (e) { + if (/HTTP (400|404)\b/.test(String((e as Error).message))) return { item: null, refused: true }; + throw e; + } + } + + /** The receipt of a purchase order by its number or by the test's tag (packing slip): the first query of the receiving + * resources this pod answers with a record. `refused` = this pod answered none of them (so a missing receipt proves nothing). */ + async poReceipt(numberOrTag: string): Promise<{ receipt: PoReceipt | null; refused: boolean }> { + let asked = 0; + let refused = 0; + for (const resource of RECEIPT_RESOURCES) { + for (const query of receiptQueries(numberOrTag)) { + asked++; + const r = await this.tryFirst(resource, query); + if (r.item) return { receipt: r.item, refused: false }; + if (r.refused) refused++; + } + } + return { receipt: null, refused: refused === asked }; + } + + private async getAll(path: string): Promise[]> { + const r = await this.call('GET', `${path}?onlyData=true&limit=100`); + if (r.status !== 200) throw new Error(`GET ${path} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`); + return (JSON.parse(r.text).items || []) as Record[]; + } + + /** The quantity received on the order, summed over its lines' schedules; null when the order or its schedules cannot be read. */ + async orderReceivedQuantity(orderNumber: string): Promise { + const o = await this.purchaseOrder(orderNumber); + if (!o || o.draft) return null; + try { + let total = 0; + let seen = false; + for (const line of await this.getAll(`purchaseOrders/${o.POHeaderId}/child/lines`)) { + const q = scheduleReceivedQuantity(await this.getAll(`purchaseOrders/${o.POHeaderId}/child/lines/${line.POLineId}/child/schedules`)); + if (!Number.isNaN(q)) { total += q; seen = true; } + } + return seen ? total : null; + } catch (e) { + if (/HTTP (400|404)\b/.test(String((e as Error).message))) return null; + throw e; + } + } + + /** Clean-up of a test receipt of an order (found by its tag, the packing slip): only a person undoes it (corrects it to + * zero or returns the items), so it is left for one; a receipt that cannot be looked up at all is left too, because it may + * have been saved. Nothing is written. */ + async cleanPoReceipt(tag: string): Promise { + const { receipt, refused } = await this.poReceipt(tag); + if (receipt) { + throw new LeftForPerson(`receipt ${receipt.ReceiptNumber ?? tag} (packing slip ${tag}) received the order's line: correct it or return the items ` + + 'on Receiving > Manage Receipts, then cancel or close the order'); + } + if (refused) { + throw new LeftForPerson(`this pod's REST answers none of the receipt queries, so it is not known whether the receipt with packing slip ${tag} ` + + 'was saved: look for it on Receiving > Manage Receipts and correct or return it'); + } + return `${tag}: no receipt saved, nothing to clean up`; + } + /** Clean-up of a test requisition (found by its tag): an Incomplete one is deleted; a canceled, withdrawn or rejected * one needs nothing. A submitted one has no cancel over REST: NeedsScreen, and the fixture cancels it on the screens. */ async cleanRequisition(tag: string): Promise { @@ -291,13 +512,23 @@ export class FusionRest { /** Clean-up of a test order (found by its tag): an Incomplete draft is deleted, an open one cancelled with Fusion's * cancel action; canceled and closed ones need nothing. One pending approval cannot be cancelled until it is - * withdrawn, and a cancel action this pod does not offer is done on the screens: NeedsScreen for both. */ - async cleanPurchaseOrder(tag: string): Promise { + * withdrawn, and a cancel action this pod does not offer is done on the screens: NeedsScreen for both. An order with a + * receipt a person has still to undo (`received`) cannot be cancelled: LeftForPerson. */ + async cleanPurchaseOrder(tag: string, received = false): Promise { const o = await this.purchaseOrder(tag); if (!o) return `${tag}: no purchase order saved, nothing to clean up`; const status = orderStatus(o); - const s = spelling(status); - if (s === 'canceled' || s.includes('closed')) return `purchase order ${o.OrderNumber}: already ${status.toLowerCase()}`; + const s = statusKey(status); + if (s === 'canceled') return `purchase order ${o.OrderNumber}: already ${status.toLowerCase()}`; + if (s.includes('closed')) { // closed by the test (close_purchase_order): only a person reopens it + throw new LeftForPerson(`purchase order ${o.OrderNumber} is ${status}: ` + (s.includes('finally') + ? 'it cannot be reopened or cancelled; it stays on the pod as a closed test order' + : 'reopen it on Manage Orders (Actions > Open) and cancel it if it should go')); + } + if (received) { + throw new LeftForPerson(`purchase order ${o.OrderNumber} is ${status} and has received lines: Fusion does not cancel it; close it on Manage Orders ` + + '(Actions > Close) once its receipt is corrected or returned'); + } if (s === 'incomplete') { await this.remove(`draftPurchaseOrders/${o.POHeaderId}`, `purchase order ${o.OrderNumber}`); return `purchase order ${o.OrderNumber}: deleted by clean-up (never submitted)`; @@ -326,4 +557,39 @@ export class FusionRest { } return done.join('; '); } + + /** The transaction with this number, else the one carrying the test's tag in its Comments (or Internal Notes). */ + async transaction(numberOrTag: string): Promise { + return await this.first('receivablesInvoices', `TransactionNumber='${q(numberOrTag)}'`) + ?? await this.first('receivablesInvoices', `Comments LIKE '${q(numberOrTag)}%'`) + ?? await this.first('receivablesInvoices', `InternalNotes LIKE '${q(numberOrTag)}%'`); + } + + /** The receipt with this number: the test's own tag. */ + async receipt(number: string): Promise { + return this.first('standardReceipts', `ReceiptNumber='${q(number)}'`); + } + + /** Clean-up of a test transaction (found by its tag): an Incomplete one is deleted. A completed one stays: it needs + * a credit memo, which a person raises (LeftForPerson). */ + async cleanTransaction(tag: string): Promise { + const t = await this.transaction(tag); + if (!t) return `${tag}: no transaction saved, nothing to clean up`; + const status = transactionStatus(t); + if (spelling(status) === 'incomplete') { + await this.remove(`receivablesInvoices/${t.CustomerTransactionId}`, `transaction ${t.TransactionNumber}`); + if (await this.transaction(tag)) throw new Error(`transaction ${t.TransactionNumber}: Fusion accepted the delete but it is still there`); + return `transaction ${t.TransactionNumber}: deleted by clean-up (never completed)`; + } + throw new LeftForPerson(`transaction ${t.TransactionNumber} is ${status || 'completed'}: credit it on Manage Transactions (Actions > Credit Transaction)`); + } + + /** Clean-up of a test receipt: only a person reverses it (REST offers no reversal this clean-up may use). */ + async cleanReceipt(number: string): Promise { + const r = await this.receipt(number); + if (!r) return `${number}: no receipt saved, nothing to clean up`; + const state = receiptState(r); + if (/revers/i.test(state)) return `receipt ${number}: already reversed`; + throw new LeftForPerson(`receipt ${number} is ${state || 'saved'}: reverse it on Manage Receipts (Actions > Reverse Receipt)`); + } } diff --git a/automation/src/fusion/steps.ts b/automation/src/fusion/steps.ts index e192ce314ecbca771ba2d4f8e2d4bac2c632f03d..24b7486cf19a31fbd54d5ddeb7d46c1f708a0c93 100644 --- a/automation/src/fusion/steps.ts +++ b/automation/src/fusion/steps.ts @@ -2,8 +2,8 @@ import * as fs from 'fs'; import * as path from 'path'; import YAML from 'yaml'; import { expect, test, type DocKind, type FusionDocs } from './fixtures'; -import { activeHolds, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, purchaseOrderProblems, requisitionProblems, - REST_SKIPPED, type DocExpectation, type FusionRest, type InvoiceExpectation } from './rest'; +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'; import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui'; /* @@ -21,11 +21,15 @@ import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, Valu * per area (tests/cases/CANARY-.yaml) runs each of them once before a run, to prove they still work on the pod. * Purchasing: create_requisition, expect_requisition, cancel_requisition, create_purchase_order, submit_purchase_order, * find_purchase_order, expect_purchase_order, cancel_purchase_order (extra fields quantity, price). General Ledger: - * create_journal, post_journal, find_journal, expect_journal, reverse_journal (extra field posted). + * 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). */ 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 } + quantity?: string | number; price?: string | number; posted?: boolean; applies_to?: string; invoice_type?: string; payment_method?: 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 @@ -51,6 +55,7 @@ export function loadStepCase(id: string, dir?: string): StepCase { type Ctx = { ui: FusionUi; c: StepCase; saved: Record; uniques: Record; track: (n: string) => string; chosen: Record; // the pod value Fusion accepted, per "area.key", used again for the rest of the test + orderTags: Record; // the test's tag of each purchase order made, by its number (its receipt names it for clean-up) 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 @@ -138,7 +143,7 @@ const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n') * 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 }) { +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; @@ -146,7 +151,7 @@ async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[] 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 }); + amount: h.amount, lines: h.lines, account: set.account, invoiceType: h.invoiceType, paymentMethod: h.paymentMethod }); ctx.saved[h.name] = number; return got; }; @@ -186,7 +191,7 @@ function choices(ctx: Ctx, area: string, key: string, ...also: [string, string][ } /** A new test reference for a document of this scenario (FPT--