Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/36094-flow-embed-branches.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/components': patch
'@object-ui/i18n': patch
---

feat(components): a `type: flow` metadata embed shows each decision's branches and their conditions

Clause-②: no
Metadata-protocol: none

The business view of a `type: flow` metadata embed (ADR-0051) listed the flow's steps and nothing else, so a manual could not point its readers at the diagram for an approval threshold. Under each decision step it now lists the decision's branches: the condition in readable form, such as `Amount > 500,000`, an arrow, and the step the branch leads to. A branch that is taken when no other matches reads `otherwise`. When the flow's start node has a condition, it is shown once above the steps (`Runs when Amount ≥ 100,000 and other conditions`).

The text comes from the live definition on every render: the edges' `condition` (or a decision's `config.conditions` matched by edge label), the field label from the flow's object, and the amount formatted in the reader's locale, in the field's or the tenant's currency when one is known. A changed threshold shows on the next page load with no manual edit. The embed now makes one more metadata request, for the object the flow runs on.

The reader understands comparisons of one field of that object with one literal, joined by `&&` and `||`. Presence guards on the compared field (`has(x)`, `x != null`) are left out. Anything else, such as a field compared with another field, `previous.*` or a function call, shows a neutral `condition` marker, never the raw expression. The technical view (`detail: technical`) is unchanged. The six new viewer strings ship in every locale pack.
120 changes: 120 additions & 0 deletions ui/packages/components/src/__tests__/metadata-viewer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen, waitFor, cleanup } from '@testing-library/react';
import { ComponentRegistry } from '@object-ui/core';
import { MetadataCtx } from '@object-ui/react';
import { LocalizationProvider } from '@object-ui/i18n';
import '../renderers/basic/metadata-viewer';

function metaCtx(getItem: (type: string, name: string) => Promise<any>) {
Expand Down Expand Up @@ -195,3 +196,122 @@ describe('element:metadata_viewer', () => {
expect(screen.getByText(/Unknown metadata view type/i)).toBeTruthy();
});
});

