EnergyVenom commited on
Commit
c5588b3
·
verified ·
1 Parent(s): 55ac80e

Astra 7ee368b: 26D journal lines, faster work area navigation, prepayment, paid suppliers for payments, per-step time limits, payment method coverage (7ee368b19339)

Browse files
automation/src/fusion/steps.ts CHANGED
@@ -154,6 +154,17 @@ const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chos
154
  /** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */
155
  const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } };
156
 
 
 
 
 
 
 
 
 
 
 
 
157
  const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200);
158
 
159
  /** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an
@@ -367,8 +378,9 @@ const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {
367
  if (wrong.length) throw new Error(`create_invoice invoice_type "${invoiceType || 'Standard'}": ${wrong.join('; ')}`);
368
  if (ctx.c.canary) return createWithDataSets(ctx, { amount, lines, name: s.name || 'invoice_number', invoiceType, paymentMethod });
369
  const number = ctx.track(testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, '')));
370
- const got = await ctx.ui.createInvoice({ businessUnit: apChoices(ctx, 'business_unit'), supplier: apChoices(ctx, 'supplier'), number, amount,
371
- lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: apSites(ctx), invoiceType, paymentMethod });
 
372
  ctx.chosen['ap.business_unit'] = got.businessUnit;
373
  ctx.chosen['ap.supplier'] = got.supplier;
374
  ctx.saved[s.name || 'invoice_number'] = number;
@@ -904,11 +916,18 @@ async function runStep(s: Step, ctx: Ctx) {
904
  await (fn as (...a: unknown[]) => Promise<void>).apply(ctx.ui, block.args(s, ctx));
905
  }
906
 
 
 
 
 
 
 
907
  /** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts, or
908
  * from a staged draft's entry (opts.dir = the staging folder holding its YAML). */
909
  export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {
910
  const c = loadStepCase(id, opts.dir);
911
  test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices, fusionDocs }) => {
 
912
  const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, imported: new Set(), chosen: {}, orderTags: {}, rest: apInvoices.rest, docs: fusionDocs };
913
  for (const [i, s] of c.steps.entries()) {
914
  const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;
 
154
  /** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */
155
  const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } };
156
 
157
+ /** A scenario that pays its invoice: the suppliers the pod pays (paid_supplier, from its paid invoices) come first, then
158
+ * the usual ones. The latest invoices' supplier can carry a payment hold, and Fusion then refuses Pay in Full (seen live). */
159
+ const pays = (ctx: Ctx) => ctx.c.steps.some((s) => s.action === 'create_payment');
160
+ const paidFirst = (ctx: Ctx, paid: string, usual: () => string[]): string[] => {
161
+ let first: string[] = [];
162
+ if (pays(ctx) && !ctx.chosen[`ap.${paid.replace('paid_', '')}`]) { try { first = podCandidates('ap', paid); } catch { /* not discovered yet */ } }
163
+ let rest: string[] = [];
164
+ try { rest = usual(); } catch (e) { if (!first.length) throw e; }
165
+ return [...first, ...rest].filter((v, i, all) => all.indexOf(v) === i);
166
+ };
167
+
168
  const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200);
169
 
170
  /** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an
 
378
  if (wrong.length) throw new Error(`create_invoice invoice_type "${invoiceType || 'Standard'}": ${wrong.join('; ')}`);
379
  if (ctx.c.canary) return createWithDataSets(ctx, { amount, lines, name: s.name || 'invoice_number', invoiceType, paymentMethod });
380
  const number = ctx.track(testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, '')));
381
+ const got = await ctx.ui.createInvoice({ businessUnit: apChoices(ctx, 'business_unit'),
382
+ supplier: paidFirst(ctx, 'paid_supplier', () => apChoices(ctx, 'supplier')), number, amount,
383
+ lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: paidFirst(ctx, 'paid_supplier_site', () => apSites(ctx)), invoiceType, paymentMethod });
384
  ctx.chosen['ap.business_unit'] = got.businessUnit;
385
  ctx.chosen['ap.supplier'] = got.supplier;
386
  ctx.saved[s.name || 'invoice_number'] = number;
 
916
  await (fn as (...a: unknown[]) => Promise<void>).apply(ctx.ui, block.args(s, ctx));
917
  }
918
 
919
+ /** The time a step of a scenario may take on a slow pod: a 26D screen step opens its task (one to three minutes for a work
920
+ * area reached through the Navigator, seen live) and acts on it. A scenario gets at least the run's per-test limit and
921
+ * this much per step, up to STEPS_CAP: a receivables scenario of six steps stopped at the flat ten minutes mid-way. */
922
+ const STEP_BUDGET = 150_000;
923
+ const STEPS_CAP = 1_800_000;
924
+
925
  /** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts, or
926
  * from a staged draft's entry (opts.dir = the staging folder holding its YAML). */
927
  export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {
928
  const c = loadStepCase(id, opts.dir);
929
  test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices, fusionDocs }) => {
930
+ test.setTimeout(Math.max(test.info().timeout, Math.min(STEPS_CAP, c.steps.length * STEP_BUDGET)));
931
  const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, imported: new Set(), chosen: {}, orderTags: {}, rest: apInvoices.rest, docs: fusionDocs };
