EnergyVenom commited on
Commit
2a2e3d4
·
verified ·
1 Parent(s): ef26aca

Astra: interface testing (opt-in), 26D screen fixes for journals, transactions and invoice types (15e2c63d18cb)

Browse files
automation/remote_runner/server.py CHANGED
@@ -55,7 +55,7 @@ CASES = AUTOMATION.parent / "tests" / "cases"
55
  VERSION_FILE = AUTOMATION.parent / "VERSION"
56
  CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}
57
  ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
58
- "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS"}
59
  SESSION_STATE = "sign-in-state.json" # an attempt's signed-in session (assisted sign-in), in its job folder while it runs
60
  SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")
61
  ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")
@@ -199,7 +199,7 @@ def start(body: dict) -> dict:
199
  raise ValueError(f"{kind}: {name!r} is not a spec file name")
200
  (jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")
201
  report = jd / "report.json"
202
- env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE")}
203
  env.update(env_in)
204
  if body.get("storage_state") is not None: # assisted sign-in: the tests start from the session a person signed in
205
  env["FPT_FUSION_STORAGE_STATE"] = str(write_session(jd, body["storage_state"]))
 
55
  VERSION_FILE = AUTOMATION.parent / "VERSION"
56
  CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}
57
  ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
58
+ "FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS", "FPT_ALLOW_IMPORTS"}
59
  SESSION_STATE = "sign-in-state.json" # an attempt's signed-in session (assisted sign-in), in its job folder while it runs
60
  SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")
61
  ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")
 
199
  raise ValueError(f"{kind}: {name!r} is not a spec file name")
200
  (jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")
201
  report = jd / "report.json"
202
+ env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE", "FPT_ALLOW_IMPORTS")} # imports only when the job says so
203
  env.update(env_in)
204
  if body.get("storage_state") is not None: # assisted sign-in: the tests start from the session a person signed in
205
  env["FPT_FUSION_STORAGE_STATE"] = str(write_session(jd, body["storage_state"]))
automation/scripts/check-interfaces.ts ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Checks the interface (import) building blocks (src/fusion/interfaces.ts) without a pod: `npx tsx scripts/check-interfaces.ts`. */
2
+ import assert from 'node:assert/strict';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { mkdtempSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { invoiceProblems, transactionProblems } from '../src/fusion/rest';
8
+ import { AP_INVOICE_COLUMNS, AP_LINE_COLUMNS, AR_LINE_COLUMNS, IMPORTS, WIDTH, apInvoiceFiles, arTransactionFiles, crc32, essOutcome, fbdiDate, fbdiRow,
9
+ importBody, importsAllowed, looksLikeProduction, parameterList, requestId, zipStore } from '../src/fusion/interfaces';
10
+
11
+ const TAG = 'FPT-APFUS040-1122101500';
12
+ const ap = { tag: TAG, interfaceId: 1122101500123, businessUnit: 'BU One', supplier: 'Supplier, Inc', site: 'MAIN', account: '101-10-1000',
13
+ source: 'External', amount: '100', currency: 'USD', date: '2026/11/22' };
14
+
15
+ // the column order is the template's: the key columns sit where Oracle's template puts them
16
+ assert.equal(AP_INVOICE_COLUMNS[0], 'Invoice ID');
17
+ assert.equal(AP_INVOICE_COLUMNS.indexOf('Source'), 2);
18
+ assert.equal(AP_INVOICE_COLUMNS.indexOf('Invoice Number'), 3);
19
+ assert.equal(AP_INVOICE_COLUMNS.indexOf('Supplier Name'), 6);
20
+ assert.equal(AP_LINE_COLUMNS.indexOf('Amount'), 3);
21
+ assert.equal(AR_LINE_COLUMNS.indexOf('Transaction Number'), 6);
22
+ assert.equal(AR_LINE_COLUMNS.indexOf('Interface Line Attribute 1') < AR_LINE_COLUMNS.indexOf('Interface Line Attribute 15'), true);
23
+
24
+ // AP: header and line, tagged, one cell per column, quoting where needed, empty where nothing is given
25
+ const files = apInvoiceFiles(ap);
26
+ assert.deepEqual(Object.keys(files), ['ApInvoicesInterface.csv', 'ApInvoiceLinesInterface.csv']);
27
+ const header = files['ApInvoicesInterface.csv'].trimEnd();
28
+ assert.equal(header.split('\n').length, 1);
29
+ const cells = header.replace('"Supplier, Inc"', 'Supplier Inc').split(',');
30
+ assert.equal(cells.length, AP_INVOICE_COLUMNS.length);
31
+ assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Invoice Number')], TAG);
32
+ assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Import Set')], TAG); // the job is scoped to this file's rows
33
+ assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Source')], 'External');
34
+ assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Invoice Amount')], '100');
35
+ assert.equal(cells[AP_INVOICE_COLUMNS.indexOf('Supplier Number')], '');
36
+ assert.ok(header.includes('"Supplier, Inc"'));
37
+ const line = files['ApInvoiceLinesInterface.csv'].trimEnd().split(',');
38
+ assert.equal(line.length, AP_LINE_COLUMNS.length);
39
+ assert.equal(line[0], String(ap.interfaceId)); // the line carries its header's id
40
+ assert.equal(line[AP_LINE_COLUMNS.indexOf('Line Type')], 'Item');
41
+ assert.equal(line[AP_LINE_COLUMNS.indexOf('Distribution Combination')], '101-10-1000');
42
+ assert.equal(cells[0], line[0]);
43
+ // a column the template does not have, and a value the file cannot do without
44
+ assert.throws(() => fbdiRow(AP_LINE_COLUMNS, { Nope: 1 }), /not a column/);
45
+ assert.throws(() => apInvoiceFiles({ ...ap, supplier: ' ' }), /supplier is needed/);
46
+ assert.throws(() => apInvoiceFiles({ ...ap, currency: '' }), /currency is needed/);
47
+
48
+ // AR: one line, tagged as the transaction number, the customer order number and the first interface attribute
49
+ const ar = arTransactionFiles({ tag: 'FPT-ARFUS040-1122101500', businessUnit: 'BU One', source: 'Receivables Import', type: 'Invoice',
50
+ customerAccount: '1001', amount: 250.5, currency: 'USD', date: '2026/11/22' });
51
+ assert.deepEqual(Object.keys(ar), ['RaInterfaceLinesAll.csv']);
52
+ const arc = ar['RaInterfaceLinesAll.csv'].trimEnd().split(',');
53
+ assert.equal(arc.length, AR_LINE_COLUMNS.length);
54
+ for (const [col, v] of [['Business Unit Name', 'BU One'], ['Batch Source Name', 'Receivables Import'], ['Transaction Type Name', 'Invoice'],
55
+ ['Transaction Number', 'FPT-ARFUS040-1122101500'], ['Customer Order Number', 'FPT-ARFUS040-1122101500'], ['Interface Line Attribute 1', 'FPT-ARFUS040-1122101500'],
56
+ ['Bill-to Customer Account Number', '1001'], ['Transaction Line Amount', '250.5'], ['Unit Selling Price', '250.5'], ['Transaction Line Quantity', '1'],
57
+ ['Currency Code', 'USD'], ['Payment Terms', '']]) assert.equal(arc[AR_LINE_COLUMNS.indexOf(col)], v, col);
58
+ assert.throws(() => arTransactionFiles({ tag: 'T', businessUnit: 'B', source: 'S', type: 'Invoice', customerAccount: '', amount: 1, currency: 'USD', date: 'd' }), /customer account number is needed/);
59
+
60
+ // full-width rows, once the table says so
61
+ Object.assign(WIDTH, { padTo: 30, endMarker: true });
62
+ const wide = fbdiRow(AP_LINE_COLUMNS, { 'Invoice ID': 1 }).split(',');
63
+ assert.equal(wide.length, 30);
64
+ assert.equal(wide[29], 'END');
65
+ Object.assign(WIDTH, { padTo: undefined, endMarker: false });
66
+
67
+ // dates
68
+ assert.equal(fbdiDate(new Date(Date.UTC(2026, 0, 5))), '2026/01/05');
69
+
70
+ // parameter lists: the job's order, #NULL for the rest, no comma inside a value
71
+ assert.equal(parameterList('payables_invoice', { 'Business Unit': 'BU One', Source: 'External', 'Import Set': TAG, Purge: 'Y' }),
72
+ `BU One,#NULL,External,${TAG},#NULL,#NULL,#NULL,Y,#NULL`);
73
+ assert.equal(parameterList('receivables_transaction', { 'Business Unit': 'BU One', 'Transaction Source': 'Receivables Import' }).split(',').length,
74
+ IMPORTS.receivables_transaction.params.length);
75
+ assert.throws(() => parameterList('payables_invoice', { 'Business Unit': 'A, B' }), /comma/);
76
+ assert.throws(() => parameterList('payables_invoice', { Nope: 'x' }), /not a parameter/);
77
+
78
+ // the zip is a valid zip: Python's zipfile (when present) reads it back, and the CRC and sizes are the files'
79
+ const zip = zipStore(files);
80
+ assert.equal(zip.readUInt32LE(0), 0x04034b50);
81
+ assert.equal(zip.readUInt32LE(zip.length - 22), 0x06054b50);
82
+ assert.equal(zip.readUInt16LE(zip.length - 22 + 10), 2); // two entries
83
+ assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926); // the standard check value of CRC-32
84
+ let python = true;
85
+ const dir = mkdtempSync(join(tmpdir(), 'fpt-zip-'));
86
+ writeFileSync(join(dir, 'x.zip'), zip);
87
+ let out = '';
88
+ try {
89
+ 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')],
90
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
91
+ } catch (e) {
92
+ if ((e as { code?: string }).code !== 'ENOENT') throw e;
93
+ python = false; // no python here: the structure checks above stand
94
+ }
95
+ if (python) assert.equal(out, `ApInvoicesInterface.csv=${Buffer.byteLength(files['ApInvoicesInterface.csv'])}|ApInvoiceLinesInterface.csv=${Buffer.byteLength(files['ApInvoiceLinesInterface.csv'])}`);
96
+
97
+ // the call's body
98
+ const body = importBody('payables_invoice', TAG, files, { 'Business Unit': 'BU One', Source: 'External', 'Import Set': TAG });
99
+ assert.equal(body.OperationName, 'importBulkData');
100
+ assert.equal(body.ContentType, 'zip');
101
+ assert.equal(body.FileName, `${TAG}.zip`);
102
+ assert.equal(body.DocumentAccount, 'fin$/payables$/import$');
103
+ assert.ok(body.JobName.endsWith(',APXIIMPT'));
104
+ assert.match(body.JobOptions, /^InterfaceDetails=\d+,/);
105
+ assert.deepEqual(Buffer.from(body.DocumentContent, 'base64'), zip);
106
+ assert.equal(importBody('receivables_transaction', 'a b/c', ar, {}).FileName, 'a_b_c.zip');
107
+ assert.ok(importBody('receivables_transaction', TAG, ar, {}).JobName.endsWith(',AutoInvoiceImportEss'));
108
+
109
+ // the answers
110
+ assert.equal(requestId({ ReqstId: '123456' }), '123456');
111
+ assert.equal(requestId({ RequestId: 77 }), '77');
112
+ assert.throws(() => requestId({ ReqstId: null }), /no request id/);
113
+ assert.deepEqual(essOutcome(null), { done: false, ok: false, status: 'not started' });
114
+ assert.deepEqual(essOutcome({ RequestStatus: 'RUNNING' }), { done: false, ok: false, status: 'RUNNING' });
115
+ assert.deepEqual(essOutcome({ RequestStatus: 'SUCCEEDED' }), { done: true, ok: true, status: 'SUCCEEDED' });
116
+ assert.deepEqual(essOutcome({ RequestStatus: 'WARNING' }), { done: true, ok: true, status: 'WARNING' });
117
+ assert.deepEqual(essOutcome({ RequestStatus: 'ERROR' }), { done: true, ok: false, status: 'ERROR' });
118
+ assert.equal(essOutcome({ RequestStatus: 'ERROR_AUTO_RETRY' }).done, true);
119
+
120
+ // the opt-in and the second production lock
121
+ assert.equal(importsAllowed({}), false);
122
+ assert.equal(importsAllowed({ FPT_ALLOW_IMPORTS: '0' }), false);
123
+ assert.equal(importsAllowed({ FPT_ALLOW_IMPORTS: 'true' }), false); // only the exact flag
124
+ assert.equal(importsAllowed({ FPT_ALLOW_IMPORTS: '1' }), true);
125
+ assert.equal(looksLikeProduction('acme-prod.fa.us6.oraclecloud.com'), true);
126
+ assert.equal(looksLikeProduction('acme-test.fa.us6.oraclecloud.com'), false);
127
+ // the checks of an imported document: its source (the existing expect_invoice / expect_transaction, with a source)
128
+ const inv = { InvoiceId: 1, InvoiceNumber: TAG, InvoiceAmount: 100, ValidationStatus: 'Validated', CanceledFlag: false, BusinessUnit: 'B', Supplier: 'S' };
129
+ assert.deepEqual(invoiceProblems(TAG, { ...inv, InvoiceSource: 'External' }, { source: 'external' }), []);
130
+ assert.deepEqual(invoiceProblems(TAG, { ...inv, Source: 'External' }, { source: 'External' }), []);
131
+ assert.match(invoiceProblems(TAG, { ...inv, InvoiceSource: 'Spreadsheet' }, { source: 'External' })[0], /source is "Spreadsheet", expected "External"/);
132
+ assert.match(invoiceProblems(TAG, inv, { source: 'External' })[0], /does not return the invoice's source/);
133
+ assert.deepEqual(invoiceProblems(TAG, inv, {}), []); // no source asked for: unchanged
134
+ assert.deepEqual(transactionProblems('T1', { CustomerTransactionId: 1, TransactionNumber: 'T1', TransactionSource: 'Receivables Import', EnteredAmount: 250.5, InvoiceStatus: 'Complete' },
135
+ { source: 'receivables import', status: 'Complete' }), []);
136
+ console.log('interfaces: all checks pass');
automation/src/fusion/interfaces.ts ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Interface (import) testing: the pure parts. The client's volume that arrives through imports (AutoInvoice "Receivables
3
+ * Import", Payables Standard Invoice Import "External") is tested the way the client's integrations create it: a FBDI file
4
+ * is uploaded through Fusion's ERP Integration REST service (rest.ts importBulkData), the import job runs, and the document
5
+ * it creates is checked like any other. Nothing here calls the network, so scripts/check-interfaces.ts tests it all.
6
+ *
7
+ * EVERYTHING Oracle-specific is in the data tables below (IMPORTS, the column lists): job names, the order of each job's
8
+ * parameters, the UCM account, the FBDI column order. They are written from Oracle's published FBDI templates and ERP
9
+ * Integration REST documentation as far as known and are ASSUMPTIONS to verify on a pod before imports are switched on
10
+ * (docs list them): a wrong one makes the import job fail or reject the file, it never creates a wrong document, but
11
+ * one that is wrong in a way the job accepts could import something else. Fix a table row, not the code around it.
12
+ *
13
+ * Safety: an import writes data to the pod, so FusionRest.importBulkData refuses unless the run was started with
14
+ * FPT_ALLOW_IMPORTS=1 (the pod's "allow imports" setting, set by an admin; never on production). Each file holds ONE test
15
+ * 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
16
+ * import set, the AR transaction number range), so a run never imports rows somebody else left in the interface tables.
17
+ */
18
+
19
+ /** A FBDI CSV: its name inside the zip and its columns in the template's order (the order matters, the names are for people). */
20
+ export interface FbdiFile { name: string; columns: readonly string[] }
21
+
22
+ /** One import: where the file goes, which job loads it and the job's parameters in the order Fusion takes them. */
23
+ export interface ImportSpec {
24
+ /** UCM account the file is uploaded to (ERP Integration REST: DocumentAccount). */
25
+ account: string;
26
+ /** The import job: "<job package path>,<job definition name>" (ERP Integration REST: JobName). */
27
+ jobName: string;
28
+ /** The FBDI import's interface id, in JobOptions (ERP Integration REST: InterfaceDetails=<n>). ASSUMED per import. */
29
+ interfaceDetails: number;
30
+ /** The job's parameters in order; a name the caller gives no value for is sent as #NULL. */
31
+ params: readonly string[];
32
+ files: readonly FbdiFile[];
33
+ }
34
+
35
+ const seq = (prefix: string, n: number) => Array.from({ length: n }, (_, i) => `${prefix} ${i + 1}`);
36
+
37
+ /** ApInvoicesInterface.csv: Payables Standard Invoice Import header columns, in template order, through the last one the test
38
+ * fills or needs to place; later columns are left out (see WIDTH). */
39
+ export const AP_INVOICE_COLUMNS = ['Invoice ID', 'Business Unit', 'Source', 'Invoice Number', 'Invoice Amount', 'Invoice Date',
40
+ 'Supplier Name', 'Supplier Number', 'Supplier Site', 'Invoice Currency', 'Payment Currency', 'Description', 'Import Set',
41
+ 'Invoice Type', 'Legal Entity', 'Customer Tax Registration Number', 'Customer Registration Code', 'First-Party Tax Registration Number',
42
+ 'Supplier Tax Registration Number', 'Terms', 'Terms Date', 'Goods Received Date', 'Invoice Received Date', 'Accounting Date'] as const;
43
+
44
+ /** ApInvoiceLinesInterface.csv: the line columns, in template order, through Distribution Combination. */
45
+ export const AP_LINE_COLUMNS = ['Invoice ID', 'Line Number', 'Line Type', 'Amount', 'Quantity', 'Unit Price', 'Unit of Measure', 'Description',
46
+ 'PO Number', 'PO Line Number', 'PO Schedule Number', 'PO Distribution Number', 'Item Description', 'Release Number', 'Purchasing Category',
47
+ 'Receipt Number', 'Receipt Line Number', 'Consumption Advice Number', 'Consumption Advice Line Number', 'Packing Slip', 'Final Match',
48
+ 'Distribution Combination'] as const;
49
+
50
+ /** RaInterfaceLinesAll.csv: AutoInvoice lines, in template order, through the interface line attributes. */
51
+ export const AR_LINE_COLUMNS = ['Business Unit Name', 'Batch Source Name', 'Transaction Type Name', 'Payment Terms', 'Transaction Date',
52
+ 'Accounting Date', 'Transaction Number', 'Original System Bill-to Customer Reference', 'Original System Bill-to Customer Address Reference',
53
+ 'Original System Bill-to Customer Contact Reference', 'Original System Ship-to Customer Reference',
54
+ 'Original System Ship-to Customer Address Reference', 'Original System Ship-to Customer Contact Reference',
55
+ 'Bill-to Customer Account Number', 'Bill-to Customer Site Number', 'Bill-to Contact Party Number', 'Ship-to Customer Account Number',
56
+ 'Ship-to Customer Site Number', 'Ship-to Contact Party Number', 'Sold-to Customer Account Number', 'Transaction Line Type',
57
+ 'Transaction Line Description', 'Currency Code', 'Currency Conversion Type', 'Currency Conversion Date', 'Currency Conversion Rate',
58
+ 'Transaction Line Amount', 'Transaction Line Quantity', 'Customer Order Number', 'Customer Order Date', 'Unit Selling Price',
59
+ 'Unit of Measure Code', 'Sales Order Number', 'Sales Order Date', 'Memo Line Name', 'Interface Line Context',
60
+ ...seq('Interface Line Attribute', 15)] as const;
61
+
62
+ /** Every row is exactly as wide as the columns listed above: no padding up to the template's full width and no END marker.
63
+ * ASSUMED to be accepted (trailing columns are null); if a pod's loader wants full-width rows, set `padTo` (the template's
64
+ * column count) and `endMarker` (the literal END as the last column) here, for every file at once. */
65
+ export const WIDTH: { padTo?: number; endMarker: boolean } = { endMarker: false };
66
+
67
+ /** The two imports. ASSUMPTIONS to verify live: see the file comment. */
68
+ export const IMPORTS = {
69
+ payables_invoice: {
70
+ // Payables Standard Invoice Import (APXIIMPT); the file goes to the payables import account of UCM
71
+ account: 'fin$/payables$/import$',
72
+ jobName: '/oracle/apps/ess/financials/payables/invoices/transactions,APXIIMPT',
73
+ interfaceDetails: 20, // ASSUMED id of "Payables Invoice Import" among Oracle's FBDI interface ids
74
+ // "Import Payables Invoices" parameters in the order of its Scheduled Processes form. Scoped by Import Set (the test's own
75
+ // tag) so only this file's rows are imported; Purge removes the interface rows afterwards so none are left to a later import
76
+ params: ['Business Unit', 'Ledger', 'Source', 'Import Set', 'Hold Name', 'Hold Reason', 'Accounting Date', 'Purge', 'Summarize Report'],
77
+ files: [{ name: 'ApInvoicesInterface.csv', columns: AP_INVOICE_COLUMNS }, { name: 'ApInvoiceLinesInterface.csv', columns: AP_LINE_COLUMNS }],
78
+ },
79
+ receivables_transaction: {
80
+ // Import AutoInvoice (AutoInvoiceImportEss); the file goes to the receivables import account of UCM
81
+ account: 'fin$/receivables$/import$',
82
+ jobName: '/oracle/apps/ess/financials/receivables/transactions/autoInvoices,AutoInvoiceImportEss',
83
+ interfaceDetails: 19, // ASSUMED id of "AutoInvoice Import" among Oracle's FBDI interface ids
84
+ // "Import AutoInvoice" parameters in the order of its form, up to the transaction number range, which scopes the job to the
85
+ // test's one transaction (its number is the tag). ASSUMED: a source that numbers transactions automatically ignores the
86
+ // number in the file, and the range then matches nothing; drop the two range names after checking the source holds no
87
+ // other pending rows
88
+ params: ['Business Unit', 'Transaction Source', 'Default Date', 'Transaction Flexfield', 'Transaction Type', 'From Bill-to Customer Name',
89
+ 'To Bill-to Customer Name', 'From Bill-to Customer Number', 'To Bill-to Customer Number', 'From Transaction Number', 'To Transaction Number'],
90
+ files: [{ name: 'RaInterfaceLinesAll.csv', columns: AR_LINE_COLUMNS }],
91
+ },
92
+ } as const satisfies Record<string, ImportSpec>;
93
+ export type ImportKey = keyof typeof IMPORTS;
94
+
95
+ /** FBDI dates are written YYYY/MM/DD. */
96
+ export const fbdiDate = (d: Date): string => `${d.getUTCFullYear()}/${String(d.getUTCMonth() + 1).padStart(2, '0')}/${String(d.getUTCDate()).padStart(2, '0')}`;
97
+
98
+ /** One CSV cell: quoted when it holds a comma, a quote or a line break (a quote is doubled). */
99
+ const cell = (v: string | number | undefined): string => {
100
+ const s = v === undefined || v === null ? '' : String(v);
101
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
102
+ };
103
+
104
+ export type Values = Record<string, string | number | undefined>;
105
+
106
+ /** 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
107
+ * not a column of the template is a mistake in the builder, never silently dropped. */
108
+ export function fbdiRow(columns: readonly string[], values: Values): string {
109
+ for (const k of Object.keys(values)) if (!columns.includes(k)) throw new Error(`"${k}" is not a column of this FBDI file`);
110
+ const cells = columns.map((c) => cell(values[c]));
111
+ while (WIDTH.padTo !== undefined && cells.length < WIDTH.padTo - (WIDTH.endMarker ? 1 : 0)) cells.push('');
112
+ if (WIDTH.endMarker) cells.push('END');
113
+ return cells.join(',');
114
+ }
115
+
116
+ const nonEmpty = (what: string, v: string | number | undefined): string => {
117
+ const s = String(v ?? '').trim();
118
+ if (!s) throw new Error(`${what} is needed for the file and the pod's test data has none`);
119
+ return s;
120
+ };
121
+
122
+ /** What the AP file holds: one standard invoice of one Item line. */
123
+ export interface ApInvoiceFbdi {
124
+ tag: string; // the test's FPT- tag: the invoice number, and the import set (so the job imports only this file)
125
+ interfaceId: number; // links the line to its header; unique in the interface table
126
+ businessUnit: string; supplier: string; site?: string; account?: string;
127
+ source: string; // the invoice source of the import (External ...)
128
+ amount: string | number; currency: string; date: string; // date: FBDI format (fbdiDate)
129
+ description?: string;
130
+ }
131
+
132
+ /** 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. */
133
+ export function apInvoiceFiles(a: ApInvoiceFbdi): Record<string, string> {
134
+ const [h, l] = IMPORTS.payables_invoice.files;
135
+ const header = fbdiRow(h.columns, {
136
+ 'Invoice ID': a.interfaceId, 'Business Unit': nonEmpty('the business unit', a.businessUnit), 'Source': nonEmpty('the invoice source', a.source),
137
+ 'Invoice Number': nonEmpty('the invoice number', a.tag), 'Invoice Amount': nonEmpty('the amount', a.amount), 'Invoice Date': a.date,
138
+ 'Supplier Name': nonEmpty('the supplier', a.supplier), 'Supplier Site': a.site, 'Invoice Currency': nonEmpty('the currency', a.currency),
139
+ 'Description': a.description ?? 'Test invoice imported by an automated test', 'Import Set': a.tag, 'Invoice Type': 'Standard', 'Accounting Date': a.date,
140
+ });
141
+ const line = fbdiRow(l.columns, {
142
+ 'Invoice ID': a.interfaceId, 'Line Number': 1, 'Line Type': 'Item', 'Amount': a.amount, 'Description': a.description ?? 'Test line',
143
+ 'Distribution Combination': a.account,
144
+ });
145
+ return { [h.name]: `${header}\n`, [l.name]: `${line}\n` };
146
+ }
147
+
148
+ /** What the AR file holds: one invoice line of one transaction. */
149
+ export interface ArTransactionFbdi {
150
+ tag: string; // the test's FPT- tag: the transaction number and the customer order number (both found by REST)
151
+ businessUnit: string; source: string; type: string; customerAccount: string;
152
+ amount: string | number; currency: string; date: string; memoLine?: string; description?: string;
153
+ }
154
+
155
+ /** The AutoInvoice CSV (RaInterfaceLinesAll). The tag is the transaction number (when the source takes a number from the file) and
156
+ * the customer order number, which REST returns as the transaction's PurchaseOrder: so the transaction is found by it either way. */
157
+ export function arTransactionFiles(a: ArTransactionFbdi): Record<string, string> {
158
+ const [f] = IMPORTS.receivables_transaction.files;
159
+ const row = fbdiRow(f.columns, {
160
+ 'Business Unit Name': nonEmpty('the business unit', a.businessUnit), 'Batch Source Name': nonEmpty('the transaction source', a.source),
161
+ 'Transaction Type Name': nonEmpty('the transaction type', a.type), 'Transaction Date': a.date, 'Accounting Date': a.date,
162
+ 'Transaction Number': nonEmpty('the transaction reference', a.tag), 'Bill-to Customer Account Number': nonEmpty('the customer account number', a.customerAccount),
163
+ 'Transaction Line Type': 'LINE', 'Transaction Line Description': a.description ?? 'Test transaction imported by an automated test',
164
+ 'Currency Code': nonEmpty('the currency', a.currency), 'Transaction Line Amount': nonEmpty('the amount', a.amount), 'Transaction Line Quantity': 1,
165
+ 'Customer Order Number': a.tag, 'Unit Selling Price': a.amount, 'Memo Line Name': a.memoLine, 'Interface Line Context': 'FPT',
166
+ 'Interface Line Attribute 1': a.tag,
167
+ });
168
+ return { [f.name]: `${row}\n` };
169
+ }
170
+
171
+ // ---------------------------------------------------------------------------------------------------- zip (stored, no compression)
172
+ const CRC_TABLE = (() => {
173
+ const t = new Uint32Array(256);
174
+ 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; }
175
+ return t;
176
+ })();
177
+
178
+ /** CRC-32 of the bytes (what a zip entry carries). */
179
+ export function crc32(data: Uint8Array): number {
180
+ let c = 0xffffffff;
181
+ for (const b of data) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);
182
+ return (c ^ 0xffffffff) >>> 0;
183
+ }
184
+
185
+ /** A zip of the files, stored without compression (the files are a few hundred bytes). 1980-01-01 as every entry's date. */
186
+ export function zipStore(files: Record<string, string>): Buffer {
187
+ const parts: Buffer[] = [];
188
+ const central: Buffer[] = [];
189
+ let offset = 0;
190
+ for (const [name, text] of Object.entries(files)) {
191
+ const nameBytes = Buffer.from(name, 'utf8');
192
+ const data = Buffer.from(text, 'utf8');
193
+ const crc = crc32(data);
194
+ const local = Buffer.alloc(30);
195
+ local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0, 8);
196
+ local.writeUInt16LE(0, 10); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc, 14); local.writeUInt32LE(data.length, 18);
197
+ local.writeUInt32LE(data.length, 22); local.writeUInt16LE(nameBytes.length, 26); local.writeUInt16LE(0, 28);
198
+ const dir = Buffer.alloc(46);
199
+ dir.writeUInt32LE(0x02014b50, 0); dir.writeUInt16LE(20, 4); dir.writeUInt16LE(20, 6); dir.writeUInt16LE(0x0800, 8); dir.writeUInt16LE(0, 10);
200
+ dir.writeUInt16LE(0, 12); dir.writeUInt16LE(0x21, 14); dir.writeUInt32LE(crc, 16); dir.writeUInt32LE(data.length, 20);
201
+ dir.writeUInt32LE(data.length, 24); dir.writeUInt16LE(nameBytes.length, 28); dir.writeUInt32LE(offset, 42);
202
+ parts.push(local, nameBytes, data);
203
+ central.push(dir, nameBytes);
204
+ offset += local.length + nameBytes.length + data.length;
205
+ }
206
+ const cd = Buffer.concat(central);
207
+ const end = Buffer.alloc(22);
208
+ end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(Object.keys(files).length, 8); end.writeUInt16LE(Object.keys(files).length, 10);
209
+ end.writeUInt32LE(cd.length, 12); end.writeUInt32LE(offset, 16);
210
+ return Buffer.concat([...parts, cd, end]);
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------------------------------- the ERP Integration call
214
+ /** A value in a job's parameter list: a comma ends a parameter, so a value with one cannot be sent. */
215
+ function paramValue(name: string, v: string | undefined): string {
216
+ const s = String(v ?? '').trim();
217
+ if (!s) return '#NULL';
218
+ if (s.includes(',')) throw new Error(`parameter "${name}" holds a comma (${s}): Fusion's parameter list cannot carry it`);
219
+ return s;
220
+ }
221
+
222
+ /** The job's ParameterList: its parameters in the order Fusion takes them, #NULL where no value is given. A name the job does not
223
+ * have is a mistake in the caller. */
224
+ export function parameterList(key: ImportKey, values: Record<string, string | undefined>): string {
225
+ const names: readonly string[] = IMPORTS[key].params;
226
+ for (const k of Object.keys(values)) if (!names.includes(k)) throw new Error(`"${k}" is not a parameter of the ${key} import`);
227
+ return names.map((n) => paramValue(n, values[n])).join(',');
228
+ }
229
+
230
+ /** The body of POST erpintegrations (operation importBulkData). The zip name is made of the tag, which is unique per run. */
231
+ export function importBody(key: ImportKey, tag: string, files: Record<string, string>, params: Record<string, string | undefined>) {
232
+ const spec = IMPORTS[key];
233
+ return {
234
+ OperationName: 'importBulkData',
235
+ DocumentContent: zipStore(files).toString('base64'),
236
+ ContentType: 'zip',
237
+ FileName: `${tag.replace(/[^A-Za-z0-9._-]/g, '_')}.zip`,
238
+ DocumentAccount: spec.account,
239
+ JobName: spec.jobName,
240
+ ParameterList: parameterList(key, params),
241
+ JobOptions: `InterfaceDetails=${spec.interfaceDetails},ImportOption=Y,PurgeOption=Y,ExtractFileType=ALL`,
242
+ CallbackURL: '#NULL',
243
+ NotificationCode: '00',
244
+ };
245
+ }
246
+
247
+ /** The request id of a submitted job, from the answer of importBulkData (ReqstId; other services say RequestId). */
248
+ export function requestId(answer: Record<string, unknown>): string {
249
+ for (const k of ['ReqstId', 'RequestId', 'requestId']) {
250
+ const v = answer[k];
251
+ if (v !== undefined && v !== null && String(v).trim() !== '' && String(v) !== '0') return String(v).trim();
252
+ }
253
+ throw new Error(`Fusion accepted the import but gave no request id (answer: ${JSON.stringify(answer).slice(0, 200)})`);
254
+ }
255
+
256
+ /** Where a job stands, from its ESSJobStatusRF row: `done` = it has ended, `ok` = it ended well (a warning counts: the import of
257
+ * a row can be refused while the job succeeds, the check of the document says which). */
258
+ export function essOutcome(item: Record<string, unknown> | null | undefined): { done: boolean; ok: boolean; status: string } {
259
+ const status = String(item?.RequestStatus ?? item?.Status ?? item?.ExecutionStatus ?? '').trim();
260
+ const s = status.toUpperCase();
261
+ if (!s) return { done: false, ok: false, status: 'not started' };
262
+ if (s === 'SUCCEEDED' || s === 'WARNING' || s === 'COMPLETED') return { done: true, ok: true, status };
263
+ if (/^(ERROR|FAILED|CANCELLED|CANCELED|BLOCKED|EXPIRED|ERROR_MANUAL_RECOVERY|ERROR_AUTO_RETRY|FINISHED_WITH_ERROR)/.test(s)) return { done: true, ok: false, status };
264
+ return { done: false, ok: false, status }; // READY, WAIT, RUNNING, PAUSED ...
265
+ }
266
+
267
+ /** Imports are allowed only when the run says so (FPT_ALLOW_IMPORTS=1, set from the pod's setting; see pods.executor_env). */
268
+ export const importsAllowed = (env: Record<string, string | undefined> = process.env): boolean => env.FPT_ALLOW_IMPORTS === '1';
269
+
270
+ export const IMPORTS_REFUSED = 'imports are not allowed on this pod: an admin switches "Allow imports" on for the test environment (Test environments page); '
271
+ + 'an import writes test data to the pod through its ERP Integration service';
272
+
273
+ /** A host that looks like a production pod (the registry refuses these; this is the second lock, at the call itself). */
274
+ export const looksLikeProduction = (host: string): boolean => /(^|[.-])prod(uction)?([.-]|\d|$)/i.test(host);
automation/src/fusion/rest.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import { fusionEnv } from './ui';
2
 
