/* * Interface (import) testing: the pure parts. The client's volume that arrives through imports (AutoInvoice "Receivables * Import", Payables Standard Invoice Import "External") is tested the way the client's integrations create it: a FBDI file * is uploaded through Fusion's ERP Integration REST service (rest.ts importBulkData), the import job runs, and the document * it creates is checked like any other. Nothing here calls the network, so scripts/check-interfaces.ts tests it all. * * EVERYTHING Oracle-specific is in the data tables below (IMPORTS, the column lists): job names, the order of each job's * parameters, the UCM account, the FBDI column order. They are written from Oracle's published FBDI templates and ERP * Integration REST documentation as far as known and are ASSUMPTIONS to verify on a pod before imports are switched on * (docs list them): a wrong one makes the import job fail or reject the file, it never creates a wrong document, but * one that is wrong in a way the job accepts could import something else. Fix a table row, not the code around it. * * Safety: an import writes data to the pod, so FusionRest.importBulkData refuses unless the run was started with * FPT_ALLOW_IMPORTS=1 (the pod's "allow imports" setting, set by an admin; never on production). Each file holds ONE test * document tagged with the test's FPT- tag, and the job is scoped to it where the job has a parameter for that (the AP * import set, the AR transaction number range), so a run never imports rows somebody else left in the interface tables. */ /** A FBDI CSV: its name inside the zip and its columns in the template's order (the order matters, the names are for people). */ export interface FbdiFile { name: string; columns: readonly string[] } /** One import: where the file goes, which job loads it and the job's parameters in the order Fusion takes them. */ export interface ImportSpec { /** UCM account the file is uploaded to (ERP Integration REST: DocumentAccount). */ account: string; /** The import job: "," (ERP Integration REST: JobName). */ jobName: string; /** The FBDI import's interface id, in JobOptions (ERP Integration REST: InterfaceDetails=). ASSUMED per import. */ interfaceDetails: number; /** The job's parameters in order; a name the caller gives no value for is sent as #NULL. */ params: readonly string[]; files: readonly FbdiFile[]; } const seq = (prefix: string, n: number) => Array.from({ length: n }, (_, i) => `${prefix} ${i + 1}`); /** ApInvoicesInterface.csv: Payables Standard Invoice Import header columns, in template order, through the last one the test * fills or needs to place; later columns are left out (see WIDTH). */ export const AP_INVOICE_COLUMNS = ['Invoice ID', 'Business Unit', 'Source', 'Invoice Number', 'Invoice Amount', 'Invoice Date', 'Supplier Name', 'Supplier Number', 'Supplier Site', 'Invoice Currency', 'Payment Currency', 'Description', 'Import Set', 'Invoice Type', 'Legal Entity', 'Customer Tax Registration Number', 'Customer Registration Code', 'First-Party Tax Registration Number', 'Supplier Tax Registration Number', 'Terms', 'Terms Date', 'Goods Received Date', 'Invoice Received Date', 'Accounting Date'] as const; /** ApInvoiceLinesInterface.csv: the line columns, in template order, through Distribution Combination. */ export const AP_LINE_COLUMNS = ['Invoice ID', 'Line Number', 'Line Type', 'Amount', 'Quantity', 'Unit Price', 'Unit of Measure', 'Description', 'PO Number', 'PO Line Number', 'PO Schedule Number', 'PO Distribution Number', 'Item Description', 'Release Number', 'Purchasing Category', 'Receipt Number', 'Receipt Line Number', 'Consumption Advice Number', 'Consumption Advice Line Number', 'Packing Slip', 'Final Match', 'Distribution Combination'] as const; /** RaInterfaceLinesAll.csv: AutoInvoice lines, in template order, through the interface line attributes. */ export const AR_LINE_COLUMNS = ['Business Unit Name', 'Batch Source Name', 'Transaction Type Name', 'Payment Terms', 'Transaction Date', 'Accounting Date', 'Transaction Number', 'Original System Bill-to Customer Reference', 'Original System Bill-to Customer Address Reference', 'Original System Bill-to Customer Contact Reference', 'Original System Ship-to Customer Reference', 'Original System Ship-to Customer Address Reference', 'Original System Ship-to Customer Contact Reference', 'Bill-to Customer Account Number', 'Bill-to Customer Site Number', 'Bill-to Contact Party Number', 'Ship-to Customer Account Number', 'Ship-to Customer Site Number', 'Ship-to Contact Party Number', 'Sold-to Customer Account Number', 'Transaction Line Type', 'Transaction Line Description', 'Currency Code', 'Currency Conversion Type', 'Currency Conversion Date', 'Currency Conversion Rate', 'Transaction Line Amount', 'Transaction Line Quantity', 'Customer Order Number', 'Customer Order Date', 'Unit Selling Price', 'Unit of Measure Code', 'Sales Order Number', 'Sales Order Date', 'Memo Line Name', 'Interface Line Context', ...seq('Interface Line Attribute', 15)] as const; /** Every row is exactly as wide as the columns listed above: no padding up to the template's full width and no END marker. * ASSUMED to be accepted (trailing columns are null); if a pod's loader wants full-width rows, set `padTo` (the template's * column count) and `endMarker` (the literal END as the last column) here, for every file at once. */ export const WIDTH: { padTo?: number; endMarker: boolean } = { endMarker: false }; /** The two imports. ASSUMPTIONS to verify live: see the file comment. */ export const IMPORTS = { payables_invoice: { // Payables Standard Invoice Import (APXIIMPT); the file goes to the payables import account of UCM account: 'fin$/payables$/import$', jobName: '/oracle/apps/ess/financials/payables/invoices/transactions,APXIIMPT', interfaceDetails: 20, // ASSUMED id of "Payables Invoice Import" among Oracle's FBDI interface ids // "Import Payables Invoices" parameters in the order of its Scheduled Processes form. Scoped by Import Set (the test's own // tag) so only this file's rows are imported; Purge removes the interface rows afterwards so none are left to a later import params: ['Business Unit', 'Ledger', 'Source', 'Import Set', 'Hold Name', 'Hold Reason', 'Accounting Date', 'Purge', 'Summarize Report'], files: [{ name: 'ApInvoicesInterface.csv', columns: AP_INVOICE_COLUMNS }, { name: 'ApInvoiceLinesInterface.csv', columns: AP_LINE_COLUMNS }], }, receivables_transaction: { // Import AutoInvoice (AutoInvoiceImportEss); the file goes to the receivables import account of UCM account: 'fin$/receivables$/import$', jobName: '/oracle/apps/ess/financials/receivables/transactions/autoInvoices,AutoInvoiceImportEss', interfaceDetails: 19, // ASSUMED id of "AutoInvoice Import" among Oracle's FBDI interface ids // "Import AutoInvoice" parameters in the order of its form, up to the transaction number range, which scopes the job to the // test's one transaction (its number is the tag). ASSUMED: a source that numbers transactions automatically ignores the // number in the file, and the range then matches nothing; drop the two range names after checking the source holds no // other pending rows params: ['Business Unit', 'Transaction Source', 'Default Date', 'Transaction Flexfield', 'Transaction Type', 'From Bill-to Customer Name', 'To Bill-to Customer Name', 'From Bill-to Customer Number', 'To Bill-to Customer Number', 'From Transaction Number', 'To Transaction Number'], files: [{ name: 'RaInterfaceLinesAll.csv', columns: AR_LINE_COLUMNS }], }, } as const satisfies Record; export type ImportKey = keyof typeof IMPORTS; /** FBDI dates are written YYYY/MM/DD. */ export const fbdiDate = (d: Date): string => `${d.getUTCFullYear()}/${String(d.getUTCMonth() + 1).padStart(2, '0')}/${String(d.getUTCDate()).padStart(2, '0')}`; /** One CSV cell: quoted when it holds a comma, a quote or a line break (a quote is doubled). */ const cell = (v: string | number | undefined): string => { const s = v === undefined || v === null ? '' : String(v); return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; }; export type Values = Record; /** One data row: the values by column name, in the column order of the template, empty where the test gives none. A name that is * not a column of the template is a mistake in the builder, never silently dropped. */ export function fbdiRow(columns: readonly string[], values: Values): string { for (const k of Object.keys(values)) if (!columns.includes(k)) throw new Error(`"${k}" is not a column of this FBDI file`); const cells = columns.map((c) => cell(values[c])); while (WIDTH.padTo !== undefined && cells.length < WIDTH.padTo - (WIDTH.endMarker ? 1 : 0)) cells.push(''); if (WIDTH.endMarker) cells.push('END'); return cells.join(','); } const nonEmpty = (what: string, v: string | number | undefined): string => { const s = String(v ?? '').trim(); if (!s) throw new Error(`${what} is needed for the file and the pod's test data has none`); return s; }; /** What the AP file holds: one standard invoice of one Item line. */ export interface ApInvoiceFbdi { tag: string; // the test's FPT- tag: the invoice number, and the import set (so the job imports only this file) interfaceId: number; // links the line to its header; unique in the interface table businessUnit: string; supplier: string; site?: string; account?: string; source: string; // the invoice source of the import (External ...) amount: string | number; currency: string; date: string; // date: FBDI format (fbdiDate) description?: string; } /** The AP import's two CSVs (header, line), by file name. The invoice number is the tag, so clean-up and left-on-pod find it. */ export function apInvoiceFiles(a: ApInvoiceFbdi): Record { const [h, l] = IMPORTS.payables_invoice.files; const header = fbdiRow(h.columns, { 'Invoice ID': a.interfaceId, 'Business Unit': nonEmpty('the business unit', a.businessUnit), 'Source': nonEmpty('the invoice source', a.source), 'Invoice Number': nonEmpty('the invoice number', a.tag), 'Invoice Amount': nonEmpty('the amount', a.amount), 'Invoice Date': a.date, 'Supplier Name': nonEmpty('the supplier', a.supplier), 'Supplier Site': a.site, 'Invoice Currency': nonEmpty('the currency', a.currency), 'Description': a.description ?? 'Test invoice imported by an automated test', 'Import Set': a.tag, 'Invoice Type': 'Standard', 'Accounting Date': a.date, }); const line = fbdiRow(l.columns, { 'Invoice ID': a.interfaceId, 'Line Number': 1, 'Line Type': 'Item', 'Amount': a.amount, 'Description': a.description ?? 'Test line', 'Distribution Combination': a.account, }); return { [h.name]: `${header}\n`, [l.name]: `${line}\n` }; } /** What the AR file holds: one invoice line of one transaction. */ export interface ArTransactionFbdi { tag: string; // the test's FPT- tag: the transaction number and the customer order number (both found by REST) businessUnit: string; source: string; type: string; customerAccount: string; amount: string | number; currency: string; date: string; memoLine?: string; description?: string; } /** The AutoInvoice CSV (RaInterfaceLinesAll). The tag is the transaction number (when the source takes a number from the file) and * the customer order number, which REST returns as the transaction's PurchaseOrder: so the transaction is found by it either way. */ export function arTransactionFiles(a: ArTransactionFbdi): Record { const [f] = IMPORTS.receivables_transaction.files; const row = fbdiRow(f.columns, { 'Business Unit Name': nonEmpty('the business unit', a.businessUnit), 'Batch Source Name': nonEmpty('the transaction source', a.source), 'Transaction Type Name': nonEmpty('the transaction type', a.type), 'Transaction Date': a.date, 'Accounting Date': a.date, 'Transaction Number': nonEmpty('the transaction reference', a.tag), 'Bill-to Customer Account Number': nonEmpty('the customer account number', a.customerAccount), 'Transaction Line Type': 'LINE', 'Transaction Line Description': a.description ?? 'Test transaction imported by an automated test', 'Currency Code': nonEmpty('the currency', a.currency), 'Transaction Line Amount': nonEmpty('the amount', a.amount), 'Transaction Line Quantity': 1, 'Customer Order Number': a.tag, 'Unit Selling Price': a.amount, 'Memo Line Name': a.memoLine, 'Interface Line Context': 'FPT', 'Interface Line Attribute 1': a.tag, }); return { [f.name]: `${row}\n` }; } // ---------------------------------------------------------------------------------------------------- zip (stored, no compression) const CRC_TABLE = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })(); /** CRC-32 of the bytes (what a zip entry carries). */ export function crc32(data: Uint8Array): number { let c = 0xffffffff; for (const b of data) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; } /** A zip of the files, stored without compression (the files are a few hundred bytes). 1980-01-01 as every entry's date. */ export function zipStore(files: Record): Buffer { const parts: Buffer[] = []; const central: Buffer[] = []; let offset = 0; for (const [name, text] of Object.entries(files)) { const nameBytes = Buffer.from(name, 'utf8'); const data = Buffer.from(text, 'utf8'); const crc = crc32(data); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0, 8); local.writeUInt16LE(0, 10); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc, 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(nameBytes.length, 26); local.writeUInt16LE(0, 28); const dir = Buffer.alloc(46); dir.writeUInt32LE(0x02014b50, 0); dir.writeUInt16LE(20, 4); dir.writeUInt16LE(20, 6); dir.writeUInt16LE(0x0800, 8); dir.writeUInt16LE(0, 10); dir.writeUInt16LE(0, 12); dir.writeUInt16LE(0x21, 14); dir.writeUInt32LE(crc, 16); dir.writeUInt32LE(data.length, 20); dir.writeUInt32LE(data.length, 24); dir.writeUInt16LE(nameBytes.length, 28); dir.writeUInt32LE(offset, 42); parts.push(local, nameBytes, data); central.push(dir, nameBytes); offset += local.length + nameBytes.length + data.length; } const cd = Buffer.concat(central); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(Object.keys(files).length, 8); end.writeUInt16LE(Object.keys(files).length, 10); end.writeUInt32LE(cd.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, cd, end]); } // ---------------------------------------------------------------------------------------------------- the ERP Integration call /** A value in a job's parameter list: a comma ends a parameter, so a value with one cannot be sent. */ function paramValue(name: string, v: string | undefined): string { const s = String(v ?? '').trim(); if (!s) return '#NULL'; if (s.includes(',')) throw new Error(`parameter "${name}" holds a comma (${s}): Fusion's parameter list cannot carry it`); return s; } /** The job's ParameterList: its parameters in the order Fusion takes them, #NULL where no value is given. A name the job does not * have is a mistake in the caller. */ export function parameterList(key: ImportKey, values: Record): string { const names: readonly string[] = IMPORTS[key].params; for (const k of Object.keys(values)) if (!names.includes(k)) throw new Error(`"${k}" is not a parameter of the ${key} import`); return names.map((n) => paramValue(n, values[n])).join(','); } /** The body of POST erpintegrations (operation importBulkData). The zip name is made of the tag, which is unique per run. */ export function importBody(key: ImportKey, tag: string, files: Record, params: Record) { const spec = IMPORTS[key]; return { OperationName: 'importBulkData', DocumentContent: zipStore(files).toString('base64'), ContentType: 'zip', FileName: `${tag.replace(/[^A-Za-z0-9._-]/g, '_')}.zip`, DocumentAccount: spec.account, JobName: spec.jobName, ParameterList: parameterList(key, params), JobOptions: `InterfaceDetails=${spec.interfaceDetails},ImportOption=Y,PurgeOption=Y,ExtractFileType=ALL`, CallbackURL: '#NULL', NotificationCode: '00', }; } /** The request id of a submitted job, from the answer of importBulkData (ReqstId; other services say RequestId). */ export function requestId(answer: Record): string { for (const k of ['ReqstId', 'RequestId', 'requestId']) { const v = answer[k]; if (v !== undefined && v !== null && String(v).trim() !== '' && String(v) !== '0') return String(v).trim(); } throw new Error(`Fusion accepted the import but gave no request id (answer: ${JSON.stringify(answer).slice(0, 200)})`); } /** Where a job stands, from its ESSJobStatusRF row: `done` = it has ended, `ok` = it ended well (a warning counts: the import of * a row can be refused while the job succeeds, the check of the document says which). */ export function essOutcome(item: Record | null | undefined): { done: boolean; ok: boolean; status: string } { const status = String(item?.RequestStatus ?? item?.Status ?? item?.ExecutionStatus ?? '').trim(); const s = status.toUpperCase(); if (!s) return { done: false, ok: false, status: 'not started' }; if (s === 'SUCCEEDED' || s === 'WARNING' || s === 'COMPLETED') return { done: true, ok: true, status }; if (/^(ERROR|FAILED|CANCELLED|CANCELED|BLOCKED|EXPIRED|ERROR_MANUAL_RECOVERY|ERROR_AUTO_RETRY|FINISHED_WITH_ERROR)/.test(s)) return { done: true, ok: false, status }; return { done: false, ok: false, status }; // READY, WAIT, RUNNING, PAUSED ... } /** Imports are allowed only when the run says so (FPT_ALLOW_IMPORTS=1, set from the pod's setting; see pods.executor_env). */ export const importsAllowed = (env: Record = process.env): boolean => env.FPT_ALLOW_IMPORTS === '1'; export const IMPORTS_REFUSED = 'imports are not allowed on this pod: an admin switches "Allow imports" on for the test environment (Test environments page); ' + 'an import writes test data to the pod through its ERP Integration service'; /** A host that looks like a production pod (the registry refuses these; this is the second lock, at the call itself). */ export const looksLikeProduction = (host: string): boolean => /(^|[.-])prod(uction)?([.-]|\d|$)/i.test(host);