932
  for (const [i, s] of c.steps.entries()) {
933
  const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;
automation/src/fusion/ui.ts CHANGED
@@ -118,6 +118,12 @@ const navLinks = (): Record<string, string> => {
118
  return navCache.links;
119
  };
120
 
 
 
 
 
 
 
121
  /** A note on the test in Playwright's report (outside a test, e.g. a script, nothing is recorded). The report keeps it
122
  * with the step, so a healed step is never silent; the same note twice is kept once. */
123
  function note(type: string, description: string): void {
@@ -434,7 +440,10 @@ export class FusionUi {
434
  await this.page.locator('a[id^="groupNode_"]').first().waitFor({ timeout: 60_000 }).catch(() => {});
435
  const g = this.page.locator('a[id^="groupNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(group)}\\s*$`) })
436
  .filter({ visible: true }).first();
437
- await this.press((await g.count()) ? g : await this.target(group));
 
 
 
438
  await this.settle(3000);
439
  return this.visibleNames(250);
440
  }
@@ -532,6 +541,7 @@ export class FusionUi {
532
  }
533
  }
534
  }
 
535
  const shown = await this.openGroup(group).catch(() => [] as string[]);
536
  if (shown.length) {
537
  // the group's work area entries are Fusion's "itemNode_..." elements; any visible target otherwise
@@ -540,7 +550,7 @@ export class FusionUi {
540
  if (await p.isVisible().catch(() => false)) {
541
  await this.press(p);
542
  await this.settle(6000);
543
- this.workArea = `${group} > ${pageName}`;
544
  return;
545
  }
546
  }
@@ -555,7 +565,36 @@ export class FusionUi {
555
  await item.waitFor({ state: 'visible', timeout: 30_000 });
556
  await this.drawerClick(item);
557
  await this.settle(6000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  this.workArea = `${group} > ${pageName}`;
 
559
  }
560
 
561
  /** A click inside the open Navigator drawer: scrolled to its middle, and given to the element itself when a sticky
@@ -797,12 +836,18 @@ export class FusionUi {
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
  }
@@ -878,9 +923,19 @@ export class FusionUi {
878
  async createPayment(p: { invoice: string; method?: string; bank: string[]; document: string[]; profile: string[] }): Promise<{ number: string; said: string[] }> {
879
  if (!(await this.invoiceOpen(p.invoice))) await this.openInvoice(p.invoice);
880
  await this.menuFirst(['Invoice Actions', 'Actions'], ['Pay in Full', 'Pay'], `paying invoice ${p.invoice}`);
881
- if (!(await this.dialogs()).length && !(await this.labelOf(['Bank Account', 'Payment Process Profile', 'Payment Document', 'Payment Method'], 15_000))) {
882
- throw new Error(`Pay in Full opened no window for invoice ${p.invoice}: the screen changed (verify Pay in Full on the pod)`);
883
- }
 
 
 
 
 
 
 
 
 
 
884
  if (p.method) { // the window may offer the method; when it does not, the invoice's own method is what is paid with
885
  const label = await this.labelOf(['Payment Method'], 3_000);
886
  if (label && (await this.value(label)).toLowerCase() !== p.method.toLowerCase() && await this.field(label).isEditable().catch(() => false)) await this.put(label, p.method);
@@ -2024,34 +2079,25 @@ export class FusionUi {
2024
  }
2025
 
2026
  /** A balanced pair of journal lines: a debit of `amount` on the first of `accounts` Fusion takes, and a credit of the
2027
- * same amount on that same account, so even a posted test journal leaves every balance as it was. The inputs are
2028
- * found by their names ("Debit" or "Entered Debit", ": <row>" up to 26C) in row order, not by row (26D nests tables
2029
- * in rows); a row is added while the table offers fewer than two. Returns the account Fusion took. */
 
 
2030
  private async journalLines(amount: string, accounts: string[]): Promise<string> {
 
 
 
2031
  const box = (name: RegExp) => this.page.getByRole('textbox', { name }).filter({ visible: true });
2032
  const account = box(/^(Account|Accounting Flexfield)(: \d+)?$/i);
2033
  const debit = box(/^(Entered )?(Debit|Dr)( Amount)?(: \d+)?$/i);
2034
  const credit = box(/^(Entered )?(Credit|Cr)( Amount)?(: \d+)?$/i);
2035
- // 26D: the Journal Lines toolbar's Add Row is the page's only visible "Add Row" icon (an image in an unnamed button);
2036
- // the section-based lookup clicked another region's control and no row came (seen live), so the icon is clicked
2037
- // itself and the new row awaited
2038
- const icon = this.page.getByRole('img', { name: 'Add Row', exact: true }).filter({ visible: true });
2039
- for (let i = 0; i < 2 && (await account.count()) < 2; i++) {
2040
- const before = await account.count();
2041
- if (await icon.count()) {
2042
- await icon.first().click({ timeout: 15_000 });
2043
- await this.settle(2500);
2044
- await expect.poll(() => account.count(), { timeout: 15_000 }).toBeGreaterThan(before).catch(() => {});
2045
- } else {
2046
- await this.addRow('Lines').catch(() => this.addRow('Journal Lines'));
2047
- }
2048
- }
2049
  const rows = await account.count();
2050
  if (rows < 2 || (await debit.count()) < 2 || (await credit.count()) < 2) {
2051
  throw new Error(`Create Journal offers ${rows} line(s) with an account, debit and credit to fill, two are needed: the lines table changed ` +
2052
  '(verify Create Journal on the pod)');
2053
  }
2054
- const where = 'an account of this ledger on the Test environments page (Test data, GL account)';
2055
  const took = await this.putAccount(account.nth(0), accounts, ['GL', 'account'], 'for the journal debit line', where);
2056
  await this.typeInto(debit.nth(0), amount);
2057
  await this.putAccount(account.nth(1), [took], ['GL', 'account'], 'for the journal credit line', where);
@@ -2059,6 +2105,40 @@ export class FusionUi {
2059
  return took;
2060
  }
2061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2062
  /** The journal batch `batch` is the one on the page: its Journal Batch field holds the name, or the page shows the
2063
  * name next to a Post or Batch Actions control. */
2064
  async journalOpen(batch: string): Promise<boolean> {
 
118
  return navCache.links;
119
  };
120
 
121
+ /** Work areas this test worker has reached ("Group > Page" -> its address: the page, "/fscmUI/faces/FndOverview" on 26D,
122
+ * and the fndGlobalItemNodeId it carries): the next open goes straight there instead of the springboard or Navigator,
123
+ * which on 26D took up to three minutes for a group the springboard does not show (Receivables, seen live). Kept per
124
+ * pod (base URL). */
125
+ const reachedWorkAreas = new Map<string, string>();
126
+
127
  /** A note on the test in Playwright's report (outside a test, e.g. a script, nothing is recorded). The report keeps it
128
  * with the step, so a healed step is never silent; the same note twice is kept once. */
129
  function note(type: string, description: string): void {
 
440
  await this.page.locator('a[id^="groupNode_"]').first().waitFor({ timeout: 60_000 }).catch(() => {});
441
  const g = this.page.locator('a[id^="groupNode_"]').filter({ hasText: new RegExp(`^\\s*${esc(group)}\\s*$`) })
442
  .filter({ visible: true }).first();
443
+ // a group the springboard does not show fails now, not after a click's full wait (the Navigator is the way then)
444
+ const any = (await g.count()) ? g : await this.target(group);
445
+ if (!(await any.isVisible().catch(() => false))) throw new Error(`the home page shows no group "${group}"`);
446
+ await this.press(any);
447
  await this.settle(3000);
448
  return this.visibleNames(250);
449
  }
 
541
  }
542
  }
543
  }
544
+ if (await this.reopenWorkArea(group, pageName)) return;
545
  const shown = await this.openGroup(group).catch(() => [] as string[]);
546
  if (shown.length) {
547
  // the group's work area entries are Fusion's "itemNode_..." elements; any visible target otherwise
 
550
  if (await p.isVisible().catch(() => false)) {
551
  await this.press(p);
552
  await this.settle(6000);
553
+ this.reached(group, pageName);
554
  return;
555
  }
556
  }
 
565
  await item.waitFor({ state: 'visible', timeout: 30_000 });
566
  await this.drawerClick(item);
567
  await this.settle(6000);
568
+ this.reached(group, pageName);
569
+ }
570
+
571
+ /** The work area is open: remembered as the current one, and its address's id for the next open (reopenWorkArea). */
572
+ private reached(group: string, pageName: string) {
573
+ this.workArea = `${group} > ${pageName}`;
574
+ let url: URL | null = null;
575
+ try { url = new URL(this.page.url()); } catch { return; }
576
+ const id = url.searchParams.get('fndGlobalItemNodeId');
577
+ if (id && /^itemNode_\w+$/.test(id) && /^\/\w+\/faces\/\w+$/.test(url.pathname)) {
578
+ reachedWorkAreas.set(`${fusionEnv().baseUrl} | ${this.workArea}`, `${url.pathname}?fndGlobalItemNodeId=${id}`);
579
+ }
580
+ }
581
+
582
+ /** A work area this worker reached before, opened at its address; true when its page came (its title names it). A
583
+ * remembered address that no longer opens it is forgotten, and the menus are used. */
584
+ private async reopenWorkArea(group: string, pageName: string): Promise<boolean> {
585
+ const { baseUrl } = fusionEnv();
586
+ const key = `${baseUrl} | ${group} > ${pageName}`;
587
+ const address = reachedWorkAreas.get(key);
588
+ if (!address) return false;
589
+ await this.page.goto(`${baseUrl}${address}`, { waitUntil: 'domcontentloaded' }).catch(() => {});
590
+ await this.settle(3000);
591
+ const title = new RegExp(`(^|[-–:|]\\s*)${esc(pageName)}\\b`, 'i');
592
+ const came = !(await this.onSignInPage())
593
+ && await expect.poll(async () => title.test(await this.page.title()), { timeout: 30_000 }).toBe(true).then(() => true, () => false);
594
+ if (!came) { reachedWorkAreas.delete(key); return false; }
595
+ await this.closeDialogs();
596
  this.workArea = `${group} > ${pageName}`;
597
+ return true;
598
  }
599
 