3
  /*
@@ -58,7 +59,7 @@ const q = (s: string) => s.replace(/'/g, "''");
58
 
59
  /** What a step expects of an invoice in Fusion (business action expect_invoice). */
60
  export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; type?: string;
61
- paymentMethod?: string; approvalStatus?: string; validationStatus?: string }
62
 
63
  /** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */
64
  const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled');
@@ -114,6 +115,11 @@ export function invoiceProblems(number: string, inv: Invoice | null, want: Invoi
114
  if (!got) out.push(`this pod's REST does not return the invoice's approval status, so "${want.approvalStatus}" cannot be checked`);
115
  else if (codeKey(got) !== codeKey(want.approvalStatus)) out.push(`its approval status is "${got}", expected "${want.approvalStatus}"`);
116
  }
 
 
 
 
 
117
  if (want.validationStatus && validationKey(String(inv.ValidationStatus ?? '')) !== validationKey(want.validationStatus)
118
  && !(validationKey(want.validationStatus) === 'canceled' && inv.CanceledFlag)) {
119
  out.push(`its validation status is "${inv.ValidationStatus ?? ''}", expected "${want.validationStatus}"`);
@@ -601,6 +607,57 @@ export class FusionRest {
601
  }
602
  }
603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604
  private async remove(path: string, what: string): Promise<void> {
605
  const r = await this.call('DELETE', path);
606
  if (r.status < 200 || r.status >= 300) throw new Error(`${what}: Fusion refused the delete (HTTP ${r.status} ${r.text.slice(0, 200)})`);
@@ -733,9 +790,10 @@ export class FusionRest {
733
  return done.join('; ');
734
  }
735
 
736
- /** The transaction with this number, else the one carrying the test's tag in its Comments (or Internal Notes). */
737
  async transaction(numberOrTag: string): Promise<ArTransaction | null> {
738
  return await this.first<ArTransaction>('receivablesInvoices', `TransactionNumber='${q(numberOrTag)}'`)
 
739
  ?? await this.first<ArTransaction>('receivablesInvoices', `Comments LIKE '${q(numberOrTag)}%'`)
740
  ?? await this.first<ArTransaction>('receivablesInvoices', `InternalNotes LIKE '${q(numberOrTag)}%'`);
741
  }
 
1
+ import { essOutcome, IMPORTS_REFUSED, importsAllowed, looksLikeProduction, requestId } from './interfaces';
2
  import { fusionEnv } from './ui';
3
 
4
  /*
 
59
 
60
  /** What a step expects of an invoice in Fusion (business action expect_invoice). */
61
  export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; type?: string;
62
+ paymentMethod?: string; approvalStatus?: string; validationStatus?: string; source?: string }
63
 
64
  /** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */
65
  const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled');
 
115
  if (!got) out.push(`this pod's REST does not return the invoice's approval status, so "${want.approvalStatus}" cannot be checked`);
116
  else if (codeKey(got) !== codeKey(want.approvalStatus)) out.push(`its approval status is "${got}", expected "${want.approvalStatus}"`);
117
  }
118
+ if (want.source) { // the invoice source (External, Spreadsheet, Manual Invoice Entry ...): how the invoice came in
119
+ const got = [inv.InvoiceSource, inv.Source, inv.SourceName].find((v) => v !== undefined && v !== null && v !== '');
120
+ if (got === undefined) out.push(`this pod's REST does not return the invoice's source, so "${want.source}" cannot be checked`);
121
+ else if (spelling(String(got)) !== spelling(want.source)) out.push(`its source is "${got}", expected "${want.source}"`);
122
+ }
123
  if (want.validationStatus && validationKey(String(inv.ValidationStatus ?? '')) !== validationKey(want.validationStatus)
124
  && !(validationKey(want.validationStatus) === 'canceled' && inv.CanceledFlag)) {
125
  out.push(`its validation status is "${inv.ValidationStatus ?? ''}", expected "${want.validationStatus}"`);
 
607
  }
608
  }
609
 
610
+ // ------------------------------------------------------------ interfaces: imports through the ERP Integration service
611
+ /** Upload a FBDI file and run its import job (POST erpintegrations, operation importBulkData; the body is built by
612
+ * interfaces.ts importBody). The only write of the automation that creates data without a screen, so it refuses unless the
613
+ * run was started with FPT_ALLOW_IMPORTS=1 (the pod's "allow imports" setting) and never on a pod that looks like production.
614
+ * Returns the request id of the submitted job. */
615
+ async importBulkData(body: Record<string, unknown>): Promise<string> {
616
+ if (!importsAllowed()) throw new Error(IMPORTS_REFUSED);
617
+ if (looksLikeProduction(new URL(this.baseUrl).hostname)) throw new Error('imports are never run on a production pod');
618
+ const r = await this.call('POST', 'erpintegrations', body, 'application/json');
619
+ if (r.status < 200 || r.status >= 300) throw new Error(`importBulkData failed: HTTP ${r.status} ${r.text.slice(0, 300)}`);
620
+ return requestId(JSON.parse(r.text));
621
+ }
622
+
623
+ /** The status row of a submitted job (finder ESSJobStatusRF), or null while Fusion has none. */
624
+ async essJob(id: string): Promise<Record<string, unknown> | null> {
625
+ const r = await this.call('GET', `erpintegrations?finder=ESSJobStatusRF;requestId=${encodeURIComponent(id)}&onlyData=true`);
626
+ if (r.status !== 200) throw new Error(`GET erpintegrations (job ${id}) failed: HTTP ${r.status} ${r.text.slice(0, 300)}`);
627
+ return ((JSON.parse(r.text).items || []) as Record<string, unknown>[])[0] ?? null;
628
+ }
629
+
630
+ /** Wait until the job has ended: its status (SUCCEEDED, WARNING) when it ended well; an error saying what to look at when it
631
+ * ended badly or did not end in time. A job that succeeded can still have refused the rows: the caller checks the document. */
632
+ async waitForJob(id: string, what: string, timeoutMs = 600_000, pollMs = 10_000): Promise<string> {
633
+ const end = Date.now() + timeoutMs;
634
+ let last = 'not started';
635
+ for (;;) {
636
+ const o = essOutcome(await this.essJob(id));
637
+ last = o.status;
638
+ if (o.done && o.ok) return o.status;
639
+ if (o.done) throw new Error(`${what}: the import job (request ${id}) ended ${o.status}; see its log and report under Tools > Scheduled Processes`);
640
+ if (Date.now() > end) throw new Error(`${what}: the import job (request ${id}) was still ${last} after ${Math.round(timeoutMs / 60_000)} minutes`);
641
+ await new Promise((r) => setTimeout(r, pollMs));
642
+ }
643
+ }
644
+
645
+ /** The account number of a customer, from that customer's latest transaction (the pod's test data names customers, FBDI wants the
646
+ * account number). A pod that does not return the attribute answers HTTP 400: the next name is tried; none: null. */
647
+ async customerAccountNumber(customer: string): Promise<string | null> {
648
+ for (const attr of ['BillToCustomerNumber', 'BillToAccountNumber', 'CustomerAccountNumber']) {
649
+ try {
650
+ const rows = await this.get<Record<string, unknown>>('receivablesInvoices', `BillToCustomerName='${q(customer)}'`,
651
+ { fields: attr, orderBy: 'CustomerTransactionId:desc', limit: '1' });
652
+ const v = rows[0]?.[attr];
653
+ if (v !== undefined && v !== null && String(v).trim()) return String(v).trim();
654
+ } catch (e) {
655
+ if (!/HTTP 400/.test(String((e as Error).message))) throw e;
656
+ }
657
+ }
658
+ return null;
659
+ }
660
+
661
  private async remove(path: string, what: string): Promise<void> {
662
  const r = await this.call('DELETE', path);
663
  if (r.status < 200 || r.status >= 300) throw new Error(`${what}: Fusion refused the delete (HTTP ${r.status} ${r.text.slice(0, 200)})`);
 
790
  return done.join('; ');
791
  }
