patchwise-agent-studio / automation /scripts /check-interfaces.ts
EnergyVenom's picture
Astra: interface testing (opt-in), 26D screen fixes for journals, transactions and invoice types (15e2c63d18cb)
2a2e3d4 verified
Raw History Blame Contribute Delete
9.83 kB
/* Checks the interface (import) building blocks (src/fusion/interfaces.ts) without a pod: `npx tsx scripts/check-interfaces.ts`. */
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { invoiceProblems, transactionProblems } from '../src/fusion/rest';
import { AP_INVOICE_COLUMNS, AP_LINE_COLUMNS, AR_LINE_COLUMNS, IMPORTS, WIDTH, apInvoiceFiles, arTransactionFiles, crc32, essOutcome, fbdiDate, fbdiRow,
importBody, importsAllowed, looksLikeProduction, parameterList, requestId, zipStore } from '../src/fusion/interfaces';
const TAG = 'FPT-APFUS040-1122101500';
const ap = { tag: TAG, interfaceId: 1122101500123, businessUnit: 'BU One', supplier: 'Supplier, Inc', site: 'MAIN', account: '101-10-1000',
source: 'External', amount: '100', currency: 'USD', date: '2026/11/22' };
// the column order is the template's: the key columns sit where Oracle's template puts them
assert.equal(AP_INVOICE_COLUMNS[0], 'Invoice ID');
assert.equal(AP_INVOICE_COLUMNS.indexOf('Source'), 2);
assert.equal(AP_INVOICE_COLUMNS.indexOf('Invoice Number'), 3);
assert.equal(AP_INVOICE_COLUMNS.indexOf('Supplier Name'), 6);
assert.equal(AP_LINE_COLUMNS.indexOf('Amount'), 3);
assert.equal(AR_LINE_COLUMNS.indexOf('Transaction Number'), 6);
assert.equal(AR_LINE_COLUMNS.indexOf('Interface Line Attribute 1') < AR_LINE_COLUMNS.indexOf('Interface Line Attribute 15'), true);
// AP: header and line, tagged, one cell per column, quoting where needed, empty where nothing is given
const files = apInvoiceFiles(ap);
assert.deepEqual(Object.keys(files), ['ApInvoicesInterface.csv', 'ApInvoiceLinesInterface.csv']);
const header = files['ApInvoicesInterface.csv'].trimEnd();
assert.equal(header.split('\n').length, 1);
const cells = header.replace('"Supplier, Inc"', 'Supplier Inc').split(',');
assert.equal(cells.length, AP_INVOICE_COLUMNS.length);
assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Invoice Number')], TAG);
assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Import Set')], TAG); // the job is scoped to this file's rows
assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Source')], 'External');
assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Invoice Amount')], '100');
assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Supplier Number')], '');
assert.ok(header.includes('"Supplier, Inc"'));
const line = files['ApInvoiceLinesInterface.csv'].trimEnd().split(',');
assert.equal(line.length, AP_LINE_COLUMNS.length);
assert.equal(line[0], String(ap.interfaceId)); // the line carries its header's id
assert.equal(line[AP_LINE_COLUMNS.indexOf('Line Type')], 'Item');
assert.equal(line[AP_LINE_COLUMNS.indexOf('Distribution Combination')], '101-10-1000');
assert.equal(cells[0], line[0]);
// a column the template does not have, and a value the file cannot do without
assert.throws(() => fbdiRow(AP_LINE_COLUMNS, { Nope: 1 }), /not a column/);
assert.throws(() => apInvoiceFiles({ ...ap, supplier: ' ' }), /supplier is needed/);
assert.throws(() => apInvoiceFiles({ ...ap, currency: '' }), /currency is needed/);
// AR: one line, tagged as the transaction number, the customer order number and the first interface attribute
const ar = arTransactionFiles({ tag: 'FPT-ARFUS040-1122101500', businessUnit: 'BU One', source: 'Receivables Import', type: 'Invoice',
customerAccount: '1001', amount: 250.5, currency: 'USD', date: '2026/11/22' });
assert.deepEqual(Object.keys(ar), ['RaInterfaceLinesAll.csv']);
const arc = ar['RaInterfaceLinesAll.csv'].trimEnd().split(',');
assert.equal(arc.length, AR_LINE_COLUMNS.length);
for (const [col, v] of [['Business Unit Name', 'BU One'], ['Batch Source Name', 'Receivables Import'], ['Transaction Type Name', 'Invoice'],
['Transaction Number', 'FPT-ARFUS040-1122101500'], ['Customer Order Number', 'FPT-ARFUS040-1122101500'], ['Interface Line Attribute 1', 'FPT-ARFUS040-1122101500'],
['Bill-to Customer Account Number', '1001'], ['Transaction Line Amount', '250.5'], ['Unit Selling Price', '250.5'], ['Transaction Line Quantity', '1'],
['Currency Code', 'USD'], ['Payment Terms', '']]) assert.equal(arc[AR_LINE_COLUMNS.indexOf(col)], v, col);
assert.throws(() => arTransactionFiles({ tag: 'T', businessUnit: 'B', source: 'S', type: 'Invoice', customerAccount: '', amount: 1, currency: 'USD', date: 'd' }), /customer account number is needed/);
// full-width rows, once the table says so
Object.assign(WIDTH, { padTo: 30, endMarker: true });
const wide = fbdiRow(AP_LINE_COLUMNS, { 'Invoice ID': 1 }).split(',');
assert.equal(wide.length, 30);
assert.equal(wide[29], 'END');
Object.assign(WIDTH, { padTo: undefined, endMarker: false });
// dates
assert.equal(fbdiDate(new Date(Date.UTC(2026, 0, 5))), '2026/01/05');
// parameter lists: the job's order, #NULL for the rest, no comma inside a value
assert.equal(parameterList('payables_invoice', { 'Business Unit': 'BU One', Source: 'External', 'Import Set': TAG, Purge: 'Y' }),
`BU One,#NULL,External,${TAG},#NULL,#NULL,#NULL,Y,#NULL`);
assert.equal(parameterList('receivables_transaction', { 'Business Unit': 'BU One', 'Transaction Source': 'Receivables Import' }).split(',').length,
IMPORTS.receivables_transaction.params.length);
assert.throws(() => parameterList('payables_invoice', { 'Business Unit': 'A, B' }), /comma/);
assert.throws(() => parameterList('payables_invoice', { Nope: 'x' }), /not a parameter/);
// the zip is a valid zip: Python's zipfile (when present) reads it back, and the CRC and sizes are the files'
const zip = zipStore(files);
assert.equal(zip.readUInt32LE(0), 0x04034b50);
assert.equal(zip.readUInt32LE(zip.length - 22), 0x06054b50);
assert.equal(zip.readUInt16LE(zip.length - 22 + 10), 2); // two entries
assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926); // the standard check value of CRC-32
let python = true;
const dir = mkdtempSync(join(tmpdir(), 'fpt-zip-'));
writeFileSync(join(dir, 'x.zip'), zip);
let out = '';
try {
out = execFileSync('python', ['-I', '-c', 'import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);assert z.testzip() is None;print("|".join(n+"="+str(len(z.read(n))) for n in z.namelist()))', join(dir, 'x.zip')],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch (e) {
if ((e as { code?: string }).code !== 'ENOENT') throw e;
python = false; // no python here: the structure checks above stand
}
if (python) assert.equal(out, `ApInvoicesInterface.csv=${Buffer.byteLength(files['ApInvoicesInterface.csv'])}|ApInvoiceLinesInterface.csv=${Buffer.byteLength(files['ApInvoiceLinesInterface.csv'])}`);
// the call's body
const body = importBody('payables_invoice', TAG, files, { 'Business Unit': 'BU One', Source: 'External', 'Import Set': TAG });
assert.equal(body.OperationName, 'importBulkData');
assert.equal(body.ContentType, 'zip');
assert.equal(body.FileName, `${TAG}.zip`);
assert.equal(body.DocumentAccount, 'fin$/payables$/import$');
assert.ok(body.JobName.endsWith(',APXIIMPT'));
assert.match(body.JobOptions, /^InterfaceDetails=\d+,/);
assert.deepEqual(Buffer.from(body.DocumentContent, 'base64'), zip);
assert.equal(importBody('receivables_transaction', 'a b/c', ar, {}).FileName, 'a_b_c.zip');
assert.ok(importBody('receivables_transaction', TAG, ar, {}).JobName.endsWith(',AutoInvoiceImportEss'));
// the answers
assert.equal(requestId({ ReqstId: '123456' }), '123456');
assert.equal(requestId({ RequestId: 77 }), '77');
assert.throws(() => requestId({ ReqstId: null }), /no request id/);
assert.deepEqual(essOutcome(null), { done: false, ok: false, status: 'not started' });
assert.deepEqual(essOutcome({ RequestStatus: 'RUNNING' }), { done: false, ok: false, status: 'RUNNING' });
assert.deepEqual(essOutcome({ RequestStatus: 'SUCCEEDED' }), { done: true, ok: true, status: 'SUCCEEDED' });
assert.deepEqual(essOutcome({ RequestStatus: 'WARNING' }), { done: true, ok: true, status: 'WARNING' });
assert.deepEqual(essOutcome({ RequestStatus: 'ERROR' }), { done: true, ok: false, status: 'ERROR' });
assert.equal(essOutcome({ RequestStatus: 'ERROR_AUTO_RETRY' }).done, true);
// the opt-in and the second production lock
assert.equal(importsAllowed({}), false);
assert.equal(importsAllowed({ FPT_ALLOW_IMPORTS: '0' }), false);
assert.equal(importsAllowed({ FPT_ALLOW_IMPORTS: 'true' }), false); // only the exact flag
assert.equal(importsAllowed({ FPT_ALLOW_IMPORTS: '1' }), true);
assert.equal(looksLikeProduction('acme-prod.fa.us6.oraclecloud.com'), true);
assert.equal(looksLikeProduction('acme-test.fa.us6.oraclecloud.com'), false);
// the checks of an imported document: its source (the existing expect_invoice / expect_transaction, with a source)
const inv = { InvoiceId: 1, InvoiceNumber: TAG, InvoiceAmount: 100, ValidationStatus: 'Validated', CanceledFlag: false, BusinessUnit: 'B', Supplier: 'S' };
assert.deepEqual(invoiceProblems(TAG, { ...inv, InvoiceSource: 'External' }, { source: 'external' }), []);
assert.deepEqual(invoiceProblems(TAG, { ...inv, Source: 'External' }, { source: 'External' }), []);
assert.match(invoiceProblems(TAG, { ...inv, InvoiceSource: 'Spreadsheet' }, { source: 'External' })[0], /source is "Spreadsheet", expected "External"/);
assert.match(invoiceProblems(TAG, inv, { source: 'External' })[0], /does not return the invoice's source/);
assert.deepEqual(invoiceProblems(TAG, inv, {}), []); // no source asked for: unchanged
assert.deepEqual(transactionProblems('T1', { CustomerTransactionId: 1, TransactionNumber: 'T1', TransactionSource: 'Receivables Import', EnteredAmount: 250.5, InvoiceStatus: 'Complete' },
{ source: 'receivables import', status: 'Complete' }), []);
console.log('interfaces: all checks pass');