600
  /** A click inside the open Navigator drawer: scrolled to its middle, and given to the element itself when a sticky
 
836
  const lines = h.lines?.length ? h.lines : [h.amount];
837
  let account = h.account;
838
  for (const [i, amount] of lines.entries()) account = await this.addLine(i + 1, { amount, account: h.account });
839
+ // 26D sets the invoice type back to Standard when a line's amount is entered (seen live): the type is put again before
840
+ // the save. Putting it back turns the lines into the type's other kind (a prepayment's become "Withholding tax", which
841
+ // Fusion then refuses as not negative, seen live), so each line is made an Item again, and an amount the change
842
+ // cleared is entered again
843
  if (h.invoiceType && (await this.invoiceTypeOnPage()) !== h.invoiceType.toLowerCase()) {
844
  await this.chooseInvoiceType(h.invoiceType);
845
  for (const [i, amount] of lines.entries()) {
846
+ const row = this.lineRow(i + 1);
847
+ const kind = row.getByRole('combobox', { name: new RegExp(`^Type(: ${i + 1})?$`) }).first();
848
+ const shown = await kind.evaluate((e) => (e as HTMLSelectElement).selectedOptions?.[0]?.textContent?.trim() ?? '').catch(() => 'Item');
849
+ if (shown !== 'Item') { await kind.selectOption({ label: 'Item' }); await this.settle(2000); }
850
+ const box = row.getByRole('textbox', { name: new RegExp(`^Amount(: ${i + 1})?$`) }).first();
851
  if (!(await box.inputValue().catch(() => '')).trim()) { await box.click(); await box.fill(amount); await box.press('Tab'); await this.settle(1500); }
852
  }
853
  }
 
923
  async createPayment(p: { invoice: string; method?: string; bank: string[]; document: string[]; profile: string[] }): Promise<{ number: string; said: string[] }> {
924
  if (!(await this.invoiceOpen(p.invoice))) await this.openInvoice(p.invoice);
925
  await this.menuFirst(['Invoice Actions', 'Actions'], ['Pay in Full', 'Pay'], `paying invoice ${p.invoice}`);
926
+ // Fusion can refuse in a note that shows for a few seconds and no window comes ("The supplier hold must be released
927
+ // before the invoice can be paid.", seen live on a supplier with a payment hold): its words are the failure
928
+ const refusal = this.page.getByText(/(must be released|cannot be paid|can't be paid|is on hold|not eligible for payment)/i).filter({ visible: true });
929
+ let refused = '';
930
+ const opened = await expect.poll(async () => {
931
+ if (await refusal.count()) { refused = (await refusal.first().innerText().catch(() => '')).trim(); return true; }
932
+ return (await this.dialogs()).length > 0 || !!(await this.labelOf(['Bank Account', 'Payment Process Profile', 'Payment Document', 'Payment Method'], 500));
933
+ }, { timeout: 15_000 }).toBe(true).then(() => true, () => false);
934
+ if (refused) {
935
+ const hold = /supplier hold/i.test(refused) ? ': the supplier has a payment hold; set a supplier without one on the Test environments page (Test data, AP supplier)' : '';
936
+ throw new Error(`Fusion did not pay invoice ${p.invoice}: ${refused.slice(0, 200)}${hold}`);
937
+ }
938
+ if (!opened) throw new Error(`Pay in Full opened no window for invoice ${p.invoice}: the screen changed (verify Pay in Full on the pod)`);
939
  if (p.method) { // the window may offer the method; when it does not, the invoice's own method is what is paid with
940
  const label = await this.labelOf(['Payment Method'], 3_000);
941
  if (label && (await this.value(label)).toLowerCase() !== p.method.toLowerCase() && await this.field(label).isEditable().catch(() => false)) await this.put(label, p.method);
 
2079
  }
2080
 
2081
  /** A balanced pair of journal lines: a debit of `amount` on the first of `accounts` Fusion takes, and a credit of the
2082
+ * same amount on that same account, so even a posted test journal leaves every balance as it was. Returns the
2083
+ * account Fusion took. 26D shows the lines in a table named "Journal Lines" that edits one line at a time (seen live:
2084
+ * two lines offered, only the current one has inputs, and they have no names), so each line is entered by clicking
2085
+ * it and its inputs found by their ids' column part (accountCS, EnteredDr, EnteredCr). Up to 26C every line's inputs
2086
+ * are on the page, found by their names ("Debit" or "Entered Debit", ": <row>") in row order. */
2087
  private async journalLines(amount: string, accounts: string[]): Promise<string> {
2088
+ const where = 'an account of this ledger on the Test environments page (Test data, GL account)';
2089
+ const table = this.page.locator('table[summary="Journal Lines"]').filter({ visible: true });
2090
+ if (await table.count()) return this.journalLinesOneAtATime(table.first(), amount, accounts, where);
2091
  const box = (name: RegExp) => this.page.getByRole('textbox', { name }).filter({ visible: true });
2092
  const account = box(/^(Account|Accounting Flexfield)(: \d+)?$/i);
2093
  const debit = box(/^(Entered )?(Debit|Dr)( Amount)?(: \d+)?$/i);
2094
  const credit = box(/^(Entered )?(Credit|Cr)( Amount)?(: \d+)?$/i);
2095
+ for (let i = 0; i < 2 && (await account.count()) < 2; i++) await this.addRow('Lines').catch(() => this.addRow('Journal Lines'));
 
 
 
 
 
 
 
 
 
 
 
 
 
2096
  const rows = await account.count();
2097
  if (rows < 2 || (await debit.count()) < 2 || (await credit.count()) < 2) {
2098
  throw new Error(`Create Journal offers ${rows} line(s) with an account, debit and credit to fill, two are needed: the lines table changed ` +
2099
  '(verify Create Journal on the pod)');
2100
  }
 
2101
  const took = await this.putAccount(account.nth(0), accounts, ['GL', 'account'], 'for the journal debit line', where);
2102
  await this.typeInto(debit.nth(0), amount);
2103
  await this.putAccount(account.nth(1), [took], ['GL', 'account'], 'for the journal credit line', where);
 
2105
  return took;
2106
  }
2107
 
2108
+ /** The 26D lines table: line 1 (a debit) and line 2 (a credit), each found by the number its row starts with and clicked into, a line
2109
+ * added (its Add Row icon, the page's only one) when the table offers one. */
2110
+ private async journalLinesOneAtATime(table: Locator, amount: string, accounts: string[], where: string): Promise<string> {
2111
+ const rows = table.locator(':scope > tbody > tr');
2112
+ const line = async (n: number) => {
2113
+ const index = () => rows.evaluateAll((rs, want) => rs.findIndex((r) =>
2114
+ new RegExp(`^${want}(\\D|$)`).test((r.textContent || '').trim())), n);
2115
+ if ((await index()) < 0) {
2116
+ await this.page.getByRole('img', { name: 'Add Row', exact: true }).filter({ visible: true }).first().click({ timeout: 15_000 });
2117
+ await this.settle(2500);
2118
+ }
2119
+ const i = await index();
2120
+ if (i < 0) throw new Error(`Create Journal offers no journal line ${n}: the lines table changed (verify Create Journal on the pod)`);
2121
+ const row = rows.nth(i);
2122
+ const input = (column: string) => row.locator(`input[id$="${column}::content"]`).filter({ visible: true }).first();
2123
+ if (!(await input('accountCS').count())) {
2124
+ // the cell showing the line number, else the row itself
2125
+ const cell = row.locator('td').filter({ hasText: new RegExp(`^\\s*${n}\\s*$`) }).filter({ visible: true });
2126
+ await ((await cell.count()) ? cell.first() : row).click();
2127
+ await expect(input('accountCS')).toBeVisible({ timeout: 15_000 }).catch(() => {
2128
+ throw new Error(`journal line ${n} offers no account to fill once entered: the lines table changed (verify Create Journal on the pod)`);
2129
+ });
2130
+ }
2131
+ return input;
2132
+ };
2133
+ const debit = await line(1);
2134
+ const took = await this.putAccount(debit('accountCS'), accounts, ['GL', 'account'], 'for the journal debit line', where);
2135
+ await this.typeInto(debit('EnteredDr'), amount);
2136
+ const credit = await line(2);
2137
+ await this.putAccount(credit('accountCS'), [took], ['GL', 'account'], 'for the journal credit line', where);
2138
+ await this.typeInto(credit('EnteredCr'), amount);
2139
+ return took;
2140
+ }
2141
+
2142
  /** The journal batch `batch` is the one on the page: its Journal Batch field holds the name, or the page shows the
2143
  * name next to a Post or Batch Actions control. */