792
 
793
+ /** The transaction with this number, else the one carrying the test's tag in its customer order number (an imported one), Comments or Internal Notes. */
794
  async transaction(numberOrTag: string): Promise<ArTransaction | null> {
795
  return await this.first<ArTransaction>('receivablesInvoices', `TransactionNumber='${q(numberOrTag)}'`)
796
+ ?? await this.first<ArTransaction>('receivablesInvoices', `PurchaseOrder='${q(numberOrTag)}'`) // an imported one: its customer order number is the tag
797
  ?? await this.first<ArTransaction>('receivablesInvoices', `Comments LIKE '${q(numberOrTag)}%'`)
798
  ?? await this.first<ArTransaction>('receivablesInvoices', `InternalNotes LIKE '${q(numberOrTag)}%'`);
799
  }
automation/src/fusion/steps.ts CHANGED
@@ -5,7 +5,8 @@ import { approvalRef, expect, paymentRef, test, type DocKind, type FusionDocs }
5
  import { activeHolds, closeAction, invoiceAmountProblems, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, orderCloseable,
6
  orderReceivable, orderStatus, paymentProblems, paymentTypeKey, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation, type PaymentExpectation } from './rest';
7
  import { transactionAmountProblems, type TransactionExpectation } from './rest';
8
- import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui';
 
9
 
10
  /*
11
  * Step runner: executes a scenario written as plain steps in tests/cases/<ID>.yaml (runner: steps), with no
@@ -35,6 +36,12 @@ import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, Valu
35
  * test leaves is voided by the clean-up, before the invoice is cancelled.
36
  * initiate_approval (scenario-only: name = the invoice's remembered name) sends a validated invoice for approval (Invoice Actions >
37
  * Approval > Initiate) and checks Fusion shows the approval Initiated; the clean-up withdraws it before the invoice is cancelled.
 
 
 
 
 
 
38
  */
39
  export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[];
40
  lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean;
@@ -64,6 +71,7 @@ export function loadStepCase(id: string, dir?: string): StepCase {
64
  }
65
 
