diff --git a/.changeset/36094-flow-embed-branches.md b/.changeset/36094-flow-embed-branches.md new file mode 100644 index 00000000000..b8e5c1b36d0 --- /dev/null +++ b/.changeset/36094-flow-embed-branches.md @@ -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. diff --git a/ui/packages/components/src/__tests__/metadata-viewer.test.tsx b/ui/packages/components/src/__tests__/metadata-viewer.test.tsx index d9cdaf66b52..d3846f4c90d 100644 --- a/ui/packages/components/src/__tests__/metadata-viewer.test.tsx +++ b/ui/packages/components/src/__tests__/metadata-viewer.test.tsx @@ -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) { @@ -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(); + 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(); + 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(); + 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( + + + , + ); + 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(); + 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(); + 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()); + }); +}); diff --git a/ui/packages/components/src/renderers/basic/__tests__/flow-branches-36094.test.ts b/ui/packages/components/src/renderers/basic/__tests__/flow-branches-36094.test.ts new file mode 100644 index 00000000000..2a788e77213 --- /dev/null +++ b/ui/packages/components/src/renderers/basic/__tests__/flow-branches-36094.test.ts @@ -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 = { + 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' }); + }); +}); diff --git a/ui/packages/components/src/renderers/basic/flow-branches.ts b/ui/packages/components/src/renderers/basic/flow-branches.ts new file mode 100644 index 00000000000..e3d1d7f16b2 --- /dev/null +++ b/ui/packages/components/src/renderers/basic/flow-branches.ts @@ -0,0 +1,452 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * The decision branches of a flow, and a readable form of their conditions, + * for the business view of `element:metadata_viewer`'s `type: flow` embed + * (ADR-0051: the embed draws the LIVE definition, so the text here is derived + * from the served flow on every render and never copied into a manual). + * + * Two halves, both pure: + * + * - {@link decisionBranches} reads where a decision routes, in the two forms + * the automation engine runs: a decision that declares `config.conditions` + * takes the out-edge whose `label` names the first matching branch (or the + * `default` / `isDefault` edge when none matches); a decision that declares + * none is a gateway whose out-edges carry their own `condition`. + * - {@link readCondition} turns a CEL predicate into text such as + * `Amount > 500,000`, or answers `null` when the predicate is outside the + * small grammar it reads. The caller shows a neutral "condition" marker for + * `null`, never the raw expression. + * + * The reader understands comparisons of one record field with one literal, + * joined by `&&` / `||`, with parentheses. Presence guards on a compared field + * (`has(x)`, `x != null` under `&&`; `!has(x)`, `x == null` under `||`) are + * dropped: the platform's null-guard rule makes every ordering comparison + * carry one, so they are plumbing, not the business rule. Anything else (a + * function call, a field compared with a field, `previous.*`, a flow variable + * that is not a read of the flow's own object, an escape in a string) is not + * read at all. + */ + +// --------------------------------------------------------------------------- +// Graph: decisions and their branches +// --------------------------------------------------------------------------- + +/** Where one branch of a decision goes, and on what. */ +export type BranchGuard = + /** The branch carries a CEL predicate (its source). */ + | { kind: 'cel'; source: string } + /** The branch is taken when no sibling branch matched. */ + | { kind: 'otherwise' } + /** The branch carries a condition in a form this view does not read. */ + | { kind: 'opaque' } + /** The out-edge carries no condition at all. */ + | { kind: 'none' }; + +export interface DecisionBranch { + /** The out-edge's id, or its position when it has none. */ + key: string; + /** The node id the branch leads to. */ + target: string; + guard: BranchGuard; +} + +/** The label a decision's fall-through branch carries (`DEFAULT_BRANCH_LABEL` in the engine). */ +const DEFAULT_BRANCH = 'default'; + +type Rec = Record; + +function isRec(value: unknown): value is Rec { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * The guard an evaluated-expression slot carries, read as the spec's + * `EvaluatedExpressionInputSchema` admits it: a bare CEL string, or a + * `{ dialect: 'cel', source }` envelope (what a parse normalizes the string + * to). Any other value is a condition this view cannot read. + */ +function guardOf(value: unknown): BranchGuard { + if (value === undefined || value === null) return { kind: 'none' }; + if (typeof value === 'string') return value.trim() ? { kind: 'cel', source: value } : { kind: 'opaque' }; + if (isRec(value) && value.dialect === 'cel' && typeof value.source === 'string' && value.source.trim()) { + return { kind: 'cel', source: value.source }; + } + return { kind: 'opaque' }; +} + +/** Every out-edge of `nodeId`, in declaration order (the order the engine tries them in). */ +function outEdges(flow: unknown, nodeId: string): Rec[] { + const edges = isRec(flow) && Array.isArray(flow.edges) ? flow.edges : []; + return edges.filter((e): e is Rec => isRec(e) && e.source === nodeId && typeof e.target === 'string'); +} + +/** + * The branches of the decision node `node`, in declaration order. An out-edge + * no branch can ever take (a labelled edge of a `config.conditions` decision + * whose label no condition and no default claims) is left out. + */ +export function decisionBranches(flow: unknown, node: unknown): DecisionBranch[] { + if (!isRec(node) || node.type !== 'decision' || typeof node.id !== 'string') return []; + const config = isRec(node.config) ? node.config : undefined; + const conditions = Array.isArray(config?.conditions) ? config.conditions.filter(isRec) : []; + const branches: DecisionBranch[] = []; + outEdges(flow, node.id).forEach((edge, i) => { + const key = typeof edge.id === 'string' ? edge.id : String(i); + const target = edge.target as string; + if (edge.isDefault === true || (conditions.length > 0 && edge.label === DEFAULT_BRANCH)) { + branches.push({ key, target, guard: { kind: 'otherwise' } }); + return; + } + if (conditions.length === 0) { + branches.push({ key, target, guard: guardOf(edge.condition) }); + return; + } + const claimed = conditions.find((c) => typeof edge.label === 'string' && c.label === edge.label); + if (!claimed) return; + const guard = guardOf(claimed.expression); + branches.push({ key, target, guard: guard.kind === 'none' ? { kind: 'opaque' } : guard }); + }); + return branches; +} + +/** The predicate a flow's start node gates its runs on, if it declares one. */ +export function entryGuard(flow: unknown): BranchGuard { + const nodes = isRec(flow) && Array.isArray(flow.nodes) ? flow.nodes : []; + const start = nodes.find((n): n is Rec => isRec(n) && n.type === 'start'); + return guardOf(isRec(start?.config) ? start.config.condition : undefined); +} + +/** + * The object the flow's conditions read: the start node's `objectName` (the + * record that triggers the run), plus every `get_record` output variable that + * reads the same object. A variable that reads another object is not + * resolved, so the embed needs exactly one object definition. + */ +export interface FlowSubjects { + object?: string; + /** Output variables holding a row of {@link object}. */ + rowVariables: Set; +} + +export function flowSubjects(flow: unknown): FlowSubjects { + const nodes = isRec(flow) && Array.isArray(flow.nodes) ? flow.nodes.filter(isRec) : []; + const start = nodes.find((n) => n.type === 'start'); + const startConfig = isRec(start?.config) ? start.config : undefined; + const object = typeof startConfig?.objectName === 'string' ? startConfig.objectName : undefined; + const rowVariables = new Set(); + if (object) { + for (const n of nodes) { + const c = isRec(n.config) ? n.config : undefined; + if (n.type === 'get_record' && c?.objectName === object && typeof c.outputVariable === 'string') { + rowVariables.add(c.outputVariable); + } + } + } + return { object, rowVariables }; +} + +/** + * The field of the subject object a CEL path reads, or `undefined` when the + * path is not a read of one: `record.F`, `vars.V.F` or `V.F` for a row + * variable `V`. + */ +export function subjectFieldOf(path: readonly string[], subjects: FlowSubjects): string | undefined { + if (!subjects.object) return undefined; + if (path.length === 2 && path[0] === 'record') return path[1]; + if (path.length === 3 && path[0] === 'vars' && subjects.rowVariables.has(path[1])) return path[2]; + if (path.length === 2 && subjects.rowVariables.has(path[0])) return path[1]; + return undefined; +} + +// --------------------------------------------------------------------------- +// CEL: a small, fail-closed reader +// --------------------------------------------------------------------------- + +type Literal = number | string | boolean | null; + +type Expr = + | { kind: 'and' | 'or'; terms: Expr[] } + | { kind: 'not'; expr: Expr } + | { kind: 'cmp'; op: CmpOp; left: Operand; right: Operand } + | { kind: 'has'; path: string[] } + | { kind: 'operand'; operand: Operand }; + +type Operand = { kind: 'path'; path: string[] } | { kind: 'lit'; value: Literal } | { kind: 'has'; path: string[] }; + +type CmpOp = '==' | '!=' | '>' | '>=' | '<' | '<='; + +type Token = + | { t: 'op'; v: string } + | { t: 'num'; v: number } + | { t: 'str'; v: string } + | { t: 'id'; v: string }; + +const TWO_CHAR = new Set(['&&', '||', '==', '!=', '>=', '<=']); +const ONE_CHAR = new Set(['>', '<', '!', '(', ')', ',', '.', '-']); + +/** The tokens of `src`, or `null` on any character outside the grammar. */ +function tokenize(src: string): Token[] | null { + const out: Token[] = []; + let i = 0; + while (i < src.length) { + const c = src[i]; + if (/\s/u.test(c)) { + i++; + continue; + } + const two = src.slice(i, i + 2); + if (TWO_CHAR.has(two)) { + out.push({ t: 'op', v: two }); + i += 2; + continue; + } + if (/[0-9]/u.test(c)) { + const m = /^[0-9]+(?:\.[0-9]+)?/u.exec(src.slice(i)); + if (!m) return null; + // A suffix (`1u`, `1e3`) or a second dot is outside the grammar. + if (/^[A-Za-z_.]/u.test(src.slice(i + m[0].length))) return null; + out.push({ t: 'num', v: Number(m[0]) }); + i += m[0].length; + continue; + } + if (c === '"' || c === "'") { + const end = src.indexOf(c, i + 1); + if (end === -1) return null; + const body = src.slice(i + 1, end); + // Escapes and multi-line strings are left to the real parser. + if (body.includes('\\') || body.includes('\n')) return null; + out.push({ t: 'str', v: body }); + i = end + 1; + continue; + } + if (/[A-Za-z_]/u.test(c)) { + const m = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(src.slice(i))!; + out.push({ t: 'id', v: m[0] }); + i += m[0].length; + continue; + } + if (ONE_CHAR.has(c)) { + out.push({ t: 'op', v: c }); + i++; + continue; + } + return null; + } + return out; +} + +const CMP_OPS = new Set(['==', '!=', '>', '>=', '<', '<=']); + +class Fail extends Error {} + +/** The expression tree of `src`, or `null` when it is outside the grammar. */ +function parse(src: string): Expr | null { + const tokens = tokenize(src); + if (!tokens || tokens.length === 0) return null; + let pos = 0; + const peek = (): Token | undefined => tokens[pos]; + const isOp = (v: string): boolean => { + const tok = peek(); + return tok?.t === 'op' && tok.v === v; + }; + const expect = (v: string): void => { + if (!isOp(v)) throw new Fail(); + pos++; + }; + + const junction = (kind: 'and' | 'or', op: string, next: () => Expr) => (): Expr => { + const terms = [next()]; + while (isOp(op)) { + pos++; + terms.push(next()); + } + if (terms.length === 1) return terms[0]; + // `a && (b && c)` is one conjunction. + return { kind, terms: terms.flatMap((x) => (x.kind === kind ? x.terms : [x])) }; + }; + + const operand = (): Operand => { + const tok = peek(); + if (!tok) throw new Fail(); + pos++; + if (tok.t === 'num') return { kind: 'lit', value: tok.v }; + if (tok.t === 'str') return { kind: 'lit', value: tok.v }; + if (tok.t === 'op' && tok.v === '-') { + const n = peek(); + if (n?.t !== 'num') throw new Fail(); + pos++; + return { kind: 'lit', value: -n.v }; + } + if (tok.t !== 'id') throw new Fail(); + if (tok.v === 'true' || tok.v === 'false') return { kind: 'lit', value: tok.v === 'true' }; + if (tok.v === 'null') return { kind: 'lit', value: null }; + const path = [tok.v]; + while (isOp('.')) { + pos++; + const seg = peek(); + if (seg?.t !== 'id') throw new Fail(); + pos++; + path.push(seg.v); + } + if (isOp('(')) { + // A call: only the presence macro `has(path)` is read. + if (path.length !== 1 || path[0] !== 'has') throw new Fail(); + pos++; + const arg = operand(); + expect(')'); + if (arg.kind !== 'path') throw new Fail(); + return { kind: 'has', path: arg.path }; + } + return { kind: 'path', path }; + }; + + const primary = (): Expr => { + if (isOp('(')) { + pos++; + const inner = or(); + expect(')'); + return inner; + } + const left = operand(); + if (left.kind === 'has') return { kind: 'has', path: left.path }; + const tok = peek(); + if (tok?.t === 'op' && CMP_OPS.has(tok.v)) { + pos++; + const right = operand(); + if (right.kind === 'has') throw new Fail(); + return { kind: 'cmp', op: tok.v as CmpOp, left, right }; + } + return { kind: 'operand', operand: left }; + }; + + const unary = (): Expr => { + if (isOp('!')) { + pos++; + return { kind: 'not', expr: unary() }; + } + return primary(); + }; + + const and = junction('and', '&&', unary); + const or = junction('or', '||', and); + + try { + const tree = or(); + return pos === tokens.length ? tree : null; + } catch (e) { + if (e instanceof Fail) return null; + throw e; + } +} + +/** One field as the reader needs it, resolved by the caller from the object definition. */ +export interface FlowConditionField { + label: string; + type?: string; + options?: ReadonlyArray<{ value?: unknown; label?: unknown }>; + /** The ISO 4217 code a currency field's amounts are in, handed back to `formatNumber`. */ + currency?: string; +} + +export interface ConditionContext { + /** The field a CEL path reads, or `undefined` when it is not a field of the subject object. */ + field(path: readonly string[]): FlowConditionField | undefined; + /** A number literal compared with `field`, formatted for the reader. */ + formatNumber(value: number, field: FlowConditionField): string; + /** The reader's words for the junctions. `more` stands for terms of a conjunction left unread. */ + words: { and: string; or: string; more: string }; +} + +const SYMBOL: Record = { '==': '=', '!=': '≠', '>': '>', '>=': '≥', '<': '<', '<=': '≤' }; +const FLIP: Record = { '==': '==', '!=': '!=', '>': '<', '>=': '<=', '<': '>', '<=': '>=' }; +const NUMBER_TYPES = new Set(['number', 'currency']); +const CHOICE_TYPES = new Set(['select', 'radio']); +const TEXT_TYPES = new Set(['text', 'textarea', 'email', 'url', 'phone']); + +const pathKey = (path: readonly string[]): string => path.join('.'); + +/** The field path a comparison reads and the literal it reads it against, path on the left. */ +function comparison(e: Expr): { path: string[]; op: CmpOp; value: Literal } | undefined { + if (e.kind !== 'cmp') return undefined; + if (e.left.kind === 'path' && e.right.kind === 'lit') return { path: e.left.path, op: e.op, value: e.right.value }; + if (e.left.kind === 'lit' && e.right.kind === 'path') return { path: e.right.path, op: FLIP[e.op], value: e.left.value }; + return undefined; +} + +/** Whether `prefix` is `path` or one of its ancestors (`vars.row` of `vars.row.amount`). */ +function covers(prefix: readonly string[], path: readonly string[]): boolean { + return prefix.length <= path.length && prefix.every((seg, i) => seg === path[i]); +} + +/** + * Whether `term` only guards the presence of a compared path: under `&&`, + * `has(p)` or `p != null`; under `||`, `!has(p)` or `p == null`. + */ +function isGuard(term: Expr, junction: 'and' | 'or', compared: readonly string[][]): boolean { + const hasArg = + junction === 'and' + ? term.kind === 'has' ? term.path : undefined + : term.kind === 'not' && term.expr.kind === 'has' ? term.expr.path : undefined; + if (hasArg) return compared.some((p) => covers(hasArg, p)); + const c = comparison(term); + if (!c || c.value !== null || c.op !== (junction === 'and' ? '!=' : '==')) return false; + return compared.some((p) => pathKey(p) === pathKey(c.path)); +} + +function readComparison(e: Expr, ctx: ConditionContext): string | null { + const c = comparison(e); + if (!c || c.value === null) return null; + const field = ctx.field(c.path); + if (!field) return null; + const type = field.type ?? ''; + let value: string; + if (typeof c.value === 'number' && NUMBER_TYPES.has(type)) { + value = ctx.formatNumber(c.value, field); + } else if (typeof c.value === 'string' && (c.op === '==' || c.op === '!=') && CHOICE_TYPES.has(type)) { + const option = field.options?.find((o) => o?.value === c.value); + if (!option || typeof option.label !== 'string') return null; + value = option.label; + } else if (typeof c.value === 'string' && (c.op === '==' || c.op === '!=') && TEXT_TYPES.has(type)) { + value = `“${c.value}”`; + } else { + return null; + } + return `${field.label} ${SYMBOL[c.op]} ${value}`; +} + +function read(e: Expr, ctx: ConditionContext, top: boolean): string | null { + if (e.kind !== 'and' && e.kind !== 'or') return readComparison(e, ctx); + const compared = e.terms + .map(comparison) + .filter((c): c is NonNullable => !!c && c.value !== null) + .map((c) => c.path); + const terms = e.terms.filter((term) => !isGuard(term, e.kind, compared)); + if (terms.length === 0) return null; + const parts = terms.map((term) => { + const text = read(term, ctx, false); + return text !== null && (term.kind === 'and' || term.kind === 'or') && terms.length > 1 ? `(${text})` : text; + }); + const readable = parts.filter((p): p is string => p !== null); + if (readable.length === parts.length) return readable.join(` ${ctx.words[e.kind]} `); + // Every term of a top-level conjunction must hold, so the terms that read are + // each true of a matching record; the rest are named, not dropped. + if (e.kind === 'and' && top && readable.length > 0) { + return [...readable, ctx.words.more].join(` ${ctx.words.and} `); + } + return null; +} + +/** + * `source` as text a business reader can follow (`Amount > 500,000`), or + * `null` when it is outside the reader's grammar or reads anything but the + * fields `ctx` resolves. + */ +export function readCondition(source: string, ctx: ConditionContext): string | null { + const tree = parse(source); + return tree ? read(tree, ctx, true) : null; +} diff --git a/ui/packages/components/src/renderers/basic/metadata-viewer.tsx b/ui/packages/components/src/renderers/basic/metadata-viewer.tsx index b89f604017f..b4e787426f1 100644 --- a/ui/packages/components/src/renderers/basic/metadata-viewer.tsx +++ b/ui/packages/components/src/renderers/basic/metadata-viewer.tsx @@ -21,7 +21,14 @@ import * as React from 'react'; import { ComponentRegistry } from '@object-ui/core'; import { useMetadataItem, resolveInlineAriaProps } from '@object-ui/react'; -import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; +import { + formatCurrency, + formatNumber, + resolveFieldCurrency, + useDisplayLocale, + useLocalization, + useObjectTranslation, +} from '@object-ui/i18n'; import type { AriaProps } from '@object-ui/types'; import { ArrowRight, @@ -37,6 +44,17 @@ import { import type { SelectOption as SpecSelectOption } from '@objectstack/spec/data'; import { cn } from '../../lib/utils'; import { readProps } from './readProps'; +import { + decisionBranches, + entryGuard, + flowSubjects, + readCondition, + subjectFieldOf, + type BranchGuard, + type ConditionContext, + type FlowConditionField, + type FlowSubjects, +} from './flow-branches'; // --------------------------------------------------------------------------- // Shared helpers @@ -381,9 +399,129 @@ const TECHNICAL_NODE_TYPES = new Set([ 'boundary_event', ]); +/** + * How the business view reads a condition (`flow-branches.ts`): field labels + * and options from the flow's object as served, amounts in the reader's + * locale and, for a currency field, its currency. + */ +function useConditionContext(object: any, subjects: FlowSubjects): ConditionContext { + const { t } = useObjectTranslation(); + const locale = useDisplayLocale(); + const { currency: tenantCurrency } = useLocalization(); + return { + field(path): FlowConditionField | undefined { + const name = subjectFieldOf(path, subjects); + const def = getField(object, name); + if (!name || !def || typeof def !== 'object') return undefined; + return { + label: typeof def.label === 'string' && def.label ? def.label : name, + type: def.type, + options: Array.isArray(def.options) ? def.options : undefined, + currency: def.type === 'currency' ? resolveFieldCurrency(def, tenantCurrency) : undefined, + }; + }, + formatNumber(value, field) { + if (!field.currency) return formatNumber(value, { locale }); + // A whole threshold reads whole (`$500,000`); a fractional one at the + // currency's own width. + const whole = Number.isInteger(value) ? { minimumFractionDigits: 0, maximumFractionDigits: 0 } : {}; + try { + return formatCurrency(value, { locale, currency: field.currency, ...whole }); + } catch { + return formatNumber(value, { locale }); + } + }, + words: { + and: t('element.metadataViewer.conditionAnd', { defaultValue: 'and' }), + or: t('element.metadataViewer.conditionOr', { defaultValue: 'or' }), + more: t('element.metadataViewer.conditionMore', { defaultValue: 'other conditions' }), + }, + }; +} + +/** The business view's condition reader, provided by {@link FlowConditions}. */ +const ConditionScope = React.createContext(null); + +/** + * Reads the object the flow runs on (one request per embed) and provides the + * condition reader to the branches below it. Mounted once the flow is known, + * so its object request starts in the loading state rather than drawing the + * conditions unread for a render. + */ +function FlowConditions({ flow, fallback, children }: { flow: unknown; fallback: React.ReactNode; children: React.ReactNode }) { + const subjects = flowSubjects(flow); + const subject = useMetadataItem('object', subjects.object ?? null); + const ctx = useConditionContext(subject.item, subjects); + if (subject.loading) return <>{fallback}; + return {children}; +} + +/** A branch's condition as text, or the neutral marker when it cannot be read; never the raw expression. */ +function ConditionText({ guard, ctx }: { guard: BranchGuard; ctx: ConditionContext }) { + const { t } = useObjectTranslation(); + if (guard.kind === 'none') return null; + if (guard.kind === 'otherwise') { + return ( + + {t('element.metadataViewer.otherwise', { defaultValue: 'otherwise' })} + + ); + } + const text = guard.kind === 'cel' ? readCondition(guard.source, ctx) : null; + if (text === null) { + return ( + + {t('element.metadataViewer.condition', { defaultValue: 'condition' })} + + ); + } + return ( + + {text} + + ); +} + +/** The flow's entry condition, once, above its steps. */ +function EntryCondition({ flow }: { flow: unknown }) { + const { t } = useObjectTranslation(); + const ctx = React.useContext(ConditionScope); + const guard = entryGuard(flow); + if (!ctx || guard.kind === 'none') return null; + return ( +
+ {withChips(t('element.metadataViewer.runsWhen', { defaultValue: 'Runs when {{condition}}', condition: CHIP[0] }), [ + , + ])} +
+ ); +} + +/** A decision's branches: each condition (or the neutral marker) and the step it leads to. */ +function Branches({ flow, node, nodes }: { flow: unknown; node: any; nodes: any[] }) { + const ctx = React.useContext(ConditionScope); + const branches = decisionBranches(flow, node); + if (!ctx || branches.length === 0) return null; + return ( +
    + {branches.map((b) => { + const target = nodes.find((x) => x?.id === b.target); + return ( +
  • + + + {target?.label ?? b.target} +
  • + ); + })} +
+ ); +} + function FlowView({ name, detail }: ViewerProps) { const { item: flow, loading, error } = useMetadataItem('flow', name ?? null); const { t, ...view } = useViewStates(); + const business = (detail ?? 'business') === 'business'; if (!name) return view.missing('name'); if (loading) return view.loading(name); @@ -391,11 +529,10 @@ function FlowView({ name, detail }: ViewerProps) { if (!flow) return view.notFound(name); const allNodes: any[] = Array.isArray(flow.nodes) ? flow.nodes : []; - const business = (detail ?? 'business') === 'business'; const nodes = business ? allNodes.filter((n) => !TECHNICAL_NODE_TYPES.has(n?.type)) : allNodes; const hiddenCount = allNodes.length - nodes.length; - return ( + const card = ( + {business && } {nodes.length === 0 ? ( {t('element.metadataViewer.noSteps', { defaultValue: 'No steps to show.' })} ) : (
    {nodes.map((n, i) => ( -
  1. +
  2. {i + 1} @@ -422,6 +560,7 @@ function FlowView({ name, detail }: ViewerProps) { {n.type} )} + {business && }
  3. ))}
@@ -440,6 +579,13 @@ function FlowView({ name, detail }: ViewerProps) { )}
); + return business ? ( + + {card} + + ) : ( + card + ); } // --------------------------------------------------------------------------- diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index e18bce9d7f3..333ceea6900 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -6251,6 +6251,12 @@ const ar = { object: "الكائن", unknownType: "نوع عرض بيانات وصفية غير معروف. المتوقع {{a}} أو {{b}} أو {{c}}.", unknownTypeNamed: "نوع عرض بيانات وصفية غير معروف «{{type}}». المتوقع {{a}} أو {{b}} أو {{c}}.", + condition: "شرط", + otherwise: "خلاف ذلك", + conditionAnd: "و", + conditionOr: "أو", + conditionMore: "شروط أخرى", + runsWhen: "يعمل عندما {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 2a033c8f5f2..a84bf7081db 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5600,6 +5600,12 @@ const de = { object: "Objekt", unknownType: "Unbekannter Metadaten-Ansichtstyp. Erwartet: {{a}}, {{b}} oder {{c}}.", unknownTypeNamed: "Unbekannter Metadaten-Ansichtstyp „{{type}}“. Erwartet: {{a}}, {{b}} oder {{c}}.", + condition: "Bedingung", + otherwise: "sonst", + conditionAnd: "und", + conditionOr: "oder", + conditionMore: "weitere Bedingungen", + runsWhen: "Läuft, wenn {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 4d7918692fd..3b080c846d7 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -6522,6 +6522,12 @@ const en = { object: 'Object', unknownType: 'Unknown metadata view type. Expected {{a}}, {{b}} or {{c}}.', unknownTypeNamed: 'Unknown metadata view type “{{type}}”. Expected {{a}}, {{b}} or {{c}}.', + condition: 'condition', + otherwise: 'otherwise', + conditionAnd: 'and', + conditionOr: 'or', + conditionMore: 'other conditions', + runsWhen: 'Runs when {{condition}}', }, }, // `kind:'react'` page renderer's notices (`react-page.tsx`, #25916). A diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c88ae91d62b..13cfd0af73d 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5762,6 +5762,12 @@ const es = { object: "Objeto", unknownType: "Tipo de vista de metadatos desconocido. Se esperaba {{a}}, {{b}} o {{c}}.", unknownTypeNamed: "Tipo de vista de metadatos desconocido «{{type}}». Se esperaba {{a}}, {{b}} o {{c}}.", + condition: "condición", + otherwise: "en otro caso", + conditionAnd: "y", + conditionOr: "o", + conditionMore: "otras condiciones", + runsWhen: "Se ejecuta cuando {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ef726e72880..e205f53138f 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5758,6 +5758,12 @@ const fr = { object: "Objet", unknownType: "Type de vue de métadonnées inconnu. Attendu : {{a}}, {{b}} ou {{c}}.", unknownTypeNamed: "Type de vue de métadonnées inconnu « {{type}} ». Attendu : {{a}}, {{b}} ou {{c}}.", + condition: "condition", + otherwise: "sinon", + conditionAnd: "et", + conditionOr: "ou", + conditionMore: "autres conditions", + runsWhen: "S’exécute si {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 448fa4639b3..198f72dd79a 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5601,6 +5601,12 @@ const ja = { object: "オブジェクト", unknownType: "不明なメタデータビューの種類です。{{a}}、{{b}}、{{c}} のいずれかを指定してください。", unknownTypeNamed: "不明なメタデータビューの種類「{{type}}」です。{{a}}、{{b}}、{{c}} のいずれかを指定してください。", + condition: "条件", + otherwise: "それ以外", + conditionAnd: "かつ", + conditionOr: "または", + conditionMore: "その他の条件", + runsWhen: "実行条件:{{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 4f3eaec7882..500635ecf78 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5598,6 +5598,12 @@ const ko = { object: "개체", unknownType: "알 수 없는 메타데이터 보기 유형입니다. {{a}}, {{b}} 또는 {{c}}이어야 합니다.", unknownTypeNamed: "알 수 없는 메타데이터 보기 유형 “{{type}}”입니다. {{a}}, {{b}} 또는 {{c}}이어야 합니다.", + condition: "조건", + otherwise: "그 외", + conditionAnd: "그리고", + conditionOr: "또는", + conditionMore: "기타 조건", + runsWhen: "실행 조건: {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 95ec476cf80..cc76c4580a7 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5757,6 +5757,12 @@ const pt = { object: "Objeto", unknownType: "Tipo de visualização de metadados desconhecido. Esperado {{a}}, {{b}} ou {{c}}.", unknownTypeNamed: "Tipo de visualização de metadados desconhecido “{{type}}”. Esperado {{a}}, {{b}} ou {{c}}.", + condition: "condição", + otherwise: "caso contrário", + conditionAnd: "e", + conditionOr: "ou", + conditionMore: "outras condições", + runsWhen: "Executa quando {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 1bb67efe612..4d36e735477 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5933,6 +5933,12 @@ const ru = { object: "Объект", unknownType: "Неизвестный тип представления метаданных. Ожидается {{a}}, {{b}} или {{c}}.", unknownTypeNamed: "Неизвестный тип представления метаданных «{{type}}». Ожидается {{a}}, {{b}} или {{c}}.", + condition: "условие", + otherwise: "иначе", + conditionAnd: "и", + conditionOr: "или", + conditionMore: "другие условия", + runsWhen: "Запускается, когда {{condition}}", }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index f498a05a876..8c4427976e5 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5659,6 +5659,12 @@ const zh = { object: '对象', unknownType: '未知的元数据视图类型。应为 {{a}}、{{b}} 或 {{c}}。', unknownTypeNamed: '未知的元数据视图类型“{{type}}”。应为 {{a}}、{{b}} 或 {{c}}。', + condition: '条件', + otherwise: '否则', + conditionAnd: '且', + conditionOr: '或', + conditionMore: '其他条件', + runsWhen: '运行条件:{{condition}}', }, }, reactPage: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 96b953c2254..c32a00296ce 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5659,6 +5659,12 @@ const zhHant = { object: '物件', unknownType: '未知的中繼資料檢視型別。應為 {{a}}、{{b}} 或 {{c}}。', unknownTypeNamed: '未知的中繼資料檢視型別“{{type}}”。應為 {{a}}、{{b}} 或 {{c}}。', + condition: '條件', + otherwise: '否則', + conditionAnd: '且', + conditionOr: '或', + conditionMore: '其他條件', + runsWhen: '執行條件:{{condition}}', }, }, reactPage: {