2144
  async journalOpen(batch: string): Promise<boolean> {
coworker/graph/nodes/design.py CHANGED
@@ -110,8 +110,10 @@ def test_generator(state, config, svc) -> dict:
110
  slim = [{k: c[k] for k in ("id", "title", "module", "process", "priority", "new_or_changed", "changed_by_patch", "origin",
111
  "yaml_path", "map_ids", "data_recipes", "learned")} | {"already_approved": c.get("already_approved", False)}
112
  for c in keep]
113
- # Fusion pods with an AI model on: new scenarios written by the model, dry-run on the pod before the gate
114
- ai = ai_scenarios.write_ai_scenarios(state, svc, case_lib.load_all(svc, mods) if only and mods else library)
 
 
115
  out = {"test_cases": slim + gen_cases + ai.get("cases", []), "deferred": deferred, "proposed_cases": proposals,
116
  "approvals": {"pulled_in_changed_by_patch": pulled}, "llm_calls": [resp.record]}
117
  if ai:
 
110
  slim = [{k: c[k] for k in ("id", "title", "module", "process", "priority", "new_or_changed", "changed_by_patch", "origin",
111
  "yaml_path", "map_ids", "data_recipes", "learned")} | {"already_approved": c.get("already_approved", False)}
112
  for c in keep]
113
+ # Fusion pods with an AI model on: new scenarios written by the model, dry-run on the pod before the gate. Not when a
114
+ # person chose the scenarios by name: they decided what this run tests, and the design and its dry runs took 10-20
115
+ # minutes of every such run (seen on a 26D pod)
116
+ ai = {} if only else ai_scenarios.write_ai_scenarios(state, svc, library)
117
  out = {"test_cases": slim + gen_cases + ai.get("cases", []), "deferred": deferred, "proposed_cases": proposals,
118
  "approvals": {"pulled_in_changed_by_patch": pulled}, "llm_calls": [resp.record]}
119
  if ai:
coworker/graph/nodes/research.py CHANGED
@@ -138,8 +138,8 @@ def scout(state, config, svc) -> dict:
138
  # setup words (currencies, payment terms, document types, periods) that public release notes and screen labels use too:
139
  # protecting those would refuse every public model call that mentions "Standard" or "USD". Their values still never go
140
  # to a model as data: steps carry {{pod.<area>.<key>}} placeholders.
141
- IDENTIFYING_KEYS = ("business_unit", "requisitioning_bu", "supplier", "supplier_site", "customer", "ledger", "organization",
142
- "bank_account", "account")
143
 
144
 
145
  def identifying_values(test_data: dict) -> list[str]:
 
138
  # setup words (currencies, payment terms, document types, periods) that public release notes and screen labels use too:
139
  # protecting those would refuse every public model call that mentions "Standard" or "USD". Their values still never go
140
  # to a model as data: steps carry {{pod.<area>.<key>}} placeholders.
141
+ IDENTIFYING_KEYS = ("business_unit", "requisitioning_bu", "supplier", "supplier_site", "paid_supplier", "paid_supplier_site",
142
+ "customer", "ledger", "organization", "bank_account", "account")
143
 
144
 
145
  def identifying_values(test_data: dict) -> list[str]:
coworker/platform/discovery.py CHANGED
@@ -128,17 +128,19 @@ def sample_test_data(pod, area: dict) -> dict[str, list[str]]:
128
  break
129
  else:
130
  own = spec.get("own_field")
131
- params = {"limit": SAMPLE, "fields": ",".join(sorted(set(wanted) | ({spec.get("key_field"), own} - {None})))}
 
 
132
  if spec.get("order_by"):
133
  params["orderBy"] = spec["order_by"]
134
  items = _items(pod, spec["resource"], params)
135
  if not items and spec.get("order_by"): # a pod whose resource has no such key field: plain order
136
  items = _items(pod, spec["resource"], {k: v for k, v in params.items() if k != "orderBy"})
137
  if not items: # a field this pod does not have refuses the whole list: read the records whole
138
- items = _items(pod, spec["resource"], {"limit": SAMPLE})
139
  # the pod's own records only: the invoices our tests created would otherwise be "the latest records"
140
  items = [i for i in items if not _own(i, own)]
141
- parents[spec["resource"]] = items
142
  for key, names in fields.items():
143
  vals = next((v for v in (_top(items, n) for n in names) if v), [])
144
  if vals and key not in out:
 
128
  break
129
  else:
130
  own = spec.get("own_field")
131
+ # a spec's filter (q: the paid invoices only) stays on every read: without it the values would be others
132
+ where = {"q": spec["q"]} if spec.get("q") else {}
133
+ params = {"limit": SAMPLE, "fields": ",".join(sorted(set(wanted) | ({spec.get("key_field"), own} - {None}))), **where}
134
  if spec.get("order_by"):
135
  params["orderBy"] = spec["order_by"]
136
  items = _items(pod, spec["resource"], params)
137
  if not items and spec.get("order_by"): # a pod whose resource has no such key field: plain order
138
  items = _items(pod, spec["resource"], {k: v for k, v in params.items() if k != "orderBy"})
139
  if not items: # a field this pod does not have refuses the whole list: read the records whole
140
+ items = _items(pod, spec["resource"], {"limit": SAMPLE, **where})
141
  # the pod's own records only: the invoices our tests created would otherwise be "the latest records"
142
  items = [i for i in items if not _own(i, own)]
143
+ parents.setdefault(spec["resource"], items) # a filtered second read of a resource is no parent list
144
  for key, names in fields.items():
145
  vals = next((v for v in (_top(items, n) for n in names) if v), [])
146
  if vals and key not in out:
coworker/platform/fusion_catalog.py CHANGED
@@ -77,7 +77,11 @@ AREAS: list[dict] = [
77
  "fields": {"business_unit": "BusinessUnit", "supplier": "Supplier", "supplier_site": "SupplierSite",
78
  "currency": "InvoiceCurrency", "payment_terms": "PaymentTerms", "invoice_type": "InvoiceType"}},
79
  {"resource": "invoices/{key}/child/invoiceLines", "parent": "invoices", "parent_key": "InvoiceId",
80
- "fields": {"account": "DistributionCombination"}}]},
 
 
 
 
81
  {"code": "PO", "id": "purchasing", "name": "Purchasing", "probes": ["purchaseOrders", "purchaseRequisitions"],
82
  "processes": ["Requisition entry", "Requisition approval", "Purchase order creation", "Change orders", "Receiving"],
83
  "navigator": ["Procurement > Purchase Requisitions", "Procurement > Purchase Orders"],
 
77
  "fields": {"business_unit": "BusinessUnit", "supplier": "Supplier", "supplier_site": "SupplierSite",
78
  "currency": "InvoiceCurrency", "payment_terms": "PaymentTerms", "invoice_type": "InvoiceType"}},