66
  type Ctx = { ui: FusionUi; c: StepCase; saved: Record<string, string>; uniques: Record<string, string>; track: (n: string) => string;
 
67
  chosen: Record<string, string>; // the pod value Fusion accepted, per "area.key", used again for the rest of the test
68
  orderTags: Record<string, string>; // the test's tag of each purchase order made, by its number (its receipt names it for clean-up)
69
  rest: FusionRest; // Fusion REST, for the business actions that check what the screens did
@@ -283,6 +291,21 @@ function invoiceTypes(ctx: Ctx): string[] {
283
  /** A new test document registered for clean-up BEFORE its save (its tag), so it is cleaned up even if the step fails. */
284
  const track = (ctx: Ctx, kind: DocKind) => ctx.docs.track(kind, docTag(ctx, kind === 'ar_receipt' ? 'R' : '')); // R: a receipt and its transaction never share a tag
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  /** The proven actions. Optional ones call a FusionUi method only if that building block exists. */
287
  const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
288
  sign_in: async (_s, { ui }) => ui.signIn(),
@@ -354,8 +377,8 @@ const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
354
  * Canceled ...: matched without regard to case); amount = its exact amount; amount_at_least = at least this amount
355
  * (the pod may add tax on top); canceled = true or false; invoice_type = Standard, Credit memo, Debit memo or Prepayment;
356
  * payment_method = the method's name; approval_status = Not required, Required ...; validation_status = Validated, Not validated,
357
- * Needs revalidation (REST's ValidationStatus; a never validated invoice is Not validated). With none of them, it checks that
358
- * the invoice exists. */
359
  expect_invoice: async (s, ctx) => {
360
  const number = invoiceNumber(s, ctx);
361
  const want: InvoiceExpectation = {
@@ -367,6 +390,7 @@ const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
367
  paymentMethod: s.payment_method ? fill(s.payment_method, ctx) : undefined,
368
  approvalStatus: s.approval_status ? fill(s.approval_status, ctx) : undefined,
369
  validationStatus: s.validation_status ? fill(s.validation_status, ctx) : undefined,
 
370
  };
371
  await restCheck(ctx, `expect_invoice ${number}`, () =>
372
  untilRight(async () => invoiceProblems(number, await ctx.rest.invoiceByNumber(number), want), `invoice ${number} in Fusion`));
@@ -655,6 +679,94 @@ const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
655
  await restCheck(ctx, `expect_receipt ${number}`, () =>
656
  untilRight(async () => receiptProblems(number, await ctx.rest.receipt(number), want), `receipt ${number} in Fusion`));
657
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  // General Ledger business actions
659
  /** Create and save a journal batch on its own screen: one debit and one credit of value (default {{tv.amount}}) on
660
  * the same account of the pod. category = the journal category (Adjustment, Accrual, Allocation, Reclass ... or a pod
@@ -737,7 +849,10 @@ const UI_BLOCKS: Record<string, { method: string; args: (s: Step, ctx: Ctx) => u
737
  { amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },
738
  save: { method: 'save', args: () => [] },
739
  invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] },
740
- validate_invoice: { method: 'validateInvoice', args: () => [] },
 
 
 
741
  /** Find the invoice remembered as `name` (default invoice_number) on Manage Invoices: exactly it must be listed. */
742
  find_invoice: { method: 'findInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },
743
  /** Invoice Actions > Cancel Invoice on the invoice remembered as `name`, confirmed: it must then show Canceled. */
@@ -775,7 +890,7 @@ async function runStep(s: Step, ctx: Ctx) {
775
  export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {
776
  const c = loadStepCase(id, opts.dir);
777
  test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices, fusionDocs }) => {
778
- const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, chosen: {}, orderTags: {}, rest: apInvoices.rest, docs: fusionDocs };
779
  for (const [i, s] of c.steps.entries()) {
780
  const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;
781
  await test.step(s.expected ? `${label} (expect: ${s.expected})` : label, () => runStep(s, ctx));
 
5
  import { activeHolds, closeAction, invoiceAmountProblems, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, orderCloseable,
6
  orderReceivable, orderStatus, paymentProblems, paymentTypeKey, poReceiptProblems, purchaseOrderProblems, receiptProblems, requisitionProblems, REST_SKIPPED, transactionProblems, transactionStatus, type DocExpectation, type FusionRest, type InvoiceExpectation, type PaymentExpectation } from './rest';
7
  import { transactionAmountProblems, type TransactionExpectation } from './rest';
8
+ import { apInvoiceFiles, arTransactionFiles, fbdiDate, importBody, importsAllowed, IMPORTS_REFUSED } from './interfaces';
9
+ import { apDataSets, fusionDate, podCandidates, podToday, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui';
10
 
11
  /*
12
  * Step runner: executes a scenario written as plain steps in tests/cases/<ID>.yaml (runner: steps), with no
 
36
  * test leaves is voided by the clean-up, before the invoice is cancelled.
37
  * initiate_approval (scenario-only: name = the invoice's remembered name) sends a validated invoice for approval (Invoice Actions >
38
  * Approval > Initiate) and checks Fusion shows the approval Initiated; the clean-up withdraws it before the invoice is cancelled.
39
+ * Interfaces (scenario-only, never in a canary; they write through Fusion's ERP Integration REST service, so they need REST and the pod's
40
+ * "allow imports" setting, FPT_ALLOW_IMPORTS=1): import_payables_invoice (a FBDI file through Payables invoice import; source = the
41
+ * invoice source, External by default) and import_receivables_transaction (a FBDI file through AutoInvoice; transaction_source = an import
42
+ * source of the pod, transaction_type). Each remembers the number of the document the import created (name), checked by expect_invoice
43
+ * (source) or expect_transaction (transaction_source) like any other; the clean-up cancels an imported invoice, an imported
44
+ * transaction that is complete is listed for a person to credit.
45
  */
46
  export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[];
47
  lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean;
 
71
  }
72
 
73
  type Ctx = { ui: FusionUi; c: StepCase; saved: Record<string, string>; uniques: Record<string, string>; track: (n: string) => string;
74
+ imported: Set<string>; // the invoices an import made (import_payables_invoice): validate_invoice opens them from Manage Invoices first
75
  chosen: Record<string, string>; // the pod value Fusion accepted, per "area.key", used again for the rest of the test
76
  orderTags: Record<string, string>; // the test's tag of each purchase order made, by its number (its receipt names it for clean-up)
77
  rest: FusionRest; // Fusion REST, for the business actions that check what the screens did
 
291
  /** A new test document registered for clean-up BEFORE its save (its tag), so it is cleaned up even if the step fails. */
292
  const track = (ctx: Ctx, kind: DocKind) => ctx.docs.track(kind, docTag(ctx, kind === 'ar_receipt' ? 'R' : '')); // R: a receipt and its transaction never share a tag
293
 
294
+ /** An interface id for a FBDI header row (links its lines; unique in the interface table): the clock, one per attempt. */
295
+ const interfaceId = (attempt: number) => Number(String(Date.now()).slice(-12)) * 10 + attempt;
296
+
297
+ /** The document an import should have created, asked for until it shows (REST can lag the job by a few seconds); null when it never does. */
298
+ async function findAfterImport<T>(find: () => Promise<T | null | undefined>): Promise<T | null> {
299
+ try { return await untilFound(find, 'not found', 60_000); } catch { return null; }
300
+ }
301
+
302
+ /** An import step on a pod without REST (assisted sign-in): nothing is sent, the test says so, and the name still holds a reference so
303
+ * the steps after it (their REST checks are skipped too) do not fail for want of a document. */
304
+ function importSkipped(ctx: Ctx, action: string, name: string): void {
305
+ ctx.saved[name] = docTag(ctx);
306
+ test.info().annotations.push({ type: REST_SKIPPED, description: `${action}: not run: an import is sent through Fusion REST, and this pod uses assisted sign-in (no password for REST)` });
307
+ }
308
+
309
  /** The proven actions. Optional ones call a FusionUi method only if that building block exists. */
310
  const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
311
  sign_in: async (_s, { ui }) => ui.signIn(),
 
377
  * Canceled ...: matched without regard to case); amount = its exact amount; amount_at_least = at least this amount
378
  * (the pod may add tax on top); canceled = true or false; invoice_type = Standard, Credit memo, Debit memo or Prepayment;
379
  * payment_method = the method's name; approval_status = Not required, Required ...; validation_status = Validated, Not validated,
380
+ * Needs revalidation (REST's ValidationStatus; a never validated invoice is Not validated); source = how it came in (External for
381
+ * an import, Manual Invoice Entry ...). With none of them, it checks that the invoice exists. */
382
  expect_invoice: async (s, ctx) => {
383
  const number = invoiceNumber(s, ctx);
384
  const want: InvoiceExpectation = {
 
390
  paymentMethod: s.payment_method ? fill(s.payment_method, ctx) : undefined,
391
  approvalStatus: s.approval_status ? fill(s.approval_status, ctx) : undefined,
392
  validationStatus: s.validation_status ? fill(s.validation_status, ctx) : undefined,
393
+ source: s.source ? fill(s.source, ctx).trim() : undefined,
394
  };
395
  await restCheck(ctx, `expect_invoice ${number}`, () =>
396
  untilRight(async () => invoiceProblems(number, await ctx.rest.invoiceByNumber(number), want), `invoice ${number} in Fusion`));
 
679
  await restCheck(ctx, `expect_receipt ${number}`, () =>
680
  untilRight(async () => receiptProblems(number, await ctx.rest.receipt(number), want), `receipt ${number} in Fusion`));
681
  },
682
+ // Interfaces: documents that arrive through an import, made the way the client's integrations make them
683
+ /** Import a Payables invoice through Payables Standard Invoice Import: a FBDI file of one standard invoice of value (default {{tv.amount}})
684
+ * with one Item line is uploaded through Fusion's ERP Integration REST service and its import job run, then the step waits for the job
685
+ * and finds the invoice by its FPT- number. source = the invoice source (default External); the pod's business unit, supplier, site,
686
+ * account and currency. name = what to remember the number as (default invoice_number). Registered for clean-up before the upload,
687
+ * so the invoice is cancelled after the test like a screen one. Needs the pod's "allow imports" setting; on a pod with assisted sign-in
688
+ * (no REST) it is skipped with a note. */
689
+ import_payables_invoice: async (s, ctx) => {
690
+ const amount = amountValue(s, ctx);
691
+ const source = s.source ? fill(s.source, ctx).trim() : 'External';
692
+ const name = s.name || 'invoice_number';
693
+ if (!ctx.rest.available) return importSkipped(ctx, s.action, name);
694
+ if (!importsAllowed()) throw new Error(`import_payables_invoice: ${IMPORTS_REFUSED}`);
695
+ const currency = choices(ctx, 'ap', 'currency')[0];
696
+ if (!currency) throw new Error('import_payables_invoice needs the invoice currency: the pod has no Payables test data "currency"; set it on the Test environments page');
697
+ const sets = apDataSets();
698
+ const why: string[] = [];
699
+ for (const [k, set] of sets.entries()) {
700
+ const tag = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`)); // a tag per attempt: rows of one never meet the next import
701
+ const files = apInvoiceFiles({ tag, interfaceId: interfaceId(k), businessUnit: set.businessUnit, supplier: set.supplier, site: set.site[0], account: set.account,
702
+ source, amount, currency, date: fbdiDate(podToday()) });
703
+ const job = await ctx.rest.importBulkData(importBody('payables_invoice', tag, files,
704
+ { 'Business Unit': set.businessUnit, Source: source, 'Import Set': tag, Purge: 'Y', 'Summarize Report': 'N' }));
705
+ await ctx.rest.waitForJob(job, `import_payables_invoice ${tag}`); // a job that errors is not a data problem: it stops the step
706
+ if (await findAfterImport(() => ctx.rest.invoiceByNumber(tag))) {
707
+ ctx.chosen['ap.business_unit'] = set.businessUnit;
708
+ ctx.chosen['ap.supplier'] = set.supplier;
709
+ used('AP', 'business_unit', set.businessUnit, true);
710
+ used('AP', 'supplier', set.supplier, true);
711
+ ctx.saved[name] = tag;
712
+ ctx.imported.add(tag);
713
+ return;
714
+ }
715
+ why.push(`${set.businessUnit} / ${set.supplier}: the import job succeeded but invoice ${tag} is not in Fusion (the interface rejected it: see Payables > Invoices > Review Import Results)`);
716
+ }
717
+ throw new Error(`import_payables_invoice: no invoice was imported with any of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`);
718
+ },
719
+ /** Import a Receivables transaction through AutoInvoice: a FBDI file of one invoice of one line of value (default {{tv.amount}}) is
720
+ * uploaded through Fusion's ERP Integration REST service and its import job run, then the step waits for the job and finds the
721
+ * transaction by its FPT- tag. transaction_source = the pod's import source (when not given: the pod's sources that are not Manual,
722
+ * in turn); transaction_type (Invoice by default); the pod's business unit, customer, currency and memo line. name = what to remember
723
+ * its number as (default transaction_number). Registered for clean-up before the upload: an Incomplete transaction is deleted, a
724
+ * completed one (what AutoInvoice usually makes) is listed for a person to credit. Needs the pod's "allow imports" setting; on a pod
725
+ * with assisted sign-in (no REST) it is skipped with a note. */
726
+ import_receivables_transaction: async (s, ctx) => {
727
+ const amount = amountValue(s, ctx);
728
+ const typeIs = s.transaction_type ? fill(s.transaction_type, ctx).trim() : undefined;
729
+ const sourceIs = s.transaction_source ? fill(s.transaction_source, ctx).trim() : undefined;
730
+ const wrong = transactionAmountProblems(typeIs, amountOf(amount, ctx, 'the amount'));
731
+ if (wrong.length) throw new Error(`import_receivables_transaction transaction_type "${typeIs || 'Invoice'}": ${wrong.join('; ')}`);
732
+ const name = s.name || 'transaction_number';
733
+ if (!ctx.rest.available) return importSkipped(ctx, s.action, name);
734
+ if (!importsAllowed()) throw new Error(`import_receivables_transaction: ${IMPORTS_REFUSED}`);
735
+ const currency = choices(ctx, 'ar', 'currency')[0];
736
+ if (!currency) throw new Error('import_receivables_transaction needs the currency: the pod has no Receivables test data "currency"; set it on the Test environments page');
737
+ const sources = sourceIs ? [sourceIs] : choices(ctx, 'ar', 'transaction_source').filter((v) => !/^manual$/i.test(v)).slice(0, 3);
738
+ if (!sources.length) throw new Error('import_receivables_transaction needs an import source: give transaction_source, or the pod needs a Receivables test data "transaction_source" other than Manual');
739
+ const bus = choices(ctx, 'ar', 'business_unit');
740
+ const customers = choices(ctx, 'ar', 'customer');
741
+ if (!bus.length || !customers.length) throw new Error("import_receivables_transaction needs the pod's Receivables business unit and customer test data: set them on the Test environments page");
742
+ const memo = choices(ctx, 'ar', 'memo_line')[0];
743
+ const why: string[] = [];
744
+ for (const [k, source] of sources.entries()) {
745
+ const bu = bus[Math.min(k, bus.length - 1)];
746
+ const customer = customers[Math.min(k, customers.length - 1)];
747
+ const account = await ctx.rest.customerAccountNumber(customer);
748
+ if (!account) throw new Error("import_receivables_transaction: the customer's account number could not be read through REST (receivablesInvoices has none of "
749
+ + 'BillToCustomerNumber, BillToAccountNumber, CustomerAccountNumber on this pod); AutoInvoice needs it');
750
+ const tag = ctx.docs.track('ar_transaction', docTag(ctx, k ? String(k) : '')); // before the upload: cleaned up (or listed) even if the step fails
751
+ const files = arTransactionFiles({ tag, businessUnit: bu, source, type: typeIs ?? invoiceTypes(ctx)[0], customerAccount: account, amount, currency,
752
+ date: fbdiDate(podToday()), memoLine: memo });
753
+ const job = await ctx.rest.importBulkData(importBody('receivables_transaction', tag, files,
754
+ { 'Business Unit': bu, 'Transaction Source': source, 'From Transaction Number': tag, 'To Transaction Number': tag }));
755
+ await ctx.rest.waitForJob(job, `import_receivables_transaction ${tag}`);
756
+ const found = await findAfterImport(() => ctx.rest.transaction(tag));
757
+ if (found) {
758
+ ctx.chosen['ar.business_unit'] = bu;
759
+ ctx.chosen['ar.customer'] = customer;
760
+ used('AR', 'business_unit', bu, true);
761
+ used('AR', 'customer', customer, true);
762
+ used('AR', 'transaction_source', source, true);
763
+ ctx.saved[name] = found.TransactionNumber;
764
+ return;
765
+ }
766
+ why.push(`${source}: the import job succeeded but transaction ${tag} is not in Fusion (AutoInvoice rejected the line: see Receivables > Billing > Review AutoInvoice Results)`);
767
+ }
768
+ throw new Error(`import_receivables_transaction: no transaction was imported with any of the ${sources.length} source(s) tried: ${why.join(' | ')}`);
769
+ },
770
  // General Ledger business actions
771
  /** Create and save a journal batch on its own screen: one debit and one credit of value (default {{tv.amount}}) on
772
  * the same account of the pod. category = the journal category (Adjustment, Accrual, Allocation, Reclass ... or a pod
 
849
  { amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },
850
  save: { method: 'save', args: () => [] },
851
  invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] },
852
+ validate_invoice: { method: 'validateInvoice', args: (s, ctx) => {
853
+ const n = ctx.saved[s.name || 'invoice_number']; // an imported invoice is not on the page yet: it is opened first
854
+ return [n && ctx.imported.has(n) ? n : undefined];
855
+ } },
856
  /** Find the invoice remembered as `name` (default invoice_number) on Manage Invoices: exactly it must be listed. */
857
  find_invoice: { method: 'findInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },
858
  /** Invoice Actions > Cancel Invoice on the invoice remembered as `name`, confirmed: it must then show Canceled. */
 
890
  export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {
891
  const c = loadStepCase(id, opts.dir);
892
  test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices, fusionDocs }) => {
893
+ const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, imported: new Set(), chosen: {}, orderTags: {}, rest: apInvoices.rest, docs: fusionDocs };
894
  for (const [i, s] of c.steps.entries()) {
895
  const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;
896
  await test.step(s.expected ? `${label} (expect: ${s.expected})` : label, () => runStep(s, ctx));
automation/src/fusion/ui.ts CHANGED
@@ -7,6 +7,10 @@ import { parseHeals, pick, type HealHow, type HealKind, type HealRule } from './
7
  /** A text as a literal inside a regular expression. */
8
  const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
 
 
 
 
 
10
  /** What a form field can be: what a user types into, picks from or ticks (never a button, link or heading). */
11
  const FORM_CONTROL = 'input:not([type=button]):not([type=submit]):not([type=reset]):not([type=hidden]), textarea, select, '
12
  + '[role=textbox], [role=combobox], [role=spinbutton], [role=checkbox], [role=radio], [contenteditable=true]';
@@ -700,6 +704,14 @@ export class FusionUi {
700
  return { businessUnit, supplier, site };
701
  }
702
 
 
 
 
 
 
 
 
 
703
  /** The invoice's type in Fusion's Type list (Standard, Credit memo, Debit memo, Prepayment; "Invoice Type" on layouts
704
  * that name it so). Entered before the amount. */
705
  async chooseInvoiceType(type: string) {
@@ -785,6 +797,15 @@ export class FusionUi {
785
  const lines = h.lines?.length ? h.lines : [h.amount];
786
  let account = h.account;
787
  for (const [i, amount] of lines.entries()) account = await this.addLine(i + 1, { amount, account: h.account });
 
 
 
 
 
 
 
 
 
788
  const chosen = { ...header, account };
789
  const said = await this.save();
790
  if (said.length) throw new Error(`Fusion did not save invoice ${h.number}: ${said[0].slice(0, 300)}`);
@@ -1121,8 +1142,10 @@ export class FusionUi {
1121
  /** Validate the way an AP clerk does: when Fusion's tax or freight leaves the invoice out of balance, the invoice
1122
  * amount becomes the Total (the supplier's invoice total includes tax), the invoice is saved, then validated; and
1123
  * once more if validating is what added the tax. A scenario that tests an amount mismatch uses invoiceAction. An
1124
- * invoice already Validated needs nothing (Fusion would grey out Validate). */
1125
- async validateInvoice() {
 
 
1126
  if ((await this.statusOnPage()) === 'Validated') return;
1127
  const balance = async () => {
1128
  const t = await this.invoiceTotal();
@@ -1276,9 +1299,12 @@ export class FusionUi {
1276
  const expand = this.page.locator(`a[title="Expand ${section}"]`);
1277
  if (await expand.count()) { await expand.first().click(); await this.settle(3000); }
1278
  await this.refusedRow(section);
1279
- const add = this.page.getByRole('button', { name: /^(Add Row|Add|Create)$/ });
 
 
1280
  const region = this.page.locator('div, table, section').filter({ has: this.page.getByText(section, { exact: true }) }).filter({ has: add });
1281
- const target = (await region.count()) ? region.last().getByRole('button', { name: /^(Add Row|Add|Create)$/ }).first() : add.first();
 
1282
  await target.click({ timeout: 15_000 }).catch(async (e) => { await this.refusedRow(section); throw e; });
1283
  await this.settle(2500);
1284
  await this.refusedRow(section);
@@ -2150,14 +2176,28 @@ export class FusionUi {
2150
  const label = await this.labelOf(labels, 10_000);
2151
  if (!label) throw new Error(`Create Transaction shows no ${labels[0]} field to set the ${what} "${value}" in: the screen changed (verify Create Transaction on the pod)`);
2152
  if ((await this.value(label)).toLowerCase() !== value.toLowerCase()) {
 
2153
  try { await this.put(label, value); } catch (e) {
2154
- if (e instanceof ValueRefused) throw new Error(`Fusion does not take the ${what} "${value}" on Create Transaction: the pod has no such ${what} for this user (${e.message})`);
 
2155
  throw e;
2156
  }
 
 
 
2157
  }
2158
  return (await this.value(label)) || value;
2159
  }
2160
 
 
 
 
 
 
 
 
 
 
2161
  /** The transaction number the page shows, '' when it shows none. */
2162
  transactionNumberOnPage = () => this.numberOnPage(['Transaction Number', 'Number']);
2163
 
@@ -2171,7 +2211,7 @@ export class FusionUi {
2171
  async openTransaction(number: string) {
2172
  await this.findTransaction(number);
2173
  await this.openResult([number]);
2174
- if (!(await this.firstTarget(['Complete', 'Complete Transaction'], 3_000))) {
2175
  await this.menuFirst(['Actions'], ['Edit', 'Edit Transaction'], `editing transaction ${number}`).catch(() => {});
2176
  await this.settleWindows(`editing transaction ${number}`);
2177
  }
@@ -2181,7 +2221,7 @@ export class FusionUi {
2181
  * the one on the page); Fusion's confirmations answered, its errors fail the step in its words. */
2182
  async completeTransaction(number: string): Promise<string[]> {
2183
  if ((await this.transactionNumberOnPage()) !== number) await this.openTransaction(number);
2184
- await this.menuFirst(['Actions', 'Complete'], ['Complete', 'Complete Transaction'], `completing transaction ${number}`);
2185
  return this.settleWindows(`completing transaction ${number}`);
2186
  }
2187
 
 
7
  /** A text as a literal inside a regular expression. */
8
  const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
 
10
+ /** The names of Receivables' complete control: 26D's Create Transaction completes with a "Complete and Close" button (its
11
+ * Actions menu offers only Actions, View and Edit Distributions). */
12
+ const COMPLETE_TRANSACTION = ['Complete', 'Complete Transaction', 'Complete and Close', 'Complete and Review', 'Complete and Create Another'];
13
+
14
  /** What a form field can be: what a user types into, picks from or ticks (never a button, link or heading). */
15
  const FORM_CONTROL = 'input:not([type=button]):not([type=submit]):not([type=reset]):not([type=hidden]), textarea, select, '
16
  + '[role=textbox], [role=combobox], [role=spinbutton], [role=checkbox], [role=radio], [contenteditable=true]';
 
704
  return { businessUnit, supplier, site };
705
  }
706
 
707
+ /** The invoice type shown on the page, lower case ("" when no Type field is there). */
708
+ async invoiceTypeOnPage(): Promise<string> {
709
+ const label = await this.labelOf(['Invoice Type', 'Type'], 2_000);
710
+ if (!label) return '';
711
+ return (await this.field(label).evaluate((e) => (e as HTMLSelectElement).selectedOptions?.[0]?.textContent ?? (e as HTMLInputElement).value)
712
+ .catch(() => '') ?? '').trim().toLowerCase();
713
+ }
714
+
715
  /** The invoice's type in Fusion's Type list (Standard, Credit memo, Debit memo, Prepayment; "Invoice Type" on layouts
716
  * that name it so). Entered before the amount. */
717
  async chooseInvoiceType(type: string) {
 
797
  const lines = h.lines?.length ? h.lines : [h.amount];
798
  let account = h.account;
799
  for (const [i, amount] of lines.entries()) account = await this.addLine(i + 1, { amount, account: h.account });
800
+ // 26D sets the invoice type back to Standard when a line is added (seen live): the type is put again before the save,
801
+ // and a line amount the change cleared (a prepayment's, seen live) is entered again
802
+ if (h.invoiceType && (await this.invoiceTypeOnPage()) !== h.invoiceType.toLowerCase()) {
803
+ await this.chooseInvoiceType(h.invoiceType);
804
+ for (const [i, amount] of lines.entries()) {
805
+ const box = this.lineRow(i + 1).getByRole('textbox', { name: new RegExp(`^Amount(: ${i + 1})?$`) }).first();
806
+ if (!(await box.inputValue().catch(() => '')).trim()) { await box.click(); await box.fill(amount); await box.press('Tab'); await this.settle(1500); }
807
+ }
808
+ }
809
  const chosen = { ...header, account };
810
  const said = await this.save();
811
  if (said.length) throw new Error(`Fusion did not save invoice ${h.number}: ${said[0].slice(0, 300)}`);
 
1142
  /** Validate the way an AP clerk does: when Fusion's tax or freight leaves the invoice out of balance, the invoice
1143
  * amount becomes the Total (the supplier's invoice total includes tax), the invoice is saved, then validated; and
1144
  * once more if validating is what added the tax. A scenario that tests an amount mismatch uses invoiceAction. An
1145
+ * invoice already Validated needs nothing (Fusion would grey out Validate). `number` = an invoice that arrived through an import:
1146
+ * it is not on a page of this test yet, so it is opened from Manage Invoices first. */
1147
+ async validateInvoice(number?: string) {
1148
+ if (number && !(await this.invoiceOpen(number))) await this.openInvoice(number);
1149
  if ((await this.statusOnPage()) === 'Validated') return;
1150
  const balance = async () => {
1151
  const t = await this.invoiceTotal();
 
1299
  const expand = this.page.locator(`a[title="Expand ${section}"]`);
1300
  if (await expand.count()) { await expand.first().click(); await this.settle(3000); }
1301
  await this.refusedRow(section);
1302
+ // the table toolbar's Add Row is a button named only by its icon on 26D's Create Journal (an image "Add Row" inside an
1303
+ // unnamed button): the icon is clicked then, which presses its button
1304
+ const add = this.page.getByRole('button', { name: /^(Add Row|Add|Create)$/ }).or(this.page.getByRole('img', { name: /^Add Row$/ }));
1305
  const region = this.page.locator('div, table, section').filter({ has: this.page.getByText(section, { exact: true }) }).filter({ has: add });
1306
+ const target = (await region.count()) ? region.last().getByRole('button', { name: /^(Add Row|Add|Create)$/ })
1307
+ .or(region.last().getByRole('img', { name: /^Add Row$/ })).filter({ visible: true }).first() : add.filter({ visible: true }).first();
1308
  await target.click({ timeout: 15_000 }).catch(async (e) => { await this.refusedRow(section); throw e; });
1309
  await this.settle(2500);
1310
  await this.refusedRow(section);
 
2176
  const label = await this.labelOf(labels, 10_000);
2177
  if (!label) throw new Error(`Create Transaction shows no ${labels[0]} field to set the ${what} "${value}" in: the screen changed (verify Create Transaction on the pod)`);
2178
  if ((await this.value(label)).toLowerCase() !== value.toLowerCase()) {
2179
+ const none = `Fusion does not take the ${what} "${value}" on Create Transaction: the pod has no such ${what} for this user`;
2180
  try { await this.put(label, value); } catch (e) {
2181
+ if (e instanceof ValueRefused) throw new Error(`${none} (${e.message})`);
2182
+ if (await this.closeEmptySearch()) throw new Error(`${none} (its search lists none)`);
2183
  throw e;
2184
  }
2185
+ // a value the list does not have opens Fusion's "Search and Select" window with no rows, which then covers every
2186
+ // later click (seen on 26D: "Credit Memo" on a pod without that type) — closed, and the step fails in a sentence
2187
+ if (await this.closeEmptySearch()) throw new Error(`${none} (its search lists none)`);
2188
  }
2189
  return (await this.value(label)) || value;
2190
  }
2191
 
2192
+ /** Close a "Search and Select" window that lists no rows (Cancel); true when there was one. */
2193
+ private async closeEmptySearch(): Promise<boolean> {
2194
+ const win = this.page.getByRole('dialog').filter({ hasText: /Search and Select/i }).filter({ hasText: /No rows to display/i }).filter({ visible: true }).first();
2195
+ if (!(await win.count().catch(() => 0))) return false;
2196
+ await win.getByRole('button', { name: 'Cancel', exact: true }).click({ timeout: 10_000 }).catch(() => this.page.keyboard.press('Escape'));
2197
+ await this.settle(1500);
2198
+ return true;
2199
+ }
2200
+
2201
  /** The transaction number the page shows, '' when it shows none. */
2202
  transactionNumberOnPage = () => this.numberOnPage(['Transaction Number', 'Number']);
2203
 
 
2211
  async openTransaction(number: string) {
2212
  await this.findTransaction(number);
2213
  await this.openResult([number]);
2214
+ if (!(await this.firstTarget(COMPLETE_TRANSACTION, 3_000))) {
2215
  await this.menuFirst(['Actions'], ['Edit', 'Edit Transaction'], `editing transaction ${number}`).catch(() => {});
2216
  await this.settleWindows(`editing transaction ${number}`);
2217
  }
 
2221
  * the one on the page); Fusion's confirmations answered, its errors fail the step in its words. */
2222
  async completeTransaction(number: string): Promise<string[]> {
2223
  if ((await this.transactionNumberOnPage()) !== number) await this.openTransaction(number);
2224
+ await this.menuFirst(['Actions', 'Complete'], COMPLETE_TRANSACTION, `completing transaction ${number}`);
2225
  return this.settleWindows(`completing transaction ${number}`);
2226
  }
2227
 
automation/tests/fusion/steps/AP-FUS-040.spec.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ // AP-FUS-040 (YAML: tests/cases/AP-FUS-040.yaml, runner: steps). Generated by scripts/gen-fusion-steps.js; edit the YAML, not this file.
2
+ import { stepsTest } from '../../../src/fusion/steps';
3
+
4
+ stepsTest('AP-FUS-040', ['@AP-FUS-040','@AP','@P2']);
automation/tests/fusion/steps/AR-FUS-040.spec.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ // AR-FUS-040 (YAML: tests/cases/AR-FUS-040.yaml, runner: steps). Generated by scripts/gen-fusion-steps.js; edit the YAML, not this file.
2
+ import { stepsTest } from '../../../src/fusion/steps';
3
+
4
+ stepsTest('AR-FUS-040', ['@AR-FUS-040','@AR','@P2']);
coworker/adapters/playwright.py CHANGED
@@ -114,6 +114,8 @@ def run_attempt(*, run_id: str, ids: list[str], attempt: int, mode: str, out_fil
114
  PLAYWRIGHT_JSON_OUTPUT_NAME=str(out_file), **(cred_env or {}))
115
  env.pop("PW_LOCATOR_OVERRIDES", None)
116
  env.pop("FPT_FUSION_STORAGE_STATE", None)
 
 
117
  for k in STUB_KEYS:
118
  env.pop(k, None)
119
  # Live view: the fixture hook (automation/src/live-view.ts) is active only when FPT_LIVE_VIEW_DIR is set.
 
114
  PLAYWRIGHT_JSON_OUTPUT_NAME=str(out_file), **(cred_env or {}))
115
  env.pop("PW_LOCATOR_OVERRIDES", None)
116
  env.pop("FPT_FUSION_STORAGE_STATE", None)
117
+ if "FPT_ALLOW_IMPORTS" not in (cred_env or {}):
118
+ env.pop("FPT_ALLOW_IMPORTS", None) # the server's own environment never allows imports: only the pod's setting does
119
  for k in STUB_KEYS:
120
  env.pop(k, None)
121
  # Live view: the fixture hook (automation/src/live-view.ts) is active only when FPT_LIVE_VIEW_DIR is set.
coworker/adapters/remote_runner.py CHANGED
@@ -28,7 +28,7 @@ from .playwright import AUTOMATION, testdata_used_file
28
  log = logging.getLogger("fpt.remote_runner")
29
 
30
  ENV_KEYS = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
31
- "FPT_FUSION_WORKERS", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS")
32
  JOB_FILE = "remote-job.json"
33
  JOB_ID = re.compile(r"job_[0-9a-f]{12}")
34
  # a job's last states; "failed" (the runner's own error) and "lost" (it restarted mid-job) come from runners that keep
 
28
  log = logging.getLogger("fpt.remote_runner")
29
 
30
  ENV_KEYS = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
31
+ "FPT_FUSION_WORKERS", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS", "FPT_NAV_LINKS", "FPT_ALLOW_IMPORTS")
32
  JOB_FILE = "remote-job.json"
33
  JOB_ID = re.compile(r"job_[0-9a-f]{12}")
34
  # a job's last states; "failed" (the runner's own error) and "lost" (it restarted mid-job) come from runners that keep
coworker/api/schemas.py CHANGED
@@ -149,6 +149,7 @@ class PodUpdate(Strict):
149
  enabled: bool | None = None
150
  release: str | None = Field(default=None, max_length=3) # the Oracle Fusion release the pod runs, for example 26C
151
  sign_in_mode: Literal["password", "assisted"] | None = None
 
152
 
153
 
154
  class PodScreensIn(Strict):
@@ -218,6 +219,7 @@ class PodRow(BaseModel):
218
  is_default: bool
219
  release: str | None = None
220
  sign_in_mode: Literal["password", "assisted"] = "password" # assisted: a person signs in at the start of each run
 
221
  discovery: dict | None = None # {"areas": [{code, name, status, counts, processes, detail?}]} (platform/discovery.py)
222
  discovered_at: str | None = None
223
  usage_read_at: str | None = None # when the usage profile was read (GET /pods/{id}/usage)
 
149
  enabled: bool | None = None
150
  release: str | None = Field(default=None, max_length=3) # the Oracle Fusion release the pod runs, for example 26C
151
  sign_in_mode: Literal["password", "assisted"] | None = None
152
+ allow_imports: bool | None = None # true: runs may import test data through the pod's ERP Integration service (admin; never production)
153
 
154
 
155
  class PodScreensIn(Strict):
 
219
  is_default: bool
220
  release: str | None = None
221
  sign_in_mode: Literal["password", "assisted"] = "password" # assisted: a person signs in at the start of each run
222
+ allow_imports: bool = False # runs may import test data (FBDI files: Payables invoice import, AutoInvoice); off until an admin agrees
223
  discovery: dict | None = None # {"areas": [{code, name, status, counts, processes, detail?}]} (platform/discovery.py)
224
  discovered_at: str | None = None
225
  usage_read_at: str | None = None # when the usage profile was read (GET /pods/{id}/usage)
coworker/platform/cleanup.py CHANGED
@@ -206,11 +206,12 @@ def _clean_journal(svc, base_url: str, auth, e: dict, run_id: str) -> str:
206
 
207
 
208
  def _clean_transaction(svc, base_url: str, auth, e: dict, run_id: str) -> str:
209
- """Mirror of rest.ts cleanTransaction: found by its number or the tag in its Comments; deleted while Incomplete. A
210
- completed one needs a credit memo: left for a person."""
 
211
  tag = _q(e["number"])
212
- t = _first(svc, base_url, auth, run_id, "receivablesInvoices", f"TransactionNumber='{tag}'", f"Comments LIKE '{tag}%'",
213
- f"InternalNotes LIKE '{tag}%'")
214
  if not t:
215
  return "not saved, nothing to clean up"
216
  said = next((t[k] for k in ("InvoiceStatus", "TransactionStatus", "Status", "StatusMeaning") if t.get(k) not in (None, "")), None)
 
206
 
207
 
208
  def _clean_transaction(svc, base_url: str, auth, e: dict, run_id: str) -> str:
209
+ """Mirror of rest.ts cleanTransaction: found by its number, the tag as its customer order number (an imported one: the FBDI
210
+ file carries it there) or the tag in its Comments; deleted while Incomplete. A completed one needs a credit memo: left for a
211
+ person."""
212
  tag = _q(e["number"])
213
+ t = _first(svc, base_url, auth, run_id, "receivablesInvoices", f"TransactionNumber='{tag}'", f"PurchaseOrder='{tag}'",
214
+ f"Comments LIKE '{tag}%'", f"InternalNotes LIKE '{tag}%'")
215
  if not t:
216
  return "not saved, nothing to clean up"
217
  said = next((t[k] for k in ("InvoiceStatus", "TransactionStatus", "Status", "StatusMeaning") if t.get(k) not in (None, "")), None)
coworker/platform/left_on_pod.py CHANGED
@@ -201,7 +201,7 @@ def _check(svc, base_url: str, auth, row: dict) -> tuple[str, str]:
201
  return _first(svc, base_url, auth, run_id, resource, *queries)
202
 
203
  if kind == "ar_transaction":
204
- t = look("receivablesInvoices", f"TransactionNumber='{tag}'", f"Comments LIKE '{tag}%'", f"InternalNotes LIKE '{tag}%'")
205
  if not t:
206
  return RESOLVED, gone
207
  st = _status(next((t[k] for k in ("InvoiceStatus", "TransactionStatus", "Status", "StatusMeaning") if t.get(k) not in (None, "")), ""))
 
201
  return _first(svc, base_url, auth, run_id, resource, *queries)
202
 
203
  if kind == "ar_transaction":
204
+ t = look("receivablesInvoices", f"TransactionNumber='{tag}'", f"PurchaseOrder='{tag}'", f"Comments LIKE '{tag}%'", f"InternalNotes LIKE '{tag}%'")
205
  if not t:
206
  return RESOLVED, gone
207
  st = _status(next((t[k] for k in ("InvoiceStatus", "TransactionStatus", "Status", "StatusMeaning") if t.get(k) not in (None, "")), ""))
coworker/platform/migrations/032_pod_allow_imports.sql ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ -- 032: whether runs on a Fusion pod may import data (platform/pods.py). An import (FBDI file through Fusion's ERP Integration
2
+ -- REST service: Payables invoice import, AutoInvoice) writes test data to the pod, so it is off until an admin agrees to it for
3
+ -- that test environment; a run on a pod with it on is passed FPT_ALLOW_IMPORTS=1, and the import actions refuse without it.
4
+ -- Never on production (the registry refuses those pods). 0 = no (the default), 1 = yes.
5
+ ALTER TABLE pods ADD COLUMN allow_imports INTEGER NOT NULL DEFAULT 0;
coworker/platform/pods.py CHANGED
@@ -173,7 +173,7 @@ class PodRegistry:
173
  runnable, why = self.runnable(r)
174
  disc = _json(r.get("discovery"), None)
175
  r = {k: v for k, v in r.items() if k not in ("test_data_learned", "test_data_screens", "usage")}
176
- return {**r, "modules": mods, "sign_in_mode": r.get("sign_in_mode") or "password", "from_server_settings": self.is_env_pod(r), "enabled": bool(r["enabled"]), "is_default": bool(r["is_default"]),
177
  "discovery": disc, "test_data": discovery.merged_test_data(*self._test_data_sources(r["id"])),
178
  "test_data_overrides": _json(r.get("test_data_overrides"), {}),
179
  "nav_links": _json(r.get("nav_links"), {}) or {},
@@ -236,10 +236,17 @@ class PodRegistry:
236
  if release and not RELEASE_RE.fullmatch(release):
237
  raise PodError("BAD_RELEASE", "write the Oracle Fusion release as two digits and a letter, for example 26C")
238
  mode = sign_in_mode(merged["kind"], merged.get("sign_in_mode"))
 
 
 
239
  self.db.update("pods", "id", pod_id, name=merged["name"], kind=merged["kind"], base_url=base, environment=merged["environment"],
240
  modules=json.dumps([m.upper() for m in merged.get("modules") or []]), notes=merged.get("notes"),
241
- enabled=int(bool(merged["enabled"])), release=release, sign_in_mode=mode, updated_at=now_iso())
242
  self.audit.append("pod.updated", actor=actor, summary=merged["name"], payload={"pod_id": pod_id, **changes})
 
 
 
 
243
  if release and release != cur.get("release"): # a new release: its screens may have changed
244
  self.read_in_background(pod_id, actor)
245
  return self.get(pod_id)
@@ -364,10 +371,12 @@ class PodRegistry:
364
  cands = self.test_data_candidates(pod_id, run_id)
365
  first = {**p["test_data"], **{a: {**(p["test_data"].get(a) or {}), **{k: v[0] for k, v in keys.items() if v}} for a, keys in cands.items()}}
366
  mode = {"FPT_SIGN_IN_MODE": "assisted"} if assisted(p) else {}
 
367
  from .healing import heal_map
368
  links = self.nav_links(pod_id) # work areas a consultant opened by hand; ui.ts opens them by address (FPT_NAV_LINKS)
369
  heals = heal_map(self.db, pod_id) # names a person approved for controls Oracle relabelled (ui.ts tries them first)
370
  return {"FUSION_BASE_URL": p["base_url"], "FUSION_USERNAME": auth[0], "FUSION_PASSWORD": auth[1], **mode,
 
371
  **({"FPT_HEALS": json.dumps(heals)} if heals else {}),
372
  **({"FPT_NAV_LINKS": json.dumps(links)} if links else {}),
373
  "FUSION_TESTDATA": json.dumps(first), # {{pod.<area>.<key>}} in test steps (automation/src/fusion/ui.ts)
 
173
  runnable, why = self.runnable(r)
174
  disc = _json(r.get("discovery"), None)
175
  r = {k: v for k, v in r.items() if k not in ("test_data_learned", "test_data_screens", "usage")}
176
+ return {**r, "modules": mods, "sign_in_mode": r.get("sign_in_mode") or "password", "allow_imports": bool(r.get("allow_imports")), "from_server_settings": self.is_env_pod(r), "enabled": bool(r["enabled"]), "is_default": bool(r["is_default"]),
177
  "discovery": disc, "test_data": discovery.merged_test_data(*self._test_data_sources(r["id"])),
178
  "test_data_overrides": _json(r.get("test_data_overrides"), {}),
179
  "nav_links": _json(r.get("nav_links"), {}) or {},
 
236
  if release and not RELEASE_RE.fullmatch(release):
237
  raise PodError("BAD_RELEASE", "write the Oracle Fusion release as two digits and a letter, for example 26C")
238
  mode = sign_in_mode(merged["kind"], merged.get("sign_in_mode"))
239
+ imports = bool(merged.get("allow_imports"))
240
+ if imports and merged["kind"] != "fusion":
241
+ raise PodError("BAD_ALLOW_IMPORTS", "imports go through an Oracle Fusion pod's ERP Integration service; the practice pod has none")
242
  self.db.update("pods", "id", pod_id, name=merged["name"], kind=merged["kind"], base_url=base, environment=merged["environment"],
243
  modules=json.dumps([m.upper() for m in merged.get("modules") or []]), notes=merged.get("notes"),
244
+ enabled=int(bool(merged["enabled"])), release=release, sign_in_mode=mode, allow_imports=int(imports), updated_at=now_iso())
245
  self.audit.append("pod.updated", actor=actor, summary=merged["name"], payload={"pod_id": pod_id, **changes})
246
+ if imports != bool(cur.get("allow_imports")): # a run may write test data through the pod's import services: its own record
247
+ self.audit.append("pod.imports_allowed" if imports else "pod.imports_refused", actor=actor,
248
+ summary=f"pod {pod_id}: runs {'may' if imports else 'may not'} import data (Payables invoice import, AutoInvoice)",
249
+ payload={"pod_id": pod_id, "allow_imports": imports, "environment": merged["environment"]})
250
  if release and release != cur.get("release"): # a new release: its screens may have changed
251
  self.read_in_background(pod_id, actor)
252
  return self.get(pod_id)
 
371
  cands = self.test_data_candidates(pod_id, run_id)
372
  first = {**p["test_data"], **{a: {**(p["test_data"].get(a) or {}), **{k: v[0] for k, v in keys.items() if v}} for a, keys in cands.items()}}
373
  mode = {"FPT_SIGN_IN_MODE": "assisted"} if assisted(p) else {}
374
+ imports = {"FPT_ALLOW_IMPORTS": "1"} if p.get("allow_imports") else {} # the opt-in the import actions check (automation/src/fusion/interfaces.ts)
375
  from .healing import heal_map
376
  links = self.nav_links(pod_id) # work areas a consultant opened by hand; ui.ts opens them by address (FPT_NAV_LINKS)
377
  heals = heal_map(self.db, pod_id) # names a person approved for controls Oracle relabelled (ui.ts tries them first)
378
  return {"FUSION_BASE_URL": p["base_url"], "FUSION_USERNAME": auth[0], "FUSION_PASSWORD": auth[1], **mode,
379
+ **imports,
380
  **({"FPT_HEALS": json.dumps(heals)} if heals else {}),
381
  **({"FPT_NAV_LINKS": json.dumps(links)} if links else {}),
382
  "FUSION_TESTDATA": json.dumps(first), # {{pod.<area>.<key>}} in test steps (automation/src/fusion/ui.ts)
coworker/platform/step_writer.py CHANGED
@@ -227,13 +227,35 @@ ALLOWED_ACTIONS: dict[str, str] = {
227
  "expect_receipt": "Receivables business action, a check in Fusion itself: the receipt created (or remembered) earlier "
228
  "exists and, when given, status = its state (one of Applied, Unapplied, Partially applied, "
229
  "Reversed), amount = its exact amount. name = the remembered number's name (default receipt_number)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  }
231
  # the business actions (steps.ts) per business area: each only makes sense on a scenario of its own area's screens
232
  # (task paths starting with one of `screens`)
233
  BUSINESS_AREAS: dict[str, dict] = {
234
  "AP": {"name": "Payables", "screens": ("payables",),
235
  "actions": ("create_invoice", "validate_invoice", "find_invoice", "cancel_invoice", "expect_invoice", "expect_hold",
236
- "expect_no_holds", "create_payment", "find_payment", "expect_payment", "void_payment", "initiate_approval")},
 
237
  "PO": {"name": "Purchasing", "screens": ("procurement", "purchasing", "receiving"),
238
  "actions": ("create_requisition", "expect_requisition", "cancel_requisition", "create_purchase_order",
239
  "submit_purchase_order", "find_purchase_order", "expect_purchase_order", "cancel_purchase_order",
@@ -242,7 +264,7 @@ BUSINESS_AREAS: dict[str, dict] = {
242
  "actions": ("create_journal", "post_journal", "find_journal", "expect_journal", "reverse_journal")},
243
  "AR": {"name": "Receivables", "screens": ("receivables",),
244
  "actions": ("create_transaction", "complete_transaction", "find_transaction", "expect_transaction", "create_receipt",
245
- "find_receipt", "expect_receipt")},
246
  }
247
  BUSINESS_ACTIONS = tuple(a for x in BUSINESS_AREAS.values() for a in x["actions"])
248
  # actions that leave a document only a person can undo (a receipt is corrected or returned, a closed order reopened): they
@@ -250,7 +272,11 @@ BUSINESS_ACTIONS = tuple(a for x in BUSINESS_AREAS.values() for a in x["actions"
250
  # The payment actions are scenario-only too, but a payment is not left: the clean-up voids it (on the screens) before it cancels the invoice
251
  # (a payment Fusion does not let the clean-up void is listed in the run's test data like the others)
252
  SCENARIO_ONLY_ACTIONS = ("create_receipt_for_order", "expect_receipt_of_order", "close_purchase_order",
253
- "create_payment", "find_payment", "expect_payment", "void_payment", "initiate_approval")
 
 
 
 
254
  # what close_purchase_order closes an order as (the value, as Fusion's Close action names it) and the order status that follows
255
  CLOSE_WAYS = ("Close for Receiving", "Close for Invoicing", "Close", "Finally Close")
256
  CLOSE_ACTIONS = dict(zip((w.lower() for w in CLOSE_WAYS), ("Closed for Receiving", "Closed for Invoicing", "Closed", "Finally Closed")))
@@ -278,6 +304,7 @@ DOC_KINDS = {"invoice": ("invoice_number", "create_invoice", "an invoice"),
278
  "po_receipt": ("po_receipt_number", "create_receipt_for_order", "a receipt of a purchase order"),
279
  "payment": ("payment_number", "create_payment", "a payment")}
280
  CREATES = {creator: kind for kind, (_n, creator, _w) in DOC_KINDS.items()}
 
281
  # actions that work on a document created or remembered earlier ({{saved.<name>}})
282
  DOC_ACTIONS = {"find_invoice": "invoice", "cancel_invoice": "invoice", "expect_invoice": "invoice", "expect_hold": "invoice",
283
  "expect_no_holds": "invoice", "expect_requisition": "requisition", "cancel_requisition": "requisition",
@@ -317,6 +344,10 @@ STEP_KEYS = {"status": tuple(a for a in STATUSES if a != "expect_payment"),
317
  # the payment actions that also take some of those fields (named apart so the messages about the other actions stay as they were)
318
  STEP_KEYS_OF_PAYMENTS = {"status": ("expect_payment",), "amount": ("expect_payment",), "amount_at_least": ("expect_payment",),
319
  "applies_to": ("create_payment",), "payment_method": ("create_payment", "expect_payment")}
 
 
 
 
320
  NUMBER_KEYS = ("amount", "amount_at_least", "quantity", "price")
321
  # journal categories and the one source a person can enter: the other sources (Payables, Receivables, Projects, Payroll, Cash
322
  # Management ...) are made by Create Accounting and transfers, never entered, so no step asks for them
@@ -476,31 +507,43 @@ def _screen_facts(inv: dict) -> SimpleNamespace:
476
  has_number="number" in labels)
477
 
478
 
479
- def _transaction_problems(i: int, s, test_values: dict, made: dict[str, tuple[str, str]]) -> list[str]:
480
- """The checks of create_transaction's and expect_transaction's transaction_type and transaction_source: a name as the pod
481
- writes it, a source keyed in on the screen, the sign Fusion enforces on the amount, and no expectation the transaction
482
- was not created with. `made` remembers per transaction name what create_transaction gave it."""
 
483
  a, out = s.action, []
484
  kind = " ".join((s.transaction_type or "").lower().split())
485
  source = " ".join((s.transaction_source or "").lower().split())
 
486
  for what, text in (("transaction_type", s.transaction_type), ("transaction_source", s.transaction_source)):
487
  t = (text or "").strip()
488
  if text is not None and not (PH_RE.search(t) or TRANSACTION_NAME_RE.fullmatch(t)):
489
  out.append(f"step {i}: {a} {what} must be a name as the pod writes it ({', '.join(TRANSACTION_TYPES)} or another of the "
490
  f"pod's types; the source Manual or another of the pod's), got '{text}'")
491
- if source and IMPORT_SOURCE_RE.search(source) and not PH_RE.search(source):
 
492
  out.append(f"step {i}: {a} transaction_source '{s.transaction_source}': an import is a scheduled process, it cannot be "
493
- "keyed in on Create Transaction, so no scenario of the screens tests it")
494
- name = s.name or DOC_KINDS["transaction"][0]
495
- if a == "create_transaction":
 
 
 
 
 
496
  for what, text in [("value", s.value)] if (s.value or "").strip() else [("test value 'amount'", "{{tv.amount}}")]:
497
  fig = _figure(text, test_values)
498
  if fig and kind == "credit memo" and fig[1] != -1:
499
- out.append(f"step {i}: create_transaction {what} '{fig[0]}': a credit memo is entered with a negative amount in Fusion")
500
  elif fig and kind in ("", "invoice", "debit memo") and fig[1] == -1:
501
- out.append(f"step {i}: create_transaction {what} '{fig[0]}': {kind or 'invoice'} has a positive amount "
502
  "(a negative one is a credit memo: transaction_type)")
503
  made[name] = (kind or "invoice", source)
 
 
 
 
504
  elif name in made:
505
  if kind and kind != made[name][0]:
506
  out.append(f"step {i}: expect_transaction transaction_type '{s.transaction_type}': the transaction was created as {made[name][0]}")
@@ -538,6 +581,9 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
538
  journals_made: set[str] = set() # journals create_journal made, by remembered name
539
  journals_posted: set[str] = set() # journals post_journal posted, by remembered name
540
  transaction_made: dict[str, tuple[str, str]] = {} # per remembered transaction name: the type and source it was created with
 
 
 
541
  invoice_made: dict[str, tuple[str, str]] = {} # per remembered invoice name: the type and payment method create_invoice gave it
542
  last_invoice = DOC_KINDS["invoice"][0] # the invoice create_invoice saved last: the one validate_invoice validates
543
  invoices_validated: set[str] = set() # the invoices validate_invoice validated
@@ -602,7 +648,7 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
602
  problems.append(f"step {i}: {a} needs {words} created ({creator}) or remembered (remember) earlier as "
603
  f"'{s.name or default}'")
604
  for k, owners in STEP_KEYS.items():
605
- if getattr(s, k) not in (None, "", []) and a not in owners and a not in STEP_KEYS_OF_PAYMENTS.get(k, ()):
606
  # the owners of the step's own area are named (status on create_invoice: expect_invoice)
607
  mine = [o for o in owners if ACTION_AREA.get(o) == area] or list(owners)
608
  problems.append(f"step {i}: {k} belongs to {' or '.join(mine)}, not {a}")
@@ -644,8 +690,34 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
644
  "(a negative one is a credit or debit memo: invoice_type)")
645
  invoice_made[s.name or DOC_KINDS["invoice"][0]] = (kind, (s.payment_method or "").strip())
646
  last_invoice = s.name or DOC_KINDS["invoice"][0]
 
 
647
  if a == "validate_invoice":
648
  invoices_validated.add(last_invoice)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
649
  if a == "expect_invoice":
650
  if s.validation_status and not PH_RE.search(s.validation_status) \
651
  and s.validation_status.strip().lower() not in {x.lower() for x in VALIDATION_STATUSES}:
@@ -726,12 +798,12 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
726
  journals_made.add(journal)
727
  if a == "post_journal":
728
  journals_posted.add(journal)
729
- if a in ("create_transaction", "expect_transaction"):
730
- problems += _transaction_problems(i, s, d.test_values, transaction_made)
731
  if a in ("create_requisition", "create_purchase_order") and not (s.price or "").strip() \
732
  and not {"price", "amount"} & set(d.test_values):
733
  problems.append(f"step {i}: {a} needs a price: price, or the test value 'price' ({{{{tv.price}}}})")
734
- if a in ("create_journal", "create_transaction", "create_receipt"):
735
  if not (s.value or "").strip() and "amount" not in d.test_values:
736
  problems.append(f"step {i}: {a} needs an amount: value, or the test value 'amount' ({{{{tv.amount}}}})")
737
  elif (s.value or "").strip() and not AMOUNT_RE.fullmatch(s.value):
@@ -804,7 +876,7 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
804
  if a in ("enter", "expect_filled", "expect_value", "remember", "add_line", "save", "invoice_action", "validate_invoice", "click", "add_row",
805
  "enter_in_row", "menu_action", "expect_results") and not opened:
806
  problems.append(f"step {i}: {a} comes before open_task")
807
- if a == "validate_invoice" and not invoice_page and "Validate" not in sc.actions_menu:
808
  problems.append(f"step {i}: validate_invoice needs Validate in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
809
  if a == "invoice_action" and s.value and s.value not in sc.actions_menu:
810
  problems.append(f"step {i}: '{s.value}' is not in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
 
227
  "expect_receipt": "Receivables business action, a check in Fusion itself: the receipt created (or remembered) earlier "
228
  "exists and, when given, status = its state (one of Applied, Unapplied, Partially applied, "
229
  "Reversed), amount = its exact amount. name = the remembered number's name (default receipt_number)",
230
+ # Interfaces: documents that arrive through an import, made the way the client's integrations make them. A scenario's own
231
+ # (never in a canary), they write through Fusion's ERP Integration service, so the pod must allow imports
232
+ "import_payables_invoice": "Payables business action (an interface), opens no screen: imports a standard invoice of one Item line with Payables "
233
+ "invoice import (a FBDI file uploaded through Fusion's ERP Integration service, the import job "
234
+ "run and waited for), with the pod's business unit, supplier, account and currency, a new test "
235
+ "number, and finds the invoice it created. value = the invoice amount (default {{tv.amount}}); "
236
+ "source = the invoice source of the import (default External); name = what to remember the number "
237
+ "as (default invoice_number, then {{saved.invoice_number}}). Check it with expect_invoice (source, "
238
+ "amount_at_least ...), validate it with validate_invoice. The pod must allow imports (Test "
239
+ "environments page); the clean-up cancels the invoice. Fails, saying so, when the import job errors "
240
+ "or Payables rejects the row",
241
+ "import_receivables_transaction": "Receivables business action (an interface), opens no screen: imports an invoice of one line with AutoInvoice "
242
+ "(a FBDI file uploaded through Fusion's ERP Integration service, the import job run and waited "
243
+ "for), with the pod's business unit, customer, currency and memo line, a new test reference, "
244
+ "and finds the transaction it created. value = the line amount (default {{tv.amount}}); "
245
+ "transaction_source = the import source of the pod (the sources the pod uses other than Manual "
246
+ "when not given); transaction_type = Invoice (default); name = what to remember its number as "
247
+ "(default transaction_number, then {{saved.transaction_number}}). Check it with "
248
+ "expect_transaction (transaction_source, amount_at_least ...). The pod must allow imports "
249
+ "(Test environments page); a transaction AutoInvoice completed is listed in the run's test data "
250
+ "for a person to credit. Fails, saying so, when the import job errors or AutoInvoice rejects the line",
251
  }
252
  # the business actions (steps.ts) per business area: each only makes sense on a scenario of its own area's screens
253
  # (task paths starting with one of `screens`)
254
  BUSINESS_AREAS: dict[str, dict] = {
255
  "AP": {"name": "Payables", "screens": ("payables",),
256
  "actions": ("create_invoice", "validate_invoice", "find_invoice", "cancel_invoice", "expect_invoice", "expect_hold",
257
+ "expect_no_holds", "create_payment", "find_payment", "expect_payment", "void_payment", "initiate_approval",
258
+ "import_payables_invoice")},
259
  "PO": {"name": "Purchasing", "screens": ("procurement", "purchasing", "receiving"),
260
  "actions": ("create_requisition", "expect_requisition", "cancel_requisition", "create_purchase_order",
261
  "submit_purchase_order", "find_purchase_order", "expect_purchase_order", "cancel_purchase_order",
 
264
  "actions": ("create_journal", "post_journal", "find_journal", "expect_journal", "reverse_journal")},
265
  "AR": {"name": "Receivables", "screens": ("receivables",),
266
  "actions": ("create_transaction", "complete_transaction", "find_transaction", "expect_transaction", "create_receipt",
267
+ "find_receipt", "expect_receipt", "import_receivables_transaction")},
268
  }
269
  BUSINESS_ACTIONS = tuple(a for x in BUSINESS_AREAS.values() for a in x["actions"])
270
  # actions that leave a document only a person can undo (a receipt is corrected or returned, a closed order reopened): they
 
272
  # The payment actions are scenario-only too, but a payment is not left: the clean-up voids it (on the screens) before it cancels the invoice
273
  # (a payment Fusion does not let the clean-up void is listed in the run's test data like the others)
274
  SCENARIO_ONLY_ACTIONS = ("create_receipt_for_order", "expect_receipt_of_order", "close_purchase_order",
275
+ "create_payment", "find_payment", "expect_payment", "void_payment", "initiate_approval",
276
+ "import_payables_invoice", "import_receivables_transaction")
277
+ # the interface actions: they write through the ERP Integration service (the pod must allow imports); the invoice one is cancelled
278
+ # by the clean-up like a screen invoice, the transaction one is complete and is listed for a person to credit
279
+ IMPORT_ACTIONS = ("import_payables_invoice", "import_receivables_transaction")
280
  # what close_purchase_order closes an order as (the value, as Fusion's Close action names it) and the order status that follows
281
  CLOSE_WAYS = ("Close for Receiving", "Close for Invoicing", "Close", "Finally Close")
282
  CLOSE_ACTIONS = dict(zip((w.lower() for w in CLOSE_WAYS), ("Closed for Receiving", "Closed for Invoicing", "Closed", "Finally Closed")))
 
304
  "po_receipt": ("po_receipt_number", "create_receipt_for_order", "a receipt of a purchase order"),
305
  "payment": ("payment_number", "create_payment", "a payment")}
306
  CREATES = {creator: kind for kind, (_n, creator, _w) in DOC_KINDS.items()}
307
+ CREATES.update({"import_payables_invoice": "invoice", "import_receivables_transaction": "transaction"}) # an import makes the same documents
308
  # actions that work on a document created or remembered earlier ({{saved.<name>}})
309
  DOC_ACTIONS = {"find_invoice": "invoice", "cancel_invoice": "invoice", "expect_invoice": "invoice", "expect_hold": "invoice",
310
  "expect_no_holds": "invoice", "expect_requisition": "requisition", "cancel_requisition": "requisition",
 
344
  # the payment actions that also take some of those fields (named apart so the messages about the other actions stay as they were)
345
  STEP_KEYS_OF_PAYMENTS = {"status": ("expect_payment",), "amount": ("expect_payment",), "amount_at_least": ("expect_payment",),
346
  "applies_to": ("create_payment",), "payment_method": ("create_payment", "expect_payment")}
347
+ # the interface actions that also take some of those fields (named apart for the same reason): the source an import is made from and
348
+ # checked against (an invoice's source, a transaction's type and source)
349
+ STEP_KEYS_OF_IMPORTS = {"source": ("import_payables_invoice", "expect_invoice"), "transaction_type": ("import_receivables_transaction",),
350
+ "transaction_source": ("import_receivables_transaction",)}
351
  NUMBER_KEYS = ("amount", "amount_at_least", "quantity", "price")
352
  # journal categories and the one source a person can enter: the other sources (Payables, Receivables, Projects, Payroll, Cash
353
  # Management ...) are made by Create Accounting and transfers, never entered, so no step asks for them
 
507
  has_number="number" in labels)
508
 
509
 
510
+ def _transaction_problems(i: int, s, test_values: dict, made: dict[str, tuple[str, str]], imported: set[str]) -> list[str]:
511
+ """The checks of create_transaction's, import_receivables_transaction's and expect_transaction's transaction_type and
512
+ transaction_source: a name as the pod writes it, a source keyed in on the screen (an import source is made only by
513
+ import_receivables_transaction), the sign Fusion enforces on the amount, and no expectation the transaction was not created
514
+ with. `made` remembers per transaction name what its create (or import) action gave it; `imported` the names an import made."""
515
  a, out = s.action, []
516
  kind = " ".join((s.transaction_type or "").lower().split())
517
  source = " ".join((s.transaction_source or "").lower().split())
518
+ name = s.name or DOC_KINDS["transaction"][0]
519
  for what, text in (("transaction_type", s.transaction_type), ("transaction_source", s.transaction_source)):
520
  t = (text or "").strip()
521
  if text is not None and not (PH_RE.search(t) or TRANSACTION_NAME_RE.fullmatch(t)):
522
  out.append(f"step {i}: {a} {what} must be a name as the pod writes it ({', '.join(TRANSACTION_TYPES)} or another of the "
523
  f"pod's types; the source Manual or another of the pod's), got '{text}'")
524
+ is_import_source = bool(source and IMPORT_SOURCE_RE.search(source) and not PH_RE.search(source))
525
+ if is_import_source and a == "create_transaction":
526
  out.append(f"step {i}: {a} transaction_source '{s.transaction_source}': an import is a scheduled process, it cannot be "
527
+ "keyed in on Create Transaction; make it with import_receivables_transaction")
528
+ elif is_import_source and a == "expect_transaction" and name not in imported:
529
+ out.append(f"step {i}: {a} transaction_source '{s.transaction_source}': an import is a scheduled process, it cannot be "
530
+ "keyed in on Create Transaction; the transaction was not imported (import_receivables_transaction)")
531
+ if a == "import_receivables_transaction" and source == "manual":
532
+ out.append(f"step {i}: import_receivables_transaction transaction_source 'Manual': Manual is the source of a transaction keyed in "
533
+ "on a screen (create_transaction); an import source is one of the pod's own (or leave it out)")
534
+ if a in ("create_transaction", "import_receivables_transaction"):
535
  for what, text in [("value", s.value)] if (s.value or "").strip() else [("test value 'amount'", "{{tv.amount}}")]:
536
  fig = _figure(text, test_values)
537
  if fig and kind == "credit memo" and fig[1] != -1:
538
+ out.append(f"step {i}: {a} {what} '{fig[0]}': a credit memo is entered with a negative amount in Fusion")
539
  elif fig and kind in ("", "invoice", "debit memo") and fig[1] == -1:
540
+ out.append(f"step {i}: {a} {what} '{fig[0]}': {kind or 'invoice'} has a positive amount "
541
  "(a negative one is a credit memo: transaction_type)")
542
  made[name] = (kind or "invoice", source)
543
+ if a == "import_receivables_transaction":
544
+ imported.add(name)
545
+ else:
546
+ imported.discard(name)
547
  elif name in made:
548
  if kind and kind != made[name][0]:
549
  out.append(f"step {i}: expect_transaction transaction_type '{s.transaction_type}': the transaction was created as {made[name][0]}")
 
581
  journals_made: set[str] = set() # journals create_journal made, by remembered name
582
  journals_posted: set[str] = set() # journals post_journal posted, by remembered name
583
  transaction_made: dict[str, tuple[str, str]] = {} # per remembered transaction name: the type and source it was created with
584
+ transactions_imported: set[str] = set() # ... and the names import_receivables_transaction made
585
+ invoice_source: dict[str, str] = {} # per remembered invoice name: the source it came in with (an import's, or a keyed one's)
586
+ invoices_imported: set[str] = set() # the invoices import_payables_invoice made: validate_invoice opens them itself
587
  invoice_made: dict[str, tuple[str, str]] = {} # per remembered invoice name: the type and payment method create_invoice gave it
588
  last_invoice = DOC_KINDS["invoice"][0] # the invoice create_invoice saved last: the one validate_invoice validates
589
  invoices_validated: set[str] = set() # the invoices validate_invoice validated
 
648
  problems.append(f"step {i}: {a} needs {words} created ({creator}) or remembered (remember) earlier as "
649
  f"'{s.name or default}'")
650
  for k, owners in STEP_KEYS.items():
651
+ if getattr(s, k) not in (None, "", []) and a not in owners and a not in STEP_KEYS_OF_PAYMENTS.get(k, ()) and a not in STEP_KEYS_OF_IMPORTS.get(k, ()):
652
  # the owners of the step's own area are named (status on create_invoice: expect_invoice)
653
  mine = [o for o in owners if ACTION_AREA.get(o) == area] or list(owners)
654
  problems.append(f"step {i}: {k} belongs to {' or '.join(mine)}, not {a}")
 
690
  "(a negative one is a credit or debit memo: invoice_type)")
691
  invoice_made[s.name or DOC_KINDS["invoice"][0]] = (kind, (s.payment_method or "").strip())
692
  last_invoice = s.name or DOC_KINDS["invoice"][0]
693
+ invoices_imported.discard(last_invoice)
694
+ invoice_source[last_invoice] = "" # keyed in: the pod's own Manual Invoice Entry
695
  if a == "validate_invoice":
696
  invoices_validated.add(last_invoice)
697
+ if a == "import_payables_invoice":
698
+ name_ = s.name or DOC_KINDS["invoice"][0]
699
+ fig = _figure(s.value if (s.value or "").strip() else "{{tv.amount}}", d.test_values)
700
+ if fig and fig[1] != 1:
701
+ problems.append(f"step {i}: import_payables_invoice amount '{fig[0]}': a standard invoice has a positive amount")
702
+ invoice_made[name_] = ("standard", "")
703
+ if PH_RE.search(s.source or ""):
704
+ invoice_source.pop(name_, None) # a pod value: not known before the run
705
+ else:
706
+ invoice_source[name_] = " ".join((s.source or "External").lower().split())
707
+ invoices_imported.add(name_)
708
+ last_invoice = name_
709
+ opened = True # the steps that follow open the invoice themselves (validate_invoice, find_invoice)
710
+ if a in ("import_payables_invoice", "expect_invoice") and s.source is not None:
711
+ src = s.source.strip()
712
+ if not (PH_RE.search(src) or TRANSACTION_NAME_RE.fullmatch(src)):
713
+ problems.append(f"step {i}: {a} source must be the invoice source's name as the pod writes it (External, Spreadsheet, "
714
+ f"Manual Invoice Entry ...), got '{s.source}'")
715
+ elif a == "expect_invoice" and not PH_RE.search(src):
716
+ name_ = s.name or DOC_KINDS["invoice"][0]
717
+ came = invoice_source.get(name_)
718
+ if came is not None and " ".join(src.lower().split()) != (came or "manual invoice entry"):
719
+ problems.append(f"step {i}: expect_invoice source '{s.source}': the invoice came in as "
720
+ f"{(came or 'manual invoice entry')} ({'import_payables_invoice' if name_ in invoices_imported else 'create_invoice'})")
721
  if a == "expect_invoice":
722
  if s.validation_status and not PH_RE.search(s.validation_status) \
723
  and s.validation_status.strip().lower() not in {x.lower() for x in VALIDATION_STATUSES}:
 
798
  journals_made.add(journal)
799
  if a == "post_journal":
800
  journals_posted.add(journal)
801
+ if a in ("create_transaction", "expect_transaction", "import_receivables_transaction"):
802
+ problems += _transaction_problems(i, s, d.test_values, transaction_made, transactions_imported)
803
  if a in ("create_requisition", "create_purchase_order") and not (s.price or "").strip() \
804
  and not {"price", "amount"} & set(d.test_values):
805
  problems.append(f"step {i}: {a} needs a price: price, or the test value 'price' ({{{{tv.price}}}})")
806
+ if a in ("create_journal", "create_transaction", "create_receipt", *IMPORT_ACTIONS):
807
  if not (s.value or "").strip() and "amount" not in d.test_values:
808
  problems.append(f"step {i}: {a} needs an amount: value, or the test value 'amount' ({{{{tv.amount}}}})")
809
  elif (s.value or "").strip() and not AMOUNT_RE.fullmatch(s.value):
 
876
  if a in ("enter", "expect_filled", "expect_value", "remember", "add_line", "save", "invoice_action", "validate_invoice", "click", "add_row",
877
  "enter_in_row", "menu_action", "expect_results") and not opened:
878
  problems.append(f"step {i}: {a} comes before open_task")
879
+ if a == "validate_invoice" and not invoice_page and last_invoice not in invoices_imported and "Validate" not in sc.actions_menu:
880
  problems.append(f"step {i}: validate_invoice needs Validate in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
881
  if a == "invoice_action" and s.value and s.value not in sc.actions_menu:
882
  problems.append(f"step {i}: '{s.value}' is not in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
coworker/platform/usage.py CHANGED
@@ -81,7 +81,10 @@ USAGE: dict[str, list[dict]] = {
81
  "Payment Request", "Expense Report", "External", "Intercompany"),
82
  {"manual invoice entry": ["create invoice", "manual invoice", "invoice entry"], "spreadsheet": ["spreadsheet", "adfdi"],
83
  "imaging": ["imaging", "scanned invoice"], "ers": ["pay on receipt", "ers"], "b2b xml": ["b2b", "xml invoice"],
84
- "edi gateway": ["edi"], "external": ["fbdi", "invoice import"]}),
 
 
 
85
  _dim("payment_method", "Payment method", ["PaymentMethod", "PaymentMethodCode"], PAY_METHODS, PAY_WORDS),
86
  _dim("approval_status", "Approval status", "ApprovalStatus",
87
  ("Approved", "Initiated", "Required", "Not required", "Rejected", "Manually approved", "Workflow approved", "Withdrawn"),
@@ -156,7 +159,9 @@ USAGE: dict[str, list[dict]] = {
156
  {"invoice": ["invoice"], "credit memo": ["credit memo"], "debit memo": ["debit memo"], "chargeback": ["chargeback"],
157
  "deposit": ["deposit"], "guarantee": ["guarantee"]}),
158
  _dim("transaction_source", "Transaction source", "TransactionSource", ("Manual",),
159
- {"manual": ["transaction entry", "create transaction", "invoice with one line"]}),
 
 
160
  ]},
161
  {"resource": "standardReceipts", "label": "Receipts", "dimensions": [
162
  _dim("receipt_method", "Receipt method", "ReceiptMethod"), # the client's own methods
 
81
  "Payment Request", "Expense Report", "External", "Intercompany"),
82
  {"manual invoice entry": ["create invoice", "manual invoice", "invoice entry"], "spreadsheet": ["spreadsheet", "adfdi"],
83
  "imaging": ["imaging", "scanned invoice"], "ers": ["pay on receipt", "ers"], "b2b xml": ["b2b", "xml invoice"],
84
+ "edi gateway": ["edi"],
85
+ # External is what Payables invoice import (a FBDI file through the ERP Integration service) is made from; a
86
+ # scenario about the Spreadsheet source (ADFdi) or ERS is not about it, and none of these words is theirs
87
+ "external": ["fbdi", "invoice import", "external source", "payables invoice import"]}),
88
  _dim("payment_method", "Payment method", ["PaymentMethod", "PaymentMethodCode"], PAY_METHODS, PAY_WORDS),
89
  _dim("approval_status", "Approval status", "ApprovalStatus",
90
  ("Approved", "Initiated", "Required", "Not required", "Rejected", "Manually approved", "Workflow approved", "Withdrawn"),
 
159
  {"invoice": ["invoice"], "credit memo": ["credit memo"], "debit memo": ["debit memo"], "chargeback": ["chargeback"],
160
  "deposit": ["deposit"], "guarantee": ["guarantee"]}),
161
  _dim("transaction_source", "Transaction source", "TransactionSource", ("Manual",),
162
+ {"manual": ["transaction entry", "create transaction", "invoice with one line"],
163
+ # an import source (AutoInvoice's): only a scenario that imports through AutoInvoice is about it
164
+ "receivables import": ["autoinvoice", "receivables import"]}),
165
  ]},
166
  {"resource": "standardReceipts", "label": "Receipts", "dimensions": [
167
  _dim("receipt_method", "Receipt method", "ReceiptMethod"), # the client's own methods
coworker/tests/test_cov_ar.py CHANGED
@@ -1,8 +1,8 @@
1
  """Receivables scenarios written for the client's real usage (AR-FUS-001..006): transaction type (Invoice, Credit Memo, Debit
2
  Memo), transaction source Manual, receipt state Applied and Unapplied. Each loads as a Fusion scenario, uses only business
3
  actions the runner has, passes the step checks, has its spec, and makes the variants it really creates and checks covered
4
- in the usage coverage. The source "Receivables Import" is an import, not something a screen does: it stays uncovered, and
5
- create_transaction refuses to be asked for it."""
6
  from __future__ import annotations
7
 
8
  import copy
@@ -28,11 +28,11 @@ INTENDED = {
28
  "AR-FUS-004": [("transaction_type", T, "Invoice"), ("state", R, "Applied")],
29
  "AR-FUS-005": [("state", R, "Unapplied")],
30
  "AR-FUS-006": [("transaction_type", T, "Invoice"), ("transaction_source", T, "Manual")],
 
31
  }
32
- # used variants no screen creates: the scenarios must not claim them (an import is a scheduled process; a chargeback and a
33
  # reversal have no action; a type of the pod's own is only covered by a scenario that names it)
34
- NOT_COVERABLE = [("transaction_source", T, "Receivables Import"), ("transaction_type", T, "PA Invoice"),
35
- ("transaction_type", T, "Chargeback"), ("state", R, "Reversed")]
36
 
37
 
38
  def library() -> dict[str, dict]:
 
1
  """Receivables scenarios written for the client's real usage (AR-FUS-001..006): transaction type (Invoice, Credit Memo, Debit
2
  Memo), transaction source Manual, receipt state Applied and Unapplied. Each loads as a Fusion scenario, uses only business
3
  actions the runner has, passes the step checks, has its spec, and makes the variants it really creates and checks covered
4
+ in the usage coverage. The source "Receivables Import" is an import, not something a screen does: create_transaction refuses to be
5
+ asked for it, and only AR-FUS-040 (import_receivables_transaction, tests/test_interfaces.py) covers it."""
6
  from __future__ import annotations
7
 
8
  import copy
 
28
  "AR-FUS-004": [("transaction_type", T, "Invoice"), ("state", R, "Applied")],
29
  "AR-FUS-005": [("state", R, "Unapplied")],
30
  "AR-FUS-006": [("transaction_type", T, "Invoice"), ("transaction_source", T, "Manual")],
31
+ "AR-FUS-040": [("transaction_source", T, "Receivables Import")], # imported through AutoInvoice
32
  }
33
+ # used variants no screen or import creates: the scenarios must not claim them (a chargeback and a
34
  # reversal have no action; a type of the pod's own is only covered by a scenario that names it)
35
+ NOT_COVERABLE = [("transaction_type", T, "PA Invoice"), ("transaction_type", T, "Chargeback"), ("state", R, "Reversed")]
 
36
 
37
 
38
  def library() -> dict[str, dict]:
coworker/tests/test_interfaces.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interface (import) testing: the client's volume that arrives through imports (AutoInvoice "Receivables Import", Payables invoice
2
+ import "External") is tested the way the client's integrations create it. A FBDI file of one tagged test document is uploaded through
3
+ Fusion's ERP Integration REST service by the automation (automation/src/fusion/interfaces.ts, rest.ts, steps.ts).
4
+
5
+ Covered here, without a browser or a pod: the FBDI builders and the call (the TypeScript check script, and the column tables read
6
+ from the source), the step checks of import_payables_invoice and import_receivables_transaction (scenario-only, never in a canary),
7
+ the opt-in (the pod's allow_imports setting: default off, admin only, audited, never on a practice pod; passed to runs as
8
+ FPT_ALLOW_IMPORTS=1 and on both env allow-lists), the egress rule for writes to a pod, the clean-up of an imported document, and
9
+ the usage coverage of the sources External and Receivables Import (and not of Spreadsheet or ERS)."""
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import unittest
17
+
18
+ import yaml
19
+
20
+ from ..adapters import cases as cases_adapter
21
+ from ..adapters import remote_runner
22
+ from ..config import ROOT
23
+ from ..platform import cleanup, left_on_pod, usage
24
+ from ..platform import step_writer as sw
25
+ from ..platform.egress import CLEANUP_PATH, EgressDenied
26
+ from ..platform.pods import PodRegistry
27
+ from .fakes import REST, bearer, make_app
28
+ from .test_ar_business_actions import AR_INV, TestCleanupOfReceivables
29
+ from .test_business_actions import runner_actions, yaml_draft
30
+ from .test_po_gl_business_actions import AP_INV, draft, problems
31
+
32
+ AUTOMATION = ROOT / "automation"
33
+ BIN = AUTOMATION / "node_modules" / ".bin"
34
+ TSX = BIN / "tsx.cmd" if (BIN / "tsx.cmd").exists() else BIN / "tsx"
35
+ FUSION = AUTOMATION / "src" / "fusion"
36
+ INTERFACES_TS = (FUSION / "interfaces.ts").read_text(encoding="utf-8")
37
+ BASE = "https://acme-test.fa.ocs.oraclecloud.com"
38
+ POD = {"name": "Acme test pod", "kind": "fusion", "base_url": BASE, "environment": "test", "modules": ["AP", "AR"]}
39
+ IMPORTS = ("import_payables_invoice", "import_receivables_transaction")
40
+ SCENARIOS = ("AP-FUS-040", "AR-FUS-040")
41
+
42
+
43
+ def columns(name: str) -> list[str]:
44
+ """A FBDI column table of interfaces.ts, in its order."""
45
+ body = INTERFACES_TS.split(f"export const {name} = [", 1)[1].split("] as const;", 1)[0]
46
+ out: list[str] = []
47
+ for part in re.findall(r"'([^']*)'|\.\.\.seq\('([^']*)', (\d+)\)", body):
48
+ out += [part[0]] if part[0] else [f"{part[1]} {i}" for i in range(1, int(part[2]) + 1)]
49
+ return out
50
+
51
+
52
+ class TestFbdiBuilders(unittest.TestCase):
53
+ """The builders are pure TypeScript: scripts/check-interfaces.ts runs them (and has Python's zipfile read the zip back)."""
54
+
55
+ @unittest.skipUnless(shutil.which("node") and TSX.exists(), "tsx is not installed (npm ci in automation/)")
56
+ def test_the_check_script_passes(self):
57
+ r = subprocess.run([str(TSX), "scripts/check-interfaces.ts"], cwd=AUTOMATION, capture_output=True, text=True, timeout=180,
58
+ shell=TSX.suffix == ".cmd")
59
+ self.assertEqual(r.returncode, 0, (r.stdout + r.stderr)[-1500:])
60
+ self.assertIn("interfaces: all checks pass", r.stdout)
61
+
62
+ def test_the_column_order_is_the_templates_for_the_columns_the_test_fills(self):
63
+ header, lines, ar = columns("AP_INVOICE_COLUMNS"), columns("AP_LINE_COLUMNS"), columns("AR_LINE_COLUMNS")
64
+ self.assertEqual(header[:6], ["Invoice ID", "Business Unit", "Source", "Invoice Number", "Invoice Amount", "Invoice Date"])
65
+ self.assertEqual(lines[:4], ["Invoice ID", "Line Number", "Line Type", "Amount"]) # the line is tied to its header by the first column
66
+ self.assertEqual(ar[:3], ["Business Unit Name", "Batch Source Name", "Transaction Type Name"])
67
+ self.assertEqual(ar.index("Transaction Number"), 6)
68
+ self.assertEqual(ar[-15:], [f"Interface Line Attribute {i}" for i in range(1, 16)])
69
+ for table in (header, lines, ar):
70
+ self.assertEqual(len(table), len(set(table)), "a column name twice")
71
+
72
+ def test_every_document_is_tagged_so_clean_up_and_left_on_pod_find_it(self):
73
+ # the AP invoice number and the import set, the AR transaction number, customer order number (REST: PurchaseOrder) and attribute 1
74
+ for text in ("'Invoice Number': nonEmpty('the invoice number', a.tag)", "'Import Set': a.tag", "'Customer Order Number': a.tag",
75
+ "'Interface Line Attribute 1': a.tag"):
76
+ self.assertIn(text, INTERFACES_TS)
77
+ self.assertIn("PurchaseOrder='${q(numberOrTag)}'", (FUSION / "rest.ts").read_text(encoding="utf-8"))
78
+
79
+ def test_the_oracle_specific_assumptions_are_one_table(self):
80
+ for text in ("fin$/payables$/import$", "fin$/receivables$/import$", ",APXIIMPT", ",AutoInvoiceImportEss"):
81
+ self.assertEqual(INTERFACES_TS.count(text), 1, text)
82
+ self.assertEqual(len(re.findall(r"interfaceDetails: \d+,", INTERFACES_TS)), 2) # one per import
83
+ for text in ("fin$/", "APXIIMPT", "AutoInvoiceImportEss"): # and nowhere else in the automation
84
+ for f in ("steps.ts", "ui.ts", "fixtures.ts"):
85
+ self.assertNotIn(text, (FUSION / f).read_text(encoding="utf-8"), (f, text))
86
+
87
+
88
+ class TestRestCallsAreGated(unittest.TestCase):
89
+ REST_TS = (FUSION / "rest.ts").read_text(encoding="utf-8")
90
+
91
+ def test_the_only_write_to_the_erp_integration_service_checks_the_opt_in_and_production(self):
92
+ self.assertEqual(self.REST_TS.count("'erpintegrations'"), 1)
93
+ body = self.REST_TS.split("async importBulkData(", 1)[1].split("\n }\n", 1)[0]
94
+ self.assertLess(body.index("importsAllowed()"), body.index("this.call('POST'"))
95
+ self.assertLess(body.index("looksLikeProduction("), body.index("this.call('POST'"))
96
+ for f in ("steps.ts", "ui.ts", "fixtures.ts", "interfaces.ts"):
97
+ self.assertNotIn("erpintegrations'", (FUSION / f).read_text(encoding="utf-8"), f)
98
+ self.assertIn('if (!importsAllowed())', (FUSION / "steps.ts").read_text(encoding="utf-8")) # the actions refuse first themselves
99
+ self.assertEqual((FUSION / "steps.ts").read_text(encoding="utf-8").count("if (!ctx.rest.available) return importSkipped("), 2) # no REST: skipped
100
+
101
+ def test_the_python_egress_never_posts_to_the_erp_integration_service(self):
102
+ # the runner calls the pod directly: no Python egress is in that path, so FPT_ALLOW_IMPORTS is the gate. The gate in Python stays
103
+ # shut for it: a POST to it is allowed neither to clean up nor, without SEED_ALLOWED=1, to seed
104
+ app, c, svc, pod = make_app()
105
+ path = f"{REST}/erpintegrations"
106
+ for purpose in ("read", "cleanup", "seed"):
107
+ with self.assertRaises(EgressDenied, msg=purpose):
108
+ svc.egress.fusion_request(BASE, "POST", path, auth=("u", "p"), purpose=purpose, json_body={})
109
+ self.assertFalse(svc.cfg.seed_allowed)
110
+
111
+
112
+ class TestAllowedActions(unittest.TestCase):
113
+ def test_each_is_offered_belongs_to_its_area_and_the_runner_has_it(self):
114
+ known = runner_actions()
115
+ for a, area in (("import_payables_invoice", "AP"), ("import_receivables_transaction", "AR")):
116
+ self.assertIn(a, sw.ALLOWED_ACTIONS)
117
+ self.assertIn(a, known)
118
+ self.assertIn(a, sw.BUSINESS_AREAS[area]["actions"])
119
+ self.assertIn(a, sw.SCENARIO_ONLY_ACTIONS)
120
+ self.assertIn(f"{sw.BUSINESS_AREAS[area]['name']} business action", sw.ALLOWED_ACTIONS[a])
121
+ self.assertIn("allow imports", sw.ALLOWED_ACTIONS[a].lower())
122
+ self.assertFalse(re.search(r"\d", sw.ALLOWED_ACTIONS[a]), a) # no figure the leak check could take for data
123
+ self.assertEqual(sw.IMPORT_ACTIONS, IMPORTS)
124
+
125
+ def test_none_is_in_a_canary(self):
126
+ for cid in ("CANARY-AP", "CANARY-AR", "CANARY-GL", "CANARY-PO"):
127
+ acts = {s["action"] for s in yaml.safe_load((sw.CASES_DIR / f"{cid}.yaml").read_text(encoding="utf-8"))["steps"]}
128
+ self.assertFalse(acts & set(IMPORTS), cid)
129
+
130
+ def test_a_draft_keeps_the_import_steps_fields(self):
131
+ d = draft([{"action": "import_payables_invoice", "source": "External", "name": "inv"},
132
+ {"action": "import_receivables_transaction", "transaction_source": "Receivables Import", "transaction_type": "Invoice"}])
133
+ steps = yaml.safe_load(sw.to_case_yaml({"title": "t", "type": "happy", "task": AP_INV["task"]}, d, "AP-AI-001"))["steps"]
134
+ self.assertEqual((steps[1]["source"], steps[1]["name"]), ("External", "inv"))
135
+ self.assertEqual((steps[2]["transaction_source"], steps[2]["transaction_type"]), ("Receivables Import", "Invoice"))
136
+
137
+
138
+ class TestStepChecks(unittest.TestCase):
139
+ def ap(self, *steps, **over):
140
+ return problems(draft([*steps], **over), AP_INV)
141
+
142
+ def ar(self, *steps, **over):
143
+ return problems(draft([*steps], **over), AR_INV)
144
+
145
+ def test_an_imported_invoice_is_checked_validated_and_checked_again_without_a_screen_before_it(self):
146
+ self.assertEqual(self.ap({"action": "import_payables_invoice", "source": "External"}, {"action": "expect_invoice", "source": "external"},
147
+ {"action": "validate_invoice"}, {"action": "expect_invoice", "status": "Validated", "source": "External"}), "")
148
+ self.assertEqual(self.ap({"action": "import_payables_invoice", "name": "imp"}, {"action": "expect_invoice", "name": "imp", "source": "{{tv.s}}"},
149
+ test_values={"amount": "5", "s": "External"}), "") # a placeholder is a pod value: not compared
150
+
151
+ def test_an_imported_transaction_may_be_checked_for_its_import_source_a_keyed_one_may_not(self):
152
+ self.assertEqual(self.ar({"action": "import_receivables_transaction", "transaction_source": "Receivables Import", "transaction_type": "Invoice"},
153
+ {"action": "find_transaction"}, {"action": "expect_transaction", "transaction_source": "receivables import",
154
+ "transaction_type": "invoice", "amount_at_least": "{{tv.amount}}"}), "")
155
+ p = self.ar({"action": "create_transaction", "transaction_source": "Receivables Import"})
156
+ self.assertIn("an import is a scheduled process", p)
157
+ self.assertIn("make it with import_receivables_transaction", p)
158
+ p = self.ar({"action": "create_transaction"}, {"action": "expect_transaction", "transaction_source": "AutoInvoice"})
159
+ self.assertIn("the transaction was not imported", p)
160
+
161
+ def test_the_source_must_be_the_one_it_came_in_with(self):
162
+ self.assertIn("the invoice came in as external (import_payables_invoice)",
163
+ self.ap({"action": "import_payables_invoice"}, {"action": "expect_invoice", "source": "Spreadsheet"}))
164
+ self.assertIn("the invoice came in as manual invoice entry (create_invoice)",
165
+ self.ap({"action": "create_invoice"}, {"action": "expect_invoice", "source": "External"}))
166
+ self.assertEqual(self.ap({"action": "create_invoice"}, {"action": "expect_invoice", "source": "Manual Invoice Entry"}), "")
167
+ self.assertIn("transaction_source 'Other': the transaction was created from receivables import",
168
+ self.ar({"action": "import_receivables_transaction", "transaction_source": "Receivables Import"},
169
+ {"action": "expect_transaction", "transaction_source": "Other"}))
170
+ self.assertIn("source must be the invoice source's name", self.ap({"action": "import_payables_invoice", "source": "5; drop"}))
171
+
172
+ def test_the_amount_manual_and_the_fields_are_checked(self):
173
+ self.assertIn("a standard invoice has a positive amount", self.ap({"action": "import_payables_invoice", "value": "-5"}))
174
+ self.assertIn("a standard invoice has a positive amount", self.ap({"action": "import_payables_invoice"}, test_values={"amount": "-5"}))
175
+ self.assertIn("needs an amount", self.ap({"action": "import_payables_invoice"}, test_values={}))
176
+ self.assertIn("needs an amount", self.ar({"action": "import_receivables_transaction"}, test_values={}))
177
+ self.assertIn("'Manual': Manual is the source of a transaction keyed in",
178
+ self.ar({"action": "import_receivables_transaction", "transaction_source": "Manual"}))
179
+ self.assertIn("a credit memo is entered with a negative amount",
180
+ self.ar({"action": "import_receivables_transaction", "transaction_type": "Credit Memo", "value": "5"}))
181
+ # the fields belong to their actions, and the journal source stays Manual
182
+ self.assertIn("transaction_source belongs to", self.ar({"action": "find_transaction", "transaction_source": "Manual"}))
183
+ self.assertIn("source belongs to create_journal or expect_journal, not validate_invoice", self.ap({"action": "validate_invoice", "source": "External"}))
184
+ self.assertIn("a person enters only Manual journals", problems(draft([{"action": "create_journal", "source": "Payables"}]), {
185
+ "task": "General Accounting > Journals > Create Journal", "fields": [{"label": "Journal Batch", "kind": "text"}], "buttons": [], "menus": {},
186
+ "sections": [], "tables": {}}))
187
+
188
+ def test_an_import_belongs_to_its_areas_screens(self):
189
+ self.assertIn("import_receivables_transaction is a Receivables business action and this scenario is not on a Receivables screen",
190
+ self.ap({"action": "import_receivables_transaction"}))
191
+ self.assertIn("import_payables_invoice is a Payables business action and this scenario is not on a Payables screen",
192
+ self.ar({"action": "import_payables_invoice"}))
193
+
194
+ def test_an_expectation_needs_the_document_an_import_made(self):
195
+ self.assertIn("expect_invoice needs an invoice created (create_invoice) or remembered", self.ap({"action": "expect_invoice", "source": "External"}))
196
+ self.assertIn("expect_transaction needs a transaction created", self.ar({"action": "expect_transaction", "transaction_source": "Receivables Import"}))
197
+ self.assertIn("needs an invoice created", self.ap({"action": "import_payables_invoice", "name": "a"}, {"action": "expect_invoice", "name": "b"}))
198
+
199
+
200
+ class TestScenarios(unittest.TestCase):
201
+ def test_each_loads_as_a_fusion_scenario_passes_the_checks_and_has_its_spec(self):
202
+ lib = {c["id"]: c for c in cases_adapter.load_cases()}
203
+ known = runner_actions()
204
+ for cid, module, inv in (("AP-FUS-040", "AP", AP_INV), ("AR-FUS-040", "AR", AR_INV)):
205
+ self.assertIn(cid, lib)
206
+ self.assertEqual((lib[cid]["target"], lib[cid]["module"]), ("fusion", module), cid)
207
+ d = yaml_draft(cid)
208
+ acts = {s["action"] for s in d["steps"]}
209
+ self.assertTrue(acts <= set(sw.ALLOWED_ACTIONS) and acts <= known, (cid, acts))
210
+ self.assertEqual(sw.check_steps(d, inv), [], cid)
211
+ doc = yaml.safe_load((sw.CASES_DIR / f"{cid}.yaml").read_text(encoding="utf-8"))
212
+ self.assertEqual(doc["runner"], "steps")
213
+ self.assertFalse(doc.get("canary"))
214
+ entry = (ROOT / "automation" / "tests" / "fusion" / "steps" / f"{cid}.spec.ts").read_text(encoding="utf-8")
215
+ self.assertIn(f"stepsTest('{cid}', ['@{cid}','@{module}'", entry)
216
+ self.assertIn("allow", " ".join(doc["preconditions"]).lower()) # the precondition says imports must be allowed
217
+
218
+ def test_they_do_what_their_titles_say(self):
219
+ ap = yaml_draft("AP-FUS-040")["steps"]
220
+ self.assertEqual([s["action"] for s in ap][1:], ["import_payables_invoice", "expect_invoice", "validate_invoice", "expect_invoice"])
221
+ self.assertEqual((ap[1]["source"], ap[2]["source"], ap[4]["source"], ap[4]["status"]), ("External", "External", "External", "Validated"))
222
+ ar = yaml_draft("AR-FUS-040")["steps"]
223
+ self.assertEqual([s["action"] for s in ar][1:], ["import_receivables_transaction", "find_transaction", "expect_transaction"])
224
+ self.assertEqual((ar[1]["transaction_source"], ar[3]["transaction_source"], ar[1]["transaction_type"], ar[3]["transaction_type"]),
225
+ ("Receivables Import",) * 2 + ("Invoice",) * 2)
226
+ for cid in SCENARIOS:
227
+ self.assertIn("never in\n# a canary", (sw.CASES_DIR / f"{cid}.yaml").read_text(encoding="utf-8").replace("\r\n", "\n"))
228
+
229
+
230
+ def profile() -> dict:
231
+ """A profile in which the sources of both areas are used (counts are small samples of a client's records)."""
232
+ def dims(code: str, values_by_dim: dict[tuple[str, str], list[str]]) -> dict:
233
+ out = []
234
+ for (resource, key), values in values_by_dim.items():
235
+ spec = next(s for s in usage.USAGE[code] if s["resource"] == resource)
236
+ d = next(x for x in spec["dimensions"] if x["key"] == key)
237
+ field = d["field"] if isinstance(d["field"], str) else d["field"][0]
238
+ out.append(usage.count_dimension(d, [{field: v} for v in values for _ in range(10)], resource))
239
+ return out
240
+ return {"read_at": "2026-11-21T00:00:00Z", "days": 90, "since": "2026-08-23", "areas": [
241
+ {"code": "AP", "name": "Payables", "status": "read", "resources": [{"resource": "invoices", "status": "read", "total": 100}],
242
+ "dimensions": dims("AP", {("invoices", "source"): ["Manual Invoice Entry", "External", "Spreadsheet", "ERS"]})},
243
+ {"code": "AR", "name": "Receivables", "status": "read", "resources": [{"resource": "receivablesInvoices", "status": "read", "total": 100}],
244
+ "dimensions": dims("AR", {("receivablesInvoices", "transaction_source"): ["Manual", "Receivables Import"]})}]}
245
+
246
+
247
+ class TestUsageCoverage(unittest.TestCase):
248
+ def setUp(self):
249
+ self.lib = list(cases_adapter.load_cases())
250
+ self.by = {(v["area"], v["value"]): v for v in usage.coverage(profile(), self.lib)["variants"]}
251
+
252
+ def ids(self, area: str, value: str) -> set[str]:
253
+ return {m["id"] for m in self.by[(area, value)]["matches"]}
254
+
255
+ def test_external_and_receivables_import_are_covered_by_their_import_scenarios(self):
256
+ for area, value, cid in (("AP", "External", "AP-FUS-040"), ("AR", "Receivables Import", "AR-FUS-040")):
257
+ self.assertEqual(self.by[(area, value)]["status"], "covered", value)
258
+ self.assertIn(cid, self.ids(area, value))
259
+
260
+ def test_the_other_sources_are_not_claimed_by_them(self):
261
+ # Spreadsheet (ADFdi) and ERS are other ways in: the Payables import scenario is not about them
262
+ for value in ("Spreadsheet", "ERS"):
263
+ self.assertNotIn("AP-FUS-040", self.ids("AP", value), value)
264
+ self.assertNotEqual(self.by[("AP", value)]["status"], "covered", value)
265
+ # keyed in on a screen is not an import, and an import is not keyed in
266
+ self.assertNotIn("AP-FUS-040", self.ids("AP", "Manual Invoice Entry"))
267
+ self.assertNotIn("AR-FUS-040", self.ids("AR", "Manual"))
268
+ self.assertNotIn("AP-FUS-012", self.ids("AP", "External"))
269
+ self.assertTrue(not ({"AR-FUS-001", "AR-FUS-002", "AR-FUS-003", "AR-FUS-004", "AR-FUS-006"} & self.ids("AR", "Receivables Import")))
270
+
271
+
272
+ class TestAllowImportsSetting(unittest.TestCase):
273
+ def setUp(self):
274
+ self.app, self.c, self.svc, self.pod = make_app()
275
+ self.h = {r: bearer(self.c, r) for r in ("viewer", "consultant", "admin")}
276
+ r = self.c.post("/api/pods", json=POD, headers=self.h["admin"])
277
+ self.assertEqual(r.status_code, 201, r.text)
278
+ self.row = r.json()
279
+ self.pid = self.row["id"]
280
+ self.c.post(f"/api/pods/{self.pid}/credentials", json={"module": "AP", "username": "zz.ap", "password": "pw-imports-test-1"}, headers=self.h["admin"])
281
+ self.reg = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit)
282
+
283
+ def patch(self, body, who="admin", pid=None):
284
+ return self.c.patch(f"/api/pods/{pid or self.pid}", json=body, headers=self.h[who])
285
+
286
+ def audit(self, kind):
287
+ rows = self.c.get("/api/audit?limit=500", headers=self.h["admin"]).json()
288
+ return [a for a in (rows["items"] if isinstance(rows, dict) else rows) if a["kind"] == kind]
289
+
290
+ def test_it_is_off_by_default_and_the_run_is_not_told_otherwise(self):
291
+ self.assertIs(self.row["allow_imports"], False)
292
+ self.assertNotIn("FPT_ALLOW_IMPORTS", self.reg.executor_env(self.pid))
293
+ self.assertFalse(self.reg.get(self.pid)["allow_imports"])
294
+
295
+ def test_an_admin_switches_it_on_and_off_and_the_runs_follow(self):
296
+ r = self.patch({"allow_imports": True})
297
+ self.assertEqual(r.status_code, 200, r.text)
298
+ self.assertIs(r.json()["allow_imports"], True)
299
+ self.assertEqual(self.reg.executor_env(self.pid)["FPT_ALLOW_IMPORTS"], "1")
300
+ self.assertIs(next(p for p in self.c.get("/api/pods", headers=self.h["viewer"]).json() if p["id"] == self.pid)["allow_imports"], True)
301
+ self.patch({"notes": "another change"}) # an unrelated change keeps it
302
+ self.assertEqual(self.reg.executor_env(self.pid)["FPT_ALLOW_IMPORTS"], "1")
303
+ self.assertIs(self.patch({"allow_imports": False}).json()["allow_imports"], False)
304
+ self.assertNotIn("FPT_ALLOW_IMPORTS", self.reg.executor_env(self.pid))
305
+
306
+ def test_only_an_admin_may_and_a_refusal_changes_nothing(self):
307
+ for who in ("viewer", "consultant"):
308
+ self.assertEqual(self.patch({"allow_imports": True}, who).status_code, 403, who)
309
+ self.assertEqual(self.c.patch(f"/api/pods/{self.pid}", json={"allow_imports": True}).status_code, 401)
310
+ self.assertFalse(self.reg.get(self.pid)["allow_imports"])
311
+ self.assertEqual(self.audit("pod.imports_allowed"), [])
312
+
313
+ def test_each_change_is_audited_with_who_and_a_repeat_is_not(self):
314
+ self.patch({"allow_imports": True})
315
+ self.patch({"allow_imports": True}) # no change
316
+ self.patch({"allow_imports": False})
317
+ on, off = self.audit("pod.imports_allowed"), self.audit("pod.imports_refused")
318
+ self.assertEqual((len(on), len(off)), (1, 1))
319
+ self.assertEqual((on[0]["actor"], off[0]["actor"]), ("admin", "admin"))
320
+ self.assertIn(f"pod {self.pid}", on[0]["summary"])
321
+ self.assertIs(on[0]["payload"]["allow_imports"], True)
322
+ self.assertIs(off[0]["payload"]["allow_imports"], False)
323
+
324
+ def test_the_practice_pod_has_no_erp_integration_service(self):
325
+ mock = next(p for p in self.c.get("/api/pods", headers=self.h["viewer"]).json() if p["kind"] == "mock")
326
+ r = self.patch({"allow_imports": True}, pid=mock["id"])
327
+ self.assertEqual((r.status_code, r.json()["code"]), (422, "BAD_ALLOW_IMPORTS"), r.text)
328
+ self.assertFalse(self.reg.get(mock["id"])["allow_imports"])
329
+ self.assertIsNone(self.reg.executor_env(mock["id"]))
330
+
331
+ def test_a_production_pod_cannot_exist_so_it_never_gets_the_flag(self):
332
+ r = self.c.post("/api/pods", json={**POD, "name": "Prod pod", "base_url": "https://acme-prod.fa.ocs.oraclecloud.com"}, headers=self.h["admin"])
333
+ self.assertEqual((r.status_code, r.json()["code"]), (422, "PROD_REFUSED"))
334
+ r = self.patch({"base_url": "https://acme-prod.fa.ocs.oraclecloud.com", "allow_imports": True}) # nor by editing a test pod into one
335
+ self.assertEqual((r.status_code, r.json()["code"]), (422, "PROD_REFUSED"))
336
+ self.assertFalse(self.reg.get(self.pid)["allow_imports"])
337
+
338
+ def test_the_flag_reaches_a_runner_only_through_both_allow_lists_and_not_from_the_servers_own_environment(self):
339
+ self.assertIn("FPT_ALLOW_IMPORTS", remote_runner.ENV_KEYS)
340
+ server = (ROOT / "automation" / "remote_runner" / "server.py").read_text(encoding="utf-8")
341
+ self.assertRegex(server, r'ENV_KEYS = \{[^}]*"FPT_ALLOW_IMPORTS"')
342
+ self.assertRegex(server, r'os\.environ\.items\(\) if k not in \("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE", "FPT_ALLOW_IMPORTS"\)')
343
+ local = (ROOT / "coworker" / "adapters" / "playwright.py").read_text(encoding="utf-8")
344
+ self.assertIn('env.pop("FPT_ALLOW_IMPORTS", None)', local)
345
+ self.assertIn('if "FPT_ALLOW_IMPORTS" not in (cred_env or {})', local)
346
+
347
+
348
+ class TestCleanUpOfImportedDocuments(unittest.TestCase):
349
+ """An imported AR transaction is numbered by Fusion when its source numbers automatically: it is found by the tag in its customer
350
+ order number (REST: PurchaseOrder), and a completed one is listed for a person to credit like a screen one."""
351
+
352
+ def setUp(self):
353
+ t = TestCleanupOfReceivables()
354
+ t.setUp()
355
+ self.t = t
356
+ self.pod, self.svc, self.dir, self.rid = t.pod, t.svc, t.dir, t.rid
357
+
358
+ def sweep(self, *records) -> dict:
359
+ with (self.dir / cleanup.LEDGER).open("w", encoding="utf-8") as fh:
360
+ for r in records:
361
+ fh.write(json.dumps({"test": "Import a transaction", **r}) + "\n")
362
+ return cleanup.sweep(self.svc, self.rid, "cancelled")
363
+
364
+ def test_a_complete_imported_transaction_is_listed_for_a_person_and_an_incomplete_one_is_deleted(self):
365
+ self.pod.txns = {61: {"CustomerTransactionId": 61, "TransactionNumber": "AUTO-9001", "PurchaseOrder": "FPT-ARFUS040-1", "InvoiceStatus": "Complete"},
366
+ 62: {"CustomerTransactionId": 62, "TransactionNumber": "AUTO-9002", "PurchaseOrder": "FPT-ARFUS040-2", "InvoiceStatus": "Incomplete"}}
367
+ out = self.sweep({"kind": "ar_transaction", "number": "FPT-ARFUS040-1"}, {"kind": "ar_transaction", "number": "FPT-ARFUS040-2"},
368
+ {"kind": "ar_transaction", "number": "FPT-ARFUS040-3"})
369
+ left = {x["number"]: x["why"] for x in out["left"]}
370
+ self.assertIn("transaction AUTO-9001 is complete", left["FPT-ARFUS040-1"])
371
+ self.assertIn("credit it on Manage Transactions", left["FPT-ARFUS040-1"])
372
+ done = {x["number"]: x["result"] for x in out["cleaned"]}
373
+ self.assertIn("AUTO-9002 deleted", done["FPT-ARFUS040-2"])
374
+ self.assertEqual(done["FPT-ARFUS040-3"], "not saved, nothing to clean up")
375
+ self.assertEqual(self.pod.writes, [("DELETE", f"{REST}/receivablesInvoices/62")])
376
+
377
+ def test_it_lands_in_the_left_on_pod_ledger_and_is_looked_at_again_by_the_tag(self):
378
+ self.pod.txns = {61: {"CustomerTransactionId": 61, "TransactionNumber": "AUTO-9001", "PurchaseOrder": "FPT-ARFUS040-1", "InvoiceStatus": "Complete"}}
379
+ self.sweep({"kind": "ar_transaction", "number": "FPT-ARFUS040-1"})
380
+ left_on_pod.record(self.svc, self.rid)
381
+ row = self.svc.db.one("SELECT * FROM left_on_pod WHERE reference=?", ("FPT-ARFUS040-1",))
382
+ self.assertEqual((row["kind"], row["status"]), ("ar_transaction", "open"))
383
+ self.assertIn("Credit Transaction", row["todo"])
384
+ self.assertEqual(left_on_pod.recheck(self.svc, row["id"])["check_state"], "still_on_pod")
385
+ self.assertEqual(self.pod.writes, []) # looking again changes nothing
386
+
387
+ def test_an_imported_ap_invoice_is_cancelled_like_a_screen_one(self):
388
+ self.assertIn("ap_invoice", left_on_pod.KINDS)
389
+ self.assertTrue(CLEANUP_PATH.fullmatch(f"{REST}/invoices/action/cancelInvoice"))
390
+ # steps.ts registers it with the same track() as create_invoice: the ledger and the fixture cancel it
391
+ steps = (FUSION / "steps.ts").read_text(encoding="utf-8")
392
+ body = steps.split("import_payables_invoice: async", 1)[1].split("import_receivables_transaction: async", 1)[0]
393
+ self.assertIn("ctx.track(testNumber(", body)
394
+ self.assertLess(body.index("ctx.track(testNumber("), body.index("ctx.rest.importBulkData(")) # registered before the upload
395
+ body_ar = steps.split("import_receivables_transaction: async", 1)[1].split("// General Ledger business actions", 1)[0]
396
+ self.assertLess(body_ar.index("ctx.docs.track('ar_transaction'"), body_ar.index("ctx.rest.importBulkData("))
397
+
398
+
399
+ if __name__ == "__main__":
400
+ unittest.main()
tests/cases/AP-FUS-040.yaml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Oracle Fusion Payables test case written as plain steps (runner: steps): no hand-written code. An interface test: the invoice is not keyed in on
2
+ # a screen but imported the way the client's integrations create invoices (source External): a FBDI file of one standard invoice is uploaded through
3
+ # Fusion's ERP Integration REST service and Payables invoice import is run (automation/src/fusion/steps.ts import_payables_invoice), then the
4
+ # imported invoice is checked through Fusion REST and validated on the screens like any other. import_payables_invoice is a scenario's own (never in
5
+ # a canary): it writes through the ERP Integration service, so the pod must allow imports (Test environments page) and it needs Fusion REST; on a pod
6
+ # without either it fails saying so, or is skipped with a note (assisted sign-in). The clean-up cancels the test invoice (pass or fail).
7
+ # Written for a usage gap of the client's pod (invoice source External).
8
+ id: AP-FUS-040
9
+ title: "Invoice imported through Payables invoice import (External source) is created and validated (step runner)"
10
+ runner: steps
11
+ process: Invoice import
12
+ priority: P2
13
+ priority_rationale: "A share of the client's invoices arrives through Payables invoice import with the source External; the imported invoice must be created with that source and validate like a keyed one."
14
+ map_ids: []
15
+ verification: VERIFIED on a real Fusion pod when its run passes
16
+ approval_status: draft - pending consultant approval (architecture approval gate)
17
+ type: happy
18
+ tags:
19
+ - payables
20
+ - invoice-import
21
+ - external-source
22
+ - interface
23
+ - fbdi
24
+ - fusion
25
+ - step-runner
26
+ roles:
27
+ - payables_user
28
+ preconditions:
29
+ - "The pod allows imports (Allow imports on the Test environments page) and the test user may run Payables invoice import and read invoices through Fusion REST."
30
+ - "The invoice source External is set up on the pod."
31
+ - "The Payables test data (business unit, supplier, site, account, currency) is one the user may import invoices for."
32
+ data_recipes: []
33
+ test_values:
34
+ amount: "100"
35
+ steps:
36
+ - n: 1
37
+ action: sign_in
38
+ expected: "The Fusion home page opens for the test user."
39
+ - n: 2
40
+ action: import_payables_invoice
41
+ value: "{{tv.amount}}"
42
+ source: "External"
43
+ expected: "A FBDI file of one standard invoice of 100 with one Item line is uploaded and Payables invoice import finishes; the invoice is in Fusion."
44
+ - n: 3
45
+ action: expect_invoice
46
+ source: "External"
47
+ canceled: false
48
+ amount_at_least: "{{tv.amount}}"
49
+ expected: "Fusion has the invoice with source External, not cancelled, for at least the line amount."
50
+ - n: 4
51
+ action: validate_invoice
52
+ expected: "The invoice is opened from Manage Invoices and validated (nothing to do when the import already validated it)."
53
+ - n: 5
54
+ action: expect_invoice
55
+ status: Validated
56
+ source: "External"
57
+ amount_at_least: "{{tv.amount}}"
58
+ expected: "Fusion has the imported invoice as Validated, still with source External."
59
+ expected_result: "The invoice imported through Payables invoice import is in Fusion with source External and validates; the clean-up cancels the test invoice afterwards."
tests/cases/AR-FUS-040.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Oracle Fusion Receivables test case written as plain steps (runner: steps): no hand-written code. An interface test: the transaction is not keyed
2
+ # in on a screen but imported the way the client's integrations create them (source Receivables Import): a FBDI file of one invoice line is uploaded
3
+ # through Fusion's ERP Integration REST service and AutoInvoice is run (automation/src/fusion/steps.ts import_receivables_transaction), then the
4
+ # imported transaction is found on Manage Transactions and checked through Fusion REST. import_receivables_transaction is a scenario's own (never in
5
+ # a canary): it writes through the ERP Integration service, so the pod must allow imports (Test environments page) and it needs Fusion REST; on a pod
6
+ # without either it fails saying so, or is skipped with a note (assisted sign-in). AutoInvoice usually completes the transaction: clean-up deletes it
7
+ # while it is Incomplete, a completed one is listed in the run's test data for a person to credit.
8
+ # Written for a usage gap of the client's pod (transaction source Receivables Import).
9
+ id: AR-FUS-040
10
+ title: "Transaction imported through AutoInvoice (Receivables Import source) is created and found (step runner)"
11
+ runner: steps
12
+ process: Transaction import
13
+ priority: P2
14
+ priority_rationale: "Most of the client's transactions arrive through AutoInvoice with the source Receivables Import; an imported invoice must be created with that source and be found like a keyed one."
15
+ map_ids: []
16
+ verification: VERIFIED on a real Fusion pod when its run passes
17
+ approval_status: draft - pending consultant approval (architecture approval gate)
18
+ type: happy
19
+ tags:
20
+ - receivables
21
+ - transaction-import
22
+ - autoinvoice
23
+ - interface
24
+ - fbdi
25
+ - fusion
26
+ - step-runner
27
+ roles:
28
+ - accounts_receivable_specialist
29
+ preconditions:
30
+ - "The pod allows imports (Allow imports on the Test environments page) and the test user may run AutoInvoice and read transactions through Fusion REST."
31
+ - "The transaction source Receivables Import (an Imported-type source) and the transaction type Invoice are set up on the pod."
32
+ - "The Receivables test data (business unit, customer, currency) is one the user may import transactions for."
33
+ data_recipes: []
34
+ test_values:
35
+ amount: "100"
36
+ steps:
37
+ - n: 1
38
+ action: sign_in
39
+ expected: "The Fusion home page opens for the test user."
40
+ - n: 2
41
+ action: import_receivables_transaction
42
+ value: "{{tv.amount}}"
43
+ transaction_type: "Invoice"
44
+ transaction_source: "Receivables Import"
45
+ expected: "A FBDI file of one invoice line is uploaded and AutoInvoice finishes; the transaction is in Fusion."
46
+ - n: 3
47
+ action: find_transaction
48
+ expected: "Manage Transactions finds exactly this transaction by its number."
49
+ - n: 4
50
+ action: expect_transaction
51
+ transaction_type: "Invoice"
52
+ transaction_source: "Receivables Import"
53
+ amount_at_least: "{{tv.amount}}"
54
+ expected: "Fusion has the transaction as an Invoice from source Receivables Import, for at least the line amount."
55
+ expected_result: "The invoice imported through AutoInvoice is in Fusion with source Receivables Import and is found on Manage Transactions; the clean-up deletes it while it is Incomplete, a completed one is listed in the run's test data for a person to credit."
web/src/api/openapi.json CHANGED
@@ -2594,6 +2594,11 @@
2594
  },
2595
  "PodRow": {
2596
  "properties": {
 
 
 
 
 
2597
  "base_url": {
2598
  "title": "Base Url",
2599
  "type": "string"
@@ -2916,6 +2921,17 @@
2916
  "PodUpdate": {
2917
  "additionalProperties": false,
2918
  "properties": {
 
 
 
 
 
 
 
 
 
 
 
2919
  "base_url": {
2920
  "anyOf": [
2921
  {
@@ -9565,7 +9581,7 @@
9565
  "schema": {
9566
  "anyOf": [
9567
  {
9568
- "pattern": "^(ap_invoice|po_requisition|po_order|po_receipt|gl_journal|ar_transaction|ar_receipt)$",
9569
  "type": "string"
9570
  },
9571
  {
 
2594
  },
2595
  "PodRow": {
2596
  "properties": {
2597
+ "allow_imports": {
2598
+ "default": false,
2599
+ "title": "Allow Imports",
2600
+ "type": "boolean"
2601
+ },
2602
  "base_url": {
2603
  "title": "Base Url",
2604
  "type": "string"
 
2921
  "PodUpdate": {
2922
  "additionalProperties": false,
2923
  "properties": {
2924
+ "allow_imports": {
2925
+ "anyOf": [
2926
+ {
2927
+ "type": "boolean"
2928
+ },
2929
+ {
2930
+ "type": "null"
2931
+ }
2932
+ ],
2933
+ "title": "Allow Imports"
2934
+ },
2935
  "base_url": {
2936
  "anyOf": [
2937
  {
 
9581
  "schema": {
9582
  "anyOf": [
9583
  {
9584
+ "pattern": "^(ap_invoice|ap_payment|ap_approval|po_requisition|po_order|po_receipt|gl_journal|ar_transaction|ar_receipt)$",
9585
  "type": "string"
9586
  },
9587
  {
web/src/api/schema.d.ts CHANGED
@@ -3965,6 +3965,12 @@ export interface components {
3965
  };
3966
  /** PodRow */
3967
  PodRow: {
 
 
 
 
 
 
3968
  /** Base Url */
3969
  base_url: string;
3970
  /** Created By */
@@ -4074,6 +4080,11 @@ export interface components {
4074
  };
4075
  /** PodUpdate */
4076
  PodUpdate: {
 
 
 
 
 
4077
  /** Base Url */
4078
  base_url?: string | null;
4079
  /** Enabled */
 
3965
  };
3966
  /** PodRow */
3967
  PodRow: {
3968
+ /**
3969
+ * Allow Imports
3970
+ * @description runs may import test data (FBDI files: Payables invoice import, AutoInvoice); off until an admin agrees
3971
+ * @default false
3972
+ */
3973
+ allow_imports: boolean;
3974
  /** Base Url */
3975
  base_url: string;
3976
  /** Created By */
 
4080
  };
4081
  /** PodUpdate */
4082
  PodUpdate: {
4083
+ /**
4084
+ * Allow Imports
4085
+ * @description true: runs may import test data through the pod's ERP Integration service (admin; never production)
4086
+ */
4087
+ allow_imports?: boolean | null;
4088
  /** Base Url */
4089
  base_url?: string | null;
4090
  /** Enabled */
web/src/pages/setup/PodsPage.tsx CHANGED
@@ -455,6 +455,11 @@ function PodCard({ p, onCreds, onTestData }: { p: Pod; onCreds: (p: Pod) => void
455
  {can('admin') && !p.is_default && (
456
  <Switch label="Enabled" checked={p.enabled} onChange={(e) => m.update.mutate({ id: p.id, body: { enabled: e.currentTarget.checked } })} />
457
  )}
 
 
 
 
 
458
  </Group>
459
  </div>
460
  );
 
455
  {can('admin') && !p.is_default && (
456
  <Switch label="Enabled" checked={p.enabled} onChange={(e) => m.update.mutate({ id: p.id, body: { enabled: e.currentTarget.checked } })} />
457
  )}
458
+ {can('admin') && fusion && (
459
+ <Switch label="Allow imports" checked={p.allow_imports} data-testid={`pod-allow-imports-${p.id}`}
460
+ description="Interface tests write test data through Fusion's import services (Payables invoice import, AutoInvoice). Off until you agree."
461
+ onChange={(e) => m.update.mutate({ id: p.id, body: { allow_imports: e.currentTarget.checked } })} />
462
+ )}
463
  </Group>
464
  </div>
465
  );