// objectstack#36094 — the business view draws each decision's branches with
// its condition read from the LIVE definition: the served flow, the edges'
// `{ dialect: 'cel', source }` envelopes, and the label and currency of the
// field from the flow's object.
describe('element:metadata_viewer flow branches (objectstack#36094)', () => {
const DEAL = {
name: 'crm_opportunity',
fields: {
amount: { type: 'currency', label: 'Amount' },
updated_by: { type: 'lookup', label: 'Updated By' },
},
};
const cel = (source: string) => ({ dialect: 'cel', source });
const approvalFlow = (threshold: number) => ({
name: 'opportunity_approval',
label: 'Large Deal Approval',
nodes: [
{
id: 'start', type: 'start', label: 'Start',
config: {
objectName: 'crm_opportunity',
condition: cel(`has(record.amount) && record.amount != null && record.amount >= 100000
&& (!has(record.approval_status) || record.approval_status == "not_required")
&& (!has(record.stage) || record.stage != "closed_won")`),
},
},
{ id: 'get_opportunity', type: 'get_record', label: 'Get Opportunity', config: { objectName: 'crm_opportunity', outputVariable: 'oppRecord' } },
{ id: 'check_high_value', type: 'decision', label: 'High Value?' },
{ id: 'director_signoff', type: 'approval', label: 'Sales Director Sign-off' },
{ id: 'mark_approved', type: 'update_record', label: 'Mark Approved' },
{ id: 'check_owner', type: 'decision', label: 'Owner Submitted?' },
{ id: 'end', type: 'end', label: 'End' },
],
edges: [
{ id: 'e1', source: 'start', target: 'get_opportunity' },
{ id: 'e2', source: 'get_opportunity', target: 'check_high_value' },
{ id: 'e5', source: 'check_high_value', target: 'director_signoff', type: 'conditional',
condition: cel(`has(vars.oppRecord) && has(vars.oppRecord.amount)
&& vars.oppRecord.amount != null && vars.oppRecord.amount > ${threshold}`) },
{ id: 'e6', source: 'check_high_value', target: 'mark_approved', type: 'conditional',
condition: cel(`!has(vars.oppRecord) || !has(vars.oppRecord.amount)
|| vars.oppRecord.amount == null || vars.oppRecord.amount <= ${threshold}`) },
{ id: 'e7', source: 'director_signoff', target: 'mark_approved' },
{ id: 'e9', source: 'mark_approved', target: 'check_owner' },
{ id: 'e13', source: 'check_owner', target: 'end', type: 'conditional',
condition: cel('has(record.updated_by) && record.updated_by == vars.oppRecord.owner_id') },
{ id: 'e14', source: 'check_owner', target: 'end', isDefault: true },
],
});
const served = (flow: unknown) => vi.fn(async (type: string) => (type === 'object' ? DEAL : flow));
const branch = (container: HTMLElement, decision: string, target: string) =>
container.querySelector(`[data-flow-branches="${decision}"] [data-branch-target="${target}"]`);

it('draws a decision’s branches with the amount condition, locale-formatted, beside each target', async () => {
const getItem = served(approvalFlow(500000));
const { container } = render(<Viewer getItem={getItem} properties={{ type: 'flow', name: 'opportunity_approval' }} />);
await waitFor(() => expect(screen.getByText('Large Deal Approval')).toBeTruthy());

expect(branch(container, 'check_high_value', 'director_signoff')?.textContent).toBe('Amount > 500,000Sales Director Sign-off');
expect(branch(container, 'check_high_value', 'mark_approved')?.textContent).toBe('Amount ≤ 500,000Mark Approved');
// One extra request, for the flow's object.
expect(getItem).toHaveBeenCalledWith('object', 'crm_opportunity');
// The entry condition, once, with its unread terms named rather than dropped.
expect(container.querySelector('[data-flow-entry]')?.textContent).toBe('Runs when Amount ≥ 100,000 and other conditions');
});

it('draws the new amount when the served definition’s threshold changes', async () => {
const { container } = render(<Viewer getItem={served(approvalFlow(750000))} properties={{ type: 'flow', name: 'opportunity_approval' }} />);
await waitFor(() => expect(screen.getByText('Large Deal Approval')).toBeTruthy());
expect(branch(container, 'check_high_value', 'director_signoff')?.textContent).toBe('Amount > 750,000Sales Director Sign-off');
expect(container.textContent).not.toContain('500,000');
});

it('waits for the flow’s object before drawing a condition, so none is drawn unread first', async () => {
let release!: (object: unknown) => void;
const objectServed = new Promise((resolve) => {
release = resolve;
});
const getItem = vi.fn((type: string) => (type === 'object' ? objectServed : Promise.resolve(approvalFlow(500000))));
const { container } = render(<Viewer getItem={getItem} properties={{ type: 'flow', name: 'opportunity_approval' }} />);
await waitFor(() => expect(getItem).toHaveBeenCalledWith('object', 'crm_opportunity'));
expect(container.querySelector('[data-condition]')).toBeNull();
expect(container.textContent).toContain('Loading');
release(DEAL);
await waitFor(() =>
expect(branch(container, 'check_high_value', 'director_signoff')?.textContent).toBe('Amount > 500,000Sales Director Sign-off'),
);
});

it('formats the amount in the tenant currency when one is configured', async () => {
const { container } = render(
<LocalizationProvider value={{ currency: 'USD', locale: 'en-US' }}>
<Viewer getItem={served(approvalFlow(500000))} properties={{ type: 'flow', name: 'opportunity_approval' }} />
</LocalizationProvider>,
);
await waitFor(() => expect(screen.getByText('Large Deal Approval')).toBeTruthy());
expect(branch(container, 'check_high_value', 'director_signoff')?.textContent).toBe('Amount > $500,000Sales Director Sign-off');
});

it('shows a neutral marker for a condition too complex to read, never the raw CEL', async () => {
const { container } = render(<Viewer getItem={served(approvalFlow(500000))} properties={{ type: 'flow', name: 'opportunity_approval' }} />);
await waitFor(() => expect(screen.getByText('Large Deal Approval')).toBeTruthy());
const opaque = branch(container, 'check_owner', 'end')!;
expect(opaque.querySelector('[data-condition="opaque"]')?.textContent).toBe('condition');
expect(container.querySelector('[data-condition="otherwise"]')?.textContent).toBe('otherwise');
expect(container.textContent).not.toContain('updated_by');
expect(container.textContent).not.toContain('has(');
});

it('keeps the technical view as it was: no branches, no entry condition, no object request', async () => {
const getItem = served(approvalFlow(500000));
const { container } = render(<Viewer getItem={getItem} properties={{ type: 'flow', name: 'opportunity_approval', detail: 'technical' }} />);
await waitFor(() => expect(screen.getByText('Mark Approved')).toBeTruthy());
expect(container.querySelector('[data-flow-branches]')).toBeNull();
expect(container.querySelector('[data-flow-entry]')).toBeNull();
expect(getItem).not.toHaveBeenCalledWith('object', expect.anything());
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* objectstack#36094 — the pure half of the `type: flow` embed's branches:
* which out-edges a decision routes down, and the fail-closed reader that
* turns their CEL into text or answers `null` (the neutral marker).
*/

import { describe, it, expect } from 'vitest';
import {
decisionBranches,
entryGuard,
flowSubjects,
readCondition,
subjectFieldOf,
type ConditionContext,
type FlowConditionField,
} from '../flow-branches';

const FIELDS: Record<string, FlowConditionField> = {
amount: { label: 'Amount', type: 'currency' },
stage: { label: 'Stage', type: 'select', options: [{ value: 'closed_won', label: 'Closed Won' }] },
name: { label: 'Name', type: 'text' },
is_vip: { label: 'VIP', type: 'boolean' },
};

const SUBJECTS = { object: 'deal', rowVariables: new Set(['row']) };

const ctx: ConditionContext = {
field: (path) => {
const name = subjectFieldOf(path, SUBJECTS);
return name ? FIELDS[name] : undefined;
},
formatNumber: (value) => new Intl.NumberFormat('en').format(value),
words: { and: 'and', or: 'or', more: 'other conditions' },
};

describe('readCondition (objectstack#36094)', () => {
it.each([
['record.amount > 500000', 'Amount > 500,000'],
['500000 < record.amount', 'Amount > 500,000'],
['record.amount >= 1000 && record.amount <= 2000', 'Amount ≥ 1,000 and Amount ≤ 2,000'],
['has(vars.row) && has(vars.row.amount) && vars.row.amount != null && vars.row.amount > 5', 'Amount > 5'],
['!has(row.amount) || row.amount == null || row.amount <= 5', 'Amount ≤ 5'],
["record.stage == 'closed_won'", 'Stage = Closed Won'],
['record.name != "Acme"', 'Name ≠ “Acme”'],
['record.amount > 1 || (record.amount < -1 && record.stage == "closed_won")', 'Amount > 1 or (Amount < -1 and Stage = Closed Won)'],
['record.amount > 1 && record.owner == current_user.id', 'Amount > 1 and other conditions'],
])('reads %s', (source, text) => {
expect(readCondition(source, ctx)).toBe(text);
});

it.each([
['a field compared with a field', 'record.amount > record.name'],
['a field the object does not declare', 'record.discount > 5'],
['the prior row', 'previous.amount > 5'],
['a variable that holds no row of the object', 'vars.manager_review.decision != "recall"'],
['a function call', 'size(record.name) > 3'],
['a boolean field', 'record.is_vip == true'],
['an ordering on text', 'record.name > "a"'],
['an option the field does not declare', 'record.stage == "lost"'],
['an escaped string', 'record.name == "a\\"b"'],
['a list membership', 'record.stage in ["closed_won"]'],
['a ternary', 'record.amount > 1 ? true : false'],
['a presence guard alone', 'has(record.amount)'],
['a disjunction with an unread term', 'record.amount > 1 || record.owner == current_user.id'],
['a conjunction where nothing reads', 'record.owner == current_user.id && previous.amount > 1'],
['a negated comparison', '!(record.amount > 5)'],
['trailing tokens', 'record.amount > 5 5'],
['an empty source', ' '],
])('answers null for %s', (_what, source) => {
expect(readCondition(source, ctx)).toBeNull();
});
});

describe('decisionBranches (objectstack#36094)', () => {
it('reads a gateway decision from its out-edges, in declaration order', () => {
const flow = {
edges: [
{ id: 'a', source: 'd', target: 'big', condition: { dialect: 'cel', source: 'record.amount > 5' } },
{ id: 'b', source: 'd', target: 'small', condition: 'record.amount <= 5' },
{ id: 'c', source: 'd', target: 'other', condition: { dialect: 'template', source: '{x}' } },
{ id: 'e', source: 'd', target: 'fallback', isDefault: true },
{ id: 'f', source: 'x', target: 'big' },
],
};
expect(decisionBranches(flow, { id: 'd', type: 'decision' })).toEqual([
{ key: 'a', target: 'big', guard: { kind: 'cel', source: 'record.amount > 5' } },
{ key: 'b', target: 'small', guard: { kind: 'cel', source: 'record.amount <= 5' } },
{ key: 'c', target: 'other', guard: { kind: 'opaque' } },
{ key: 'e', target: 'fallback', guard: { kind: 'otherwise' } },
]);
});

it('reads a `config.conditions` decision through the out-edge labels, and leaves out an edge no branch claims', () => {
const node = { id: 'd', type: 'decision', config: { conditions: [{ label: 'big', expression: 'record.amount > 5' }] } };
const flow = {
edges: [
{ id: 'a', source: 'd', target: 'x', label: 'big' },
{ id: 'b', source: 'd', target: 'y', label: 'default' },
{ id: 'c', source: 'd', target: 'z', label: 'unclaimed' },
],
};
expect(decisionBranches(flow, node)).toEqual([
{ key: 'a', target: 'x', guard: { kind: 'cel', source: 'record.amount > 5' } },
{ key: 'b', target: 'y', guard: { kind: 'otherwise' } },
]);
});

it('answers nothing for a node that is not a decision', () => {
expect(decisionBranches({ edges: [{ source: 'a', target: 'b' }] }, { id: 'a', type: 'approval' })).toEqual([]);
});
});

describe('flowSubjects and entryGuard (objectstack#36094)', () => {
const flow = {
nodes: [
{ id: 's', type: 'start', config: { objectName: 'deal', condition: { dialect: 'cel', source: 'record.amount >= 1' } } },
{ id: 'g', type: 'get_record', config: { objectName: 'deal', outputVariable: 'row' } },
{ id: 'h', type: 'get_record', config: { objectName: 'account', outputVariable: 'acct' } },
],
};

it('resolves the trigger object and the row variables that read it, not another object’s', () => {
const subjects = flowSubjects(flow);
expect(subjects.object).toBe('deal');
expect([...subjects.rowVariables]).toEqual(['row']);
expect(subjectFieldOf(['acct', 'amount'], subjects)).toBeUndefined();
expect(subjectFieldOf(['vars', 'row', 'amount'], subjects)).toBe('amount');
});

it('reads the start node’s condition as the entry guard', () => {
expect(entryGuard(flow)).toEqual({ kind: 'cel', source: 'record.amount >= 1' });
expect(entryGuard({ nodes: [{ id: 's', type: 'start' }] })).toEqual({ kind: 'none' });
});
});
Loading
Loading