79
  {"resource": "invoices/{key}/child/invoiceLines", "parent": "invoices", "parent_key": "InvoiceId",
80
+ "fields": {"account": "DistributionCombination"}},
81
+ # the suppliers the pod actually pays: a payment test's invoice goes to one of them (the latest
82
+ # invoices' supplier can carry a payment hold, and Fusion then refuses Pay in Full, seen live)
83
+ {"resource": "invoices", "q": "PaidStatus='Paid'", "order_by": "InvoiceId:desc", "key_field": "InvoiceId",
84
+ "own_field": "InvoiceNumber", "fields": {"paid_supplier": "Supplier", "paid_supplier_site": "SupplierSite"}}]},
85
  {"code": "PO", "id": "purchasing", "name": "Purchasing", "probes": ["purchaseOrders", "purchaseRequisitions"],
86
  "processes": ["Requisition entry", "Requisition approval", "Purchase order creation", "Change orders", "Receiving"],
87
  "navigator": ["Procurement > Purchase Requisitions", "Procurement > Purchase Orders"],
coworker/platform/usage.py CHANGED
@@ -67,6 +67,10 @@ PAID_WORDS = {"check": ["quick payment by check", "payment by check", "paid by c
67
  "wire": ["quick payment by wire", "payment by wire", "paid by wire"], "clearing": ["payment by clearing"],
68
  "bills payable": ["payment by bills payable"], "outsourced check": ["payment by outsourced check"],
69
  "eft": ["quick payment by eft", "payment by eft"]}
 
 
 
 
70
 
71
  USAGE: dict[str, list[dict]] = {
72
  "AP": [
@@ -85,7 +89,7 @@ USAGE: dict[str, list[dict]] = {
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"),
91
  {"approved": ["approv"], "initiated": ["approval initiated", "sent for approval"],
 
67
  "wire": ["quick payment by wire", "payment by wire", "paid by wire"], "clearing": ["payment by clearing"],
68
  "bills payable": ["payment by bills payable"], "outsourced check": ["payment by outsourced check"],
69
  "eft": ["quick payment by eft", "payment by eft"]}
70
+ # an invoice's own method: a scenario about it (an invoice "for electronic payment"), or one that pays the invoice by it, since
71
+ # Pay in Full pays with the invoice's method (26D's Create Invoice has no method field: the supplier site's default is the
72
+ # invoice's, and what a payment scenario pays by is that method)
73
+ INVOICE_PAY_WORDS = {k: PAY_WORDS.get(k, []) + PAID_WORDS.get(k, []) for k in {*PAY_WORDS, *PAID_WORDS}}
74
 
75
  USAGE: dict[str, list[dict]] = {
76
  "AP": [
 
89
  # External is what Payables invoice import (a FBDI file through the ERP Integration service) is made from; a
90
  # scenario about the Spreadsheet source (ADFdi) or ERS is not about it, and none of these words is theirs
91
  "external": ["fbdi", "invoice import", "external source", "payables invoice import"]}),
92
+ _dim("payment_method", "Payment method", ["PaymentMethod", "PaymentMethodCode"], PAY_METHODS, INVOICE_PAY_WORDS),
93
  _dim("approval_status", "Approval status", "ApprovalStatus",
94
  ("Approved", "Initiated", "Required", "Not required", "Rejected", "Manually approved", "Workflow approved", "Withdrawn"),
95
  {"approved": ["approv"], "initiated": ["approval initiated", "sent for approval"],
coworker/tests/test_discovery.py CHANGED
@@ -1,212 +1,229 @@
1
- """Pod discovery: any Fusion pod's business areas and test data come from the pod itself (platform/discovery.py,
2
- platform/fusion_catalog.py); nothing about one particular pod is built in. Statuses, sampling, overrides, the catalog
3
- extension file, the API, the scout, the run rules and what the test runner receives."""
4
- from __future__ import annotations
5
-
6
- import json
7
- import tempfile
8
- import unittest
9
- from pathlib import Path
10
-
11
- from coworker.platform import discovery, fusion_catalog
12
- from coworker.platform.fusion_catalog import FSCM
13
- from coworker.tests.fakes import bearer, make_app
14
-
15
-
16
- class Resp:
17
- def __init__(self, status: int, body: dict | None = None):
18
- self.status_code, self._body = status, body or {}
19
-
20
- def json(self):
21
- return self._body
22
-
23
-
24
- class ScriptedPod:
25
- """A Fusion pod as a table: resource -> (status, items). Child paths are matched as written."""
26
- def __init__(self, table: dict[str, tuple[int, list[dict]]]):
27
- self.table, self.calls = table, []
28
-
29
- def _get(self, path: str, params: dict | None = None):
30
- self.calls.append((path, dict(params or {})))
31
- res = path[len(FSCM) + 1:]
32
- if res not in self.table:
33
- return Resp(404)
34
- status, items = self.table[res]
35
- if status != 200:
36
- return Resp(status)
37
- if (params or {}).get("totalResults"):
38
- return Resp(200, {"items": items[:1], "totalResults": len(items)})
39
- return Resp(200, {"items": items[: int((params or {}).get("limit", 500))]})
40
-
41
-
42
- INVOICES = [{"InvoiceId": 300 - i, "BusinessUnit": "BU One" if i % 3 else "BU Two", "Supplier": "Acme Supplies",
43
- "SupplierSite": "MAIN", "InvoiceCurrency": "USD", "PaymentTerms": "Net 30", "InvoiceType": "Standard"} for i in range(9)]
44
-
45
-
46
- class TestDiscoveryRules(unittest.TestCase):
47
- def area(self, code: str) -> dict:
48
- return fusion_catalog.by_code(code)
49
-
50
- def test_each_status_comes_from_what_the_pod_answers(self):
51
- pod = ScriptedPod({"invoices": (200, INVOICES), "suppliers": (200, [{}]), # AP: records -> in use
52
- "purchaseOrders": (200, []), "purchaseRequisitions": (404, []), # PO: answers, empty -> no data
53
- "receivablesInvoices": (403, []), "standardReceipts": (403, []), # AR: refused -> no access
54
- "journalBatches": (500, []), "ledgersLOV": (404, [])}) # GL: server error -> error
55
- found = discovery.discover(pod, [self.area(c) for c in ("AP", "PO", "AR", "GL", "FA")])
56
- status = {a["code"]: a["status"] for a in found["areas"]}
57
- self.assertEqual(status, {"AP": "in_use", "PO": "no_data", "AR": "no_access", "GL": "error", "FA": "not_available"})
58
- ap = next(a for a in found["areas"] if a["code"] == "AP")
59
- self.assertEqual(ap["counts"], {"invoices": 9, "suppliers": 1})
60
- self.assertEqual(discovery.in_use(found), ["AP"])
61
- self.assertEqual(discovery.runnable_areas(found), ["AP", "PO"])
62
- self.assertEqual(list(found["test_data"]), ["AP"]) # test data only for areas in use
63
-
64
- def test_a_refused_sign_in_stops_discovery(self):
65
- with self.assertRaises(discovery.SignInRefused):
66
- discovery.discover(ScriptedPod({"invoices": (401, [])}), [self.area("AP"), self.area("PO")])
67
-
68
- def test_test_data_is_the_most_frequent_values_of_the_latest_records_including_child_lines(self):
69
- lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "01-100-5000"}]) for i in INVOICES}
70
- pod = ScriptedPod({"invoices": (200, INVOICES), "suppliers": (200, [{}]), **lines})
71
- td = discovery.sample_test_data(pod, self.area("AP"))
72
- self.assertEqual(td["business_unit"], ["BU One", "BU Two"]) # most frequent first
73
- self.assertEqual(td["supplier"], ["Acme Supplies"])
74
- self.assertEqual(td["account"], ["01-100-5000"])
75
- sample = next(p for path, p in pod.calls if path.endswith("/invoices") and "orderBy" in p)
76
- self.assertEqual(sample["orderBy"], "InvoiceId:desc")
77
- self.assertIn("InvoiceId", sample["fields"]) # the child sample needs the parent's key
78
- child_calls = [path for path, _ in pod.calls if "/child/" in path]
79
- self.assertLessEqual(len(child_calls), 3)
80
-
81
- def test_the_tests_own_invoices_are_not_the_pods_records(self):
82
- """Seen on a real pod: the newest invoices were ones our tests had saved without a line, so the distribution
83
- account was not found and three Payables scenarios stopped at their first line."""
84
- ours = [{"InvoiceId": 900 + i, "InvoiceNumber": f"FPT-AP2-{i}", "Supplier": "Test Supplier", "BusinessUnit": "BU Test"} for i in range(5)]
85
- real = [{**inv, "InvoiceNumber": f"INV-{inv['InvoiceId']}"} for inv in INVOICES]
86
- lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, []) for i in ours + real[:2]}
87
- lines[f"invoices/{real[2]['InvoiceId']}/child/invoiceLines"] = (200, [{"DistributionCombination": "01-100-5000"}])
88
- pod = ScriptedPod({"invoices": (200, ours + real), "suppliers": (200, [{}]), **lines})
89
- td = discovery.sample_test_data(pod, self.area("AP"))
90
- self.assertEqual(td["supplier"], ["Acme Supplies"]) # not the test's own supplier
91
- self.assertNotIn("BU Test", td["business_unit"])
92
- self.assertEqual(td["account"], ["01-100-5000"]) # found on the third real invoice, past two without lines
93
- self.assertFalse(any("/90" in path for path, _ in pod.calls if "/child/" in path)) # our invoices were not read
94
-
95
- def test_the_line_account_comes_from_the_tests_business_unit(self):
96
- """Seen on a real pod (26D): the newest invoice was another unit's, its 3-segment account was refused for the
97
- test's unit (6 segments) and every invoice scenario stopped at its first line."""
98
- lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "100-30020-100"}])
99
- for i in INVOICES if i["BusinessUnit"] == "BU Two"}
100
- lines |= {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "01.100.5000.000.000.000"}])
101
- for i in INVOICES if i["BusinessUnit"] == "BU One"}
102
- pod = ScriptedPod({"invoices": (200, INVOICES), "suppliers": (200, [{}]), **lines})
103
- self.assertEqual(INVOICES[0]["BusinessUnit"], "BU Two") # the newest invoice is the other unit's
104
- td = discovery.sample_test_data(pod, self.area("AP"))
105
- self.assertEqual(td["business_unit"][0], "BU One")
106
- self.assertEqual(td["account"], ["01.100.5000.000.000.000"])
107
-
108
- def test_a_missing_field_or_resource_leaves_the_key_out_instead_of_inventing_one(self):
109
- pod = ScriptedPod({"invoices": (200, [{"InvoiceId": 1, "Supplier": "Only Supplier"}]), "suppliers": (200, [{}])})
110
- td = discovery.sample_test_data(pod, self.area("AP"))
111
- self.assertEqual(td, {"supplier": ["Only Supplier"]})
112
-
113
- def test_overrides_win_and_empty_values_are_ignored(self):
114
- merged = discovery.merged_test_data({"AP": {"supplier": ["A", "B"], "business_unit": ["BU"]}},
115
- {"ap": {"supplier": "Chosen", "account": ""}})
116
- self.assertEqual(merged, {"AP": {"supplier": "Chosen", "business_unit": "BU"}})
117
-
118
- def test_a_deployment_adds_or_replaces_areas_without_code(self):
119
- home = Path(tempfile.mkdtemp())
120
- (home / "fusion_areas.json").write_text(json.dumps([
121
- {"code": "hcm", "name": "Human Capital", "probes": ["workers"], "processes": ["Hire"]},
122
- {"code": "AP", "name": "Payables (client)", "probes": ["invoices"]},
123
- {"code": "bad code", "name": "x", "probes": ["../etc"]}]), encoding="utf-8")
124
- areas = {a["code"]: a for a in fusion_catalog.areas(home)}
125
- self.assertEqual(areas["HCM"]["probes"], ["workers"])
126
- self.assertEqual(areas["AP"]["name"], "Payables (client)")
127
- self.assertTrue(areas["AP"]["test_data"]) # keys not given keep the built-in values
128
- self.assertNotIn("BAD CODE", areas)
129
-
130
-
131
- class TestDiscoveryInTheApp(unittest.TestCase):
132
- """Through the API and a run, with the shared fake pod (fixtures/mock_pod.json lists)."""
133
-
134
- def setUp(self):
135
- self.app, self.c, self.svc, self.fake = make_app()
136
- self.h = {r: bearer(self.c, r) for r in ("viewer", "consultant", "admin")}
137
- body = {"name": "Client test pod", "kind": "fusion", "base_url": "https://acme-test.fa.ocs.oraclecloud.com", "environment": "test"}
138
- self.pod = self.c.post("/api/pods", json=body, headers=self.h["admin"]).json()
139
- self.c.post(f"/api/pods/{self.pod['id']}/credentials", json={"module": "ALL", "username": "zz.tester", "password": "S3cret-x!"},
140
- headers=self.h["admin"])
141
-
142
- def discover(self, role="consultant"):
143
- return self.c.post(f"/api/pods/{self.pod['id']}/discover", headers=self.h[role])
144
-
145
- def test_discover_saves_areas_and_in_use_modules_on_the_pod(self):
146
- self.assertEqual(self.discover("viewer").status_code, 403)
147
- r = self.discover()
148
- self.assertEqual(r.status_code, 200, r.text)
149
- p = r.json()
150
- status = {a["code"]: a["status"] for a in p["discovery"]["areas"]}
151
- # fixture: suppliers 5 (AP in use), expense reports, fixed assets, journal batches, projects, items have records
152
- self.assertEqual(status["AP"], "in_use")
153
- self.assertEqual(status["PO"], "no_data")
154
- self.assertIn(status["CM"], ("no_data", "not_available"))
155
- self.assertEqual(sorted(p["modules"]), sorted(c for c, s in status.items() if s == "in_use"))
156
- self.assertTrue(p["discovered_at"])
157
- sent = [q for q in self.fake.requests if "/fscmRestApi/" in q.url.path]
158
- self.assertTrue(sent and all(q.method == "GET" for q in sent)) # read-only
159
- audit = self.c.get("/api/audit?limit=200", headers=self.h["admin"]).text
160
- self.assertIn("pod.discovered", audit)
161
- self.assertNotIn("S3cret-x!", audit)
162
-
163
- def test_runs_may_target_the_discovered_areas_only(self):
164
- self.discover()
165
- r = self.c.post("/api/runs", json={"modules": ["AR"], "playwright_mode": "stub", "pod_id": self.pod["id"]}, headers=self.h["consultant"])
166
- self.assertEqual(r.status_code, 202, r.text) # AR answers on this pod: it may run
167
- self.app.state.runs.cancel(r.json()["run_id"], "test")
168
- r = self.c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub", "pod_id": self.pod["id"]}, headers=self.h["consultant"])
169
- self.assertEqual((r.status_code, r.json()["code"]), (409, "AREA_NOT_ON_FUSION"))
170
- self.assertIn("AP", r.json()["detail"])
171
-
172
- def test_the_scout_discovers_at_the_start_of_every_run(self):
173
- rid = self.c.post("/api/runs", json={"modules": ["AP"], "playwright_mode": "stub", "pod_id": self.pod["id"]},
174
- headers=self.h["consultant"]).json()["run_id"]
175
- self.app.state.runs.drain()
176
- events = json.dumps(self.svc.db.events(rid))
177
- self.assertIn("Discovered on the pod", events)
178
- p = next(x for x in self.c.get("/api/pods", headers=self.h["viewer"]).json() if x["id"] == self.pod["id"])
179
- self.assertTrue(p["discovery"]) # saved for the next run and the Test environments page
180
- prof = self.svc.db.kv_get("pod_profile")
181
- self.assertEqual(prof["modules"][0]["usage_label"], "pod REST record counts")
182
- self.assertNotIn("mock-derived", json.dumps(prof["modules"]))
183
-
184
- def test_test_data_overrides_reach_the_test_runner_and_only_admins_set_them(self):
185
- url = f"/api/pods/{self.pod['id']}/test-data"
186
- body = {"overrides": {"AP": {"supplier": "Chosen Supplier", "account": "01-100-5000"}}}
187
- self.assertEqual(self.c.put(url, json=body, headers=self.h["consultant"]).status_code, 403)
188
- r = self.c.put(url, json=body, headers=self.h["admin"])
189
- self.assertEqual(r.status_code, 200, r.text)
190
- self.assertEqual(r.json()["test_data"]["AP"]["supplier"], "Chosen Supplier")
191
- self.assertEqual(self.c.put(url, json={"overrides": {"AP": {"Bad Key": "x"}}}, headers=self.h["admin"]).status_code, 422)
192
- from coworker.platform.pods import PodRegistry
193
- env = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).executor_env(self.pod["id"])
194
- self.assertEqual(json.loads(env["FUSION_TESTDATA"])["AP"], {"supplier": "Chosen Supplier", "account": "01-100-5000"})
195
-
196
- def test_the_release_is_recorded_on_the_pod_and_checked(self):
197
- url = f"/api/pods/{self.pod['id']}"
198
- self.assertEqual(self.c.patch(url, json={"release": "26c"}, headers=self.h["admin"]).json()["release"], "26C")
199
- r = self.c.patch(url, json={"release": "R13"}, headers=self.h["admin"])
200
- self.assertEqual((r.status_code, r.json()["code"]), (422, "BAD_RELEASE"))
201
- from coworker.platform.pods import PodRegistry
202
- about = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).client(self.pod["id"]).about()
203
- self.assertEqual((about["release"], about["release_known"]), ("26C", True))
204
-
205
- def test_the_practice_pod_has_no_discovery(self):
206
- default = next(p for p in self.c.get("/api/pods", headers=self.h["viewer"]).json() if p["is_default"])
207
- r = self.c.post(f"/api/pods/{default['id']}/discover", headers=self.h["consultant"])
208
- self.assertEqual((r.status_code, r.json()["code"]), (422, "NOT_FUSION"))
209
-
210
-
211
- if __name__ == "__main__":
212
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pod discovery: any Fusion pod's business areas and test data come from the pod itself (platform/discovery.py,
2
+ platform/fusion_catalog.py); nothing about one particular pod is built in. Statuses, sampling, overrides, the catalog
3
+ extension file, the API, the scout, the run rules and what the test runner receives."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import tempfile
8
+ import unittest
9
+ from pathlib import Path
10
+
11
+ from coworker.platform import discovery, fusion_catalog
12
+ from coworker.platform.fusion_catalog import FSCM
13
+ from coworker.tests.fakes import bearer, make_app
14
+
15
+
16
+ class Resp:
17
+ def __init__(self, status: int, body: dict | None = None):
18
+ self.status_code, self._body = status, body or {}
19
+
20
+ def json(self):
21
+ return self._body
22
+
23
+
24
+ class ScriptedPod:
25
+ """A Fusion pod as a table: resource -> (status, items). Child paths are matched as written."""
26
+ def __init__(self, table: dict[str, tuple[int, list[dict]]]):
27
+ self.table, self.calls = table, []
28
+
29
+ def _get(self, path: str, params: dict | None = None):
30
+ self.calls.append((path, dict(params or {})))
31
+ res = path[len(FSCM) + 1:]
32
+ if res not in self.table:
33
+ return Resp(404)
34
+ status, items = self.table[res]
35
+ if status != 200:
36
+ return Resp(status)
37
+ for cond in filter(None, str((params or {}).get("q") or "").split(";")): # Field='Value' filters, as Fusion reads them
38
+ field, _, value = cond.partition("=")
39
+ items = [i for i in items if str(i.get(field.strip())) == value.strip().strip("'")]
40
+ if (params or {}).get("totalResults"):
41
+ return Resp(200, {"items": items[:1], "totalResults": len(items)})
42
+ return Resp(200, {"items": items[: int((params or {}).get("limit", 500))]})
43
+
44
+
45
+ INVOICES = [{"InvoiceId": 300 - i, "BusinessUnit": "BU One" if i % 3 else "BU Two", "Supplier": "Acme Supplies",
46
+ "SupplierSite": "MAIN", "InvoiceCurrency": "USD", "PaymentTerms": "Net 30", "InvoiceType": "Standard"} for i in range(9)]
47
+
48
+
49
+ class TestDiscoveryRules(unittest.TestCase):
50
+ def area(self, code: str) -> dict:
51
+ return fusion_catalog.by_code(code)
52
+
53
+ def test_each_status_comes_from_what_the_pod_answers(self):
54
+ pod = ScriptedPod({"invoices": (200, INVOICES), "suppliers": (200, [{}]), # AP: records -> in use
55
+ "purchaseOrders": (200, []), "purchaseRequisitions": (404, []), # PO: answers, empty -> no data
56
+ "receivablesInvoices": (403, []), "standardReceipts": (403, []), # AR: refused -> no access
57
+ "journalBatches": (500, []), "ledgersLOV": (404, [])}) # GL: server error -> error
58
+ found = discovery.discover(pod, [self.area(c) for c in ("AP", "PO", "AR", "GL", "FA")])
59
+ status = {a["code"]: a["status"] for a in found["areas"]}
60
+ self.assertEqual(status, {"AP": "in_use", "PO": "no_data", "AR": "no_access", "GL": "error", "FA": "not_available"})
61
+ ap = next(a for a in found["areas"] if a["code"] == "AP")
62
+ self.assertEqual(ap["counts"], {"invoices": 9, "suppliers": 1})
63
+ self.assertEqual(discovery.in_use(found), ["AP"])
64
+ self.assertEqual(discovery.runnable_areas(found), ["AP", "PO"])
65
+ self.assertEqual(list(found["test_data"]), ["AP"]) # test data only for areas in use
66
+
67
+ def test_a_refused_sign_in_stops_discovery(self):
68
+ with self.assertRaises(discovery.SignInRefused):
69
+ discovery.discover(ScriptedPod({"invoices": (401, [])}), [self.area("AP"), self.area("PO")])
70
+
71
+ def test_test_data_is_the_most_frequent_values_of_the_latest_records_including_child_lines(self):
72
+ lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "01-100-5000"}]) for i in INVOICES}
73
+ pod = ScriptedPod({"invoices": (200, INVOICES), "suppliers": (200, [{}]), **lines})
74
+ td = discovery.sample_test_data(pod, self.area("AP"))
75
+ self.assertEqual(td["business_unit"], ["BU One", "BU Two"]) # most frequent first
76
+ self.assertEqual(td["supplier"], ["Acme Supplies"])
77
+ self.assertEqual(td["account"], ["01-100-5000"])
78
+ sample = next(p for path, p in pod.calls if path.endswith("/invoices") and "orderBy" in p)
79
+ self.assertEqual(sample["orderBy"], "InvoiceId:desc")
80
+ self.assertIn("InvoiceId", sample["fields"]) # the child sample needs the parent's key
81
+ child_calls = [path for path, _ in pod.calls if "/child/" in path]
82
+ self.assertLessEqual(len(child_calls), 3)
83
+
84
+ def test_the_tests_own_invoices_are_not_the_pods_records(self):
85
+ """Seen on a real pod: the newest invoices were ones our tests had saved without a line, so the distribution
86
+ account was not found and three Payables scenarios stopped at their first line."""
87
+ ours = [{"InvoiceId": 900 + i, "InvoiceNumber": f"FPT-AP2-{i}", "Supplier": "Test Supplier", "BusinessUnit": "BU Test"} for i in range(5)]
88
+ real = [{**inv, "InvoiceNumber": f"INV-{inv['InvoiceId']}"} for inv in INVOICES]
89
+ lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, []) for i in ours + real[:2]}
90
+ lines[f"invoices/{real[2]['InvoiceId']}/child/invoiceLines"] = (200, [{"DistributionCombination": "01-100-5000"}])
91
+ pod = ScriptedPod({"invoices": (200, ours + real), "suppliers": (200, [{}]), **lines})
92
+ td = discovery.sample_test_data(pod, self.area("AP"))
93
+ self.assertEqual(td["supplier"], ["Acme Supplies"]) # not the test's own supplier
94
+ self.assertNotIn("BU Test", td["business_unit"])
95
+ self.assertEqual(td["account"], ["01-100-5000"]) # found on the third real invoice, past two without lines
96
+ self.assertFalse(any("/90" in path for path, _ in pod.calls if "/child/" in path)) # our invoices were not read
97
+
98
+ def test_the_line_account_comes_from_the_tests_business_unit(self):
99
+ """Seen on a real pod (26D): the newest invoice was another unit's, its 3-segment account was refused for the
100
+ test's unit (6 segments) and every invoice scenario stopped at its first line."""
101
+ lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "100-30020-100"}])
102
+ for i in INVOICES if i["BusinessUnit"] == "BU Two"}
103
+ lines |= {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "01.100.5000.000.000.000"}])
104
+ for i in INVOICES if i["BusinessUnit"] == "BU One"}
105
+ pod = ScriptedPod({"invoices": (200, INVOICES), "suppliers": (200, [{}]), **lines})
106
+ self.assertEqual(INVOICES[0]["BusinessUnit"], "BU Two") # the newest invoice is the other unit's
107
+ td = discovery.sample_test_data(pod, self.area("AP"))
108
+ self.assertEqual(td["business_unit"][0], "BU One")
109
+ self.assertEqual(td["account"], ["01.100.5000.000.000.000"])
110
+
111
+ def test_the_suppliers_the_pod_pays_come_from_its_paid_invoices_only(self):
112
+ """Seen on a real pod (26D): the latest invoices' supplier had a payment hold, so Pay in Full was refused; the
113
+ suppliers of the pod's paid invoices are sampled apart for payment tests, and that read keeps its filter."""
114
+ paid = [{**inv, "InvoiceId": 100 + n, "Supplier": "Paid Co", "SupplierSite": "PAID MAIN", "PaidStatus": "Paid"} for n, inv in enumerate(INVOICES[:4])]
115
+ unpaid = [{**inv, "Supplier": "Held Co", "PaidStatus": "Unpaid"} for inv in INVOICES]
116
+ lines = {f"invoices/{i['InvoiceId']}/child/invoiceLines": (200, [{"DistributionCombination": "01-100-5000"}]) for i in unpaid}
117
+ pod = ScriptedPod({"invoices": (200, unpaid + paid), "suppliers": (200, [{}]), **lines})
118
+ td = discovery.sample_test_data(pod, self.area("AP"))
119
+ self.assertEqual(td["paid_supplier"], ["Paid Co"])
120
+ self.assertEqual(td["paid_supplier_site"], ["PAID MAIN"])
121
+ self.assertEqual(td["account"], ["01-100-5000"]) # the lines still come from the latest invoices
122
+ paid_reads = [p for path, p in pod.calls if path.endswith("/invoices") and "InvoiceType" not in p.get("fields", "InvoiceType")]
123
+ self.assertTrue(paid_reads and all(p.get("q") == "PaidStatus='Paid'" for p in paid_reads))
124
+
125
+ def test_a_missing_field_or_resource_leaves_the_key_out_instead_of_inventing_one(self):
126
+ pod = ScriptedPod({"invoices": (200, [{"InvoiceId": 1, "Supplier": "Only Supplier"}]), "suppliers": (200, [{}])})
127
+ td = discovery.sample_test_data(pod, self.area("AP"))
128
+ self.assertEqual(td, {"supplier": ["Only Supplier"]})
129
+
130
+ def test_overrides_win_and_empty_values_are_ignored(self):
131
+ merged = discovery.merged_test_data({"AP": {"supplier": ["A", "B"], "business_unit": ["BU"]}},
132
+ {"ap": {"supplier": "Chosen", "account": ""}})
133
+ self.assertEqual(merged, {"AP": {"supplier": "Chosen", "business_unit": "BU"}})
134
+
135
+ def test_a_deployment_adds_or_replaces_areas_without_code(self):
136
+ home = Path(tempfile.mkdtemp())
137
+ (home / "fusion_areas.json").write_text(json.dumps([
138
+ {"code": "hcm", "name": "Human Capital", "probes": ["workers"], "processes": ["Hire"]},
139
+ {"code": "AP", "name": "Payables (client)", "probes": ["invoices"]},
140
+ {"code": "bad code", "name": "x", "probes": ["../etc"]}]), encoding="utf-8")
141
+ areas = {a["code"]: a for a in fusion_catalog.areas(home)}
142
+ self.assertEqual(areas["HCM"]["probes"], ["workers"])
143
+ self.assertEqual(areas["AP"]["name"], "Payables (client)")
144
+ self.assertTrue(areas["AP"]["test_data"]) # keys not given keep the built-in values
145
+ self.assertNotIn("BAD CODE", areas)
146
+
147
+
148
+ class TestDiscoveryInTheApp(unittest.TestCase):
149
+ """Through the API and a run, with the shared fake pod (fixtures/mock_pod.json lists)."""
150
+
151
+ def setUp(self):
152
+ self.app, self.c, self.svc, self.fake = make_app()
153
+ self.h = {r: bearer(self.c, r) for r in ("viewer", "consultant", "admin")}
154
+ body = {"name": "Client test pod", "kind": "fusion", "base_url": "https://acme-test.fa.ocs.oraclecloud.com", "environment": "test"}
155
+ self.pod = self.c.post("/api/pods", json=body, headers=self.h["admin"]).json()
156
+ self.c.post(f"/api/pods/{self.pod['id']}/credentials", json={"module": "ALL", "username": "zz.tester", "password": "S3cret-x!"},
157
+ headers=self.h["admin"])
158
+
159
+ def discover(self, role="consultant"):
160
+ return self.c.post(f"/api/pods/{self.pod['id']}/discover", headers=self.h[role])
161
+
162
+ def test_discover_saves_areas_and_in_use_modules_on_the_pod(self):
163
+ self.assertEqual(self.discover("viewer").status_code, 403)
164
+ r = self.discover()
165
+ self.assertEqual(r.status_code, 200, r.text)
166
+ p = r.json()
167
+ status = {a["code"]: a["status"] for a in p["discovery"]["areas"]}
168
+ # fixture: suppliers 5 (AP in use), expense reports, fixed assets, journal batches, projects, items have records
169
+ self.assertEqual(status["AP"], "in_use")
170
+ self.assertEqual(status["PO"], "no_data")
171
+ self.assertIn(status["CM"], ("no_data", "not_available"))
172
+ self.assertEqual(sorted(p["modules"]), sorted(c for c, s in status.items() if s == "in_use"))
173
+ self.assertTrue(p["discovered_at"])
174
+ sent = [q for q in self.fake.requests if "/fscmRestApi/" in q.url.path]
175
+ self.assertTrue(sent and all(q.method == "GET" for q in sent)) # read-only
176
+ audit = self.c.get("/api/audit?limit=200", headers=self.h["admin"]).text
177
+ self.assertIn("pod.discovered", audit)
178
+ self.assertNotIn("S3cret-x!", audit)
179
+
180
+ def test_runs_may_target_the_discovered_areas_only(self):
181
+ self.discover()
182
+ r = self.c.post("/api/runs", json={"modules": ["AR"], "playwright_mode": "stub", "pod_id": self.pod["id"]}, headers=self.h["consultant"])
183
+ self.assertEqual(r.status_code, 202, r.text) # AR answers on this pod: it may run
184
+ self.app.state.runs.cancel(r.json()["run_id"], "test")
185
+ r = self.c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub", "pod_id": self.pod["id"]}, headers=self.h["consultant"])
186
+ self.assertEqual((r.status_code, r.json()["code"]), (409, "AREA_NOT_ON_FUSION"))
187
+ self.assertIn("AP", r.json()["detail"])
188
+
189
+ def test_the_scout_discovers_at_the_start_of_every_run(self):
190
+ rid = self.c.post("/api/runs", json={"modules": ["AP"], "playwright_mode": "stub", "pod_id": self.pod["id"]},
191
+ headers=self.h["consultant"]).json()["run_id"]
192
+ self.app.state.runs.drain()
193
+ events = json.dumps(self.svc.db.events(rid))
194
+ self.assertIn("Discovered on the pod", events)
195
+ p = next(x for x in self.c.get("/api/pods", headers=self.h["viewer"]).json() if x["id"] == self.pod["id"])
196
+ self.assertTrue(p["discovery"]) # saved for the next run and the Test environments page
197
+ prof = self.svc.db.kv_get("pod_profile")
198
+ self.assertEqual(prof["modules"][0]["usage_label"], "pod REST record counts")
199
+ self.assertNotIn("mock-derived", json.dumps(prof["modules"]))
200
+
201
+ def test_test_data_overrides_reach_the_test_runner_and_only_admins_set_them(self):
202
+ url = f"/api/pods/{self.pod['id']}/test-data"
203
+ body = {"overrides": {"AP": {"supplier": "Chosen Supplier", "account": "01-100-5000"}}}
204
+ self.assertEqual(self.c.put(url, json=body, headers=self.h["consultant"]).status_code, 403)
205
+ r = self.c.put(url, json=body, headers=self.h["admin"])
206
+ self.assertEqual(r.status_code, 200, r.text)
207
+ self.assertEqual(r.json()["test_data"]["AP"]["supplier"], "Chosen Supplier")
208
+ self.assertEqual(self.c.put(url, json={"overrides": {"AP": {"Bad Key": "x"}}}, headers=self.h["admin"]).status_code, 422)
209
+ from coworker.platform.pods import PodRegistry
210
+ env = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).executor_env(self.pod["id"])
211
+ self.assertEqual(json.loads(env["FUSION_TESTDATA"])["AP"], {"supplier": "Chosen Supplier", "account": "01-100-5000"})
212
+
213
+ def test_the_release_is_recorded_on_the_pod_and_checked(self):
214
+ url = f"/api/pods/{self.pod['id']}"
215
+ self.assertEqual(self.c.patch(url, json={"release": "26c"}, headers=self.h["admin"]).json()["release"], "26C")
216
+ r = self.c.patch(url, json={"release": "R13"}, headers=self.h["admin"])
217
+ self.assertEqual((r.status_code, r.json()["code"]), (422, "BAD_RELEASE"))
218
+ from coworker.platform.pods import PodRegistry
219
+ about = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).client(self.pod["id"]).about()
220
+ self.assertEqual((about["release"], about["release_known"]), ("26C", True))
221
+
222
+ def test_the_practice_pod_has_no_discovery(self):
223
+ default = next(p for p in self.c.get("/api/pods", headers=self.h["viewer"]).json() if p["is_default"])
224
+ r = self.c.post(f"/api/pods/{default['id']}/discover", headers=self.h["consultant"])
225
+ self.assertEqual((r.status_code, r.json()["code"]), (422, "NOT_FUSION"))
226
+
227
+
228
+ if __name__ == "__main__":
229
+ unittest.main()
coworker/tests/test_usage.py CHANGED
@@ -166,6 +166,16 @@ class TestCoverage(unittest.TestCase):
166
  self.assertEqual(self.v("hold_name", "Line Variance")["matches"][0]["why"], "its title says 'lines do not equal'")
167
  self.assertEqual(self.v("has_holds", "With holds")["status"], "covered")
168
 
 
 
 
 
 
 
 
 
 
 
169
  def test_coverage_is_weighted_by_volume_and_gaps_come_most_used_first(self):
170
  self.assertEqual(self.v("invoice_type", "Credit memo")["volume"], round(0.25 * 105))
171
  vols = [g["volume"] for g in self.cov["gaps"]]
 
166
  self.assertEqual(self.v("hold_name", "Line Variance")["matches"][0]["why"], "its title says 'lines do not equal'")
167
  self.assertEqual(self.v("has_holds", "With holds")["status"], "covered")
168
 
169
+ def test_a_fusion_payment_by_a_method_covers_the_invoices_of_that_method(self):
170
+ """26D's Create Invoice has no payment method (the supplier site's default is the invoice's), and Pay in Full pays with
171
+ the invoice's method: a Fusion scenario that pays by Electronic covers the invoices whose method is Electronic."""
172
+ paying = {"id": "AP-FUS-030", "title": "Quick payment by Electronic of a validated invoice is made and Negotiable",
173
+ "module": "AP", "process": "Payments", "target": "fusion", "tags": []}
174
+ cov = usage.coverage(self.prof, [*scenarios(), paying])
175
+ el = next(x for x in cov["variants"] if x["dimension"] == "payment_method" and x["value"] == "Electronic")
176
+ self.assertEqual(el["status"], "covered")
177
+ self.assertEqual(el["matches"][0]["id"], "AP-FUS-030")
178
+
179
  def test_coverage_is_weighted_by_volume_and_gaps_come_most_used_first(self):
180
  self.assertEqual(self.v("invoice_type", "Credit memo")["volume"], round(0.25 * 105))
181
  vols = [g["volume"] for g in self.cov["gaps"]]