From a29ca9676cda9240d6438ac35d9f452522646c5a Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 24 Jun 2026 13:56:23 +0200 Subject: [PATCH 01/62] add files --- src/CONST/index.ts | 1 + .../API/parameters/ApprovalWorkflowParams.ts | 13 + src/libs/API/parameters/index.ts | 1 + src/libs/API/types.ts | 2 + src/libs/WorkflowUtils.ts | 762 ++++++++++++++++++ src/libs/actions/Workflow.ts | 84 +- src/types/onyx/ApprovalWorkflowRules.ts | 72 ++ src/types/onyx/Policy.ts | 10 +- 8 files changed, 943 insertions(+), 2 deletions(-) create mode 100644 src/libs/API/parameters/ApprovalWorkflowParams.ts create mode 100644 src/types/onyx/ApprovalWorkflowRules.ts diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 01959d09842d..8274c3f09f30 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -7043,6 +7043,7 @@ const CONST = { IS: 'is', REPORT_FIELD: 'reportField', EXPORTED_TO: 'exportedTo', + PREVIOUS_APPROVER: 'previousApprover', }, REPORT_FIELD: { // All report fields start with this, so use this to check if a search key is a report field diff --git a/src/libs/API/parameters/ApprovalWorkflowParams.ts b/src/libs/API/parameters/ApprovalWorkflowParams.ts new file mode 100644 index 000000000000..4eca1d7e3ec7 --- /dev/null +++ b/src/libs/API/parameters/ApprovalWorkflowParams.ts @@ -0,0 +1,13 @@ +type SetApprovalWorkflowParams = { + /** The policy ID whose approval-workflow rules are being mutated. */ + policyID: string; + + /** + * JSON-stringified object keyed by ruleID, mapping to either: + * - a full `ApprovalWorkflowRule` to add or replace, or + * - `null` / `{}` to remove the rule from the policy. + */ + rules: string; +}; + +export type {SetApprovalWorkflowParams}; diff --git a/src/libs/API/parameters/index.ts b/src/libs/API/parameters/index.ts index f769632dfe53..cccf7141341a 100644 --- a/src/libs/API/parameters/index.ts +++ b/src/libs/API/parameters/index.ts @@ -527,6 +527,7 @@ export type {default as DeleteDomainParams} from './DeleteDomainParams'; export type {default as GetDuplicateTransactionDetailsParams} from './GetDuplicateTransactionDetailsParams'; export type {default as SetPolicyCategoryReceiptsAndItemizedReceiptRequiredParams} from './SetPolicyCategoryReceiptsAndItemizedReceiptRequiredParams'; export type {default as SetPolicyCodingRuleParams} from './SetPolicyCodingRuleParams'; +export type {SetApprovalWorkflowParams} from './ApprovalWorkflowParams'; export type {default as RegisterAuthenticationKeyParams} from './RegisterAuthenticationKeyParams'; export type {default as RevokeMultifactorAuthenticationCredentialsParams} from './RevokeMultifactorAuthenticationCredentialsParams'; export type {default as TroubleshootMultifactorAuthenticationParams} from './TroubleshootMultifactorAuthenticationParams'; diff --git a/src/libs/API/types.ts b/src/libs/API/types.ts index b359d5b38127..6f0cd7121759 100644 --- a/src/libs/API/types.ts +++ b/src/libs/API/types.ts @@ -273,6 +273,7 @@ const WRITE_COMMANDS = { SET_POLICY_TIME_TRACKING_DEFAULT_RATE: 'SetPolicyTimeTrackingDefaultRate', SET_POLICY_RULES_ENABLED: 'SetPolicyRulesEnabled', SET_POLICY_CODING_RULE: 'SetPolicyCodingRule', + SET_APPROVAL_WORKFLOW: 'SetApprovalWorkflow', SET_POLICY_EXPENSE_MAX_AMOUNT_NO_RECEIPT: 'SetPolicyExpenseMaxAmountNoReceipt', SET_POLICY_EXPENSE_MAX_AMOUNT_NO_ITEMIZED_RECEIPT: 'SetPolicyExpenseMaxAmountNoItemizedReceipt', SET_POLICY_EXPENSE_MAX_AMOUNT: 'SetPolicyExpenseMaxAmount', @@ -909,6 +910,7 @@ type WriteCommandParameters = { [WRITE_COMMANDS.ENABLE_POLICY_TIME_TRACKING]: Parameters.EnablePolicyTimeTrackingParams; [WRITE_COMMANDS.SET_POLICY_RULES_ENABLED]: Parameters.SetPolicyRulesEnabledParams; [WRITE_COMMANDS.SET_POLICY_CODING_RULE]: Parameters.SetPolicyCodingRuleParams; + [WRITE_COMMANDS.SET_APPROVAL_WORKFLOW]: Parameters.SetApprovalWorkflowParams; [WRITE_COMMANDS.SET_POLICY_REQUIRE_COMPANY_CARDS_ENABLED]: Parameters.SetPolicyRequireCompanyCardsEnabledParams; [WRITE_COMMANDS.SET_POLICY_CATEGORY_DESCRIPTION_REQUIRED]: Parameters.SetPolicyCategoryDescriptionRequiredParams; [WRITE_COMMANDS.SET_POLICY_CATEGORY_ATTENDEES_REQUIRED]: Parameters.SetPolicyCategoryAttendeesRequiredParams; diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index c5cff6e27412..031ffab87103 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -7,6 +7,7 @@ import CONST from '@src/CONST'; import type {BankAccountList} from '@src/types/onyx'; import type {ApprovalWorkflowOnyx, Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; +import type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; import type {PersonalDetailsList} from '@src/types/onyx/PersonalDetails'; import type PersonalDetails from '@src/types/onyx/PersonalDetails'; import type Policy from '@src/types/onyx/Policy'; @@ -14,6 +15,7 @@ import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; import type {PolicyEmployeeList} from '@src/types/onyx/PolicyEmployee'; import {isBankAccountPartiallySetup} from './BankAccountUtils'; import {getHRAdvancedModeFinalApprover, getHRFinalApprover} from './HRUtils'; +import {rand64} from './NumberUtils'; import {getDefaultApprover, isExpensifyTeam, shouldFilterExpensifyTeam} from './PolicyUtils'; const INITIAL_APPROVAL_WORKFLOW: ApprovalWorkflowOnyx = { @@ -716,8 +718,763 @@ function mergeWorkflowMembersWithAvailableMembers(workflowMembers: Member[], all return [...workflowMembers, ...additionalMembers]; } +// --------------------------------------------------------------------------- +// Approval-workflow rules (rules.approvalWorkflows on the policy) +// --------------------------------------------------------------------------- +// +// These helpers translate the in-app `ApprovalWorkflow` model into the rule +// format the backend stores under `Policy.rules.approvalWorkflows`, and +// reconcile a workflow change against the existing rules so we can hand a +// minimal diff to `Auth/SetApprovalWorkflow`. +// +// Diff convention: a value of `ApprovalWorkflowRule` upserts the rule; a value +// of `null` removes it. JSON-stringified, that matches what Auth expects. + +const APPROVAL_WORKFLOW_FORWARD_ACTION = 'forward' as const; + +/** Diff shape passed to the backend: ruleID -> rule (upsert) or null (remove). */ +type ApprovalWorkflowRulesDiff = Record; + +/** Build a leaf comparison: ` `. */ +function buildComparison( + operator: ValueOf, + left: ApprovalWorkflowFilterComparison['left'], + right: ApprovalWorkflowFilterComparison['right'], +): ApprovalWorkflowFilterComparison { + return {operator, left, right}; +} + +/** Build the `from in [emails]` leaf used by every approval-workflow rule. */ +function buildFromComparison(memberEmails: string[]): ApprovalWorkflowFilterComparison { + return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, [...memberEmails]); +} + +/** Build the `previousApprover = email` leaf used by all non-initial-hop rules. */ +function buildPreviousApproverComparison(email: string): ApprovalWorkflowFilterComparison { + return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER, email); +} + +/** + * Build the `rules.approvalWorkflows` rule chain for a single `ApprovalWorkflow`. + * + * For a workflow whose approver chain is `[A0, A1, ..., A_{N-1}]` and whose members are `M`, + * we emit one rule per approver position. The rule at position `i` routes the report TO + * `approvers[i]`: + * + * - i == 0 (initial submission): filter is `from ∈ M`, nextReceiver is `A0.email`. + * - i > 0 (after `A_{i-1}` approves): filter is `from ∈ M AND previousApprover == A_{i-1}.email`, + * nextReceiver is `A_i.email`. + * + * When `A_{i-1}` has both `approvalLimit > 0` and `overLimitForwardsTo` set, the hop after + * them splits into two rules — an under-limit rule that continues to `A_i` and an over-limit + * counterpart that jumps directly to `A_{i-1}.overLimitForwardsTo` instead. + * + * No rule is emitted "after the last approver" because nothing forwards past the terminal + * approver in the chain. + */ +function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): ApprovalWorkflowRule[] { + const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const approvers = approvalWorkflow.approvers; + + if (memberEmails.length === 0 || approvers.length === 0) { + return []; + } + + const fromComparison = buildFromComparison(memberEmails); + const rules: ApprovalWorkflowRule[] = []; + + for (let i = 0; i < approvers.length; i++) { + const current = approvers[i]; + const previous = i > 0 ? approvers.at(i - 1) : undefined; + + // Initial-submission rule: degenerate single-comparison filter, no previousApprover gate. + if (!previous) { + rules.push({ + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: fromComparison}, + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: current.email, + }); + continue; + } + + const previousApproverComparison = buildPreviousApproverComparison(previous.email); + const hasLimitSplit = !!previous.approvalLimit && previous.approvalLimit > 0 && !!previous.overLimitForwardsTo; + + if (!hasLimitSplit) { + rules.push({ + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: fromComparison, right: previousApproverComparison}, + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: current.email, + }); + continue; + } + + // Split: amount < limit continues to the next approver, amount >= limit jumps to overLimit. + const limit = previous.approvalLimit as number; + const overLimitTarget = previous.overLimitForwardsTo as string; + + rules.push({ + filters: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: fromComparison, + right: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: previousApproverComparison, + right: buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit), + }, + }, + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: current.email, + }); + + rules.push({ + filters: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: fromComparison, + right: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: previousApproverComparison, + right: buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit), + }, + }, + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: overLimitTarget, + }); + } + + return rules; +} + +// --------------------------------------------------------------------------- +// Rule introspection helpers (used by reconciliation) +// --------------------------------------------------------------------------- + +/** True when a comparison node targets the `from` field with an equality operator. */ +function isFromComparison(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): boolean { + return node.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && (node as ApprovalWorkflowFilterComparison).left === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM; +} + +/** Walk a filter tree and call `visitor` on every `from` comparison leaf. */ +function forEachFromComparison(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, visitor: (leaf: ApprovalWorkflowFilterComparison) => void): void { + if (!node) { + return; + } + if (isFromComparison(node)) { + visitor(node as ApprovalWorkflowFilterComparison); + return; + } + // Only filter nodes (which always carry a left filter) and AND/OR nodes have children to recurse into. + const leftIsNode = typeof (node as ApprovalWorkflowFilter).left === 'object' && (node as ApprovalWorkflowFilter).left !== null; + if (leftIsNode) { + forEachFromComparison((node as ApprovalWorkflowFilter).left, visitor); + } + const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; + if (right && typeof right === 'object') { + forEachFromComparison(right, visitor); + } +} + +/** Extract the union of email values across every `from` leaf in a rule. */ +function extractFromEmails(rule: ApprovalWorkflowRule): string[] { + const emails = new Set(); + forEachFromComparison(rule.filters, (leaf) => { + const right = leaf.right; + if (Array.isArray(right)) { + right.forEach((email) => { + if (typeof email === 'string') { + emails.add(email); + } + }); + } else if (typeof right === 'string') { + emails.add(right); + } + }); + return Array.from(emails); +} + +/** + * Return a structural fingerprint of a rule with the `right` values of every `from` leaf + * stripped. Two rules with the same fingerprint differ only in their submitter list, which + * is what we look for when deciding whether to merge two workflows into a shared rule. + */ +function structuralFingerprint(rule: ApprovalWorkflowRule): string { + const stripFromValues = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): unknown => { + if (!node) { + return node; + } + if (isFromComparison(node)) { + return {operator: node.operator, left: (node as ApprovalWorkflowFilterComparison).left}; + } + const out: Record = {operator: node.operator}; + const left = (node as ApprovalWorkflowFilter).left; + if (left !== undefined) { + out.left = typeof left === 'object' && left !== null ? stripFromValues(left) : left; + } + const right = (node as ApprovalWorkflowFilter).right as unknown; + if (right !== undefined) { + out.right = typeof right === 'object' && right !== null ? stripFromValues(right as ApprovalWorkflowFilter) : right; + } + return out; + }; + + return JSON.stringify({ + filters: stripFromValues(rule.filters), + action: rule.action, + nextReceiver: rule.nextReceiver, + }); +} + +/** Replace the `right` value on every `from` leaf with `newEmails`. */ +function withFromEmails(rule: ApprovalWorkflowRule, newEmails: string[]): ApprovalWorkflowRule { + const rewrite = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison => { + if (isFromComparison(node)) { + return {...node, right: [...newEmails]} as ApprovalWorkflowFilterComparison; + } + const left = (node as ApprovalWorkflowFilter).left; + const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; + return { + ...node, + ...(typeof left === 'object' && left !== null ? {left: rewrite(left)} : {}), + ...(right && typeof right === 'object' ? {right: rewrite(right)} : {}), + } as ApprovalWorkflowFilter; + }; + return {...rule, filters: rewrite(rule.filters) as ApprovalWorkflowFilter}; +} + +/** Union of `existingEmails` and `additions`, preserving the order of `existingEmails`. */ +function unionEmails(existingEmails: string[], additions: string[]): string[] { + const seen = new Set(existingEmails); + const result = [...existingEmails]; + additions.forEach((email) => { + if (seen.has(email)) { + return; + } + seen.add(email); + result.push(email); + }); + return result; +} + +/** `existingEmails` with everything in `removals` filtered out. */ +function differenceEmails(existingEmails: string[], removals: string[]): string[] { + const removalSet = new Set(removals); + return existingEmails.filter((email) => !removalSet.has(email)); +} + +// --------------------------------------------------------------------------- +// Reconciliation against the existing `rules.approvalWorkflows` map +// --------------------------------------------------------------------------- + +type ReconcileContext = { + /** The existing `Policy.rules.approvalWorkflows` snapshot, defaulting to `{}`. */ + existingRules: Record; +}; + +/** + * Reconcile a freshly created workflow against the existing rules. New rules that match an + * existing rule's structure (ignoring `from`) are folded into that existing rule by appending + * the new workflow's members to its `from` list. Anything left over is saved under a fresh + * client-generated ruleID. + */ +function reconcileApprovalWorkflowRulesForCreate(newRules: ApprovalWorkflowRule[], memberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { + const diff: ApprovalWorkflowRulesDiff = {}; + const existingEntries = Object.entries(context.existingRules); + + for (const newRule of newRules) { + const fingerprint = structuralFingerprint(newRule); + const match = existingEntries.find(([, existing]) => structuralFingerprint(existing) === fingerprint); + + if (match) { + const [existingID, existingRule] = match; + const mergedEmails = unionEmails(extractFromEmails(existingRule), memberEmails); + diff[existingID] = withFromEmails(existingRule, mergedEmails); + continue; + } + + diff[rand64()] = newRule; + } + + return diff; +} + +/** + * Reconcile an edit to an existing workflow. Returns add/replace/remove instructions to + * morph the existing rule set into the new chain while preserving rules shared with other + * workflows. + * + * Two passes: + * 1. Walk every existing rule that contains any of the workflow's members. If a new rule + * structurally matches, leave it alone; otherwise either drop this workflow's members + * from the rule (when it's shared with other workflows) or remove the rule entirely. + * 2. For every new rule that didn't already exist, look for a structurally matching rule + * under a different membership and fold this workflow into it; failing that, create + * a fresh rule with a new ruleID. + */ +function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], memberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { + const diff: ApprovalWorkflowRulesDiff = {}; + const memberSet = new Set(memberEmails); + const newFingerprints = new Set(newRules.map(structuralFingerprint)); + + // Track which existing rules we've already turned into a no-op match so we don't drop them in pass 2. + const matchedExistingIDs = new Set(); + + // Pass 1: walk existing rules that belong (at least partially) to this workflow. + for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { + const ruleEmails = extractFromEmails(existingRule); + const sharedWithThisWorkflow = ruleEmails.some((email) => memberSet.has(email)); + if (!sharedWithThisWorkflow) { + continue; + } + + const fingerprint = structuralFingerprint(existingRule); + if (newFingerprints.has(fingerprint)) { + // Structurally identical to a new rule: leave it alone but remember it as "covered". + matchedExistingIDs.add(ruleID); + continue; + } + + const remaining = differenceEmails(ruleEmails, memberEmails); + if (remaining.length === 0) { + // No other workflow shares this rule — drop it entirely. + diff[ruleID] = null; + } else { + // Keep the rule for the other workflows that still need it, minus our members. + diff[ruleID] = withFromEmails(existingRule, remaining); + } + } + + // Pass 2: create or extend rules for any new rule that wasn't already covered. + const existingEntries = Object.entries(context.existingRules); + for (const newRule of newRules) { + const fingerprint = structuralFingerprint(newRule); + + // Already in place via a pass-1 match — nothing to do. + const alreadyCovered = existingEntries.some(([id, existing]) => matchedExistingIDs.has(id) && structuralFingerprint(existing) === fingerprint); + if (alreadyCovered) { + continue; + } + + // Look for a rule belonging to a different workflow that we can fold into. + const foreignMatch = existingEntries.find(([id, existing]) => { + if (matchedExistingIDs.has(id)) { + return false; + } + if (structuralFingerprint(existing) !== fingerprint) { + return false; + } + const existingEmails = extractFromEmails(existing); + // "Different workflow" => no overlap with our members. + return !existingEmails.some((email) => memberSet.has(email)); + }); + + if (foreignMatch) { + const [existingID, existingRule] = foreignMatch; + const mergedEmails = unionEmails(extractFromEmails(existingRule), memberEmails); + diff[existingID] = withFromEmails(existingRule, mergedEmails); + continue; + } + + diff[rand64()] = newRule; + } + + return diff; +} + +/** + * Reconcile the deletion of a workflow. Rules that listed only this workflow's members in + * their `from` filter are removed outright; rules shared with other workflows have just + * this workflow's members stripped from `from`. + */ +function reconcileApprovalWorkflowRulesForRemove(memberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { + const diff: ApprovalWorkflowRulesDiff = {}; + const memberSet = new Set(memberEmails); + + for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { + const ruleEmails = extractFromEmails(existingRule); + const sharedWithThisWorkflow = ruleEmails.some((email) => memberSet.has(email)); + if (!sharedWithThisWorkflow) { + continue; + } + + const remaining = differenceEmails(ruleEmails, memberEmails); + diff[ruleID] = remaining.length === 0 ? null : withFromEmails(existingRule, remaining); + } + + return diff; +} + +/** + * Reconcile a member-only change (the approver chain is unchanged but the workflow's + * member list changed). For every existing rule that includes any of the previous members + * we add the new members and drop any previous members that aren't part of the new set. + */ +function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: string[], newMemberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { + const diff: ApprovalWorkflowRulesDiff = {}; + const previousSet = new Set(previousMemberEmails); + const newSet = new Set(newMemberEmails); + const removed = previousMemberEmails.filter((email) => !newSet.has(email)); + + for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { + const ruleEmails = extractFromEmails(existingRule); + if (!ruleEmails.some((email) => previousSet.has(email))) { + continue; + } + + const afterRemoval = differenceEmails(ruleEmails, removed); + const updatedEmails = unionEmails(afterRemoval, newMemberEmails); + + // No effective change to this rule's `from` — skip the round-trip. + if (updatedEmails.length === ruleEmails.length && updatedEmails.every((email, idx) => email === ruleEmails[idx])) { + continue; + } + + diff[ruleID] = updatedEmails.length === 0 ? null : withFromEmails(existingRule, updatedEmails); + } + + return diff; +} + +// --------------------------------------------------------------------------- +// Reconstruct ApprovalWorkflow[] from `policy.rules.approvalWorkflows` +// --------------------------------------------------------------------------- +// +// Inverse of `buildApprovalWorkflowRules`. Given the policy's rule set we walk +// each submitter's hop chain and rebuild the same `PolicyConversionResult` the +// legacy employeeList-based converter produces, so the rest of the workflows UI +// keeps working unchanged. +// +// Per-hop employeeList fallback: when a hop has no matching rule we fall back +// to that approver's employeeList entry. This keeps pre-beta workflows visible +// during the migration window. We deliberately don't fuse legacy chains with +// rule-based chains even when they share a shape — the legacy chains will go +// away on their own as workflows are re-saved. + +/** A leaf comparison node — its `left` is a primitive (field name), unlike a boolean filter whose `left` is another node. */ +function isComparisonLeaf(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): node is ApprovalWorkflowFilterComparison { + if (!node) { + return false; + } + const nodeLeft = (node as ApprovalWorkflowFilter).left; + return typeof nodeLeft !== 'object' || nodeLeft === null || Array.isArray(nodeLeft); +} + +/** Return the first comparison leaf in the filter tree whose `left` field matches. */ +function findComparisonByLeft(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, leftKey: string): ApprovalWorkflowFilterComparison | undefined { + if (!node) { + return undefined; + } + if (isComparisonLeaf(node)) { + return node.left === leftKey ? node : undefined; + } + const fromLeft = findComparisonByLeft((node as ApprovalWorkflowFilter).left, leftKey); + if (fromLeft) { + return fromLeft; + } + const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; + return findComparisonByLeft(right, leftKey); +} + +/** Initial-submission rule for a submitter — `from` includes them and no `previousApprover` filter exists. */ +function findInitialSubmissionRule(submitter: string, rules: Record): ApprovalWorkflowRule | undefined { + for (const rule of Object.values(rules)) { + if (!extractFromEmails(rule).includes(submitter)) { + continue; + } + if (!findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER)) { + return rule; + } + } + return undefined; +} + +/** Resolved hop info — where the report goes after the current approver acts, and any limit split that controlled it. */ +type ApprovalWorkflowHopInfo = { + /** Next approver email (under-limit path, or the only path when no split). */ + forwardsTo: string; + /** Amount threshold from the under/over-limit split, if any. */ + approvalLimit?: number; + /** Over-limit forward target, if the hop is split. */ + overLimitForwardsTo?: string; +}; + +/** + * Look for the rules describing what happens after `currentApproverEmail` approves a report + * submitted by `submitter`. Returns: + * - {forwardsTo, approvalLimit, overLimitForwardsTo} when both halves of a limit split exist + * - {forwardsTo} when there's a single normal rule (or only one half of a partial/broken split) + * - undefined when no matching rule exists, signaling the caller to fall back to employeeList + */ +function extractHopFromRules(submitter: string, currentApproverEmail: string, rules: Record): ApprovalWorkflowHopInfo | undefined { + let underLimitRule: ApprovalWorkflowRule | undefined; + let overLimitRule: ApprovalWorkflowRule | undefined; + let normalRule: ApprovalWorkflowRule | undefined; + let approvalLimit: number | undefined; + + for (const rule of Object.values(rules)) { + if (!extractFromEmails(rule).includes(submitter)) { + continue; + } + const previousApproverLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER); + if (!previousApproverLeaf || previousApproverLeaf.right !== currentApproverEmail) { + continue; + } + + const amountLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT); + if (amountLeaf && typeof amountLeaf.right === 'number') { + if (amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN) { + underLimitRule = rule; + approvalLimit = amountLeaf.right; + } else if (amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO) { + overLimitRule = rule; + approvalLimit = approvalLimit ?? amountLeaf.right; + } else { + normalRule = rule; + } + } else { + normalRule = rule; + } + } + + if (underLimitRule && overLimitRule) { + return { + forwardsTo: underLimitRule.nextReceiver, + approvalLimit, + overLimitForwardsTo: overLimitRule.nextReceiver, + }; + } + if (normalRule) { + return {forwardsTo: normalRule.nextReceiver}; + } + // Partial split (one half missing): use whichever rule we found as the next hop. This is a + // best-effort recovery from a corrupted rule pair rather than an expected state. + const partial = underLimitRule ?? overLimitRule; + if (partial) { + return {forwardsTo: partial.nextReceiver}; + } + return undefined; +} + +type BuildApproverChainFromRulesParams = { + submitter: string; + rules: Record; + employees: PolicyEmployeeList; + personalDetailsByEmail: PersonalDetailsList; +}; + +/** + * Walk a submitter's approval chain by following rules from their initial-submission rule + * forward. Each hop's `forwardsTo` / `approvalLimit` / `overLimitForwardsTo` is taken from + * the rule when one exists, and falls back to the current approver's `employeeList` entry + * when the rule chain runs out. Stops at circular references (matching `calculateApprovers`). + */ +function buildApproverChainFromRules({submitter, rules, employees, personalDetailsByEmail}: BuildApproverChainFromRulesParams): Approver[] { + // First approver: prefer the initial-submission rule, fall back to employeeList.submitsTo for + // pre-beta workflows that haven't been re-saved yet. + const initialRule = findInitialSubmissionRule(submitter, rules); + let currentEmail: string | undefined = initialRule?.nextReceiver ?? employees[submitter]?.submitsTo; + if (!currentEmail) { + return []; + } + + const chain: Approver[] = []; + const seenEmails = new Set(); + + while (currentEmail) { + const isCircularReference = seenEmails.has(currentEmail); + const employee: PolicyEmployee | undefined = employees[currentEmail]; + + const hopInfo = extractHopFromRules(submitter, currentEmail, rules); + const approvalLimit: number | null = hopInfo?.approvalLimit ?? employee?.approvalLimit ?? null; + const overLimitForwardsTo: string | undefined = hopInfo?.overLimitForwardsTo ?? employee?.overLimitForwardsTo; + const forwardsTo: string | undefined = hopInfo?.forwardsTo ?? employee?.forwardsTo; + + chain.push({ + email: currentEmail, + forwardsTo, + avatar: personalDetailsByEmail[currentEmail]?.avatar, + displayName: personalDetailsByEmail[currentEmail]?.displayName ?? currentEmail, + isCircularReference, + approvalLimit, + overLimitForwardsTo, + overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(overLimitForwardsTo, personalDetailsByEmail), + pendingAction: employee?.pendingAction, + errors: employee?.errors, + }); + + if (isCircularReference) { + break; + } + seenEmails.add(currentEmail); + currentEmail = forwardsTo; + } + + return chain; +} + +/** Structural identity of a chain — used to fold submitters with identical chains into one workflow. */ +function approverChainFingerprint(chain: Approver[]): string { + return JSON.stringify( + chain.map((approver) => ({ + email: approver.email, + approvalLimit: approver.approvalLimit ?? null, + overLimitForwardsTo: approver.overLimitForwardsTo ?? null, + isCircularReference: !!approver.isCircularReference, + })), + ); +} + +/** True when at least one rule mentions this submitter in any `from` filter. */ +function isSubmitterCoveredByRules(submitter: string, rules: Record): boolean { + for (const rule of Object.values(rules)) { + if (extractFromEmails(rule).includes(submitter)) { + return true; + } + } + return false; +} + +/** + * Beta-enabled counterpart to `convertPolicyEmployeesToApprovalWorkflows`: rebuild the same + * `PolicyConversionResult` shape from `policy.rules.approvalWorkflows`, with per-hop + * fallback to `employeeList` for any chain step the rules don't cover. Rule-based chains + * are kept separate from legacy chains even when their shapes match — the legacy ones are + * expected to disappear as workflows are migrated. + */ +function convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, firstApprover, localeCompare, currentUserLogin}: PolicyConversionParams): PolicyConversionResult { + const employees = policy?.employeeList ?? {}; + const rules = policy?.rules?.approvalWorkflows ?? {}; + const defaultApprover = getHRFinalApprover(policy) ?? getDefaultApprover(policy); + const shouldFilterOutExpensifyTeam = shouldFilterExpensifyTeam(policy?.owner, currentUserLogin); + const hrAdvancedModeFinalApproverEmail = getHRAdvancedModeFinalApprover(policy); + + const personalDetailsByEmail: PersonalDetailsList = {}; + for (const [key, value] of Object.entries(personalDetails)) { + personalDetailsByEmail[value?.login ?? key] = value; + } + + // Source-tagged fingerprint groups so a legacy chain and a rule-based chain with the same + // shape stay in separate workflows. Tag values: 'r' (any rule mentions the submitter) or 'l'. + type WorkflowGroup = { + chain: Approver[]; + members: Member[]; + isDefault: boolean; + pendingAction: ApprovalWorkflow['pendingAction']; + }; + const groupedByFingerprint = new Map(); + const usedApproverEmails = new Set(); + const availableMembers: Member[] = []; + + for (const employee of Object.values(employees)) { + const {email, submitsTo, pendingAction} = employee; + if (!email) { + continue; + } + if (shouldFilterOutExpensifyTeam && isExpensifyTeam(email)) { + continue; + } + + const member = buildMemberFromEmployee(employee, personalDetailsByEmail, email); + + if (pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + availableMembers.push(member); + } + + const initialRule = findInitialSubmissionRule(email, rules); + if (!initialRule && (!submitsTo || (!employees[submitsTo] && !hrAdvancedModeFinalApproverEmail))) { + // Mirrors the existing legacy filter: skip submitters whose first approver isn't reachable. + continue; + } + + let chain = buildApproverChainFromRules({submitter: email, rules, employees, personalDetailsByEmail}); + if (chain.length === 0) { + continue; + } + + if (shouldFilterOutExpensifyTeam) { + chain = chain.filter((approver) => !isExpensifyTeam(approver.email)); + } + if (hrAdvancedModeFinalApproverEmail) { + const last = chain.at(-1); + if (last && last.email !== hrAdvancedModeFinalApproverEmail) { + chain.push({ + email: hrAdvancedModeFinalApproverEmail, + forwardsTo: undefined, + avatar: personalDetailsByEmail[hrAdvancedModeFinalApproverEmail]?.avatar, + displayName: personalDetailsByEmail[hrAdvancedModeFinalApproverEmail]?.displayName ?? hrAdvancedModeFinalApproverEmail, + isCircularReference: false, + }); + usedApproverEmails.add(hrAdvancedModeFinalApproverEmail); + } + } + if (chain.length === 0) { + continue; + } + + const firstApproverEmail = chain[0].email; + if (firstApproverEmail !== firstApprover) { + for (const approver of chain) { + usedApproverEmails.add(approver.email); + } + } + + const sourceTag = isSubmitterCoveredByRules(email, rules) ? 'r' : 'l'; + const fingerprint = `${sourceTag}|${approverChainFingerprint(chain)}`; + const existingGroup = groupedByFingerprint.get(fingerprint); + + if (existingGroup) { + if (pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + existingGroup.members.push(member); + } + if (pendingAction && pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + existingGroup.pendingAction = pendingAction; + } + continue; + } + + const workflowPendingAction = pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ? pendingAction : undefined; + groupedByFingerprint.set(fingerprint, { + chain, + members: pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ? [member] : [], + isDefault: firstApproverEmail === defaultApprover, + pendingAction: workflowPendingAction, + }); + } + + const sortedApprovalWorkflows: ApprovalWorkflow[] = Array.from(groupedByFingerprint.values()) + .map(({chain, members, isDefault, pendingAction}) => ({ + members, + approvers: chain, + isDefault, + pendingAction, + })) + .sort((a, b) => { + if (a.isDefault) { + return -1; + } + if (b.isDefault) { + return 1; + } + return localeCompare(a.approvers.at(0)?.displayName ?? '', b.approvers.at(0)?.displayName ?? ''); + }); + + const firstWorkflow = sortedApprovalWorkflows.at(0); + if (firstWorkflow && !firstWorkflow.isDefault) { + sortedApprovalWorkflows.unshift({ + members: [], + approvers: calculateApprovers({employees, firstEmail: defaultApprover, personalDetailsByEmail}), + isDefault: true, + }); + } + + availableMembers.sort((a, b) => localeCompare(a.displayName ?? a.email, b.displayName ?? b.email)); + + return {approvalWorkflows: sortedApprovalWorkflows, usedApproverEmails: [...usedApproverEmails], availableMembers}; +} + export { + buildApprovalWorkflowRules, calculateApprovers, + convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, convertApprovalWorkflowToPolicyEmployees, getApprovalLimitDescription, @@ -726,5 +1483,10 @@ export { getOverLimitForwardsToDisplayName, INITIAL_APPROVAL_WORKFLOW, mergeWorkflowMembersWithAvailableMembers, + reconcileApprovalWorkflowRulesForCreate, + reconcileApprovalWorkflowRulesForEdit, + reconcileApprovalWorkflowRulesForMembersChange, + reconcileApprovalWorkflowRulesForRemove, updateWorkflowDataOnApproverRemoval, }; +export type {ApprovalWorkflowRulesDiff}; diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 1bf80b830df2..6f0c09e6b669 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -2,9 +2,11 @@ import lodashDropRightWhile from 'lodash/dropRightWhile'; import type {NullishDeep, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import * as API from '@libs/API'; -import type {CreateWorkspaceApprovalParams, RemoveWorkspaceApprovalParams, UpdateWorkspaceApprovalParams} from '@libs/API/parameters'; +import type {CreateWorkspaceApprovalParams, RemoveWorkspaceApprovalParams, SetApprovalWorkflowParams, UpdateWorkspaceApprovalParams} from '@libs/API/parameters'; import {WRITE_COMMANDS} from '@libs/API/types'; +import * as ErrorUtils from '@libs/ErrorUtils'; import {getDefaultApprover} from '@libs/PolicyUtils'; +import type {ApprovalWorkflowRulesDiff} from '@libs/WorkflowUtils'; import {calculateApprovers, convertApprovalWorkflowToPolicyEmployees, getOverLimitForwardsToDisplayName, mergeWorkflowMembersWithAvailableMembers} from '@libs/WorkflowUtils'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; @@ -12,6 +14,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {ApprovalWorkflowOnyx, PersonalDetailsList, Policy, Report} from '@src/types/onyx'; import type {Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; +import type {ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import {completeTask} from './Task'; @@ -262,6 +265,84 @@ function removeApprovalWorkflow(approvalWorkflow: ApprovalWorkflow, policy: Onyx API.write(WRITE_COMMANDS.REMOVE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); } +type SetApprovalWorkflowRulesParams = { + policyID: string; + + /** + * Diff to apply to `Policy.rules.approvalWorkflows`. A value of `ApprovalWorkflowRule` + * upserts the rule under its `ruleID`; a value of `null` removes it. Produced by the + * `reconcileApprovalWorkflowRules*` helpers in `WorkflowUtils`. + */ + rulesDiff: ApprovalWorkflowRulesDiff; + + /** Snapshot of the policy's `rules.approvalWorkflows` taken before applying `rulesDiff`. Used to roll back on failure. */ + previousApprovalWorkflows: Record; +}; + +/** + * Apply a set of approval-workflow rule changes to a policy via the new SetApprovalWorkflow + * Auth command. Mirrors the optimistic/success/failure dance of `createApprovalWorkflow`, + * but operates on `rules.approvalWorkflows` instead of `employeeList`. + * + * No-op when `rulesDiff` is empty — there's nothing to send to the backend. + */ +function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflows}: SetApprovalWorkflowRulesParams) { + if (!policyID || isEmptyObject(rulesDiff)) { + return; + } + + const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policyID}` as const; + + // Build the rollback shape: for every rule we're about to touch, either restore the + // previous value (if one existed) or clear the optimistic upsert with `null`. Without + // the explicit `null`s, newly-added rules would survive the failure rollback. + const failureApprovalWorkflows: Record = {}; + for (const ruleID of Object.keys(rulesDiff)) { + failureApprovalWorkflows[ruleID] = previousApprovalWorkflows[ruleID] ?? null; + } + + const optimisticData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: policyKey, + value: { + rules: {approvalWorkflows: rulesDiff}, + pendingFields: {approvalWorkflows: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}, + errorFields: {approvalWorkflows: null}, + }, + }, + ]; + + const successData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: policyKey, + value: { + pendingFields: {approvalWorkflows: null}, + }, + }, + ]; + + const failureData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: policyKey, + value: { + rules: {approvalWorkflows: failureApprovalWorkflows}, + pendingFields: {approvalWorkflows: null}, + errorFields: {approvalWorkflows: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage')}, + }, + }, + ]; + + const parameters: SetApprovalWorkflowParams = { + policyID, + rules: JSON.stringify(rulesDiff), + }; + + API.write(WRITE_COMMANDS.SET_APPROVAL_WORKFLOW, parameters, {optimisticData, successData, failureData}); +} + /** Set the members of the approval workflow that is currently edited */ function setApprovalWorkflowMembers(members: Member[]) { Onyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, {members, errors: null}); @@ -428,6 +509,7 @@ export { setApprovalWorkflowMembers, setApprovalWorkflowApprover, setApprovalWorkflow, + setApprovalWorkflowRules, selectApprovalWorkflowForEdit, clearApprovalWorkflowApprover, clearApprovalWorkflowApprovers, diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts new file mode 100644 index 000000000000..63dba2016ef2 --- /dev/null +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -0,0 +1,72 @@ +import type {ValueOf} from 'type-fest'; +import type CONST from '@src/CONST'; + +/** + * Operand of a comparison in an approval-workflow filter. + * + * - The left operand is a field identifier — one of the search-syntax filter keys (extended + * with `previousApprover` for approval rules). + * - The right operand is the literal value the field is compared against. For email-typed + * fields like `from`, the value may be a list of emails to match against. + */ +type ApprovalWorkflowFilterOperand = ValueOf | string | number | string[]; + +/** + * A single comparison node: ` `. + * + * `right` is optional because a future operator may be unary, but for the operators currently + * in use (`eq`, `lt`, `gte`, ...) both sides are required. + */ +type ApprovalWorkflowFilterComparison = { + /** The comparison operator. */ + operator: ValueOf; + + /** The field identifier being compared. */ + left: ApprovalWorkflowFilterOperand; + + /** The literal value being compared against. */ + right?: ApprovalWorkflowFilterOperand; +}; + +/** + * Top-level filter for an approval-workflow rule. Combines two child nodes with a boolean + * operator. `left` / `right` may be either leaf comparisons or nested filters, so the tree + * can express arbitrarily deep `from AND (previousApprover AND amount < limit)` shapes. + * + * For this project the operator is constrained to `AND` at runtime, but the type uses + * `ValueOf` so future operators (e.g. `OR`) can slot in without changing + * the contract. + */ +type ApprovalWorkflowFilter = { + /** Boolean combinator — currently always `AND` in production. */ + operator: ValueOf; + + /** Left-hand child: leaf comparison or nested boolean filter. */ + left: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; + + /** Right-hand child. Optional so a degenerate single-comparison filter can be represented. */ + right?: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; +}; + +/** + * A single approval-workflow rule, keyed by ruleID inside `Policy.rules.approvalWorkflows`. + * When all `filters` match a report, the report is forwarded to `nextReceiver`. + */ +type ApprovalWorkflowRule = { + /** Conditions that must match the report for the rule to fire. */ + filters: ApprovalWorkflowFilter; + + /** Currently the only supported action. Kept as a literal to leave room for future actions. */ + action: 'forward'; + + /** Email of the user the report is forwarded to when the rule matches. */ + nextReceiver: string; +}; + +/** + * Map of approval-workflow rules keyed by ruleID, as stored on the policy under + * `rules.approvalWorkflows`. + */ +type ApprovalWorkflowRules = Record; + +export type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowFilterOperand, ApprovalWorkflowRule, ApprovalWorkflowRules}; diff --git a/src/types/onyx/Policy.ts b/src/types/onyx/Policy.ts index 7473b11e5d4c..6e9d6d6b6903 100644 --- a/src/types/onyx/Policy.ts +++ b/src/types/onyx/Policy.ts @@ -5,6 +5,7 @@ import type CONST from '@src/CONST'; import type {Country} from '@src/CONST'; import type {MergeHRProviderSlug} from '@src/CONST/MERGE_HR_PROVIDERS'; import type * as OnyxTypes from '.'; +import type {ApprovalWorkflowRule} from './ApprovalWorkflowRules'; import type * as OnyxCommon from './OnyxCommon'; import type {WorkspaceTravelSettings} from './TravelSettings'; @@ -2293,6 +2294,13 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< /** A set of Agent rules defined with natural language - The rules are run by the "RuleBot" */ agentRules?: Record; + + /** + * Approval-workflow rules keyed by ruleID. Each rule routes a report to a `nextReceiver` + * when its `filters` match. Multiple workflows can share the same rule by listing more + * than one submitter in the `from` filter. + */ + approvalWorkflows?: Record; }; /** The "RuleBot" agent account ID */ @@ -2439,7 +2447,7 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< /** Whether the policy requires purchases to be on a company card */ requireCompanyCardsEnabled?: boolean; } & Partial, - 'addWorkspaceRoom' | keyof ACHAccount | keyof Attributes | 'isHREnabled' | 'isTimeTrackingEnabled' | 'timeTrackingDefaultRate' + 'addWorkspaceRoom' | keyof ACHAccount | keyof Attributes | 'isHREnabled' | 'isTimeTrackingEnabled' | 'timeTrackingDefaultRate' | 'approvalWorkflows' >; /** Stages of policy connection sync */ From 420b7a265469dab0527c7acb8afa3341add5e9bb Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 26 Jun 2026 15:50:05 +0200 Subject: [PATCH 02/62] better rule building --- src/CONST/index.ts | 1 + src/libs/WorkflowUtils.ts | 116 ++++++++++-------- src/libs/actions/Workflow.ts | 36 +++++- .../WorkspaceWorkflowsApprovalsCreatePage.tsx | 12 +- src/types/onyx/ApprovalWorkflowRules.ts | 8 +- 5 files changed, 113 insertions(+), 60 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 8274c3f09f30..211d316ca31e 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -1042,6 +1042,7 @@ const CONST = { VENDOR_MATCHING: 'vendorMatching', RULES_REVAMP: 'rulesRevamp', COMMUTER_EXCLUSIONS: 'commuterExclusions', + MULTIPLE_APPROVERS: 'multipleApprovers', }, BUTTON_STATES: { DEFAULT: 'default', diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 031ffab87103..6ba167b73ecb 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -754,23 +754,49 @@ function buildPreviousApproverComparison(email: string): ApprovalWorkflowFilterC return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER, email); } +/** + * Assemble the filter tree for a single rule from its parts. The `from` comparison is always + * present; the `previousApprover` gate and `amount` comparison are optional. When neither is + * present we return the bare `from` comparison rather than wrapping it in an `AND` with no `right`. + */ +function buildLevelFilters( + fromComparison: ApprovalWorkflowFilterComparison, + previousApproverComparison: ApprovalWorkflowFilterComparison | undefined, + amountComparison: ApprovalWorkflowFilterComparison | undefined, +): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison { + let right: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter | undefined; + if (previousApproverComparison && amountComparison) { + right = {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: previousApproverComparison, right: amountComparison}; + } else { + right = previousApproverComparison ?? amountComparison; + } + + if (!right) { + return fromComparison; + } + + return {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: fromComparison, right}; +} + /** * Build the `rules.approvalWorkflows` rule chain for a single `ApprovalWorkflow`. * - * For a workflow whose approver chain is `[A0, A1, ..., A_{N-1}]` and whose members are `M`, - * we emit one rule per approver position. The rule at position `i` routes the report TO - * `approvers[i]`: - * - * - i == 0 (initial submission): filter is `from ∈ M`, nextReceiver is `A0.email`. - * - i > 0 (after `A_{i-1}` approves): filter is `from ∈ M AND previousApprover == A_{i-1}.email`, - * nextReceiver is `A_i.email`. + * For a workflow whose approver chain is `[A0, A1, ..., A_{N-1}]` and whose members are `M`, we emit + * the rule(s) that route the report INTO each level. The split happens at the level being routed + * into: at level `i`, the approver `A_i` and their over-limit approver `A_i.overLimitForwardsTo` + * share the same `previousApprover` gate — `A_{i-1}.email` — or NO `previousApprover` at all for the + * first level (a freshly-submitted report). The level's `A_i.approvalLimit` drives the mirrored + * amount pair: * - * When `A_{i-1}` has both `approvalLimit > 0` and `overLimitForwardsTo` set, the hop after - * them splits into two rules — an under-limit rule that continues to `A_i` and an over-limit - * counterpart that jumps directly to `A_{i-1}.overLimitForwardsTo` instead. + * - i == 0, no limit: `from ∈ M` → A0 + * - i == 0, limit: `from ∈ M AND amount < limit` → A0 + * `from ∈ M AND amount >= limit` → A0.overLimitForwardsTo + * - i > 0, no limit: `from ∈ M AND previousApprover == A_{i-1}` → A_i + * - i > 0, limit: `from ∈ M AND (previousApprover == A_{i-1} AND amount < limit)` → A_i + * `from ∈ M AND (previousApprover == A_{i-1} AND amount >= limit)` → A_i.overLimitForwardsTo * - * No rule is emitted "after the last approver" because nothing forwards past the terminal - * approver in the chain. + * The last approver still gets an "into" rule (routed from the previous level); there's just no rule + * forwarding back OUT of them, since nothing forwards past the terminal approver. */ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): ApprovalWorkflowRule[] { const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); @@ -784,61 +810,43 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva const rules: ApprovalWorkflowRule[] = []; for (let i = 0; i < approvers.length; i++) { - const current = approvers[i]; + const approver = approvers.at(i); + if (!approver) { + continue; + } + + // The level's `previousApprover` gate is the approver from the previous level. The first + // level has none — a freshly-submitted report is routed by `from` (and amount) alone. const previous = i > 0 ? approvers.at(i - 1) : undefined; + const previousApproverComparison = previous ? buildPreviousApproverComparison(previous.email) : undefined; + + const hasLimitSplit = !!approver.approvalLimit && approver.approvalLimit > 0 && !!approver.overLimitForwardsTo; - // Initial-submission rule: degenerate single-comparison filter, no previousApprover gate. - if (!previous) { + if (hasLimitSplit) { + const limit = approver.approvalLimit as number; + const underAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit); + const overAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit); + + // The approver and their over-limit approver share the same previousApprover gate (or lack + // of one at the first level) and differ only by the mirrored amount comparison. rules.push({ - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: fromComparison}, + filters: buildLevelFilters(fromComparison, previousApproverComparison, underAmount), action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: current.email, + nextReceiver: approver.email, }); - continue; - } - - const previousApproverComparison = buildPreviousApproverComparison(previous.email); - const hasLimitSplit = !!previous.approvalLimit && previous.approvalLimit > 0 && !!previous.overLimitForwardsTo; - - if (!hasLimitSplit) { rules.push({ - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: fromComparison, right: previousApproverComparison}, + filters: buildLevelFilters(fromComparison, previousApproverComparison, overAmount), action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: current.email, + nextReceiver: approver.overLimitForwardsTo as string, }); continue; } - // Split: amount < limit continues to the next approver, amount >= limit jumps to overLimit. - const limit = previous.approvalLimit as number; - const overLimitTarget = previous.overLimitForwardsTo as string; - + // No limit at this level: a single rule routes the report to this approver. rules.push({ - filters: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: fromComparison, - right: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: previousApproverComparison, - right: buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit), - }, - }, - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: current.email, - }); - - rules.push({ - filters: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: fromComparison, - right: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: previousApproverComparison, - right: buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit), - }, - }, + filters: buildLevelFilters(fromComparison, previousApproverComparison, undefined), action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: overLimitTarget, + nextReceiver: approver.email, }); } diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 6f0c09e6b669..ec6301bbcc98 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -7,7 +7,14 @@ import {WRITE_COMMANDS} from '@libs/API/types'; import * as ErrorUtils from '@libs/ErrorUtils'; import {getDefaultApprover} from '@libs/PolicyUtils'; import type {ApprovalWorkflowRulesDiff} from '@libs/WorkflowUtils'; -import {calculateApprovers, convertApprovalWorkflowToPolicyEmployees, getOverLimitForwardsToDisplayName, mergeWorkflowMembersWithAvailableMembers} from '@libs/WorkflowUtils'; +import { + buildApprovalWorkflowRules, + calculateApprovers, + convertApprovalWorkflowToPolicyEmployees, + getOverLimitForwardsToDisplayName, + mergeWorkflowMembersWithAvailableMembers, + reconcileApprovalWorkflowRulesForCreate, +} from '@libs/WorkflowUtils'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -343,6 +350,32 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflow API.write(WRITE_COMMANDS.SET_APPROVAL_WORKFLOW, parameters, {optimisticData, successData, failureData}); } +/** + * Create an approval workflow using the new rules-based backend (SetApprovalWorkflow), gated + * behind the `multipleApprovers` beta. Mirrors `createApprovalWorkflow`'s signature and its + * onboarding-task side-effect, but writes to `Policy.rules.approvalWorkflows` instead of + * `employeeList`. + */ +function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport}: CreateApprovalWorkflowParams) { + if (!policy) { + return; + } + + const newRules = buildApprovalWorkflowRules(approvalWorkflow); + const memberEmails = approvalWorkflow.members.map((member) => member.email); + const existingRules = policy.rules?.approvalWorkflows ?? {}; + const rulesDiff = reconcileApprovalWorkflowRulesForCreate(newRules, memberEmails, {existingRules}); + + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); + + if ( + addExpenseApprovalsTaskReport && + (addExpenseApprovalsTaskReport.stateNum !== CONST.REPORT.STATE_NUM.APPROVED || addExpenseApprovalsTaskReport.statusNum !== CONST.REPORT.STATUS_NUM.APPROVED) + ) { + completeTask(addExpenseApprovalsTaskReport, false, false, undefined, undefined, undefined, false); + } +} + /** Set the members of the approval workflow that is currently edited */ function setApprovalWorkflowMembers(members: Member[]) { Onyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, {members, errors: null}); @@ -504,6 +537,7 @@ function validateApprovalWorkflow(approvalWorkflow: ApprovalWorkflowOnyx): appro export { createApprovalWorkflow, + createApprovalWorkflowRules, updateApprovalWorkflow, removeApprovalWorkflow, setApprovalWorkflowMembers, diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx index 28f5ec4e179c..2c629f0ea94f 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx @@ -10,6 +10,7 @@ import ScreenWrapper from '@components/ScreenWrapper'; import useBottomSafeSafeAreaPaddingStyle from '@hooks/useBottomSafeSafeAreaPaddingStyle'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePermissions from '@hooks/usePermissions'; import useThemeStyles from '@hooks/useThemeStyles'; import {isAnyHRReadOnlyWorkflowMode} from '@libs/HRUtils'; import Navigation from '@libs/Navigation/Navigation'; @@ -19,7 +20,7 @@ import {canEditWorkspaceSettings, goBackFromInvalidPolicy, isPendingDeletePolicy import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading'; import type {WithPolicyAndFullscreenLoadingProps} from '@pages/workspace/withPolicyAndFullscreenLoading'; -import {createApprovalWorkflow as createApprovalWorkflowAction, validateApprovalWorkflow} from '@userActions/Workflow'; +import {createApprovalWorkflow as createApprovalWorkflowAction, createApprovalWorkflowRules, validateApprovalWorkflow} from '@userActions/Workflow'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; @@ -32,6 +33,7 @@ type WorkspaceWorkflowsApprovalsCreatePageProps = WithPolicyAndFullscreenLoading function WorkspaceWorkflowsApprovalsCreatePage({policy, isLoadingReportData = true, route}: WorkspaceWorkflowsApprovalsCreatePageProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); + const {isBetaEnabled} = usePermissions(); const [approvalWorkflow] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const addExpenseApprovalsTaskReportID = introSelected?.addExpenseApprovals; @@ -50,9 +52,13 @@ function WorkspaceWorkflowsApprovalsCreatePage({policy, isLoadingReportData = tr return; } - createApprovalWorkflowAction({approvalWorkflow, policy, addExpenseApprovalsTaskReport}); + if (isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS)) { + createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport}); + } else { + createApprovalWorkflowAction({approvalWorkflow, policy, addExpenseApprovalsTaskReport}); + } Navigation.dismissModal(); - }, [approvalWorkflow, policy, addExpenseApprovalsTaskReport]); + }, [approvalWorkflow, policy, addExpenseApprovalsTaskReport, isBetaEnabled]); const submitButtonContainerStyles = useBottomSafeSafeAreaPaddingStyle({addBottomSafeAreaPadding: true, style: [styles.mb5, styles.mh5]}); diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 63dba2016ef2..92b3ecc78c78 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -53,8 +53,12 @@ type ApprovalWorkflowFilter = { * When all `filters` match a report, the report is forwarded to `nextReceiver`. */ type ApprovalWorkflowRule = { - /** Conditions that must match the report for the rule to fire. */ - filters: ApprovalWorkflowFilter; + /** + * Conditions that must match the report for the rule to fire. Usually an `AND` filter, but a + * rule with a single condition (e.g. the initial-submission rule that only checks `from`) is + * stored as a bare comparison rather than a degenerate `AND` with no `right`. + */ + filters: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison; /** Currently the only supported action. Kept as a literal to leave room for future actions. */ action: 'forward'; From df701b64b228fe03f341dc6a6adc39f2b3ce9376 Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 26 Jun 2026 16:19:56 +0200 Subject: [PATCH 03/62] better edition handling --- src/libs/WorkflowUtils.ts | 75 ++++++++++++++++++++++----------------- 1 file changed, 42 insertions(+), 33 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 6ba167b73ecb..8d7b703528f4 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -791,9 +791,13 @@ function buildLevelFilters( * - i == 0, no limit: `from ∈ M` → A0 * - i == 0, limit: `from ∈ M AND amount < limit` → A0 * `from ∈ M AND amount >= limit` → A0.overLimitForwardsTo - * - i > 0, no limit: `from ∈ M AND previousApprover == A_{i-1}` → A_i - * - i > 0, limit: `from ∈ M AND (previousApprover == A_{i-1} AND amount < limit)` → A_i - * `from ∈ M AND (previousApprover == A_{i-1} AND amount >= limit)` → A_i.overLimitForwardsTo + * - i > 0, no limit: `from ∈ M AND previousApprover == P` → A_i + * - i > 0, limit: `from ∈ M AND (previousApprover == P AND amount < limit)` → A_i + * `from ∈ M AND (previousApprover == P AND amount >= limit)` → A_i.overLimitForwardsTo + * + * Because the previous level's over-limit approver also approves and forwards onward, the report + * can reach level `i` from EITHER the previous level's base approver or its over-limit approver. So + * `P` ranges over every "exit" of the previous level, and we emit the level's rule(s) once per `P`. * * The last approver still gets an "into" rule (routed from the previous level); there's just no rule * forwarding back OUT of them, since nothing forwards past the terminal approver. @@ -809,45 +813,50 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva const fromComparison = buildFromComparison(memberEmails); const rules: ApprovalWorkflowRule[] = []; + // The approvers that could have approved at the PREVIOUS level and forwarded here. An empty list + // means "no previous approver" — the first level / a freshly-submitted report. + let previousApproverEmails: string[] = []; + for (let i = 0; i < approvers.length; i++) { const approver = approvers.at(i); if (!approver) { continue; } - // The level's `previousApprover` gate is the approver from the previous level. The first - // level has none — a freshly-submitted report is routed by `from` (and amount) alone. - const previous = i > 0 ? approvers.at(i - 1) : undefined; - const previousApproverComparison = previous ? buildPreviousApproverComparison(previous.email) : undefined; - const hasLimitSplit = !!approver.approvalLimit && approver.approvalLimit > 0 && !!approver.overLimitForwardsTo; - - if (hasLimitSplit) { - const limit = approver.approvalLimit as number; - const underAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit); - const overAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit); - - // The approver and their over-limit approver share the same previousApprover gate (or lack - // of one at the first level) and differ only by the mirrored amount comparison. - rules.push({ - filters: buildLevelFilters(fromComparison, previousApproverComparison, underAmount), - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.email, - }); - rules.push({ - filters: buildLevelFilters(fromComparison, previousApproverComparison, overAmount), - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.overLimitForwardsTo as string, - }); - continue; + const limit = hasLimitSplit ? (approver.approvalLimit as number) : undefined; + const underAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; + const overAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; + + // One gate per possible previous approver (or a single "no previousApprover" gate at level 0). + const gates = previousApproverEmails.length === 0 ? [undefined] : previousApproverEmails.map((email) => buildPreviousApproverComparison(email)); + + for (const gate of gates) { + if (hasLimitSplit) { + // The approver and their over-limit approver share this previousApprover gate (or its + // absence at level 0) and differ only by the mirrored amount comparison. + rules.push({ + filters: buildLevelFilters(fromComparison, gate, underAmount), + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: approver.email, + }); + rules.push({ + filters: buildLevelFilters(fromComparison, gate, overAmount), + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: approver.overLimitForwardsTo as string, + }); + } else { + rules.push({ + filters: buildLevelFilters(fromComparison, gate, undefined), + action: APPROVAL_WORKFLOW_FORWARD_ACTION, + nextReceiver: approver.email, + }); + } } - // No limit at this level: a single rule routes the report to this approver. - rules.push({ - filters: buildLevelFilters(fromComparison, previousApproverComparison, undefined), - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.email, - }); + // Exits from this level feed the next level's previousApprover gates: when this level splits, + // both the base approver and the over-limit approver can have approved and forwarded onward. + previousApproverEmails = hasLimitSplit ? [approver.email, approver.overLimitForwardsTo as string] : [approver.email]; } return rules; From f121f2c2200563bf7d15c74b2be0e1a544e95af5 Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 26 Jun 2026 17:46:07 +0200 Subject: [PATCH 04/62] better handling of rule generation --- src/ROUTES.ts | 5 +- src/libs/Navigation/types.ts | 2 + src/libs/WorkflowUtils.ts | 164 ++++++++++++------ src/libs/actions/Workflow.ts | 82 ++++++++- .../workflows/WorkspaceWorkflowsPage.tsx | 38 ++-- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 47 ++++- ...paceWorkflowsApprovalsExpensesFromPage.tsx | 35 +++- 7 files changed, 290 insertions(+), 83 deletions(-) diff --git a/src/ROUTES.ts b/src/ROUTES.ts index ad3fcc28e61b..84fd9f9f324e 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -2341,7 +2341,10 @@ const ROUTES = { }, WORKSPACE_WORKFLOWS_APPROVALS_EDIT: { route: 'workspaces/:policyID/workflows/approvals/:firstApproverEmail/edit', - getRoute: (policyID: string, firstApproverEmail: string) => `workspaces/${policyID}/workflows/approvals/${encodeURIComponent(firstApproverEmail)}/edit` as const, + // `memberEmail` disambiguates workflows that share a first approver (possible once rule-based + // chains diverge) — a member belongs to exactly one workflow, so it uniquely identifies it. + getRoute: (policyID: string, firstApproverEmail: string, memberEmail?: string) => + `workspaces/${policyID}/workflows/approvals/${encodeURIComponent(firstApproverEmail)}/edit${memberEmail ? `?memberEmail=${encodeURIComponent(memberEmail)}` : ''}` as const, }, WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROM: { route: 'workspaces/:policyID/workflows/approvals/expenses-from', diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index e4a2393095c3..5c2da6224543 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -2787,6 +2787,8 @@ type WorkspaceSplitNavigatorParamList = { [SCREENS.WORKSPACE.WORKFLOWS_APPROVALS_EDIT]: { policyID: string; firstApproverEmail: string; + /** Disambiguates workflows that share a first approver (rule-based diverging chains). A member belongs to exactly one workflow. */ + memberEmail?: string; }; [SCREENS.WORKSPACE.WORKFLOWS_APPROVALS_EXPENSES_FROM]: { policyID: string; diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 8d7b703528f4..db6c30e66fca 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1151,6 +1151,23 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st return diff; } +/** + * Apply an `ApprovalWorkflowRulesDiff` to a rule map, returning a new map. A `null` value removes + * the rule; any other value upserts it. Lets us chain reconcilers — e.g. apply a membership change, + * then reconcile the approver chain against the result. + */ +function applyApprovalWorkflowRulesDiff(existingRules: Record, diff: ApprovalWorkflowRulesDiff): Record { + const result: Record = {...existingRules}; + for (const [ruleID, value] of Object.entries(diff)) { + if (value === null) { + delete result[ruleID]; + } else { + result[ruleID] = value; + } + } + return result; +} + // --------------------------------------------------------------------------- // Reconstruct ApprovalWorkflow[] from `policy.rules.approvalWorkflows` // --------------------------------------------------------------------------- @@ -1191,37 +1208,30 @@ function findComparisonByLeft(node: ApprovalWorkflowFilter | ApprovalWorkflowFil return findComparisonByLeft(right, leftKey); } -/** Initial-submission rule for a submitter — `from` includes them and no `previousApprover` filter exists. */ -function findInitialSubmissionRule(submitter: string, rules: Record): ApprovalWorkflowRule | undefined { - for (const rule of Object.values(rules)) { - if (!extractFromEmails(rule).includes(submitter)) { - continue; - } - if (!findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER)) { - return rule; - } - } - return undefined; -} - -/** Resolved hop info — where the report goes after the current approver acts, and any limit split that controlled it. */ -type ApprovalWorkflowHopInfo = { - /** Next approver email (under-limit path, or the only path when no split). */ - forwardsTo: string; - /** Amount threshold from the under/over-limit split, if any. */ +/** The approver a level routes the report INTO, plus that approver's own limit split (if any). */ +type ApprovalWorkflowLevelInfo = { + /** The approver the level routes to (under-limit / only path). */ + email: string; + /** This approver's own approval limit, from the level's amount split. */ approvalLimit?: number; - /** Over-limit forward target, if the hop is split. */ + /** This approver's own over-limit target, from the level's amount split. */ overLimitForwardsTo?: string; }; /** - * Look for the rules describing what happens after `currentApproverEmail` approves a report - * submitted by `submitter`. Returns: - * - {forwardsTo, approvalLimit, overLimitForwardsTo} when both halves of a limit split exist - * - {forwardsTo} when there's a single normal rule (or only one half of a partial/broken split) - * - undefined when no matching rule exists, signaling the caller to fall back to employeeList + * Resolve the level routed into by the rules that gate on `previousApproverEmail` (or the rules with + * NO `previousApprover` filter when it's `undefined` — the initial-submission level). Mirrors a single + * "into a level" step of `buildApprovalWorkflowRules`: + * - both halves of a split present → {email: under target, approvalLimit, overLimitForwardsTo: over target} + * - a single non-amount rule → {email: target} + * - only one half of a split → {email: that target} (best-effort recovery from a broken pair) + * - no matching rule → undefined, so the caller can fall back to employeeList + * + * The level's amount split describes the *target* approver's own limit/over (the approver being routed + * into), not the approver who forwarded here — that's the inverse of how `buildApprovalWorkflowRules` + * emits them. */ -function extractHopFromRules(submitter: string, currentApproverEmail: string, rules: Record): ApprovalWorkflowHopInfo | undefined { +function resolveLevelFromRules(submitter: string, previousApproverEmail: string | undefined, rules: Record): ApprovalWorkflowLevelInfo | undefined { let underLimitRule: ApprovalWorkflowRule | undefined; let overLimitRule: ApprovalWorkflowRule | undefined; let normalRule: ApprovalWorkflowRule | undefined; @@ -1232,7 +1242,12 @@ function extractHopFromRules(submitter: string, currentApproverEmail: string, ru continue; } const previousApproverLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER); - if (!previousApproverLeaf || previousApproverLeaf.right !== currentApproverEmail) { + if (previousApproverEmail === undefined) { + // Initial-submission level: only rules with no previousApprover gate. + if (previousApproverLeaf) { + continue; + } + } else if (!previousApproverLeaf || previousApproverLeaf.right !== previousApproverEmail) { continue; } @@ -1254,19 +1269,18 @@ function extractHopFromRules(submitter: string, currentApproverEmail: string, ru if (underLimitRule && overLimitRule) { return { - forwardsTo: underLimitRule.nextReceiver, + email: underLimitRule.nextReceiver, approvalLimit, overLimitForwardsTo: overLimitRule.nextReceiver, }; } if (normalRule) { - return {forwardsTo: normalRule.nextReceiver}; + return {email: normalRule.nextReceiver}; } - // Partial split (one half missing): use whichever rule we found as the next hop. This is a - // best-effort recovery from a corrupted rule pair rather than an expected state. + // Partial split (one half missing): use whichever rule we found. Best-effort recovery. const partial = underLimitRule ?? overLimitRule; if (partial) { - return {forwardsTo: partial.nextReceiver}; + return {email: partial.nextReceiver}; } return undefined; } @@ -1279,19 +1293,23 @@ type BuildApproverChainFromRulesParams = { }; /** - * Walk a submitter's approval chain by following rules from their initial-submission rule - * forward. Each hop's `forwardsTo` / `approvalLimit` / `overLimitForwardsTo` is taken from - * the rule when one exists, and falls back to the current approver's `employeeList` entry - * when the rule chain runs out. Stops at circular references (matching `calculateApprovers`). + * Walk a submitter's approval chain forward from their initial-submission level. At each step we + * resolve the level the report is routed into to learn the next approver's email AND that + * approver's own `approvalLimit` / `overLimitForwardsTo`; the current approver's `forwardsTo` is the + * next approver's email. Each piece falls back to the current/next approver's `employeeList` entry + * when no rule covers that hop, so pre-beta (legacy) workflows still resolve. Stops at circular + * references (matching `calculateApprovers`). */ function buildApproverChainFromRules({submitter, rules, employees, personalDetailsByEmail}: BuildApproverChainFromRulesParams): Approver[] { - // First approver: prefer the initial-submission rule, fall back to employeeList.submitsTo for - // pre-beta workflows that haven't been re-saved yet. - const initialRule = findInitialSubmissionRule(submitter, rules); - let currentEmail: string | undefined = initialRule?.nextReceiver ?? employees[submitter]?.submitsTo; + // The first approver, and its own limit/over, come from the initial (no-previousApprover) level. + // Fall back to employeeList.submitsTo for pre-beta workflows that haven't been re-saved yet. + const initialLevel = resolveLevelFromRules(submitter, undefined, rules); + let currentEmail: string | undefined = initialLevel?.email ?? employees[submitter]?.submitsTo; if (!currentEmail) { return []; } + let currentApprovalLimit: number | null = initialLevel?.approvalLimit ?? employees[currentEmail]?.approvalLimit ?? null; + let currentOverLimitForwardsTo: string | undefined = initialLevel?.overLimitForwardsTo ?? employees[currentEmail]?.overLimitForwardsTo; const chain: Approver[] = []; const seenEmails = new Set(); @@ -1300,10 +1318,11 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai const isCircularReference = seenEmails.has(currentEmail); const employee: PolicyEmployee | undefined = employees[currentEmail]; - const hopInfo = extractHopFromRules(submitter, currentEmail, rules); - const approvalLimit: number | null = hopInfo?.approvalLimit ?? employee?.approvalLimit ?? null; - const overLimitForwardsTo: string | undefined = hopInfo?.overLimitForwardsTo ?? employee?.overLimitForwardsTo; - const forwardsTo: string | undefined = hopInfo?.forwardsTo ?? employee?.forwardsTo; + // The rules gated on `previousApprover == currentEmail` describe the NEXT approver: their + // email is where the current approver forwards, and the level also carries the NEXT + // approver's own limit/over. + const nextLevel = resolveLevelFromRules(submitter, currentEmail, rules); + const forwardsTo: string | undefined = nextLevel?.email ?? employee?.forwardsTo; chain.push({ email: currentEmail, @@ -1311,18 +1330,23 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai avatar: personalDetailsByEmail[currentEmail]?.avatar, displayName: personalDetailsByEmail[currentEmail]?.displayName ?? currentEmail, isCircularReference, - approvalLimit, - overLimitForwardsTo, - overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(overLimitForwardsTo, personalDetailsByEmail), + approvalLimit: currentApprovalLimit, + overLimitForwardsTo: currentOverLimitForwardsTo, + overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(currentOverLimitForwardsTo, personalDetailsByEmail), pendingAction: employee?.pendingAction, errors: employee?.errors, }); - if (isCircularReference) { + if (isCircularReference || !forwardsTo) { break; } seenEmails.add(currentEmail); + + // Advance: the next approver's own limit/over come from the level that routed into them + // (the `nextLevel` we just resolved), falling back to their employeeList entry. currentEmail = forwardsTo; + currentApprovalLimit = nextLevel?.approvalLimit ?? employees[currentEmail]?.approvalLimit ?? null; + currentOverLimitForwardsTo = nextLevel?.overLimitForwardsTo ?? employees[currentEmail]?.overLimitForwardsTo; } return chain; @@ -1340,14 +1364,40 @@ function approverChainFingerprint(chain: Approver[]): string { ); } +/** The sorted set of ruleIDs whose `from` filter includes this submitter — their exact rule membership. */ +function getSubmitterRuleIDs(submitter: string, rules: Record): string[] { + return Object.entries(rules) + .filter(([, rule]) => extractFromEmails(rule).includes(submitter)) + .map(([ruleID]) => ruleID) + .sort(); +} + /** True when at least one rule mentions this submitter in any `from` filter. */ function isSubmitterCoveredByRules(submitter: string, rules: Record): boolean { + return getSubmitterRuleIDs(submitter, rules).length > 0; +} + +/** + * Map every submitter found in the rules to their workflow's first approver (the `nextReceiver` of + * their initial, no-`previousApprover` rule). Used to warn when a member is about to be moved out of + * an existing workflow into another one. + */ +function getRulesSubmitterToFirstApprover(rules: Record): Record { + const submitters = new Set(); for (const rule of Object.values(rules)) { - if (extractFromEmails(rule).includes(submitter)) { - return true; + for (const email of extractFromEmails(rule)) { + submitters.add(email); } } - return false; + + const result: Record = {}; + for (const submitter of submitters) { + const initialLevel = resolveLevelFromRules(submitter, undefined, rules); + if (initialLevel?.email) { + result[submitter] = initialLevel.email; + } + } + return result; } /** @@ -1396,8 +1446,8 @@ function convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, first availableMembers.push(member); } - const initialRule = findInitialSubmissionRule(email, rules); - if (!initialRule && (!submitsTo || (!employees[submitsTo] && !hrAdvancedModeFinalApproverEmail))) { + const hasInitialRule = !!resolveLevelFromRules(email, undefined, rules); + if (!hasInitialRule && (!submitsTo || (!employees[submitsTo] && !hrAdvancedModeFinalApproverEmail))) { // Mirrors the existing legacy filter: skip submitters whose first approver isn't reachable. continue; } @@ -1434,8 +1484,12 @@ function convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, first } } - const sourceTag = isSubmitterCoveredByRules(email, rules) ? 'r' : 'l'; - const fingerprint = `${sourceTag}|${approverChainFingerprint(chain)}`; + // Group submitters that share the same rules into one workflow. A submitter's "rules" is the + // exact set of ruleIDs whose `from` includes them, so two submitters that belong to the same + // rules land in the same workflow (and submitters whose chains diverge — different rule sets — + // stay separate). Legacy submitters (no rules) still group by their reconstructed chain. + const submitterRuleIDs = getSubmitterRuleIDs(email, rules); + const fingerprint = submitterRuleIDs.length > 0 ? `r|${submitterRuleIDs.join(',')}` : `l|${approverChainFingerprint(chain)}`; const existingGroup = groupedByFingerprint.get(fingerprint); if (existingGroup) { @@ -1489,12 +1543,14 @@ function convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, first } export { + applyApprovalWorkflowRulesDiff, buildApprovalWorkflowRules, calculateApprovers, convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, convertApprovalWorkflowToPolicyEmployees, getApprovalLimitDescription, + getRulesSubmitterToFirstApprover, getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, getOverLimitForwardsToDisplayName, diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index ec6301bbcc98..feb7e6c95fa3 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -8,12 +8,16 @@ import * as ErrorUtils from '@libs/ErrorUtils'; import {getDefaultApprover} from '@libs/PolicyUtils'; import type {ApprovalWorkflowRulesDiff} from '@libs/WorkflowUtils'; import { + applyApprovalWorkflowRulesDiff, buildApprovalWorkflowRules, calculateApprovers, convertApprovalWorkflowToPolicyEmployees, getOverLimitForwardsToDisplayName, mergeWorkflowMembersWithAvailableMembers, reconcileApprovalWorkflowRulesForCreate, + reconcileApprovalWorkflowRulesForEdit, + reconcileApprovalWorkflowRulesForMembersChange, + reconcileApprovalWorkflowRulesForRemove, } from '@libs/WorkflowUtils'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; @@ -361,10 +365,18 @@ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprov return; } - const newRules = buildApprovalWorkflowRules(approvalWorkflow); - const memberEmails = approvalWorkflow.members.map((member) => member.email); const existingRules = policy.rules?.approvalWorkflows ?? {}; - const rulesDiff = reconcileApprovalWorkflowRulesForCreate(newRules, memberEmails, {existingRules}); + const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + + // A submitter can only belong to one workflow, so first drop these members from any OTHER + // workflow's rules, then add them to the new workflow. + const removeDiff = reconcileApprovalWorkflowRulesForRemove(memberEmails, {existingRules}); + const rulesAfterRemoval = applyApprovalWorkflowRulesDiff(existingRules, removeDiff); + + const newRules = buildApprovalWorkflowRules(approvalWorkflow); + const createDiff = reconcileApprovalWorkflowRulesForCreate(newRules, memberEmails, {existingRules: rulesAfterRemoval}); + + const rulesDiff = {...removeDiff, ...createDiff}; setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); @@ -376,6 +388,68 @@ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprov } } +type UpdateApprovalWorkflowRulesParams = { + approvalWorkflow: ApprovalWorkflow; + initialApprovalWorkflow: ApprovalWorkflow; + policy: OnyxEntry; +}; + +/** + * Update an existing workflow using the new rules-based backend, gated behind the `multipleApprovers` + * beta. A single edit can change both the membership and the approver chain, so we reconcile in two + * composable steps against the existing `rules.approvalWorkflows`: + * 1. Membership: add joiners / drop leavers across the workflow's rules (so an added member lands in + * the same rules and stays in the same workflow rather than splitting off). + * 2. Chain: reconcile the (possibly changed) approver chain against the membership-updated rules. + * The two diffs are merged (the chain diff, computed against the membership-updated rules, wins on + * overlap) and sent as one SetApprovalWorkflow command. + */ +function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}: UpdateApprovalWorkflowRulesParams) { + if (!policy) { + return; + } + + const existingRules = policy.rules?.approvalWorkflows ?? {}; + const previousMemberEmails = initialApprovalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const newMemberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + + // 1. A submitter can only belong to one workflow, so drop joining members (those not previously in + // this workflow) from any OTHER workflow's rules first. Joiners aren't in this workflow's rules + // yet, so this only touches other workflows. + const joiningMemberEmails = newMemberEmails.filter((email) => !previousMemberEmails.includes(email)); + const removeFromOthersDiff = reconcileApprovalWorkflowRulesForRemove(joiningMemberEmails, {existingRules}); + const rulesAfterRemoval = applyApprovalWorkflowRulesDiff(existingRules, removeFromOthersDiff); + + // 2. Sync membership across this workflow's rules (add joiners, drop leavers). + const memberDiff = reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails, newMemberEmails, {existingRules: rulesAfterRemoval}); + const rulesAfterMembers = applyApprovalWorkflowRulesDiff(rulesAfterRemoval, memberDiff); + + // 3. Reconcile the approver chain against the membership-updated rules. + const newRules = buildApprovalWorkflowRules(approvalWorkflow); + const chainDiff = reconcileApprovalWorkflowRulesForEdit(newRules, newMemberEmails, {existingRules: rulesAfterMembers}); + + const rulesDiff = {...removeFromOthersDiff, ...memberDiff, ...chainDiff}; + + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); +} + +/** + * Delete a workflow using the new rules-based backend, gated behind the `multipleApprovers` beta. + * Strips the workflow's members from every rule's `from` filter and removes any rule that ends up + * with no submitters, via the SetApprovalWorkflow command. + */ +function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry) { + if (!policy) { + return; + } + + const existingRules = policy.rules?.approvalWorkflows ?? {}; + const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const rulesDiff = reconcileApprovalWorkflowRulesForRemove(memberEmails, {existingRules}); + + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); +} + /** Set the members of the approval workflow that is currently edited */ function setApprovalWorkflowMembers(members: Member[]) { Onyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, {members, errors: null}); @@ -538,7 +612,9 @@ function validateApprovalWorkflow(approvalWorkflow: ApprovalWorkflowOnyx): appro export { createApprovalWorkflow, createApprovalWorkflowRules, + removeApprovalWorkflowRules, updateApprovalWorkflow, + updateApprovalWorkflowRules, removeApprovalWorkflow, setApprovalWorkflowMembers, setApprovalWorkflowApprover, diff --git a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx index ec3947ea78bb..86652b5af967 100644 --- a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx +++ b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx @@ -64,7 +64,7 @@ import { } from '@libs/PolicyUtils'; import {hasInProgressVBBA} from '@libs/ReimbursementAccountUtils'; import tokenizedSearch from '@libs/tokenizedSearch'; -import {convertPolicyEmployeesToApprovalWorkflows, getEligibleExistingBusinessBankAccounts, INITIAL_APPROVAL_WORKFLOW} from '@libs/WorkflowUtils'; +import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, getEligibleExistingBusinessBankAccounts, INITIAL_APPROVAL_WORKFLOW} from '@libs/WorkflowUtils'; import type {WorkspaceSplitNavigatorParamList} from '@navigation/types'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import ExpenseReportRulesSection from '@pages/workspace/rules/ExpenseReportRulesSection'; @@ -171,16 +171,16 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { const delegateAccountID = useDelegateAccountID(); const {accountID: currentUserAccountID, email: currentUserEmail = '', login: currentUserLogin = ''} = useCurrentUserPersonalDetails(); const isUserReimburser = policy?.achAccount?.reimburser !== undefined && account?.primaryLogin !== undefined && policy?.achAccount?.reimburser === account?.primaryLogin; - const {approvalWorkflows, availableMembers, usedApproverEmails} = useMemo( - () => - convertPolicyEmployeesToApprovalWorkflows({ - policy, - personalDetails: personalDetails ?? {}, - localeCompare, - currentUserLogin, - }), - [policy, personalDetails, localeCompare, currentUserLogin], - ); + const isMultipleApproversBetaEnabled = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS); + const {approvalWorkflows, availableMembers, usedApproverEmails} = useMemo(() => { + const params = { + policy, + personalDetails: personalDetails ?? {}, + localeCompare, + currentUserLogin, + }; + return isMultipleApproversBetaEnabled ? convertApprovalWorkflowRulesToWorkflows(params) : convertPolicyEmployeesToApprovalWorkflows(params); + }, [policy, personalDetails, localeCompare, currentUserLogin, isMultipleApproversBetaEnabled]); const canAccessSubmit2026Features = canAccessSubmitWorkspaceFeatures(policy, isSubmit2026BetaEnabled); const hasValidExistingAccounts = getEligibleExistingBusinessBankAccounts(bankAccountList, policy?.outputCurrency, true).length > 0; @@ -294,8 +294,15 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { const isHRAdvancedModeEnabled = isHRAdvancedMode(policy); const hrFinalApproverEmail = getHRFinalApprover(policy) ?? undefined; + // With the multipleApprovers beta on, `approvalWorkflows` is reconstructed from + // `rules.approvalWorkflows` and already contains exactly the workflows that exist, so we don't + // collapse to the default workflow based on `approvalMode` (which the rules-create path doesn't + // bump to ADVANCED). const filteredApprovalWorkflows = - policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.ADVANCED || policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL || isHRAdvancedModeEnabled + isMultipleApproversBetaEnabled || + policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.ADVANCED || + policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL || + isHRAdvancedModeEnabled ? approvalWorkflows : approvalWorkflows.filter((workflow) => workflow.isDefault); @@ -524,10 +531,13 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { /> {displayedWorkflows.map((workflow) => { const firstApproverEmail = workflow.approvers.at(0)?.email ?? ''; + // A workflow's first approver isn't unique once rule-based chains diverge, but a member + // belongs to exactly one workflow — use it to disambiguate both the React key and the edit route. + const firstMemberEmail = workflow.members.at(0)?.email ?? ''; return ( { // Discard stale onyx edits or the Edit page's resume check would surface a prior abandoned session. clearApprovalWorkflow(); - Navigation.navigate(ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(route.params.policyID, firstApproverEmail)); + Navigation.navigate(ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(route.params.policyID, firstApproverEmail, firstMemberEmail)); } } onShowAllMembersPress={ diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index a5e96772d802..9cf736b86503 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -12,17 +12,26 @@ import useConfirmModal from '@hooks/useConfirmModal'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePermissions from '@hooks/usePermissions'; import useThemeStyles from '@hooks/useThemeStyles'; import {isAnyHRReadOnlyWorkflowMode} from '@libs/HRUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import {canEditWorkspaceSettings, goBackFromInvalidPolicy, isPendingDeletePolicy} from '@libs/PolicyUtils'; -import {convertPolicyEmployeesToApprovalWorkflows} from '@libs/WorkflowUtils'; +import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows} from '@libs/WorkflowUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading'; import type {WithPolicyAndFullscreenLoadingProps} from '@pages/workspace/withPolicyAndFullscreenLoading'; -import {clearApprovalWorkflow, removeApprovalWorkflow, selectApprovalWorkflowForEdit, updateApprovalWorkflow, validateApprovalWorkflow} from '@userActions/Workflow'; +import { + clearApprovalWorkflow, + removeApprovalWorkflow, + removeApprovalWorkflowRules, + selectApprovalWorkflowForEdit, + updateApprovalWorkflow, + updateApprovalWorkflowRules, + validateApprovalWorkflow, +} from '@userActions/Workflow'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; @@ -41,6 +50,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true const [approvalWorkflow, approvalWorkflowMetadata] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW); const isLoadingApprovalWorkflow = isLoadingOnyxValue(approvalWorkflowMetadata); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); + const {isBetaEnabled} = usePermissions(); const [initialApprovalWorkflow, setInitialApprovalWorkflow] = useState(); const formRef = useRef(null); const {showConfirmModal} = useConfirmModal(); @@ -55,6 +65,15 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true return; } + if (isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS)) { + Navigation.dismissModal({ + afterTransition: () => { + updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}); + }, + }); + return; + } + // We need to remove members and approvers that are no longer in the updated workflow const membersToRemove = initialApprovalWorkflow.members.filter((initialMember) => !approvalWorkflow.members.some((member) => member.email === initialMember.email)); const approversToRemove = initialApprovalWorkflow.approvers.filter((initialApprover) => !approvalWorkflow.approvers.some((approver) => approver.email === initialApprover.email)); @@ -72,10 +91,15 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true // Mark as deleting to prevent the useEffect from clearing the workflow and causing a blink isDeleting.current = true; + const useRulesBackend = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS); Navigation.dismissModal({ afterTransition: () => { // Remove the approval workflow using the initial data as it could be already edited - removeApprovalWorkflow(initialApprovalWorkflow, policy); + if (useRulesBackend) { + removeApprovalWorkflowRules(initialApprovalWorkflow, policy); + } else { + removeApprovalWorkflow(initialApprovalWorkflow, policy); + } }, }); }; @@ -86,18 +110,29 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true } const firstApprover = route.params.firstApproverEmail; - const result = convertPolicyEmployeesToApprovalWorkflows({ + const conversionParams = { policy, personalDetails, firstApprover, localeCompare, currentUserLogin: currentUserPersonalDetails?.login, - }); + }; + const result = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS) + ? convertApprovalWorkflowRulesToWorkflows(conversionParams) + : convertPolicyEmployeesToApprovalWorkflows(conversionParams); + + // `firstApproverEmail` isn't unique once rule-based chains diverge, so prefer matching on the + // member that opened this workflow (a member belongs to exactly one workflow). Fall back to the + // first-approver match for the default workflow (no members) and legacy/unspecified cases. + const memberEmail = route.params.memberEmail; + const currentApprovalWorkflow = + (memberEmail ? result.approvalWorkflows.find((workflow) => workflow.members.some((member) => member.email === memberEmail)) : undefined) ?? + result.approvalWorkflows.find((workflow) => workflow.approvers.at(0)?.email === firstApprover); return { defaultWorkflowMembers: result.availableMembers, usedApproverEmails: result.usedApproverEmails, - currentApprovalWorkflow: result.approvalWorkflows.find((workflow) => workflow.approvers.at(0)?.email === firstApprover), + currentApprovalWorkflow, }; }; diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx index abead1019d05..1f501223f031 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx @@ -9,6 +9,7 @@ import useConfirmModal from '@hooks/useConfirmModal'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePermissions from '@hooks/usePermissions'; import useSearchSelector from '@hooks/useSearchSelector'; import useThemeStyles from '@hooks/useThemeStyles'; import {clearInviteDraft, setWorkspaceInviteMembersDraft} from '@libs/actions/Policy/Member'; @@ -22,6 +23,7 @@ import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import {addSMSDomainIfPhoneNumber} from '@libs/PhoneNumber'; import {canEditWorkspaceSettings, getDefaultApprover, getExcludedUsers, getMemberAccountIDsForWorkspace, isPendingDeletePolicy} from '@libs/PolicyUtils'; +import {getRulesSubmitterToFirstApprover} from '@libs/WorkflowUtils'; import type {AvatarSource} from '@libs/UserAvatarUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import MemberRightIcon from '@pages/workspace/MemberRightIcon'; @@ -55,6 +57,8 @@ function WorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingReportDat const [invitedEmailsToAccountIDsDraft] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_INVITE_MEMBERS_DRAFT}${route.params.policyID}`); const icons = useMemoizedLazyExpensifyIcons(['FallbackAvatar']); const {showConfirmModal} = useConfirmModal(); + const {isBetaEnabled} = usePermissions(); + const isMultipleApproversBetaEnabled = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS); const personalDetailLogins = useMemo(() => Object.fromEntries(Object.entries(personalDetails ?? {}).map(([id, details]) => [id, details?.login])), [personalDetails]); @@ -95,8 +99,14 @@ function WorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingReportDat const isCreateAction = approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.CREATE; const policyMemberEmailsToAccountIDs = getMemberAccountIDsForWorkspace(policy?.employeeList); - // Build a map of member emails to their existing workflow's approver email (for non-default workflows only) + // Build a map of member emails to their existing workflow's first approver. With the beta on this + // is derived from `rules.approvalWorkflows`; otherwise it falls back to the legacy employeeList + // `submitsTo` (non-default workflows only). const membersInExistingWorkflows = (() => { + if (isMultipleApproversBetaEnabled) { + return new Map(Object.entries(getRulesSubmitterToFirstApprover(policy?.rules?.approvalWorkflows ?? {}))); + } + const employees = policy?.employeeList ?? {}; const defaultApprover = getDefaultApprover(policy); const map = new Map(); @@ -469,12 +479,16 @@ function WorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingReportDat setSelectedMembers(nextMembers); }; - // Only show warning when creating a new workflow and a member is being added (not removed) - if (isCreateAction && members.length > selectedMembers.length) { + // Warn when adding a member who already belongs to another workflow. With the beta on this + // applies to both create and edit (a submitter can only be in one workflow, so confirming + // moves them); legacy keeps the create-only behavior. The `!== firstApprover` check skips + // members who are already in the workflow being edited. + const shouldCheckCrossWorkflow = isCreateAction || isMultipleApproversBetaEnabled; + if (shouldCheckCrossWorkflow && members.length > selectedMembers.length) { const newMember = members.find((m) => !selectedMembers.some((s) => s.login === m.login)); const existingApproverEmail = newMember?.login ? membersInExistingWorkflows.get(newMember.login) : undefined; - if (newMember && existingApproverEmail) { + if (newMember && existingApproverEmail && existingApproverEmail !== firstApprover) { const memberName = Str.removeSMSDomain(newMember.text ?? newMember.login ?? ''); const approverDetails = getPersonalDetailByEmail(existingApproverEmail); const approverName = Str.removeSMSDomain(approverDetails?.displayName ?? existingApproverEmail); @@ -496,7 +510,18 @@ function WorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingReportDat applySelection(members); }, - [policy?.employeeList, invitedEmailsToAccountIDsDraft, route.params.policyID, isCreateAction, selectedMembers, membersInExistingWorkflows, showConfirmModal, translate], + [ + policy?.employeeList, + invitedEmailsToAccountIDsDraft, + route.params.policyID, + isCreateAction, + isMultipleApproversBetaEnabled, + firstApprover, + selectedMembers, + membersInExistingWorkflows, + showConfirmModal, + translate, + ], ); return ( From 9602c8638b703c655d08a3c6eca11ab223ea501b Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 13:18:19 +0200 Subject: [PATCH 05/62] some cleanup --- src/libs/actions/Workflow.ts | 36 +++++++++--------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index feb7e6c95fa3..747b8680d563 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -281,8 +281,7 @@ type SetApprovalWorkflowRulesParams = { /** * Diff to apply to `Policy.rules.approvalWorkflows`. A value of `ApprovalWorkflowRule` - * upserts the rule under its `ruleID`; a value of `null` removes it. Produced by the - * `reconcileApprovalWorkflowRules*` helpers in `WorkflowUtils`. + * sets/replaces the rule under its `ruleID`; a value of `null` removes it */ rulesDiff: ApprovalWorkflowRulesDiff; @@ -291,11 +290,9 @@ type SetApprovalWorkflowRulesParams = { }; /** - * Apply a set of approval-workflow rule changes to a policy via the new SetApprovalWorkflow - * Auth command. Mirrors the optimistic/success/failure dance of `createApprovalWorkflow`, - * but operates on `rules.approvalWorkflows` instead of `employeeList`. + * Apply a set of approval-workflow rule changes to a policy via the SetApprovalWorkflow + * Auth command. * - * No-op when `rulesDiff` is empty — there's nothing to send to the backend. */ function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflows}: SetApprovalWorkflowRulesParams) { if (!policyID || isEmptyObject(rulesDiff)) { @@ -304,9 +301,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflow const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policyID}` as const; - // Build the rollback shape: for every rule we're about to touch, either restore the - // previous value (if one existed) or clear the optimistic upsert with `null`. Without - // the explicit `null`s, newly-added rules would survive the failure rollback. + // Build the rollback shape const failureApprovalWorkflows: Record = {}; for (const ruleID of Object.keys(rulesDiff)) { failureApprovalWorkflows[ruleID] = previousApprovalWorkflows[ruleID] ?? null; @@ -355,10 +350,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflow } /** - * Create an approval workflow using the new rules-based backend (SetApprovalWorkflow), gated - * behind the `multipleApprovers` beta. Mirrors `createApprovalWorkflow`'s signature and its - * onboarding-task side-effect, but writes to `Policy.rules.approvalWorkflows` instead of - * `employeeList`. + * Create an approval workflow using the rules-based backend structure, */ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport}: CreateApprovalWorkflowParams) { if (!policy) { @@ -395,14 +387,7 @@ type UpdateApprovalWorkflowRulesParams = { }; /** - * Update an existing workflow using the new rules-based backend, gated behind the `multipleApprovers` - * beta. A single edit can change both the membership and the approver chain, so we reconcile in two - * composable steps against the existing `rules.approvalWorkflows`: - * 1. Membership: add joiners / drop leavers across the workflow's rules (so an added member lands in - * the same rules and stays in the same workflow rather than splitting off). - * 2. Chain: reconcile the (possibly changed) approver chain against the membership-updated rules. - * The two diffs are merged (the chain diff, computed against the membership-updated rules, wins on - * overlap) and sent as one SetApprovalWorkflow command. + * Update an existing workflow using the rules-based backend structure */ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}: UpdateApprovalWorkflowRulesParams) { if (!policy) { @@ -414,8 +399,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, const newMemberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); // 1. A submitter can only belong to one workflow, so drop joining members (those not previously in - // this workflow) from any OTHER workflow's rules first. Joiners aren't in this workflow's rules - // yet, so this only touches other workflows. + // this workflow) from any OTHER workflow's rules first. const joiningMemberEmails = newMemberEmails.filter((email) => !previousMemberEmails.includes(email)); const removeFromOthersDiff = reconcileApprovalWorkflowRulesForRemove(joiningMemberEmails, {existingRules}); const rulesAfterRemoval = applyApprovalWorkflowRulesDiff(existingRules, removeFromOthersDiff); @@ -424,7 +408,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, const memberDiff = reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails, newMemberEmails, {existingRules: rulesAfterRemoval}); const rulesAfterMembers = applyApprovalWorkflowRulesDiff(rulesAfterRemoval, memberDiff); - // 3. Reconcile the approver chain against the membership-updated rules. + // 3. Reconcile the approver chain with the membership-updated rules. const newRules = buildApprovalWorkflowRules(approvalWorkflow); const chainDiff = reconcileApprovalWorkflowRulesForEdit(newRules, newMemberEmails, {existingRules: rulesAfterMembers}); @@ -434,9 +418,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, } /** - * Delete a workflow using the new rules-based backend, gated behind the `multipleApprovers` beta. - * Strips the workflow's members from every rule's `from` filter and removes any rule that ends up - * with no submitters, via the SetApprovalWorkflow command. + * Delete an approval workflow using the rules-based backend structure, gated behind the `multipleApprovers` beta. */ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry) { if (!policy) { From 0af1aa7b8ef97f5f92392a529b775f210e2dd900 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 13:54:29 +0200 Subject: [PATCH 06/62] rename helper functions --- .../API/parameters/ApprovalWorkflowParams.ts | 4 +- src/libs/Navigation/types.ts | 1 - src/libs/WorkflowUtils.ts | 78 +++++-------------- 3 files changed, 20 insertions(+), 63 deletions(-) diff --git a/src/libs/API/parameters/ApprovalWorkflowParams.ts b/src/libs/API/parameters/ApprovalWorkflowParams.ts index 4eca1d7e3ec7..bab03b2bf134 100644 --- a/src/libs/API/parameters/ApprovalWorkflowParams.ts +++ b/src/libs/API/parameters/ApprovalWorkflowParams.ts @@ -3,9 +3,7 @@ type SetApprovalWorkflowParams = { policyID: string; /** - * JSON-stringified object keyed by ruleID, mapping to either: - * - a full `ApprovalWorkflowRule` to add or replace, or - * - `null` / `{}` to remove the rule from the policy. + * JSON-stringified object keyed by ruleID */ rules: string; }; diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index fb52e8f24631..d813fb74e0b0 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -2791,7 +2791,6 @@ type WorkspaceSplitNavigatorParamList = { [SCREENS.WORKSPACE.WORKFLOWS_APPROVALS_EDIT]: { policyID: string; firstApproverEmail: string; - /** Disambiguates workflows that share a first approver (rule-based diverging chains). A member belongs to exactly one workflow. */ memberEmail?: string; }; [SCREENS.WORKSPACE.WORKFLOWS_APPROVALS_EXPENSES_FROM]: { diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index db6c30e66fca..e6801d144cd3 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -718,24 +718,14 @@ function mergeWorkflowMembersWithAvailableMembers(workflowMembers: Member[], all return [...workflowMembers, ...additionalMembers]; } -// --------------------------------------------------------------------------- -// Approval-workflow rules (rules.approvalWorkflows on the policy) -// --------------------------------------------------------------------------- -// // These helpers translate the in-app `ApprovalWorkflow` model into the rule // format the backend stores under `Policy.rules.approvalWorkflows`, and -// reconcile a workflow change against the existing rules so we can hand a -// minimal diff to `Auth/SetApprovalWorkflow`. -// -// Diff convention: a value of `ApprovalWorkflowRule` upserts the rule; a value -// of `null` removes it. JSON-stringified, that matches what Auth expects. - +// handle any changes const APPROVAL_WORKFLOW_FORWARD_ACTION = 'forward' as const; -/** Diff shape passed to the backend: ruleID -> rule (upsert) or null (remove). */ type ApprovalWorkflowRulesDiff = Record; -/** Build a leaf comparison: ` `. */ +/** Build a filter: ` `. */ function buildComparison( operator: ValueOf, left: ApprovalWorkflowFilterComparison['left'], @@ -744,20 +734,19 @@ function buildComparison( return {operator, left, right}; } -/** Build the `from in [emails]` leaf used by every approval-workflow rule. */ -function buildFromComparison(memberEmails: string[]): ApprovalWorkflowFilterComparison { +/** Build the `from in [emails]` filter used by every approval-workflow rule. */ +function buildSubmitterFilter(memberEmails: string[]): ApprovalWorkflowFilterComparison { return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, [...memberEmails]); } -/** Build the `previousApprover = email` leaf used by all non-initial-hop rules. */ +/** Build the `previousApprover = email` filter used by all non-initial rules. */ function buildPreviousApproverComparison(email: string): ApprovalWorkflowFilterComparison { return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER, email); } /** * Assemble the filter tree for a single rule from its parts. The `from` comparison is always - * present; the `previousApprover` gate and `amount` comparison are optional. When neither is - * present we return the bare `from` comparison rather than wrapping it in an `AND` with no `right`. + * present; the `previousApprover` gate and `amount` comparison are optional. */ function buildLevelFilters( fromComparison: ApprovalWorkflowFilterComparison, @@ -780,27 +769,6 @@ function buildLevelFilters( /** * Build the `rules.approvalWorkflows` rule chain for a single `ApprovalWorkflow`. - * - * For a workflow whose approver chain is `[A0, A1, ..., A_{N-1}]` and whose members are `M`, we emit - * the rule(s) that route the report INTO each level. The split happens at the level being routed - * into: at level `i`, the approver `A_i` and their over-limit approver `A_i.overLimitForwardsTo` - * share the same `previousApprover` gate — `A_{i-1}.email` — or NO `previousApprover` at all for the - * first level (a freshly-submitted report). The level's `A_i.approvalLimit` drives the mirrored - * amount pair: - * - * - i == 0, no limit: `from ∈ M` → A0 - * - i == 0, limit: `from ∈ M AND amount < limit` → A0 - * `from ∈ M AND amount >= limit` → A0.overLimitForwardsTo - * - i > 0, no limit: `from ∈ M AND previousApprover == P` → A_i - * - i > 0, limit: `from ∈ M AND (previousApprover == P AND amount < limit)` → A_i - * `from ∈ M AND (previousApprover == P AND amount >= limit)` → A_i.overLimitForwardsTo - * - * Because the previous level's over-limit approver also approves and forwards onward, the report - * can reach level `i` from EITHER the previous level's base approver or its over-limit approver. So - * `P` ranges over every "exit" of the previous level, and we emit the level's rule(s) once per `P`. - * - * The last approver still gets an "into" rule (routed from the previous level); there's just no rule - * forwarding back OUT of them, since nothing forwards past the terminal approver. */ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): ApprovalWorkflowRule[] { const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); @@ -810,11 +778,11 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva return []; } - const fromComparison = buildFromComparison(memberEmails); + const fromComparison = buildSubmitterFilter(memberEmails); const rules: ApprovalWorkflowRule[] = []; // The approvers that could have approved at the PREVIOUS level and forwarded here. An empty list - // means "no previous approver" — the first level / a freshly-submitted report. + // means "no previous approver" let previousApproverEmails: string[] = []; for (let i = 0; i < approvers.length; i++) { @@ -828,13 +796,11 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva const underAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; const overAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; - // One gate per possible previous approver (or a single "no previousApprover" gate at level 0). + // One per possible previous approver const gates = previousApproverEmails.length === 0 ? [undefined] : previousApproverEmails.map((email) => buildPreviousApproverComparison(email)); for (const gate of gates) { if (hasLimitSplit) { - // The approver and their over-limit approver share this previousApprover gate (or its - // absence at level 0) and differ only by the mirrored amount comparison. rules.push({ filters: buildLevelFilters(fromComparison, gate, underAmount), action: APPROVAL_WORKFLOW_FORWARD_ACTION, @@ -854,48 +820,42 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva } } - // Exits from this level feed the next level's previousApprover gates: when this level splits, - // both the base approver and the over-limit approver can have approved and forwarded onward. previousApproverEmails = hasLimitSplit ? [approver.email, approver.overLimitForwardsTo as string] : [approver.email]; } return rules; } -// --------------------------------------------------------------------------- -// Rule introspection helpers (used by reconciliation) -// --------------------------------------------------------------------------- - /** True when a comparison node targets the `from` field with an equality operator. */ -function isFromComparison(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): boolean { +function isSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): boolean { return node.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && (node as ApprovalWorkflowFilterComparison).left === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM; } -/** Walk a filter tree and call `visitor` on every `from` comparison leaf. */ -function forEachFromComparison(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, visitor: (leaf: ApprovalWorkflowFilterComparison) => void): void { +/** Walk a filter tree and call `visitor` on every submitter filter (the `from` leaf) in it. */ +function forEachSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, visitor: (filter: ApprovalWorkflowFilterComparison) => void): void { if (!node) { return; } - if (isFromComparison(node)) { + if (isSubmitterFilter(node)) { visitor(node as ApprovalWorkflowFilterComparison); return; } // Only filter nodes (which always carry a left filter) and AND/OR nodes have children to recurse into. const leftIsNode = typeof (node as ApprovalWorkflowFilter).left === 'object' && (node as ApprovalWorkflowFilter).left !== null; if (leftIsNode) { - forEachFromComparison((node as ApprovalWorkflowFilter).left, visitor); + forEachSubmitterFilter((node as ApprovalWorkflowFilter).left, visitor); } const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; if (right && typeof right === 'object') { - forEachFromComparison(right, visitor); + forEachSubmitterFilter(right, visitor); } } /** Extract the union of email values across every `from` leaf in a rule. */ function extractFromEmails(rule: ApprovalWorkflowRule): string[] { const emails = new Set(); - forEachFromComparison(rule.filters, (leaf) => { - const right = leaf.right; + forEachSubmitterFilter(rule.filters, (filter) => { + const right = filter.right; if (Array.isArray(right)) { right.forEach((email) => { if (typeof email === 'string') { @@ -919,7 +879,7 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { if (!node) { return node; } - if (isFromComparison(node)) { + if (isSubmitterFilter(node)) { return {operator: node.operator, left: (node as ApprovalWorkflowFilterComparison).left}; } const out: Record = {operator: node.operator}; @@ -944,7 +904,7 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { /** Replace the `right` value on every `from` leaf with `newEmails`. */ function withFromEmails(rule: ApprovalWorkflowRule, newEmails: string[]): ApprovalWorkflowRule { const rewrite = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison => { - if (isFromComparison(node)) { + if (isSubmitterFilter(node)) { return {...node, right: [...newEmails]} as ApprovalWorkflowFilterComparison; } const left = (node as ApprovalWorkflowFilter).left; From 6a1eadc623d02c56074c1661492e46c6bf847af4 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 14:52:03 +0200 Subject: [PATCH 07/62] better naming --- src/libs/WorkflowUtils.ts | 62 +++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index e6801d144cd3..e4333a98a901 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -831,28 +831,28 @@ function isSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilter return node.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && (node as ApprovalWorkflowFilterComparison).left === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM; } -/** Walk a filter tree and call `visitor` on every submitter filter (the `from` leaf) in it. */ -function forEachSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, visitor: (filter: ApprovalWorkflowFilterComparison) => void): void { +/** Walk a filter tree and call `callback` on every submitter filter (the `from` leaf) in it. */ +function forEachSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, callback: (filter: ApprovalWorkflowFilterComparison) => void): void { if (!node) { return; } if (isSubmitterFilter(node)) { - visitor(node as ApprovalWorkflowFilterComparison); + callback(node as ApprovalWorkflowFilterComparison); return; } // Only filter nodes (which always carry a left filter) and AND/OR nodes have children to recurse into. const leftIsNode = typeof (node as ApprovalWorkflowFilter).left === 'object' && (node as ApprovalWorkflowFilter).left !== null; if (leftIsNode) { - forEachSubmitterFilter((node as ApprovalWorkflowFilter).left, visitor); + forEachSubmitterFilter((node as ApprovalWorkflowFilter).left, callback); } const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; if (right && typeof right === 'object') { - forEachSubmitterFilter(right, visitor); + forEachSubmitterFilter(right, callback); } } /** Extract the union of email values across every `from` leaf in a rule. */ -function extractFromEmails(rule: ApprovalWorkflowRule): string[] { +function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { const emails = new Set(); forEachSubmitterFilter(rule.filters, (filter) => { const right = filter.right; @@ -902,7 +902,7 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { } /** Replace the `right` value on every `from` leaf with `newEmails`. */ -function withFromEmails(rule: ApprovalWorkflowRule, newEmails: string[]): ApprovalWorkflowRule { +function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]): ApprovalWorkflowRule { const rewrite = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison => { if (isSubmitterFilter(node)) { return {...node, right: [...newEmails]} as ApprovalWorkflowFilterComparison; @@ -918,11 +918,11 @@ function withFromEmails(rule: ApprovalWorkflowRule, newEmails: string[]): Approv return {...rule, filters: rewrite(rule.filters) as ApprovalWorkflowFilter}; } -/** Union of `existingEmails` and `additions`, preserving the order of `existingEmails`. */ -function unionEmails(existingEmails: string[], additions: string[]): string[] { +/** Merge `emailsToAdd` into `existingEmails`, preserving the order of `existingEmails` and dropping duplicates. */ +function mergeEmails(existingEmails: string[], emailsToAdd: string[]): string[] { const seen = new Set(existingEmails); const result = [...existingEmails]; - additions.forEach((email) => { + emailsToAdd.forEach((email) => { if (seen.has(email)) { return; } @@ -932,9 +932,9 @@ function unionEmails(existingEmails: string[], additions: string[]): string[] { return result; } -/** `existingEmails` with everything in `removals` filtered out. */ -function differenceEmails(existingEmails: string[], removals: string[]): string[] { - const removalSet = new Set(removals); +/** Remove everything in `emailsToRemove` from `existingEmails`, preserving the order of `existingEmails`. */ +function removeEmails(existingEmails: string[], emailsToRemove: string[]): string[] { + const removalSet = new Set(emailsToRemove); return existingEmails.filter((email) => !removalSet.has(email)); } @@ -963,8 +963,8 @@ function reconcileApprovalWorkflowRulesForCreate(newRules: ApprovalWorkflowRule[ if (match) { const [existingID, existingRule] = match; - const mergedEmails = unionEmails(extractFromEmails(existingRule), memberEmails); - diff[existingID] = withFromEmails(existingRule, mergedEmails); + const mergedEmails = mergeEmails(extractSubmitterEmails(existingRule), memberEmails); + diff[existingID] = replaceSubmitterEmails(existingRule, mergedEmails); continue; } @@ -997,7 +997,7 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], // Pass 1: walk existing rules that belong (at least partially) to this workflow. for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { - const ruleEmails = extractFromEmails(existingRule); + const ruleEmails = extractSubmitterEmails(existingRule); const sharedWithThisWorkflow = ruleEmails.some((email) => memberSet.has(email)); if (!sharedWithThisWorkflow) { continue; @@ -1010,13 +1010,13 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], continue; } - const remaining = differenceEmails(ruleEmails, memberEmails); + const remaining = removeEmails(ruleEmails, memberEmails); if (remaining.length === 0) { // No other workflow shares this rule — drop it entirely. diff[ruleID] = null; } else { // Keep the rule for the other workflows that still need it, minus our members. - diff[ruleID] = withFromEmails(existingRule, remaining); + diff[ruleID] = replaceSubmitterEmails(existingRule, remaining); } } @@ -1039,15 +1039,15 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], if (structuralFingerprint(existing) !== fingerprint) { return false; } - const existingEmails = extractFromEmails(existing); + const existingEmails = extractSubmitterEmails(existing); // "Different workflow" => no overlap with our members. return !existingEmails.some((email) => memberSet.has(email)); }); if (foreignMatch) { const [existingID, existingRule] = foreignMatch; - const mergedEmails = unionEmails(extractFromEmails(existingRule), memberEmails); - diff[existingID] = withFromEmails(existingRule, mergedEmails); + const mergedEmails = mergeEmails(extractSubmitterEmails(existingRule), memberEmails); + diff[existingID] = replaceSubmitterEmails(existingRule, mergedEmails); continue; } @@ -1067,14 +1067,14 @@ function reconcileApprovalWorkflowRulesForRemove(memberEmails: string[], context const memberSet = new Set(memberEmails); for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { - const ruleEmails = extractFromEmails(existingRule); + const ruleEmails = extractSubmitterEmails(existingRule); const sharedWithThisWorkflow = ruleEmails.some((email) => memberSet.has(email)); if (!sharedWithThisWorkflow) { continue; } - const remaining = differenceEmails(ruleEmails, memberEmails); - diff[ruleID] = remaining.length === 0 ? null : withFromEmails(existingRule, remaining); + const remaining = removeEmails(ruleEmails, memberEmails); + diff[ruleID] = remaining.length === 0 ? null : replaceSubmitterEmails(existingRule, remaining); } return diff; @@ -1092,20 +1092,20 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st const removed = previousMemberEmails.filter((email) => !newSet.has(email)); for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { - const ruleEmails = extractFromEmails(existingRule); + const ruleEmails = extractSubmitterEmails(existingRule); if (!ruleEmails.some((email) => previousSet.has(email))) { continue; } - const afterRemoval = differenceEmails(ruleEmails, removed); - const updatedEmails = unionEmails(afterRemoval, newMemberEmails); + const afterRemoval = removeEmails(ruleEmails, removed); + const updatedEmails = mergeEmails(afterRemoval, newMemberEmails); // No effective change to this rule's `from` — skip the round-trip. if (updatedEmails.length === ruleEmails.length && updatedEmails.every((email, idx) => email === ruleEmails[idx])) { continue; } - diff[ruleID] = updatedEmails.length === 0 ? null : withFromEmails(existingRule, updatedEmails); + diff[ruleID] = updatedEmails.length === 0 ? null : replaceSubmitterEmails(existingRule, updatedEmails); } return diff; @@ -1198,7 +1198,7 @@ function resolveLevelFromRules(submitter: string, previousApproverEmail: string let approvalLimit: number | undefined; for (const rule of Object.values(rules)) { - if (!extractFromEmails(rule).includes(submitter)) { + if (!extractSubmitterEmails(rule).includes(submitter)) { continue; } const previousApproverLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER); @@ -1327,7 +1327,7 @@ function approverChainFingerprint(chain: Approver[]): string { /** The sorted set of ruleIDs whose `from` filter includes this submitter — their exact rule membership. */ function getSubmitterRuleIDs(submitter: string, rules: Record): string[] { return Object.entries(rules) - .filter(([, rule]) => extractFromEmails(rule).includes(submitter)) + .filter(([, rule]) => extractSubmitterEmails(rule).includes(submitter)) .map(([ruleID]) => ruleID) .sort(); } @@ -1345,7 +1345,7 @@ function isSubmitterCoveredByRules(submitter: string, rules: Record): Record { const submitters = new Set(); for (const rule of Object.values(rules)) { - for (const email of extractFromEmails(rule)) { + for (const email of extractSubmitterEmails(rule)) { submitters.add(email); } } From ae82565d4d394992dfbbf470682da4b5888d315e Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 14:58:03 +0200 Subject: [PATCH 08/62] some more naming/doc changes --- src/libs/WorkflowUtils.ts | 55 +++++---------------------------------- 1 file changed, 6 insertions(+), 49 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index e4333a98a901..c552221dbcd4 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -938,10 +938,6 @@ function removeEmails(existingEmails: string[], emailsToRemove: string[]): strin return existingEmails.filter((email) => !removalSet.has(email)); } -// --------------------------------------------------------------------------- -// Reconciliation against the existing `rules.approvalWorkflows` map -// --------------------------------------------------------------------------- - type ReconcileContext = { /** The existing `Policy.rules.approvalWorkflows` snapshot, defaulting to `{}`. */ existingRules: Record; @@ -1113,8 +1109,6 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st /** * Apply an `ApprovalWorkflowRulesDiff` to a rule map, returning a new map. A `null` value removes - * the rule; any other value upserts it. Lets us chain reconcilers — e.g. apply a membership change, - * then reconcile the approver chain against the result. */ function applyApprovalWorkflowRulesDiff(existingRules: Record, diff: ApprovalWorkflowRulesDiff): Record { const result: Record = {...existingRules}; @@ -1128,20 +1122,10 @@ function applyApprovalWorkflowRulesDiff(existingRules: Record): ApprovalWorkflowLevelInfo | undefined { let underLimitRule: ApprovalWorkflowRule | undefined; @@ -1253,12 +1227,9 @@ type BuildApproverChainFromRulesParams = { }; /** - * Walk a submitter's approval chain forward from their initial-submission level. At each step we + * Loop through a submitter's approval chain forward from their initial-submission level. At each step we * resolve the level the report is routed into to learn the next approver's email AND that - * approver's own `approvalLimit` / `overLimitForwardsTo`; the current approver's `forwardsTo` is the - * next approver's email. Each piece falls back to the current/next approver's `employeeList` entry - * when no rule covers that hop, so pre-beta (legacy) workflows still resolve. Stops at circular - * references (matching `calculateApprovers`). + * approver's own `approvalLimit` / `overLimitForwardsTo`; */ function buildApproverChainFromRules({submitter, rules, employees, personalDetailsByEmail}: BuildApproverChainFromRulesParams): Approver[] { // The first approver, and its own limit/over, come from the initial (no-previousApprover) level. @@ -1278,9 +1249,6 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai const isCircularReference = seenEmails.has(currentEmail); const employee: PolicyEmployee | undefined = employees[currentEmail]; - // The rules gated on `previousApprover == currentEmail` describe the NEXT approver: their - // email is where the current approver forwards, and the level also carries the NEXT - // approver's own limit/over. const nextLevel = resolveLevelFromRules(submitter, currentEmail, rules); const forwardsTo: string | undefined = nextLevel?.email ?? employee?.forwardsTo; @@ -1301,9 +1269,6 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai break; } seenEmails.add(currentEmail); - - // Advance: the next approver's own limit/over come from the level that routed into them - // (the `nextLevel` we just resolved), falling back to their employeeList entry. currentEmail = forwardsTo; currentApprovalLimit = nextLevel?.approvalLimit ?? employees[currentEmail]?.approvalLimit ?? null; currentOverLimitForwardsTo = nextLevel?.overLimitForwardsTo ?? employees[currentEmail]?.overLimitForwardsTo; @@ -1332,15 +1297,8 @@ function getSubmitterRuleIDs(submitter: string, rules: Record): boolean { - return getSubmitterRuleIDs(submitter, rules).length > 0; -} - /** - * Map every submitter found in the rules to their workflow's first approver (the `nextReceiver` of - * their initial, no-`previousApprover` rule). Used to warn when a member is about to be moved out of - * an existing workflow into another one. + * Map every submitter found in the rules to their workflow's first approver */ function getRulesSubmitterToFirstApprover(rules: Record): Record { const submitters = new Set(); @@ -1446,8 +1404,7 @@ function convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, first // Group submitters that share the same rules into one workflow. A submitter's "rules" is the // exact set of ruleIDs whose `from` includes them, so two submitters that belong to the same - // rules land in the same workflow (and submitters whose chains diverge — different rule sets — - // stay separate). Legacy submitters (no rules) still group by their reconstructed chain. + // rules land in the same workflow const submitterRuleIDs = getSubmitterRuleIDs(email, rules); const fingerprint = submitterRuleIDs.length > 0 ? `r|${submitterRuleIDs.join(',')}` : `l|${approverChainFingerprint(chain)}`; const existingGroup = groupedByFingerprint.get(fingerprint); From 9973de0a2afa8b4f262306a337215709e46e9870 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 15:02:57 +0200 Subject: [PATCH 09/62] some more cleanup --- src/ROUTES.ts | 2 -- .../workflows/WorkspaceWorkflowsPage.tsx | 6 +----- ...orkspaceWorkflowsApprovalsExpensesFromPage.tsx | 3 +-- src/types/onyx/ApprovalWorkflowRules.ts | 15 ++++----------- src/types/onyx/Policy.ts | 3 +-- 5 files changed, 7 insertions(+), 22 deletions(-) diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 03cfd172eb85..cded97d36eaa 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -2351,8 +2351,6 @@ const ROUTES = { }, WORKSPACE_WORKFLOWS_APPROVALS_EDIT: { route: 'workspaces/:policyID/workflows/approvals/:firstApproverEmail/edit', - // `memberEmail` disambiguates workflows that share a first approver (possible once rule-based - // chains diverge) — a member belongs to exactly one workflow, so it uniquely identifies it. getRoute: (policyID: string, firstApproverEmail: string, memberEmail?: string) => `workspaces/${policyID}/workflows/approvals/${encodeURIComponent(firstApproverEmail)}/edit${memberEmail ? `?memberEmail=${encodeURIComponent(memberEmail)}` : ''}` as const, }, diff --git a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx index 86652b5af967..daf02f9da7a2 100644 --- a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx +++ b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx @@ -294,10 +294,6 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { const isHRAdvancedModeEnabled = isHRAdvancedMode(policy); const hrFinalApproverEmail = getHRFinalApprover(policy) ?? undefined; - // With the multipleApprovers beta on, `approvalWorkflows` is reconstructed from - // `rules.approvalWorkflows` and already contains exactly the workflows that exist, so we don't - // collapse to the default workflow based on `approvalMode` (which the rules-create path doesn't - // bump to ADVANCED). const filteredApprovalWorkflows = isMultipleApproversBetaEnabled || policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.ADVANCED || @@ -532,7 +528,7 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { {displayedWorkflows.map((workflow) => { const firstApproverEmail = workflow.approvers.at(0)?.email ?? ''; // A workflow's first approver isn't unique once rule-based chains diverge, but a member - // belongs to exactly one workflow — use it to disambiguate both the React key and the edit route. + // belongs to exactly one workflow const firstMemberEmail = workflow.members.at(0)?.email ?? ''; return ( diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx index 9517fe5cbfd3..acd0328a3761 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx @@ -475,8 +475,7 @@ function WorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingReportDat // Warn when adding a member who already belongs to another workflow. With the beta on this // applies to both create and edit (a submitter can only be in one workflow, so confirming - // moves them); legacy keeps the create-only behavior. The `!== firstApprover` check skips - // members who are already in the workflow being edited. + // moves them); legacy keeps the create-only behavior. const shouldCheckCrossWorkflow = isCreateAction || isMultipleApproversBetaEnabled; if (shouldCheckCrossWorkflow && members.length > selectedMembers.length) { const newMember = members.find((m) => !selectedMembers.some((s) => s.login === m.login)); diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 92b3ecc78c78..0cb640341e88 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -30,21 +30,16 @@ type ApprovalWorkflowFilterComparison = { /** * Top-level filter for an approval-workflow rule. Combines two child nodes with a boolean - * operator. `left` / `right` may be either leaf comparisons or nested filters, so the tree - * can express arbitrarily deep `from AND (previousApprover AND amount < limit)` shapes. - * - * For this project the operator is constrained to `AND` at runtime, but the type uses - * `ValueOf` so future operators (e.g. `OR`) can slot in without changing - * the contract. + * operator. `left` / `right` may be either leaf comparisons or nested filters */ type ApprovalWorkflowFilter = { - /** Boolean combinator — currently always `AND` in production. */ + /** Boolean combinator */ operator: ValueOf; /** Left-hand child: leaf comparison or nested boolean filter. */ left: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; - /** Right-hand child. Optional so a degenerate single-comparison filter can be represented. */ + /** Right-hand child */ right?: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; }; @@ -54,9 +49,7 @@ type ApprovalWorkflowFilter = { */ type ApprovalWorkflowRule = { /** - * Conditions that must match the report for the rule to fire. Usually an `AND` filter, but a - * rule with a single condition (e.g. the initial-submission rule that only checks `from`) is - * stored as a bare comparison rather than a degenerate `AND` with no `right`. + * Conditions that must match the report for the rule to fire. */ filters: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison; diff --git a/src/types/onyx/Policy.ts b/src/types/onyx/Policy.ts index 6e9d6d6b6903..eace50dd2f88 100644 --- a/src/types/onyx/Policy.ts +++ b/src/types/onyx/Policy.ts @@ -2297,8 +2297,7 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< /** * Approval-workflow rules keyed by ruleID. Each rule routes a report to a `nextReceiver` - * when its `filters` match. Multiple workflows can share the same rule by listing more - * than one submitter in the `from` filter. + * when its `filters` match. */ approvalWorkflows?: Record; }; From 9a1199b38243de524c7bcba5d14ee18dd6fd289b Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 15:11:34 +0200 Subject: [PATCH 10/62] prettier --- .../approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx index acd0328a3761..758325704c3c 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsExpensesFromPage.tsx @@ -23,8 +23,8 @@ import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import {addSMSDomainIfPhoneNumber} from '@libs/PhoneNumber'; import {canEditWorkspaceSettings, getDefaultApprover, getExcludedUsers, getMemberAccountIDsForWorkspace, isPendingDeletePolicy} from '@libs/PolicyUtils'; -import {getRulesSubmitterToFirstApprover} from '@libs/WorkflowUtils'; import type {AvatarSource} from '@libs/UserAvatarUtils'; +import {getRulesSubmitterToFirstApprover} from '@libs/WorkflowUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import MemberRightIcon from '@pages/workspace/MemberRightIcon'; import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading'; From 4b5c3e215714dcc36c3a0ff4c36ceaa850d29d28 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 15:15:30 +0200 Subject: [PATCH 11/62] knip --- src/libs/actions/Workflow.ts | 1 - src/types/onyx/ApprovalWorkflowRules.ts | 2 +- src/types/onyx/Policy.ts | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 747b8680d563..d1b383d54af9 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -601,7 +601,6 @@ export { setApprovalWorkflowMembers, setApprovalWorkflowApprover, setApprovalWorkflow, - setApprovalWorkflowRules, selectApprovalWorkflowForEdit, clearApprovalWorkflowApprover, clearApprovalWorkflowApprovers, diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 0cb640341e88..f6519338d850 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -66,4 +66,4 @@ type ApprovalWorkflowRule = { */ type ApprovalWorkflowRules = Record; -export type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowFilterOperand, ApprovalWorkflowRule, ApprovalWorkflowRules}; +export type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowRule, ApprovalWorkflowRules}; diff --git a/src/types/onyx/Policy.ts b/src/types/onyx/Policy.ts index eace50dd2f88..a6b6995fa5fe 100644 --- a/src/types/onyx/Policy.ts +++ b/src/types/onyx/Policy.ts @@ -5,7 +5,7 @@ import type CONST from '@src/CONST'; import type {Country} from '@src/CONST'; import type {MergeHRProviderSlug} from '@src/CONST/MERGE_HR_PROVIDERS'; import type * as OnyxTypes from '.'; -import type {ApprovalWorkflowRule} from './ApprovalWorkflowRules'; +import type {ApprovalWorkflowRules} from './ApprovalWorkflowRules'; import type * as OnyxCommon from './OnyxCommon'; import type {WorkspaceTravelSettings} from './TravelSettings'; @@ -2299,7 +2299,7 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< * Approval-workflow rules keyed by ruleID. Each rule routes a report to a `nextReceiver` * when its `filters` match. */ - approvalWorkflows?: Record; + approvalWorkflows?: ApprovalWorkflowRules; }; /** The "RuleBot" agent account ID */ From dcfe92cdf9fad0ad91ecfdc7f71bbf6e34e691e3 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 15:56:21 +0200 Subject: [PATCH 12/62] lint --- .../API/parameters/ApprovalWorkflowParams.ts | 2 +- src/libs/API/parameters/index.ts | 2 +- src/libs/WorkflowUtils.ts | 99 +++++++++---------- 3 files changed, 47 insertions(+), 56 deletions(-) diff --git a/src/libs/API/parameters/ApprovalWorkflowParams.ts b/src/libs/API/parameters/ApprovalWorkflowParams.ts index bab03b2bf134..838dd39843c3 100644 --- a/src/libs/API/parameters/ApprovalWorkflowParams.ts +++ b/src/libs/API/parameters/ApprovalWorkflowParams.ts @@ -8,4 +8,4 @@ type SetApprovalWorkflowParams = { rules: string; }; -export type {SetApprovalWorkflowParams}; +export default SetApprovalWorkflowParams; diff --git a/src/libs/API/parameters/index.ts b/src/libs/API/parameters/index.ts index 926f9c2d76dc..44cf21f15d2d 100644 --- a/src/libs/API/parameters/index.ts +++ b/src/libs/API/parameters/index.ts @@ -526,7 +526,7 @@ export type {default as DeleteDomainParams} from './DeleteDomainParams'; export type {default as GetDuplicateTransactionDetailsParams} from './GetDuplicateTransactionDetailsParams'; export type {default as SetPolicyCategoryReceiptsAndItemizedReceiptRequiredParams} from './SetPolicyCategoryReceiptsAndItemizedReceiptRequiredParams'; export type {default as SetPolicyCodingRuleParams} from './SetPolicyCodingRuleParams'; -export type {SetApprovalWorkflowParams} from './ApprovalWorkflowParams'; +export type {default as SetApprovalWorkflowParams} from './ApprovalWorkflowParams'; export type {default as RegisterAuthenticationKeyParams} from './RegisterAuthenticationKeyParams'; export type {default as RevokeMultifactorAuthenticationCredentialsParams} from './RevokeMultifactorAuthenticationCredentialsParams'; export type {default as TroubleshootMultifactorAuthenticationParams} from './TroubleshootMultifactorAuthenticationParams'; diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index c552221dbcd4..cab4237121bd 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -792,7 +792,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva } const hasLimitSplit = !!approver.approvalLimit && approver.approvalLimit > 0 && !!approver.overLimitForwardsTo; - const limit = hasLimitSplit ? (approver.approvalLimit as number) : undefined; + const limit = hasLimitSplit ? approver.approvalLimit! : undefined; const underAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; const overAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; @@ -809,7 +809,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva rules.push({ filters: buildLevelFilters(fromComparison, gate, overAmount), action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.overLimitForwardsTo as string, + nextReceiver: approver.overLimitForwardsTo!, }); } else { rules.push({ @@ -820,15 +820,27 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva } } - previousApproverEmails = hasLimitSplit ? [approver.email, approver.overLimitForwardsTo as string] : [approver.email]; + previousApproverEmails = hasLimitSplit ? [approver.email, approver.overLimitForwardsTo!] : [approver.email]; } return rules; } +/** + * A leaf comparison node — its `left` is a primitive field name (or an array of values), unlike a + * boolean filter whose `left` is another node. + */ +function isComparisonLeaf(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): node is ApprovalWorkflowFilterComparison { + if (!node) { + return false; + } + const nodeLeft = node.left; + return typeof nodeLeft !== 'object' || nodeLeft === null || Array.isArray(nodeLeft); +} + /** True when a comparison node targets the `from` field with an equality operator. */ function isSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): boolean { - return node.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && (node as ApprovalWorkflowFilterComparison).left === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM; + return isComparisonLeaf(node) && node.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && node.left === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM; } /** Walk a filter tree and call `callback` on every submitter filter (the `from` leaf) in it. */ @@ -836,19 +848,15 @@ function forEachSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowF if (!node) { return; } - if (isSubmitterFilter(node)) { - callback(node as ApprovalWorkflowFilterComparison); + if (isComparisonLeaf(node)) { + // A leaf has no children to recurse into; only `from` leaves are reported. + if (isSubmitterFilter(node)) { + callback(node); + } return; } - // Only filter nodes (which always carry a left filter) and AND/OR nodes have children to recurse into. - const leftIsNode = typeof (node as ApprovalWorkflowFilter).left === 'object' && (node as ApprovalWorkflowFilter).left !== null; - if (leftIsNode) { - forEachSubmitterFilter((node as ApprovalWorkflowFilter).left, callback); - } - const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; - if (right && typeof right === 'object') { - forEachSubmitterFilter(right, callback); - } + forEachSubmitterFilter(node.left, callback); + forEachSubmitterFilter(node.right, callback); } /** Extract the union of email values across every `from` leaf in a rule. */ @@ -857,11 +865,11 @@ function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { forEachSubmitterFilter(rule.filters, (filter) => { const right = filter.right; if (Array.isArray(right)) { - right.forEach((email) => { + for (const email of right) { if (typeof email === 'string') { emails.add(email); } - }); + } } else if (typeof right === 'string') { emails.add(right); } @@ -879,19 +887,14 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { if (!node) { return node; } - if (isSubmitterFilter(node)) { - return {operator: node.operator, left: (node as ApprovalWorkflowFilterComparison).left}; - } - const out: Record = {operator: node.operator}; - const left = (node as ApprovalWorkflowFilter).left; - if (left !== undefined) { - out.left = typeof left === 'object' && left !== null ? stripFromValues(left) : left; - } - const right = (node as ApprovalWorkflowFilter).right as unknown; - if (right !== undefined) { - out.right = typeof right === 'object' && right !== null ? stripFromValues(right as ApprovalWorkflowFilter) : right; + if (isComparisonLeaf(node)) { + // Drop the `right` (submitter list) from `from` leaves so only the structure remains. + if (isSubmitterFilter(node)) { + return {operator: node.operator, left: node.left}; + } + return {operator: node.operator, left: node.left, right: node.right}; } - return out; + return {operator: node.operator, left: stripFromValues(node.left), right: stripFromValues(node.right)}; }; return JSON.stringify({ @@ -904,31 +907,29 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { /** Replace the `right` value on every `from` leaf with `newEmails`. */ function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]): ApprovalWorkflowRule { const rewrite = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison => { - if (isSubmitterFilter(node)) { - return {...node, right: [...newEmails]} as ApprovalWorkflowFilterComparison; + if (isComparisonLeaf(node)) { + return isSubmitterFilter(node) ? {...node, right: [...newEmails]} : node; } - const left = (node as ApprovalWorkflowFilter).left; - const right = (node as ApprovalWorkflowFilter).right as ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined; return { ...node, - ...(typeof left === 'object' && left !== null ? {left: rewrite(left)} : {}), - ...(right && typeof right === 'object' ? {right: rewrite(right)} : {}), - } as ApprovalWorkflowFilter; + left: rewrite(node.left), + ...(node.right ? {right: rewrite(node.right)} : {}), + }; }; - return {...rule, filters: rewrite(rule.filters) as ApprovalWorkflowFilter}; + return {...rule, filters: rewrite(rule.filters)}; } /** Merge `emailsToAdd` into `existingEmails`, preserving the order of `existingEmails` and dropping duplicates. */ function mergeEmails(existingEmails: string[], emailsToAdd: string[]): string[] { const seen = new Set(existingEmails); const result = [...existingEmails]; - emailsToAdd.forEach((email) => { + for (const email of emailsToAdd) { if (seen.has(email)) { - return; + continue; } seen.add(email); result.push(email); - }); + } return result; } @@ -1097,7 +1098,7 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st const updatedEmails = mergeEmails(afterRemoval, newMemberEmails); // No effective change to this rule's `from` — skip the round-trip. - if (updatedEmails.length === ruleEmails.length && updatedEmails.every((email, idx) => email === ruleEmails[idx])) { + if (updatedEmails.length === ruleEmails.length && updatedEmails.every((email, idx) => email === ruleEmails.at(idx))) { continue; } @@ -1127,15 +1128,6 @@ function applyApprovalWorkflowRulesDiff(existingRules: Record Date: Mon, 29 Jun 2026 16:04:58 +0200 Subject: [PATCH 13/62] more lint --- src/types/onyx/ApprovalWorkflowRules.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index f6519338d850..339d37e5d82c 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -9,7 +9,7 @@ import type CONST from '@src/CONST'; * - The right operand is the literal value the field is compared against. For email-typed * fields like `from`, the value may be a list of emails to match against. */ -type ApprovalWorkflowFilterOperand = ValueOf | string | number | string[]; +type ApprovalWorkflowFilterOperand = string | number | string[]; /** * A single comparison node: ` `. From 437c9e4a006f86e7038706917fbae007dff759c7 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 16:47:43 +0200 Subject: [PATCH 14/62] more lint --- src/libs/WorkflowUtils.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index cab4237121bd..2ee5b43fd42e 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -791,16 +791,20 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva continue; } - const hasLimitSplit = !!approver.approvalLimit && approver.approvalLimit > 0 && !!approver.overLimitForwardsTo; - const limit = hasLimitSplit ? approver.approvalLimit! : undefined; - const underAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; - const overAmount = limit !== undefined ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limit) : undefined; + // Narrow once: when the approver has a positive limit and an over-limit target, capture both + // (already non-null inside this branch) so the level can route under/over amounts separately. + const limitSplit = + approver.approvalLimit && approver.approvalLimit > 0 && approver.overLimitForwardsTo + ? {limit: approver.approvalLimit, overLimitForwardsTo: approver.overLimitForwardsTo} + : undefined; + const underAmount = limitSplit ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit) : undefined; + const overAmount = limitSplit ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit) : undefined; // One per possible previous approver const gates = previousApproverEmails.length === 0 ? [undefined] : previousApproverEmails.map((email) => buildPreviousApproverComparison(email)); for (const gate of gates) { - if (hasLimitSplit) { + if (limitSplit) { rules.push({ filters: buildLevelFilters(fromComparison, gate, underAmount), action: APPROVAL_WORKFLOW_FORWARD_ACTION, @@ -809,7 +813,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva rules.push({ filters: buildLevelFilters(fromComparison, gate, overAmount), action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.overLimitForwardsTo!, + nextReceiver: limitSplit.overLimitForwardsTo, }); } else { rules.push({ @@ -820,7 +824,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva } } - previousApproverEmails = hasLimitSplit ? [approver.email, approver.overLimitForwardsTo!] : [approver.email]; + previousApproverEmails = limitSplit ? [approver.email, limitSplit.overLimitForwardsTo] : [approver.email]; } return rules; From 3cce08e48deb60286cab79170ee0050c0dabedde Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 18:01:04 +0200 Subject: [PATCH 15/62] lint again --- src/libs/actions/Workflow.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index d1b383d54af9..112929133fb8 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -1,10 +1,10 @@ import lodashDropRightWhile from 'lodash/dropRightWhile'; import type {NullishDeep, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; -import * as API from '@libs/API'; +import {write} from '@libs/API'; import type {CreateWorkspaceApprovalParams, RemoveWorkspaceApprovalParams, SetApprovalWorkflowParams, UpdateWorkspaceApprovalParams} from '@libs/API/parameters'; import {WRITE_COMMANDS} from '@libs/API/types'; -import * as ErrorUtils from '@libs/ErrorUtils'; +import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {getDefaultApprover} from '@libs/PolicyUtils'; import type {ApprovalWorkflowRulesDiff} from '@libs/WorkflowUtils'; import { @@ -100,7 +100,7 @@ function createApprovalWorkflow({approvalWorkflow, policy, addExpenseApprovalsTa ]; const parameters: CreateWorkspaceApprovalParams = {policyID: policy.id, employees: JSON.stringify(Object.values(updatedEmployees))}; - API.write(WRITE_COMMANDS.CREATE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); + write(WRITE_COMMANDS.CREATE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); if ( addExpenseApprovalsTaskReport && @@ -214,7 +214,7 @@ function updateApprovalWorkflow(approvalWorkflow: ApprovalWorkflow, membersToRem employees: JSON.stringify(Object.values(updatedEmployees)), defaultApprover: newDefaultApprover, }; - API.write(WRITE_COMMANDS.UPDATE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); + write(WRITE_COMMANDS.UPDATE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); } function removeApprovalWorkflow(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry) { @@ -273,7 +273,7 @@ function removeApprovalWorkflow(approvalWorkflow: ApprovalWorkflow, policy: Onyx ]; const parameters: RemoveWorkspaceApprovalParams = {policyID: policy.id, employees: JSON.stringify(Object.values(updatedEmployees))}; - API.write(WRITE_COMMANDS.REMOVE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); + write(WRITE_COMMANDS.REMOVE_WORKSPACE_APPROVAL, parameters, {optimisticData, failureData, successData}); } type SetApprovalWorkflowRulesParams = { @@ -336,7 +336,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflow value: { rules: {approvalWorkflows: failureApprovalWorkflows}, pendingFields: {approvalWorkflows: null}, - errorFields: {approvalWorkflows: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage')}, + errorFields: {approvalWorkflows: getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage')}, }, }, ]; @@ -346,7 +346,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflow rules: JSON.stringify(rulesDiff), }; - API.write(WRITE_COMMANDS.SET_APPROVAL_WORKFLOW, parameters, {optimisticData, successData, failureData}); + write(WRITE_COMMANDS.SET_APPROVAL_WORKFLOW, parameters, {optimisticData, successData, failureData}); } /** From 3fa8579e736e003ab46d6f880cd908827d67a783 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 18:17:32 +0200 Subject: [PATCH 16/62] Add tests --- tests/actions/WorkflowTest.ts | 155 ++++++++++++++++- tests/unit/WorkflowUtilsTest.ts | 294 ++++++++++++++++++++++++++++++++ 2 files changed, 448 insertions(+), 1 deletion(-) diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index ea960b0aee8c..3e8f93edf4df 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -4,7 +4,16 @@ import CONST from '@src/CONST'; import OnyxUpdateManager from '@src/libs/actions/OnyxUpdateManager'; import {generatePolicyID} from '@src/libs/actions/Policy/Policy'; import * as Task from '@src/libs/actions/Task'; -import {clearApprovalWorkflowApprover, createApprovalWorkflow, removeApprovalWorkflow, setApprovalWorkflowApprover, updateApprovalWorkflow} from '@src/libs/actions/Workflow'; +import { + clearApprovalWorkflowApprover, + createApprovalWorkflow, + createApprovalWorkflowRules, + removeApprovalWorkflow, + removeApprovalWorkflowRules, + setApprovalWorkflowApprover, + updateApprovalWorkflow, + updateApprovalWorkflowRules, +} from '@src/libs/actions/Workflow'; import {calculateApprovers} from '@src/libs/WorkflowUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ApprovalWorkflowOnyx, PersonalDetailsList, Policy, Policy as PolicyType, Report} from '@src/types/onyx'; @@ -837,4 +846,148 @@ describe('actions/Workflow', () => { await waitForBatchedUpdates(); }); }); + + describe('createApprovalWorkflowRules', () => { + it('writes a new rule-based approval workflow to the policy rules', async () => { + mockFetch.pause(); + + const policyID = '123456789'; + const policy = { + id: policyID, + name: 'Test Workspace', + role: 'admin', + type: 'corporate', + owner: ownerEmail, + rules: {}, + } as unknown as Policy; + + const approvalWorkflow = { + members: [{email: employee1Email, displayName: employee1Email}], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + availableMembers: [], + usedApproverEmails: [], + isDefault: false, + action: 'create', + originalApprovers: [], + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined}); + await waitForBatchedUpdates(); + + const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); + const rules = Object.values(updatedPolicy?.rules?.approvalWorkflows ?? {}); + expect(rules).toHaveLength(1); + expect(rules.at(0)?.nextReceiver).toBe(ownerEmail); + expect(rules.at(0)?.filters).toEqual({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}); + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); + }); + + describe('updateApprovalWorkflowRules', () => { + it('replaces the approver chain when the workflow approver changes', async () => { + mockFetch.pause(); + + const policyID = '123456789'; + const policy = { + id: policyID, + name: 'Test Workspace', + role: 'admin', + type: 'corporate', + owner: ownerEmail, + rules: { + approvalWorkflows: { + rule1: { + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, + action: 'forward', + nextReceiver: ownerEmail, + }, + }, + }, + } as unknown as Policy; + + const initialApprovalWorkflow = { + members: [{email: employee1Email, displayName: employee1Email}], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + availableMembers: [], + usedApproverEmails: [], + isDefault: false, + action: 'update', + originalApprovers: [], + }; + const approvalWorkflow = { + ...initialApprovalWorkflow, + approvers: [{email: employee2Email, displayName: employee2Email, isCircularReference: false}], + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}); + await waitForBatchedUpdates(); + + const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); + const rules = Object.values(updatedPolicy?.rules?.approvalWorkflows ?? {}); + // The old rule (forwarding to the owner) is removed and a new rule forwarding to employee2 is created. + expect(updatedPolicy?.rules?.approvalWorkflows?.rule1).toBeUndefined(); + expect(rules).toHaveLength(1); + expect(rules.at(0)?.nextReceiver).toBe(employee2Email); + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); + }); + + describe('removeApprovalWorkflowRules', () => { + it('removes the rules that belong only to the workflow members', async () => { + mockFetch.pause(); + + const policyID = '123456789'; + const policy = { + id: policyID, + name: 'Test Workspace', + role: 'admin', + type: 'corporate', + owner: ownerEmail, + rules: { + approvalWorkflows: { + rule1: { + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, + action: 'forward', + nextReceiver: ownerEmail, + }, + }, + }, + } as unknown as Policy; + + const approvalWorkflow = { + members: [{email: employee1Email, displayName: employee1Email}], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + availableMembers: [], + usedApproverEmails: [], + isDefault: false, + action: 'remove', + originalApprovers: [], + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + removeApprovalWorkflowRules(approvalWorkflow, policy); + await waitForBatchedUpdates(); + + const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); + expect(updatedPolicy?.rules?.approvalWorkflows?.rule1).toBeUndefined(); + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); + }); }); diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 132ac40c4683..135a7a7ce61e 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -3,18 +3,28 @@ import {convertToDisplayString} from '@libs/CurrencyUtils'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; import { + applyApprovalWorkflowRulesDiff, + buildApprovalWorkflowRules, calculateApprovers, + convertApprovalWorkflowRulesToWorkflows, convertApprovalWorkflowToPolicyEmployees, convertPolicyEmployeesToApprovalWorkflows, getApprovalLimitDescription, + getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, getOverLimitForwardsToDisplayName, + getRulesSubmitterToFirstApprover, mergeWorkflowMembersWithAvailableMembers, + reconcileApprovalWorkflowRulesForCreate, + reconcileApprovalWorkflowRulesForEdit, + reconcileApprovalWorkflowRulesForMembersChange, + reconcileApprovalWorkflowRulesForRemove, updateWorkflowDataOnApproverRemoval, } from '@src/libs/WorkflowUtils'; import type {Policy} from '@src/types/onyx'; import type {Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; +import type {ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; import type {BankAccountList} from '@src/types/onyx/BankAccount'; import type {PersonalDetailsList} from '@src/types/onyx/PersonalDetails'; import type {Connections} from '@src/types/onyx/Policy'; @@ -1627,4 +1637,288 @@ describe('WorkflowUtils', () => { expect(result).toEqual([openBusinessBankAccount, secondMatchingAccount]); }); }); + + describe('getEligibleExistingBusinessBankAccounts', () => { + const openBusinessBankAccount = { + bankCurrency: 'USD', + accountData: { + state: CONST.BANK_ACCOUNT.STATE.OPEN, + type: CONST.BANK_ACCOUNT.TYPE.BUSINESS, + }, + }; + + it('should return an empty array when the bank account list is undefined', () => { + expect(getEligibleExistingBusinessBankAccounts(undefined, 'USD')).toEqual([]); + }); + + it('should return an empty array when the policy currency is undefined', () => { + expect(getEligibleExistingBusinessBankAccounts({'1': openBusinessBankAccount}, undefined)).toEqual([]); + }); + + it('should return open business accounts matching the policy currency', () => { + expect(getEligibleExistingBusinessBankAccounts({'1': openBusinessBankAccount}, 'USD')).toEqual([openBusinessBankAccount]); + }); + + it('should filter out accounts with a non-matching currency', () => { + const eurAccount = {...openBusinessBankAccount, bankCurrency: 'EUR'}; + expect(getEligibleExistingBusinessBankAccounts({'1': eurAccount}, 'USD')).toEqual([]); + }); + + it('should filter out non-business accounts', () => { + const personalAccount = {...openBusinessBankAccount, accountData: {...openBusinessBankAccount.accountData, type: CONST.BANK_ACCOUNT.TYPE.PERSONAL}}; + expect(getEligibleExistingBusinessBankAccounts({'1': personalAccount}, 'USD')).toEqual([]); + }); + + it('should exclude partially set up accounts by default but include them when requested', () => { + const setupAccount = {...openBusinessBankAccount, accountData: {...openBusinessBankAccount.accountData, state: CONST.BANK_ACCOUNT.STATE.SETUP}}; + + expect(getEligibleExistingBusinessBankAccounts({'1': setupAccount}, 'USD')).toEqual([]); + expect(getEligibleExistingBusinessBankAccounts({'1': setupAccount}, 'USD', true)).toEqual([setupAccount]); + }); + }); + + describe('rule-based approval workflows', () => { + const FORWARD_ACTION = 'forward' as const; + const buildFromFilter = (emails: string[]) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: emails}); + const buildPreviousApproverFilter = (email: string) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER, right: email}); + const keyRules = (rules: ApprovalWorkflowRule[]): Record => Object.fromEntries(rules.map((rule, index) => [`rule${index}`, rule])); + + describe('buildApprovalWorkflowRules', () => { + it('Should return an empty list when there are no members', () => { + expect(buildApprovalWorkflowRules(buildWorkflow([], [1]))).toEqual([]); + }); + + it('Should return an empty list when there are no approvers', () => { + expect(buildApprovalWorkflowRules(buildWorkflow([2], []))).toEqual([]); + }); + + it('Should build a single `from` rule for a one-approver workflow', () => { + expect(buildApprovalWorkflowRules(buildWorkflow([2], [1]))).toEqual([{filters: buildFromFilter(['2@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}]); + }); + + it('Should chain approvers with `previousApprover` gates', () => { + expect(buildApprovalWorkflowRules(buildWorkflow([3], [1, 2]))).toEqual([ + {filters: buildFromFilter(['3@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + { + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['3@example.com']), right: buildPreviousApproverFilter('1@example.com')}, + action: FORWARD_ACTION, + nextReceiver: '2@example.com', + }, + ]); + }); + + it('Should split a level into under/over amount rules when the approver has a limit split', () => { + const workflow: ApprovalWorkflow = { + members: [buildMember(2)], + approvers: [buildApprover(1, {approvalLimit: 50000, overLimitForwardsTo: '3@example.com'})], + isDefault: false, + }; + const underAmountFilter = {operator: CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; + const overAmountFilter = {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; + + expect(buildApprovalWorkflowRules(workflow)).toEqual([ + {filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: underAmountFilter}, action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + {filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: overAmountFilter}, action: FORWARD_ACTION, nextReceiver: '3@example.com'}, + ]); + }); + + it('Should ignore a limit split when the limit is not positive', () => { + const workflow: ApprovalWorkflow = { + members: [buildMember(2)], + approvers: [buildApprover(1, {approvalLimit: 0, overLimitForwardsTo: '3@example.com'})], + isDefault: false, + }; + + expect(buildApprovalWorkflowRules(workflow)).toEqual([{filters: buildFromFilter(['2@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}]); + }); + }); + + describe('applyApprovalWorkflowRulesDiff', () => { + const ruleA: ApprovalWorkflowRule = {filters: buildFromFilter(['2@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}; + const ruleB: ApprovalWorkflowRule = {filters: buildFromFilter(['3@example.com']), action: FORWARD_ACTION, nextReceiver: '4@example.com'}; + + it('Should upsert non-null entries and delete null entries', () => { + expect(applyApprovalWorkflowRulesDiff({a: ruleA}, {a: null, b: ruleB})).toEqual({b: ruleB}); + }); + + it('Should not mutate the input map', () => { + const existingRules = {a: ruleA}; + applyApprovalWorkflowRulesDiff(existingRules, {a: null}); + expect(existingRules).toEqual({a: ruleA}); + }); + }); + + describe('reconcileApprovalWorkflowRulesForCreate', () => { + it('Should create fresh rules when nothing matches', () => { + const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); + const diff = reconcileApprovalWorkflowRulesForCreate(newRules, ['10@example.com'], {existingRules: {}}); + + expect(Object.values(diff)).toEqual(newRules); + }); + + it('Should merge members into a structurally identical existing rule', () => { + const existingRules: Record = { + existing1: {filters: buildFromFilter(['20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); + const diff = reconcileApprovalWorkflowRulesForCreate(newRules, ['10@example.com'], {existingRules}); + + expect(diff).toEqual({existing1: {filters: buildFromFilter(['20@example.com', '10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}}); + }); + }); + + describe('reconcileApprovalWorkflowRulesForEdit', () => { + it('Should drop the old rule and create the new chain when the approver changes', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [2])); + const diff = reconcileApprovalWorkflowRulesForEdit(newRules, ['10@example.com'], {existingRules}); + + expect(diff.r1).toBeNull(); + const createdRules = Object.entries(diff) + .filter(([ruleID]) => ruleID !== 'r1') + .map(([, rule]) => rule); + expect(createdRules).toEqual(newRules); + }); + + it('Should leave a structurally identical rule untouched', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); + const diff = reconcileApprovalWorkflowRulesForEdit(newRules, ['10@example.com'], {existingRules}); + + expect(diff).toEqual({}); + }); + }); + + describe('reconcileApprovalWorkflowRulesForRemove', () => { + it('Should remove a rule that only contains the workflow members', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + + expect(reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules})).toEqual({r1: null}); + }); + + it('Should strip only the workflow members from a shared rule', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com', '20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + + expect(reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules})).toEqual({ + r1: {filters: buildFromFilter(['20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }); + }); + + it('Should ignore rules that do not contain the members', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['30@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + + expect(reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules})).toEqual({}); + }); + }); + + describe('reconcileApprovalWorkflowRulesForMembersChange', () => { + it('Should add new members and drop removed ones from matching rules', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com', '20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + const diff = reconcileApprovalWorkflowRulesForMembersChange(['10@example.com', '20@example.com'], ['20@example.com', '30@example.com'], {existingRules}); + + expect(diff).toEqual({r1: {filters: buildFromFilter(['20@example.com', '30@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}}); + }); + + it('Should skip rules with no net change to the submitter list', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + + expect(reconcileApprovalWorkflowRulesForMembersChange(['10@example.com'], ['10@example.com'], {existingRules})).toEqual({}); + }); + + it('Should remove a rule when all of its members are dropped', () => { + const existingRules: Record = { + r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, + }; + + expect(reconcileApprovalWorkflowRulesForMembersChange(['10@example.com'], [], {existingRules})).toEqual({r1: null}); + }); + }); + + describe('getRulesSubmitterToFirstApprover', () => { + it('Should map each submitter to the first approver in their chain', () => { + const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); + + expect(getRulesSubmitterToFirstApprover(rules)).toEqual({'5@example.com': '1@example.com'}); + }); + }); + + describe('convertApprovalWorkflowRulesToWorkflows', () => { + const createPolicyWithRules = (employees: PolicyEmployeeList, rules: Record, defaultApprover: string) => + ({ + id: 'test-policy', + name: 'Test Policy', + role: 'admin' as const, + type: 'team' as const, + owner: 'owner@example.com', + outputCurrency: 'USD', + isPolicyExpenseChatEnabled: true, + employeeList: employees, + approver: defaultApprover, + rules: {approvalWorkflows: rules}, + }) as Policy; + + it('Should reconstruct a multi-approver chain from rules', () => { + const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); + const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; + const policy = createPolicyWithRules(employees, rules, '1@example.com'); + + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare}); + + expect(approvalWorkflows).toHaveLength(1); + const workflow = approvalWorkflows.at(0); + expect(workflow?.isDefault).toBe(true); + expect(workflow?.members.map((member) => member.email)).toEqual(['5@example.com']); + expect(workflow?.approvers.map((approver) => approver.email)).toEqual(['1@example.com', '2@example.com']); + expect(workflow?.approvers.at(0)?.forwardsTo).toBe('2@example.com'); + expect(workflow?.approvers.at(1)?.forwardsTo).toBeUndefined(); + }); + + it('Should reconstruct an approver limit split from rules', () => { + const workflow: ApprovalWorkflow = { + members: [buildMember(5)], + approvers: [buildApprover(1, {approvalLimit: 50000, overLimitForwardsTo: '3@example.com'})], + isDefault: false, + }; + const rules = keyRules(buildApprovalWorkflowRules(workflow)); + const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; + const policy = createPolicyWithRules(employees, rules, '1@example.com'); + + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare}); + + const firstApprover = approvalWorkflows.at(0)?.approvers.at(0); + expect(firstApprover?.email).toBe('1@example.com'); + expect(firstApprover?.approvalLimit).toBe(50000); + expect(firstApprover?.overLimitForwardsTo).toBe('3@example.com'); + }); + + it('Should round-trip a workflow through rules and back', () => { + const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); + const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; + const policy = createPolicyWithRules(employees, rules, '1@example.com'); + + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare}); + + // Rebuilding rules from the reconstructed workflow should reproduce the original rule set. + const workflow = approvalWorkflows.at(0); + expect(workflow).toBeDefined(); + if (workflow) { + expect(buildApprovalWorkflowRules(workflow)).toEqual(Object.values(rules)); + } + }); + }); + }); }); From 53cbedf2759e4be48c4ba141f607c33fa54bf79b Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 21:21:05 +0200 Subject: [PATCH 17/62] prettier --- tests/unit/WorkflowUtilsTest.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 135a7a7ce61e..0b3c3912e55a 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1717,8 +1717,16 @@ describe('WorkflowUtils', () => { const overAmountFilter = {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; expect(buildApprovalWorkflowRules(workflow)).toEqual([ - {filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: underAmountFilter}, action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - {filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: overAmountFilter}, action: FORWARD_ACTION, nextReceiver: '3@example.com'}, + { + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: underAmountFilter}, + action: FORWARD_ACTION, + nextReceiver: '1@example.com', + }, + { + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: overAmountFilter}, + action: FORWARD_ACTION, + nextReceiver: '3@example.com', + }, ]); }); From a05bc37eca1405bf0598a3042e02ac7d6393322d Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 29 Jun 2026 21:30:49 +0200 Subject: [PATCH 18/62] type --- tests/unit/WorkflowUtilsTest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 0b3c3912e55a..d43e4b37e3e0 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1641,6 +1641,7 @@ describe('WorkflowUtils', () => { describe('getEligibleExistingBusinessBankAccounts', () => { const openBusinessBankAccount = { bankCurrency: 'USD', + bankCountry: 'US', accountData: { state: CONST.BANK_ACCOUNT.STATE.OPEN, type: CONST.BANK_ACCOUNT.TYPE.BUSINESS, From 72cdcaebe22acc2520e31b6cb67e01cb4c6402e5 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 30 Jun 2026 00:01:45 +0200 Subject: [PATCH 19/62] types --- tests/actions/WorkflowTest.ts | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 3e8f93edf4df..3154a3903e9c 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -852,14 +852,12 @@ describe('actions/Workflow', () => { mockFetch.pause(); const policyID = '123456789'; - const policy = { + const policy: Policy = { + ...createRandomPolicy(1), id: policyID, - name: 'Test Workspace', - role: 'admin', - type: 'corporate', owner: ownerEmail, rules: {}, - } as unknown as Policy; + }; const approvalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], @@ -894,11 +892,9 @@ describe('actions/Workflow', () => { mockFetch.pause(); const policyID = '123456789'; - const policy = { + const policy: Policy = { + ...createRandomPolicy(1), id: policyID, - name: 'Test Workspace', - role: 'admin', - type: 'corporate', owner: ownerEmail, rules: { approvalWorkflows: { @@ -909,7 +905,7 @@ describe('actions/Workflow', () => { }, }, }, - } as unknown as Policy; + }; const initialApprovalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], @@ -949,11 +945,9 @@ describe('actions/Workflow', () => { mockFetch.pause(); const policyID = '123456789'; - const policy = { + const policy: Policy = { + ...createRandomPolicy(1), id: policyID, - name: 'Test Workspace', - role: 'admin', - type: 'corporate', owner: ownerEmail, rules: { approvalWorkflows: { @@ -964,7 +958,7 @@ describe('actions/Workflow', () => { }, }, }, - } as unknown as Policy; + }; const approvalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], From 42a1bbc3380900dc71576b8b41e99f1089d9b150 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 14 Jul 2026 13:00:43 +0200 Subject: [PATCH 20/62] handle new rules correctly --- src/CONST/index.ts | 19 +- src/ONYXKEYS.ts | 4 + src/libs/WorkflowUtils.ts | 396 ++++++++++++------ src/libs/actions/Policy/Policy.ts | 25 +- src/libs/actions/Workflow.ts | 112 ++--- .../workflows/WorkspaceWorkflowsPage.tsx | 12 +- ...paceWorkflowsApprovalsExpensesFromPage.tsx | 10 +- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 4 +- src/types/onyx/ApprovalWorkflowRules.ts | 98 +++-- src/types/onyx/Policy.ts | 9 +- src/types/onyx/index.ts | 4 + tests/actions/WorkflowTest.ts | 120 ++++-- tests/unit/WorkflowUtilsTest.ts | 142 +++---- 13 files changed, 609 insertions(+), 346 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index e38934eb4277..e2d90540fe33 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -7202,7 +7202,6 @@ const CONST = { IS: 'is', REPORT_FIELD: 'reportField', EXPORTED_TO: 'exportedTo', - PREVIOUS_APPROVER: 'previousApprover', }, REPORT_FIELD: { // All report fields start with this, so use this to check if a search key is a report field @@ -7800,6 +7799,24 @@ const CONST = { }, }, + /** Vocabulary for the AST-based approval-workflow rules stored in the `rules` table / `ONYXKEYS.COLLECTION.RULE`. */ + APPROVAL_WORKFLOW_RULE: { + /** The kind of entity a rule is scoped to. Currently only workspace policies. */ + SCOPE: { + POLICY: 'policy', + }, + /** The report lifecycle event that fires a rule. */ + TRIGGER: { + REPORT_SUBMIT: 'ReportSubmit', + REPORT_APPROVE: 'ReportApprove', + }, + /** The action taken when a rule matches. */ + ACTION: { + FORWARD_TO: 'ForwardTo', + APPROVE_REPORT: 'ApproveReport', + }, + }, + BOOT_SPLASH_STATE: { VISIBLE: 'visible', READY_TO_BE_HIDDEN: 'readyToBeHidden', diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 4949274983be..e2fdd4906928 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -814,6 +814,9 @@ const ONYXKEYS = { POLICY_HAS_CONNECTIONS_DATA_BEEN_FETCHED: 'policyHasConnectionsDataBeenFetched_', POLICY_CONNECTION_SYNC_PROGRESS: 'policyConnectionSyncProgress_', POLICY_MERGE_HR_INITIAL_SYNC_MODAL_SHOWN: 'policyMergeHRInitialSyncModalShown_', + // AST rules keyed by ruleID (`rules_`). Mirrors a row of the server `rules` table. + // Currently holds approval-workflow rules; intended for all AST rules in the future. + RULE: 'rules_', WORKSPACE_INVITE_MEMBERS_DRAFT: 'workspaceInviteMembersDraft_', WORKSPACE_INVITE_MESSAGE_DRAFT: 'workspaceInviteMessageDraft_', WORKSPACE_INVITE_ROLE_DRAFT: 'workspaceInviteRoleDraft_', @@ -1389,6 +1392,7 @@ type OnyxCollectionValuesMapping = { [ONYXKEYS.COLLECTION.EXPORT_DOWNLOAD]: OnyxTypes.ExportDownload; [ONYXKEYS.COLLECTION.POLICY]: OnyxTypes.Policy; [ONYXKEYS.COLLECTION.POLICY_DRAFTS]: OnyxTypes.Policy; + [ONYXKEYS.COLLECTION.RULE]: OnyxTypes.Rule; [ONYXKEYS.COLLECTION.POLICY_CATEGORIES]: OnyxTypes.PolicyCategories; [ONYXKEYS.COLLECTION.POLICY_CATEGORIES_DRAFT]: OnyxTypes.PolicyCategories; [ONYXKEYS.COLLECTION.POLICY_TAGS]: OnyxTypes.PolicyTagLists; diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index ba4fb49631bc..d964a6d4cb6d 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -3,17 +3,26 @@ import type {LocaleContextProps} from '@components/LocaleContextProvider'; import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; import type {BankAccountList} from '@src/types/onyx'; import type {ApprovalWorkflowOnyx, Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; -import type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; +import type { + ApprovalWorkflowAction, + ApprovalWorkflowActions, + ApprovalWorkflowFilter, + ApprovalWorkflowFilterComparison, + ApprovalWorkflowRule, + ApprovalWorkflowTriggers, +} from '@src/types/onyx/ApprovalWorkflowRules'; import type {PersonalDetailsList} from '@src/types/onyx/PersonalDetails'; import type PersonalDetails from '@src/types/onyx/PersonalDetails'; import type Policy from '@src/types/onyx/Policy'; import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; import type {PolicyEmployeeList} from '@src/types/onyx/PolicyEmployee'; +import type Rule from '@src/types/onyx/Rule'; -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import {Str} from 'expensify-common'; @@ -124,6 +133,12 @@ type PolicyConversionParams = { /** Current user's login email, used to determine if Expensify team members should be shown */ currentUserLogin?: string; + + /** + * The policy's approval-workflow rules keyed by ruleID, read from the `ONYXKEYS.COLLECTION.RULE` + * collection (see `getApprovalWorkflowRulesForPolicy`). Only consumed by the rules-based converter. + */ + rules?: Record; }; type PolicyConversionResult = { @@ -723,14 +738,13 @@ function mergeWorkflowMembersWithAvailableMembers(workflowMembers: Member[], all return [...workflowMembers, ...additionalMembers]; } -// These helpers translate the in-app `ApprovalWorkflow` model into the rule -// format the backend stores under `Policy.rules.approvalWorkflows`, and -// handle any changes -const APPROVAL_WORKFLOW_FORWARD_ACTION = 'forward' as const; +// These helpers translate the in-app `ApprovalWorkflow` model into the AST rule +// format the backend stores in the `rules` table (mirrored in `ONYXKEYS.COLLECTION.RULE`), +// and handle any changes. type ApprovalWorkflowRulesDiff = Record; -/** Build a filter: ` `. */ +/** Build a comparison filter: ` `. */ function buildComparison( operator: ValueOf, left: ApprovalWorkflowFilterComparison['left'], @@ -739,41 +753,54 @@ function buildComparison( return {operator, left, right}; } -/** Build the `from in [emails]` filter used by every approval-workflow rule. */ +/** Combine two filter nodes with a boolean `AND`. */ +function buildAnd(left: ApprovalWorkflowFilter['left'], right: ApprovalWorkflowFilter['right']): ApprovalWorkflowFilter { + return {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left, right}; +} + +/** Build the `from = [emails]` filter used by every approval-workflow rule. Kept at the top-level left of the tree. */ function buildSubmitterFilter(memberEmails: string[]): ApprovalWorkflowFilterComparison { return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, [...memberEmails]); } -/** Build the `previousApprover = email` filter used by all non-initial rules. */ -function buildPreviousApproverComparison(email: string): ApprovalWorkflowFilterComparison { - return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER, email); +/** Build the `to = email` filter that matches the approver who just approved the report. */ +function buildToComparison(email: string): ApprovalWorkflowFilterComparison { + return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, email); } -/** - * Assemble the filter tree for a single rule from its parts. The `from` comparison is always - * present; the `previousApprover` gate and `amount` comparison are optional. - */ -function buildLevelFilters( - fromComparison: ApprovalWorkflowFilterComparison, - previousApproverComparison: ApprovalWorkflowFilterComparison | undefined, - amountComparison: ApprovalWorkflowFilterComparison | undefined, -): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison { - let right: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter | undefined; - if (previousApproverComparison && amountComparison) { - right = {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: previousApproverComparison, right: amountComparison}; - } else { - right = previousApproverComparison ?? amountComparison; - } +/** A rule that fires when a report is submitted. */ +function buildSubmitTriggers(): ApprovalWorkflowTriggers { + return {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}; +} - if (!right) { - return fromComparison; - } +/** A rule that fires when a report is approved. */ +function buildApproveTriggers(): ApprovalWorkflowTriggers { + return {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}; +} - return {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: fromComparison, right}; +/** Forward the report to `approver`. */ +function buildForwardActions(approver: string): ApprovalWorkflowActions { + return {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}}; +} + +/** Approve (finalize) the report. */ +function buildApproveActions(): ApprovalWorkflowActions { + return {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}; } /** - * Build the `rules.approvalWorkflows` rule chain for a single `ApprovalWorkflow`. + * Build the AST rule chain for a single `ApprovalWorkflow` (members + ordered approvers). + * + * For approvers `[A0, A1, …, A_{n-1}]` and members `M` this produces: + * - a `ReportSubmit` rule: `from ∈ M` → forward to `A0`. + * - for each approver `A_i`, a `ReportApprove` rule gated on `to == A_i` (the approver who just + * approved) describing the next hop: + * - normally forward to `A_{i+1}`, or approve the report if `A_i` is the last approver. + * - if `A_i` has a positive `approvalLimit` and an `overLimitForwardsTo`, the hop splits: + * under the limit → the normal hop above; at/over the limit → forward to `overLimitForwardsTo`, + * who then finalizes the report (a terminal `ApproveReport` rule for `to == overLimitForwardsTo`). + * + * The `from` filter is always the top-level left of the tree so it can be checked cheaply. */ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): ApprovalWorkflowRule[] { const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); @@ -783,56 +810,77 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva return []; } + const firstApproverEmail = approvers.at(0)?.email; + if (!firstApproverEmail) { + return []; + } + const fromComparison = buildSubmitterFilter(memberEmails); const rules: ApprovalWorkflowRule[] = []; - // The approvers that could have approved at the PREVIOUS level and forwarded here. An empty list - // means "no previous approver" - let previousApproverEmails: string[] = []; + // On submission, route the report to the first approver. + rules.push({ + triggers: buildSubmitTriggers(), + filters: fromComparison, + actions: buildForwardActions(firstApproverEmail), + }); + // For each approver, describe what happens after THEY approve (gated on `to == approver`). for (let i = 0; i < approvers.length; i++) { const approver = approvers.at(i); - if (!approver) { + if (!approver?.email) { continue; } - // Narrow once: when the approver has a positive limit and an over-limit target, capture both - // (already non-null inside this branch) so the level can route under/over amounts separately. + const nextApproverEmail = approvers.at(i + 1)?.email; + const toComparison = buildToComparison(approver.email); + const limitSplit = approver.approvalLimit && approver.approvalLimit > 0 && approver.overLimitForwardsTo ? {limit: approver.approvalLimit, overLimitForwardsTo: approver.overLimitForwardsTo} : undefined; - const underAmount = limitSplit ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit) : undefined; - const overAmount = limitSplit ? buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit) : undefined; - - // One per possible previous approver - const gates = previousApproverEmails.length === 0 ? [undefined] : previousApproverEmails.map((email) => buildPreviousApproverComparison(email)); - - for (const gate of gates) { - if (limitSplit) { - rules.push({ - filters: buildLevelFilters(fromComparison, gate, underAmount), - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.email, - }); - rules.push({ - filters: buildLevelFilters(fromComparison, gate, overAmount), - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: limitSplit.overLimitForwardsTo, - }); - } else { - rules.push({ - filters: buildLevelFilters(fromComparison, gate, undefined), - action: APPROVAL_WORKFLOW_FORWARD_ACTION, - nextReceiver: approver.email, - }); - } - } - previousApproverEmails = limitSplit ? [approver.email, limitSplit.overLimitForwardsTo] : [approver.email]; + if (limitSplit) { + const underAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit); + const overAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit); + + // Under the limit: continue the chain, or approve if this is the last approver. + rules.push({ + triggers: buildApproveTriggers(), + filters: buildAnd(fromComparison, buildAnd(toComparison, underAmount)), + actions: nextApproverEmail ? buildForwardActions(nextApproverEmail) : buildApproveActions(), + }); + // At/over the limit: escalate to the over-limit approver. + rules.push({ + triggers: buildApproveTriggers(), + filters: buildAnd(fromComparison, buildAnd(toComparison, overAmount)), + actions: buildForwardActions(limitSplit.overLimitForwardsTo), + }); + // The over-limit approver finalizes the report. + rules.push({ + triggers: buildApproveTriggers(), + filters: buildAnd(fromComparison, buildToComparison(limitSplit.overLimitForwardsTo)), + actions: buildApproveActions(), + }); + } else { + rules.push({ + triggers: buildApproveTriggers(), + filters: buildAnd(fromComparison, toComparison), + actions: nextApproverEmail ? buildForwardActions(nextApproverEmail) : buildApproveActions(), + }); + } } - return rules; + // Different approvers may share an `overLimitForwardsTo`, which would emit identical terminal rules. + const seen = new Set(); + return rules.filter((rule) => { + const fingerprint = JSON.stringify(rule); + if (seen.has(fingerprint)) { + return false; + } + seen.add(fingerprint); + return true; + }); } /** @@ -907,9 +955,9 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { }; return JSON.stringify({ + triggers: rule.triggers, filters: stripFromValues(rule.filters), - action: rule.action, - nextReceiver: rule.nextReceiver, + actions: rule.actions, }); } @@ -922,7 +970,7 @@ function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]) return { ...node, left: rewrite(node.left), - ...(node.right ? {right: rewrite(node.right)} : {}), + right: rewrite(node.right), }; }; return {...rule, filters: rewrite(rule.filters)}; @@ -949,7 +997,7 @@ function removeEmails(existingEmails: string[], emailsToRemove: string[]): strin } type ReconcileContext = { - /** The existing `Policy.rules.approvalWorkflows` snapshot, defaulting to `{}`. */ + /** The policy's existing approval-workflow rules (`ruleID -> rule body`), defaulting to `{}`. */ existingRules: Record; }; @@ -1152,71 +1200,112 @@ function findComparisonByLeft(node: ApprovalWorkflowFilter | ApprovalWorkflowFil return findComparisonByLeft(node.right, leftKey); } -/** The approver a level routes the report INTO, plus that approver's own limit split (if any). */ -type ApprovalWorkflowLevelInfo = { - /** The approver the level routes to. */ - email: string; - /** This approver's own approval limit, from the level's amount split. */ +/** The triggers of a rule as a flat list. */ +function getRuleTriggers(rule: ApprovalWorkflowRule): Array> { + return Object.values(rule.triggers ?? {}); +} + +/** The actions of a rule as a flat list. */ +function getRuleActions(rule: ApprovalWorkflowRule): ApprovalWorkflowAction[] { + return Object.values(rule.actions ?? {}); +} + +/** True when the rule fires on report submission. */ +function isSubmitRule(rule: ApprovalWorkflowRule): boolean { + return getRuleTriggers(rule).includes(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT); +} + +/** True when the rule approves (finalizes) the report. */ +function isApproveReportRule(rule: ApprovalWorkflowRule): boolean { + return getRuleActions(rule).some((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT); +} + +/** The approver a `ForwardTo` rule routes to, if any. */ +function getForwardApprover(rule: ApprovalWorkflowRule): string | undefined { + return getRuleActions(rule).find((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO)?.approver; +} + +/** + * Resolve the first approver a submitter's report is routed to on submission — the `ForwardTo` + * target of the submitter's `ReportSubmit` rule. Falls back to `employeeList.submitsTo` for + * pre-beta chains that haven't been re-saved as rules yet. + */ +function resolveFirstApprover(submitter: string, rules: Record, employees: PolicyEmployeeList): string | undefined { + for (const rule of Object.values(rules)) { + if (!isSubmitRule(rule) || !extractSubmitterEmails(rule).includes(submitter)) { + continue; + } + const approver = getForwardApprover(rule); + if (approver) { + return approver; + } + } + return employees[submitter]?.submitsTo; +} + +/** What happens after `currentApprover` approves a report from `submitter`. */ +type AfterApproveInfo = { + /** The next approver in the chain, from the normal / under-limit `ForwardTo`. `undefined` means the report is approved (terminal). */ + nextEmail?: string; + /** `currentApprover`'s own approval limit, present only when there is an over-limit split. */ approvalLimit?: number; - /** This approver's own over-limit target, from the level's amount split. */ + /** `currentApprover`'s own over-limit target, present only when there is an over-limit split. */ overLimitForwardsTo?: string; }; /** - * Resolve the level routed into by the rules by `previousApproverEmail` + * Resolve what the rules say happens after `currentApprover` approves a report from `submitter`, by + * inspecting every rule gated on `to == currentApprover`. Returns `undefined` when no rule covers + * this approver (so callers can fall back to `employeeList`). */ -function resolveLevelFromRules(submitter: string, previousApproverEmail: string | undefined, rules: Record): ApprovalWorkflowLevelInfo | undefined { - let underLimitRule: ApprovalWorkflowRule | undefined; - let overLimitRule: ApprovalWorkflowRule | undefined; - let normalRule: ApprovalWorkflowRule | undefined; +function resolveAfterApprove(submitter: string, currentApprover: string, rules: Record): AfterApproveInfo | undefined { + let hasNormalBranch = false; + let normalIsTerminal = false; + let normalNextEmail: string | undefined; + let overLimitForwardsTo: string | undefined; let approvalLimit: number | undefined; for (const rule of Object.values(rules)) { if (!extractSubmitterEmails(rule).includes(submitter)) { continue; } - const previousApproverLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER); - if (previousApproverEmail === undefined) { - // Initial-submission level: only rules with no previousApprover gate. - if (previousApproverLeaf) { - continue; - } - } else if (!previousApproverLeaf || previousApproverLeaf.right !== previousApproverEmail) { + const toLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.TO); + if (!toLeaf || toLeaf.right !== currentApprover) { continue; } const amountLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT); + const isOverLimit = + !!amountLeaf && (amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO || amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN); + if (amountLeaf && typeof amountLeaf.right === 'number') { - if (amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN) { - underLimitRule = rule; - approvalLimit = amountLeaf.right; - } else if (amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO) { - overLimitRule = rule; - approvalLimit = approvalLimit ?? amountLeaf.right; - } else { - normalRule = rule; - } + approvalLimit = approvalLimit ?? amountLeaf.right; + } + + if (isOverLimit) { + overLimitForwardsTo = getForwardApprover(rule) ?? overLimitForwardsTo; + continue; + } + + // Normal branch: either a no-amount rule or the under-limit half of a split. + hasNormalBranch = true; + if (isApproveReportRule(rule)) { + normalIsTerminal = true; } else { - normalRule = rule; + normalNextEmail = getForwardApprover(rule) ?? normalNextEmail; } } - if (underLimitRule && overLimitRule) { - return { - email: underLimitRule.nextReceiver, - approvalLimit, - overLimitForwardsTo: overLimitRule.nextReceiver, - }; - } - if (normalRule) { - return {email: normalRule.nextReceiver}; - } - // Partial split (one half missing): use whichever rule we found. Best-effort recovery. - const partial = underLimitRule ?? overLimitRule; - if (partial) { - return {email: partial.nextReceiver}; + if (!hasNormalBranch && overLimitForwardsTo === undefined) { + return undefined; } - return undefined; + + const hasSplit = overLimitForwardsTo !== undefined; + return { + nextEmail: normalIsTerminal ? undefined : normalNextEmail, + approvalLimit: hasSplit ? approvalLimit : undefined, + overLimitForwardsTo, + }; } type BuildApproverChainFromRulesParams = { @@ -1227,20 +1316,16 @@ type BuildApproverChainFromRulesParams = { }; /** - * Loop through a submitter's approval chain forward from their initial-submission level. At each step we - * resolve the level the report is routed into to learn the next approver's email AND that - * approver's own `approvalLimit` / `overLimitForwardsTo`; + * Walk a submitter's approval chain forward. The first approver comes from the `ReportSubmit` rule; + * for each approver we look at the `to == approver` rules to learn that approver's own + * `approvalLimit` / `overLimitForwardsTo` and where the report goes next (or whether it is approved). + * Any step the rules don't cover falls back to the legacy `employeeList` fields. */ function buildApproverChainFromRules({submitter, rules, employees, personalDetailsByEmail}: BuildApproverChainFromRulesParams): Approver[] { - // The first approver, and its own limit/over, come from the initial (no-previousApprover) level. - // Fall back to employeeList.submitsTo for pre-beta workflows that haven't been re-saved yet. - const initialLevel = resolveLevelFromRules(submitter, undefined, rules); - let currentEmail: string | undefined = initialLevel?.email ?? employees[submitter]?.submitsTo; + let currentEmail: string | undefined = resolveFirstApprover(submitter, rules, employees); if (!currentEmail) { return []; } - let currentApprovalLimit: number | null = initialLevel?.approvalLimit ?? employees[currentEmail]?.approvalLimit ?? null; - let currentOverLimitForwardsTo: string | undefined = initialLevel?.overLimitForwardsTo ?? employees[currentEmail]?.overLimitForwardsTo; const chain: Approver[] = []; const seenEmails = new Set(); @@ -1249,8 +1334,11 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai const isCircularReference = seenEmails.has(currentEmail); const employee: PolicyEmployee | undefined = employees[currentEmail]; - const nextLevel = resolveLevelFromRules(submitter, currentEmail, rules); - const forwardsTo: string | undefined = nextLevel?.email ?? employee?.forwardsTo; + const after = resolveAfterApprove(submitter, currentEmail, rules); + const approvalLimit: number | null = after?.approvalLimit ?? employee?.approvalLimit ?? null; + const overLimitForwardsTo: string | undefined = after?.overLimitForwardsTo ?? employee?.overLimitForwardsTo; + // When a rule covers this approver, trust its next hop (possibly terminal). Otherwise fall back. + const forwardsTo: string | undefined = after ? after.nextEmail : employee?.forwardsTo; chain.push({ email: currentEmail, @@ -1258,9 +1346,9 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai avatar: personalDetailsByEmail[currentEmail]?.avatar, displayName: personalDetailsByEmail[currentEmail]?.displayName ?? currentEmail, isCircularReference, - approvalLimit: currentApprovalLimit, - overLimitForwardsTo: currentOverLimitForwardsTo, - overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(currentOverLimitForwardsTo, personalDetailsByEmail), + approvalLimit, + overLimitForwardsTo, + overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(overLimitForwardsTo, personalDetailsByEmail), pendingAction: employee?.pendingAction, errors: employee?.errors, }); @@ -1270,8 +1358,6 @@ function buildApproverChainFromRules({submitter, rules, employees, personalDetai } seenEmails.add(currentEmail); currentEmail = forwardsTo; - currentApprovalLimit = nextLevel?.approvalLimit ?? employees[currentEmail]?.approvalLimit ?? null; - currentOverLimitForwardsTo = nextLevel?.overLimitForwardsTo ?? employees[currentEmail]?.overLimitForwardsTo; } return chain; @@ -1297,10 +1383,34 @@ function getSubmitterRuleIDs(submitter: string, rules: Record rule body` map used by the + * builder, reconcilers and converters, keeping only non-deleted rules scoped to `policyID`. + */ +function getApprovalWorkflowRulesForPolicy(rulesCollection: OnyxCollection | undefined, policyID: string | undefined): Record { + const result: Record = {}; + if (!rulesCollection || !policyID) { + return result; + } + + for (const [onyxKey, rule] of Object.entries(rulesCollection)) { + if (!rule || rule.scope !== CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY || rule.scopeID !== policyID) { + continue; + } + if (rule.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + continue; + } + const ruleID = onyxKey.slice(ONYXKEYS.COLLECTION.RULE.length); + result[ruleID] = {triggers: rule.triggers, filters: rule.filters, actions: rule.actions}; + } + + return result; +} + /** * Map every submitter found in the rules to their workflow's first approver */ -function getRulesSubmitterToFirstApprover(rules: Record): Record { +function getRulesSubmitterToFirstApprover(rules: Record, employees: PolicyEmployeeList = {}): Record { const submitters = new Set(); for (const rule of Object.values(rules)) { for (const email of extractSubmitterEmails(rule)) { @@ -1310,9 +1420,9 @@ function getRulesSubmitterToFirstApprover(rules: Record = {}; for (const submitter of submitters) { - const initialLevel = resolveLevelFromRules(submitter, undefined, rules); - if (initialLevel?.email) { - result[submitter] = initialLevel.email; + const firstApprover = resolveFirstApprover(submitter, rules, employees); + if (firstApprover) { + result[submitter] = firstApprover; } } return result; @@ -1320,14 +1430,21 @@ function getRulesSubmitterToFirstApprover(rules: Record (deprecatedAllPersonalDetails = val), }); +let allRules: OnyxCollection; +Onyx.connect({ + key: ONYXKEYS.COLLECTION.RULE, + waitForCollectionCallback: true, + callback: (val) => (allRules = val), +}); + /** * Stores in Onyx the policy ID of the last workspace that was accessed by the user */ @@ -976,7 +984,7 @@ function setWorkspaceApprovalMode( } } - const optimisticData: Array> = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, @@ -995,7 +1003,7 @@ function setWorkspaceApprovalMode( optimisticData.push(...nextStepOptimisticData); } - const failureData: Array> = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, @@ -1013,6 +1021,19 @@ function setWorkspaceApprovalMode( failureData.push(...nextStepFailureData); } + // Disabling approvals removes every approval workflow, which now lives in the `rules_` Onyx + // collection. Auth's DisablePolicyApprovals deletes those rows server-side, but we must also clear them + // optimistically so the workflows UI doesn't keep rebuilding stale workflows (e.g. after re-enabling). + if (approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL && allRules) { + for (const [ruleKey, rule] of Object.entries(allRules)) { + if (!rule || rule.scope !== CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY || rule.scopeID !== policyID) { + continue; + } + optimisticData.push({onyxMethod: Onyx.METHOD.SET, key: ruleKey as `${typeof ONYXKEYS.COLLECTION.RULE}${string}`, value: null}); + failureData.push({onyxMethod: Onyx.METHOD.SET, key: ruleKey as `${typeof ONYXKEYS.COLLECTION.RULE}${string}`, value: rule}); + } + } + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 703ea8cb3557..9013ae553a64 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -9,6 +9,7 @@ import { buildApprovalWorkflowRules, calculateApprovers, convertApprovalWorkflowToPolicyEmployees, + getApprovalWorkflowRulesForPolicy, getOverLimitForwardsToDisplayName, mergeWorkflowMembersWithAvailableMembers, reconcileApprovalWorkflowRulesForCreate, @@ -24,15 +25,26 @@ import type {ApprovalWorkflowOnyx, PersonalDetailsList, Policy, Report} from '@s import type {Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; import type {ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; +import type Rule from '@src/types/onyx/Rule'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; -import type {NullishDeep, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; +import type {NullishDeep, OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; import lodashDropRightWhile from 'lodash/dropRightWhile'; import Onyx from 'react-native-onyx'; import {completeTask} from './Task'; +/** Cache of every approval-workflow rule (`ONYXKEYS.COLLECTION.RULE`) so actions can read the current rule set. */ +let allRules: OnyxCollection = {}; +Onyx.connect({ + key: ONYXKEYS.COLLECTION.RULE, + waitForCollectionCallback: true, + callback: (value) => { + allRules = value ?? {}; + }, +}); + type CreateApprovalWorkflowParams = { approvalWorkflow: ApprovalWorkflow; policy: OnyxEntry; @@ -284,67 +296,61 @@ type SetApprovalWorkflowRulesParams = { policyID: string; /** - * Diff to apply to `Policy.rules.approvalWorkflows`. A value of `ApprovalWorkflowRule` - * sets/replaces the rule under its `ruleID`; a value of `null` removes it + * Diff of rule bodies keyed by ruleID. A value of `ApprovalWorkflowRule` sets/replaces the rule + * under its `ruleID` in the `ONYXKEYS.COLLECTION.RULE` collection; a value of `null` removes it. */ rulesDiff: ApprovalWorkflowRulesDiff; - /** Snapshot of the policy's `rules.approvalWorkflows` taken before applying `rulesDiff`. Used to roll back on failure. */ - previousApprovalWorkflows: Record; + /** Snapshot of the policy's rules (`ruleID -> rule body`) taken before applying `rulesDiff`. Used to roll back on failure. */ + previousRules: Record; }; /** - * Apply a set of approval-workflow rule changes to a policy via the SetApprovalWorkflow - * Auth command. + * Apply a set of approval-workflow rule changes to a policy via the SetApprovalWorkflow Auth command. * + * Each rule lives under its own `ONYXKEYS.COLLECTION.RULE` key (`rules_`). Upserts use SET so + * a structurally different replacement doesn't deep-merge stale filters; removals mark the rule as + * pending-delete optimistically and clear it on success (or restore the previous rule on failure). + * Only the rule bodies (no `scope`/`scopeID`) are sent over the wire — the backend derives those. */ -function setApprovalWorkflowRules({policyID, rulesDiff, previousApprovalWorkflows}: SetApprovalWorkflowRulesParams) { +function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetApprovalWorkflowRulesParams) { if (!policyID || isEmptyObject(rulesDiff)) { return; } - const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policyID}` as const; + const genericError = getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage'); + + const optimisticData: Array> = []; + const successData: Array> = []; + const failureData: Array> = []; + + for (const [ruleID, rule] of Object.entries(rulesDiff)) { + const ruleKey = `${ONYXKEYS.COLLECTION.RULE}${ruleID}` as const; + const previousRule = previousRules[ruleID]; + const restore: OnyxUpdate = previousRule + ? { + onyxMethod: Onyx.METHOD.SET, + key: ruleKey, + value: {...previousRule, scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, scopeID: policyID, pendingAction: null, errors: genericError}, + } + : {onyxMethod: Onyx.METHOD.SET, key: ruleKey, value: null}; + + if (rule === null) { + optimisticData.push({onyxMethod: Onyx.METHOD.MERGE, key: ruleKey, value: {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, errors: null}}); + successData.push({onyxMethod: Onyx.METHOD.SET, key: ruleKey, value: null}); + failureData.push(restore); + continue; + } - // Build the rollback shape - const failureApprovalWorkflows: Record = {}; - for (const ruleID of Object.keys(rulesDiff)) { - failureApprovalWorkflows[ruleID] = previousApprovalWorkflows[ruleID] ?? null; + optimisticData.push({ + onyxMethod: Onyx.METHOD.SET, + key: ruleKey, + value: {...rule, scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, scopeID: policyID, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, errors: null}, + }); + successData.push({onyxMethod: Onyx.METHOD.MERGE, key: ruleKey, value: {pendingAction: null}}); + failureData.push(restore); } - const optimisticData: Array> = [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: policyKey, - value: { - rules: {approvalWorkflows: rulesDiff}, - pendingFields: {approvalWorkflows: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}, - errorFields: {approvalWorkflows: null}, - }, - }, - ]; - - const successData: Array> = [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: policyKey, - value: { - pendingFields: {approvalWorkflows: null}, - }, - }, - ]; - - const failureData: Array> = [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: policyKey, - value: { - rules: {approvalWorkflows: failureApprovalWorkflows}, - pendingFields: {approvalWorkflows: null}, - errorFields: {approvalWorkflows: getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage')}, - }, - }, - ]; - const parameters: SetApprovalWorkflowParams = { policyID, rules: JSON.stringify(rulesDiff), @@ -361,7 +367,7 @@ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprov return; } - const existingRules = policy.rules?.approvalWorkflows ?? {}; + const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); // A submitter can only belong to one workflow, so first drop these members from any OTHER @@ -374,7 +380,7 @@ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprov const rulesDiff = {...removeDiff, ...createDiff}; - setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); if ( addExpenseApprovalsTaskReport && @@ -398,7 +404,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, return; } - const existingRules = policy.rules?.approvalWorkflows ?? {}; + const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); const previousMemberEmails = initialApprovalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); const newMemberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); @@ -418,7 +424,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, const rulesDiff = {...removeFromOthersDiff, ...memberDiff, ...chainDiff}; - setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); } /** @@ -429,11 +435,11 @@ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: return; } - const existingRules = policy.rules?.approvalWorkflows ?? {}; + const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); const rulesDiff = reconcileApprovalWorkflowRulesForRemove(memberEmails, {existingRules}); - setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousApprovalWorkflows: existingRules}); + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); } /** Set the members of the approval workflow that is currently edited */ diff --git a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx index 24da998a9b5f..568979141e6e 100644 --- a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx +++ b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx @@ -60,7 +60,13 @@ import { } from '@libs/PolicyUtils'; import {hasInProgressVBBA} from '@libs/ReimbursementAccountUtils'; import tokenizedSearch from '@libs/tokenizedSearch'; -import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, getEligibleExistingBusinessBankAccounts, INITIAL_APPROVAL_WORKFLOW} from '@libs/WorkflowUtils'; +import { + convertApprovalWorkflowRulesToWorkflows, + convertPolicyEmployeesToApprovalWorkflows, + getApprovalWorkflowRulesForPolicy, + getEligibleExistingBusinessBankAccounts, + INITIAL_APPROVAL_WORKFLOW, +} from '@libs/WorkflowUtils'; import type {WorkspaceSplitNavigatorParamList} from '@navigation/types'; @@ -183,15 +189,17 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { const {accountID: currentUserAccountID, email: currentUserEmail = '', login: currentUserLogin = ''} = useCurrentUserPersonalDetails(); const isUserReimburser = account?.primaryLogin !== undefined && (policy?.achAccount?.reimburser ?? policy?.owner) === account?.primaryLogin; const isMultipleApproversBetaEnabled = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS); + const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE); const {approvalWorkflows, availableMembers, usedApproverEmails} = useMemo(() => { const params = { policy, personalDetails: personalDetails ?? {}, localeCompare, currentUserLogin, + rules: getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID), }; return isMultipleApproversBetaEnabled ? convertApprovalWorkflowRulesToWorkflows(params) : convertPolicyEmployeesToApprovalWorkflows(params); - }, [policy, personalDetails, localeCompare, currentUserLogin, isMultipleApproversBetaEnabled]); + }, [policy, personalDetails, localeCompare, currentUserLogin, rulesCollection, route.params.policyID, isMultipleApproversBetaEnabled]); const canAccessSubmit2026Features = canAccessSubmitWorkspaceFeatures(policy, isSubmit2026BetaEnabled); const hasValidExistingAccounts = getEligibleExistingBusinessBankAccounts(bankAccountList, policy?.outputCurrency, true).length > 0; diff --git a/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx b/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx index 23cbab689677..5fc32eba8734 100644 --- a/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx +++ b/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx @@ -26,7 +26,7 @@ import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import {addSMSDomainIfPhoneNumber} from '@libs/PhoneNumber'; import {canMemberWrite, getDefaultApprover, getExcludedUsers, getMemberAccountIDsForWorkspace, isPendingDeletePolicy} from '@libs/PolicyUtils'; import type {AvatarSource} from '@libs/UserAvatarUtils'; -import {getRulesSubmitterToFirstApprover} from '@libs/WorkflowUtils'; +import {getApprovalWorkflowRulesForPolicy, getRulesSubmitterToFirstApprover} from '@libs/WorkflowUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import MemberRightIcon from '@pages/workspace/MemberRightIcon'; @@ -60,6 +60,7 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe const {translate} = useLocalize(); const backPath = useDynamicBackPath(DYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROM.path); const [approvalWorkflow, approvalWorkflowResults] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW); + const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE); const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); const [invitedEmailsToAccountIDsDraft] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_INVITE_MEMBERS_DRAFT}${route.params.policyID}`); const icons = useMemoizedLazyExpensifyIcons(['FallbackAvatar']); @@ -107,11 +108,12 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe const policyMemberEmailsToAccountIDs = getMemberAccountIDsForWorkspace(policy?.employeeList); // Build a map of member emails to their existing workflow's first approver. With the beta on this - // is derived from `rules.approvalWorkflows`; otherwise it falls back to the legacy employeeList - // `submitsTo` (non-default workflows only). + // is derived from the `ONYXKEYS.COLLECTION.RULE` rules; otherwise it falls back to the legacy + // employeeList `submitsTo` (non-default workflows only). const membersInExistingWorkflows = (() => { if (isMultipleApproversBetaEnabled) { - return new Map(Object.entries(getRulesSubmitterToFirstApprover(policy?.rules?.approvalWorkflows ?? {}))); + const rules = getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID); + return new Map(Object.entries(getRulesSubmitterToFirstApprover(rules, policy?.employeeList ?? {}))); } const employees = policy?.employeeList ?? {}; diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index c0a83c0ee94b..3ab51e1801f4 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -19,7 +19,7 @@ import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import {canMemberWrite, goBackFromInvalidPolicy, isPendingDeletePolicy} from '@libs/PolicyUtils'; -import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows} from '@libs/WorkflowUtils'; +import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, getApprovalWorkflowRulesForPolicy} from '@libs/WorkflowUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading'; @@ -57,6 +57,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true const {translate, localeCompare} = useLocalize(); const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); const [approvalWorkflow, approvalWorkflowMetadata] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW); + const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE); const isLoadingApprovalWorkflow = isLoadingOnyxValue(approvalWorkflowMetadata); const {login: currentUserLogin = ''} = useCurrentUserPersonalDetails(); const {isBetaEnabled} = usePermissions(); @@ -128,6 +129,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true firstApprover, localeCompare, currentUserLogin, + rules: getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID), }; const result = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS) ? convertApprovalWorkflowRulesToWorkflows(conversionParams) diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 339d37e5d82c..6d1883ad3981 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -1,21 +1,50 @@ -import type {ValueOf} from 'type-fest'; import type CONST from '@src/CONST'; +import type {ValueOf} from 'type-fest'; + +/** + * A report lifecycle event that can fire an approval-workflow rule (`ReportSubmit` or `ReportApprove`). + */ +type ApprovalWorkflowTrigger = ValueOf; + +/** + * The triggers of a rule, keyed by a string index (e.g. `{"0": "ReportSubmit"}`). A rule fires when + * any of its triggers matches the report event. + */ +type ApprovalWorkflowTriggers = Record; + +/** + * The name of the action a rule performs when it matches (`ForwardTo` or `ApproveReport`). + */ +type ApprovalWorkflowActionName = ValueOf; + +/** + * A single action a rule performs when it matches. + */ +type ApprovalWorkflowAction = { + /** What the rule does when it matches. */ + name: ApprovalWorkflowActionName; + + /** Email of the approver the report is forwarded to. Present only for `ForwardTo` actions. */ + approver?: string; +}; + +/** + * The actions of a rule, keyed by a string index (e.g. `{"0": {"name": "ForwardTo", "approver": "..."}}`). + */ +type ApprovalWorkflowActions = Record; + /** * Operand of a comparison in an approval-workflow filter. * - * - The left operand is a field identifier — one of the search-syntax filter keys (extended - * with `previousApprover` for approval rules). - * - The right operand is the literal value the field is compared against. For email-typed - * fields like `from`, the value may be a list of emails to match against. + * - The left operand is a field identifier — one of the search-syntax filter keys (`from`, `to`, `amount`). + * - The right operand is the literal value the field is compared against. For email-typed fields like + * `from`, the value may be a list of emails to match against. */ type ApprovalWorkflowFilterOperand = string | number | string[]; /** - * A single comparison node: ` `. - * - * `right` is optional because a future operator may be unary, but for the operators currently - * in use (`eq`, `lt`, `gte`, ...) both sides are required. + * A single comparison node: ` `. Both `left` and `right` are always present. */ type ApprovalWorkflowFilterComparison = { /** The comparison operator. */ @@ -25,45 +54,58 @@ type ApprovalWorkflowFilterComparison = { left: ApprovalWorkflowFilterOperand; /** The literal value being compared against. */ - right?: ApprovalWorkflowFilterOperand; + right: ApprovalWorkflowFilterOperand; }; /** - * Top-level filter for an approval-workflow rule. Combines two child nodes with a boolean - * operator. `left` / `right` may be either leaf comparisons or nested filters + * A boolean filter that combines two child nodes. `left` / `right` may each be either a leaf comparison + * or a nested boolean filter. Both children are always present. */ type ApprovalWorkflowFilter = { - /** Boolean combinator */ + /** Boolean combinator (`AND` in practice). */ operator: ValueOf; /** Left-hand child: leaf comparison or nested boolean filter. */ left: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; - /** Right-hand child */ - right?: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; + /** Right-hand child: leaf comparison or nested boolean filter. */ + right: ApprovalWorkflowFilterComparison | ApprovalWorkflowFilter; }; /** - * A single approval-workflow rule, keyed by ruleID inside `Policy.rules.approvalWorkflows`. - * When all `filters` match a report, the report is forwarded to `nextReceiver`. + * The body of a single approval-workflow rule. This is exactly what is stored in the server `rules` + * table `value` column, what is sent over the wire to `SetApprovalWorkflow`, and (extended with + * `scope`/`scopeID`) what is stored in the `ONYXKEYS.COLLECTION.RULE` collection. + * + * When the report event matches one of the `triggers` and the `filters` match the report, the rule's + * `actions` are performed (forward the report to an approver, or approve it). */ type ApprovalWorkflowRule = { - /** - * Conditions that must match the report for the rule to fire. - */ - filters: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison; + /** Report lifecycle events that fire this rule. */ + triggers: ApprovalWorkflowTriggers; - /** Currently the only supported action. Kept as a literal to leave room for future actions. */ - action: 'forward'; + /** Conditions that must match the report for the rule to fire. */ + filters: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison; - /** Email of the user the report is forwarded to when the rule matches. */ - nextReceiver: string; + /** What happens when the rule matches. */ + actions: ApprovalWorkflowActions; }; /** - * Map of approval-workflow rules keyed by ruleID, as stored on the policy under - * `rules.approvalWorkflows`. + * Map of approval-workflow rule bodies keyed by ruleID. Used as the in-memory working shape by the + * rules builder/reconcilers; on disk each rule lives under its own `ONYXKEYS.COLLECTION.RULE` key. */ type ApprovalWorkflowRules = Record; -export type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowRule, ApprovalWorkflowRules}; +export type { + ApprovalWorkflowAction, + ApprovalWorkflowActionName, + ApprovalWorkflowActions, + ApprovalWorkflowFilter, + ApprovalWorkflowFilterComparison, + ApprovalWorkflowFilterOperand, + ApprovalWorkflowRule, + ApprovalWorkflowRules, + ApprovalWorkflowTrigger, + ApprovalWorkflowTriggers, +}; diff --git a/src/types/onyx/Policy.ts b/src/types/onyx/Policy.ts index 8965fcee95e4..e5b538ecea21 100644 --- a/src/types/onyx/Policy.ts +++ b/src/types/onyx/Policy.ts @@ -8,7 +8,6 @@ import type {CONST as COMMON_CONST} from 'expensify-common'; import type {ValueOf} from 'type-fest'; import type * as OnyxTypes from '.'; -import type {ApprovalWorkflowRules} from './ApprovalWorkflowRules'; import type * as OnyxCommon from './OnyxCommon'; import type {WorkspaceTravelSettings} from './TravelSettings'; @@ -2634,12 +2633,6 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< /** A set of Agent rules defined with natural language - The rules are run by the "RuleBot" */ agentRules?: Record; - - /** - * Approval-workflow rules keyed by ruleID. Each rule routes a report to a `nextReceiver` - * when its `filters` match. - */ - approvalWorkflows?: ApprovalWorkflowRules; }; /** The "RuleBot" agent account ID */ @@ -2786,7 +2779,7 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< /** Whether the policy requires purchases to be on a company card */ requireCompanyCardsEnabled?: boolean; } & Partial, - 'addWorkspaceRoom' | keyof ACHAccount | keyof Attributes | 'isHREnabled' | 'isTimeTrackingEnabled' | 'timeTrackingDefaultRate' | 'approvalWorkflows' + 'addWorkspaceRoom' | keyof ACHAccount | keyof Attributes | 'isHREnabled' | 'isTimeTrackingEnabled' | 'timeTrackingDefaultRate' >; /** Stages of policy connection sync */ diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 6f5575b8e784..b1e055cad4a0 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -160,6 +160,8 @@ import type Request from './Request'; import type {AnyRequest} from './Request'; import type Response from './Response'; import type ReviewDuplicates from './ReviewDuplicates'; +import type Rule from './Rule'; +import type {RuleCollection} from './Rule'; import type {SavedCSVColumnLayoutData, SavedCSVColumnLayoutList} from './SavedCSVColumnLayout'; import type {SaveSearch} from './SaveSearch'; import type ScheduleCallDraft from './ScheduleCallDraft'; @@ -307,6 +309,8 @@ export type { RecentlyUsedTags, ReimbursementAccount, Report, + Rule, + RuleCollection, ReportNameValuePairs, ReportAction, ReportActionReactions, diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 93ef734d43be..7c1e64f64b27 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -18,6 +18,9 @@ import {calculateApprovers} from '@src/libs/WorkflowUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ApprovalWorkflowOnyx, PersonalDetailsList, Policy, Policy as PolicyType, Report} from '@src/types/onyx'; import type {Approver} from '@src/types/onyx/ApprovalWorkflow'; +import type Rule from '@src/types/onyx/Rule'; + +import type {OnyxCollection} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; @@ -52,6 +55,25 @@ const employee2Email = 'test2@gmail.com'; const employee3Email = 'test3@gmail.com'; const ownerEmail = 'owner@gmail.com'; +/** + * Reads every rule in the `ONYXKEYS.COLLECTION.RULE` collection that belongs to the given policy and is + * not optimistically pending deletion. This mirrors what the app treats as the policy's live rule set. + */ +async function getActivePolicyRules(policyID: string): Promise { + let collection: OnyxCollection = {}; + await getOnyxData({ + key: ONYXKEYS.COLLECTION.RULE, + waitForCollectionCallback: true, + callback: (value) => { + collection = value ?? {}; + }, + }); + return Object.values(collection).filter( + (rule): rule is Rule => + !!rule && rule.scope === CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY && rule.scopeID === policyID && rule.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + ); +} + describe('actions/Workflow', () => { function getApprovalWorkflowState(): Promise { return new Promise((resolve) => { @@ -852,7 +874,7 @@ describe('actions/Workflow', () => { }); describe('createApprovalWorkflowRules', () => { - it('writes a new rule-based approval workflow to the policy rules', async () => { + it('writes a new rule-based approval workflow to the rules collection', async () => { mockFetch.pause(); const policyID = '123456789'; @@ -880,11 +902,18 @@ describe('actions/Workflow', () => { createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined}); await waitForBatchedUpdates(); - const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); - const rules = Object.values(updatedPolicy?.rules?.approvalWorkflows ?? {}); - expect(rules).toHaveLength(1); - expect(rules.at(0)?.nextReceiver).toBe(ownerEmail); - expect(rules.at(0)?.filters).toEqual({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}); + // A one-approver workflow produces a submit rule (forward to the approver) and a terminal approve rule. + const rules = await getActivePolicyRules(policyID); + expect(rules).toHaveLength(2); + + const submitRule = rules.find((rule) => Object.values(rule.triggers).includes(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT)); + expect(submitRule?.scope).toBe(CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY); + expect(submitRule?.scopeID).toBe(policyID); + expect(submitRule?.filters).toEqual({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}); + expect(submitRule?.actions[0]).toEqual({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}); + + const approveRule = rules.find((rule) => Object.values(rule.triggers).includes(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE)); + expect(approveRule?.actions[0]).toEqual({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}); await mockFetch.resume(); await waitForBatchedUpdates(); @@ -900,17 +929,29 @@ describe('actions/Workflow', () => { ...createRandomPolicy(1), id: policyID, owner: ownerEmail, - rules: { - approvalWorkflows: { - rule1: { - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, - action: 'forward', - nextReceiver: ownerEmail, - }, - }, - }, + rules: {}, }; + // Seed the existing [employee1] → [owner] workflow as rules in the collection. + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}, + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, + actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}}, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}, + filters: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, + right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: ownerEmail}, + }, + actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}, + }); + const initialApprovalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], @@ -932,12 +973,14 @@ describe('actions/Workflow', () => { updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}); await waitForBatchedUpdates(); - const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); - const rules = Object.values(updatedPolicy?.rules?.approvalWorkflows ?? {}); - // The old rule (forwarding to the owner) is removed and a new rule forwarding to employee2 is created. - expect(updatedPolicy?.rules?.approvalWorkflows?.rule1).toBeUndefined(); - expect(rules).toHaveLength(1); - expect(rules.at(0)?.nextReceiver).toBe(employee2Email); + // The old rules (forwarding to the owner) are removed and new rules forwarding to employee2 are created. + const rules = await getActivePolicyRules(policyID); + const forwardApprovers = rules + .flatMap((rule) => Object.values(rule.actions)) + .filter((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO) + .map((action) => action.approver); + expect(forwardApprovers).toContain(employee2Email); + expect(forwardApprovers).not.toContain(ownerEmail); await mockFetch.resume(); await waitForBatchedUpdates(); @@ -953,17 +996,29 @@ describe('actions/Workflow', () => { ...createRandomPolicy(1), id: policyID, owner: ownerEmail, - rules: { - approvalWorkflows: { - rule1: { - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, - action: 'forward', - nextReceiver: ownerEmail, - }, - }, - }, + rules: {}, }; + // Seed the existing [employee1] → [owner] workflow as rules in the collection. + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}, + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, + actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}}, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}, + filters: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, + right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: ownerEmail}, + }, + actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}, + }); + const approvalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], @@ -981,8 +1036,9 @@ describe('actions/Workflow', () => { removeApprovalWorkflowRules(approvalWorkflow, policy); await waitForBatchedUpdates(); - const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); - expect(updatedPolicy?.rules?.approvalWorkflows?.rule1).toBeUndefined(); + // Both rules belonged only to the removed member, so no live rules remain for the policy. + const rules = await getActivePolicyRules(policyID); + expect(rules).toHaveLength(0); await mockFetch.resume(); await waitForBatchedUpdates(); diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index bf91c1e00ee0..a85d1c39150f 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1681,9 +1681,13 @@ describe('WorkflowUtils', () => { }); describe('rule-based approval workflows', () => { - const FORWARD_ACTION = 'forward' as const; + const submitTriggers = {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}; + const approveTriggers = {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}; + const forwardActions = (approver: string) => ({'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}}); + const approveActions = {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}; const buildFromFilter = (emails: string[]) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: emails}); - const buildPreviousApproverFilter = (email: string) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.PREVIOUS_APPROVER, right: email}); + const buildToFilter = (email: string) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: email}); + const and = (left: object, right: object) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left, right}); const keyRules = (rules: ApprovalWorkflowRule[]): Record => Object.fromEntries(rules.map((rule, index) => [`rule${index}`, rule])); describe('buildApprovalWorkflowRules', () => { @@ -1695,41 +1699,38 @@ describe('WorkflowUtils', () => { expect(buildApprovalWorkflowRules(buildWorkflow([2], []))).toEqual([]); }); - it('Should build a single `from` rule for a one-approver workflow', () => { - expect(buildApprovalWorkflowRules(buildWorkflow([2], [1]))).toEqual([{filters: buildFromFilter(['2@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}]); + it('Should build a submit rule and a terminal approve rule for a one-approver workflow', () => { + expect(buildApprovalWorkflowRules(buildWorkflow([2], [1]))).toEqual([ + {triggers: submitTriggers, filters: buildFromFilter(['2@example.com']), actions: forwardActions('1@example.com')}, + {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('1@example.com')), actions: approveActions}, + ]); }); - it('Should chain approvers with `previousApprover` gates', () => { + it('Should chain approvers with `to` gates and approve at the end', () => { expect(buildApprovalWorkflowRules(buildWorkflow([3], [1, 2]))).toEqual([ - {filters: buildFromFilter(['3@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - { - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['3@example.com']), right: buildPreviousApproverFilter('1@example.com')}, - action: FORWARD_ACTION, - nextReceiver: '2@example.com', - }, + {triggers: submitTriggers, filters: buildFromFilter(['3@example.com']), actions: forwardActions('1@example.com')}, + {triggers: approveTriggers, filters: and(buildFromFilter(['3@example.com']), buildToFilter('1@example.com')), actions: forwardActions('2@example.com')}, + {triggers: approveTriggers, filters: and(buildFromFilter(['3@example.com']), buildToFilter('2@example.com')), actions: approveActions}, ]); }); - it('Should split a level into under/over amount rules when the approver has a limit split', () => { + it('Should split an approver into under/over amount rules when it has a limit split', () => { const workflow: ApprovalWorkflow = { members: [buildMember(2)], approvers: [buildApprover(1, {approvalLimit: 50000, overLimitForwardsTo: '3@example.com'})], isDefault: false, }; - const underAmountFilter = {operator: CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; - const overAmountFilter = {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; + const underAmount = {operator: CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; + const overAmount = {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; expect(buildApprovalWorkflowRules(workflow)).toEqual([ - { - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: underAmountFilter}, - action: FORWARD_ACTION, - nextReceiver: '1@example.com', - }, - { - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: buildFromFilter(['2@example.com']), right: overAmountFilter}, - action: FORWARD_ACTION, - nextReceiver: '3@example.com', - }, + {triggers: submitTriggers, filters: buildFromFilter(['2@example.com']), actions: forwardActions('1@example.com')}, + // Under the limit and last approver → approve. + {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), and(buildToFilter('1@example.com'), underAmount)), actions: approveActions}, + // Over the limit → escalate to the over-limit approver. + {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), and(buildToFilter('1@example.com'), overAmount)), actions: forwardActions('3@example.com')}, + // The over-limit approver finalizes the report. + {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('3@example.com')), actions: approveActions}, ]); }); @@ -1740,13 +1741,16 @@ describe('WorkflowUtils', () => { isDefault: false, }; - expect(buildApprovalWorkflowRules(workflow)).toEqual([{filters: buildFromFilter(['2@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}]); + expect(buildApprovalWorkflowRules(workflow)).toEqual([ + {triggers: submitTriggers, filters: buildFromFilter(['2@example.com']), actions: forwardActions('1@example.com')}, + {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('1@example.com')), actions: approveActions}, + ]); }); }); describe('applyApprovalWorkflowRulesDiff', () => { - const ruleA: ApprovalWorkflowRule = {filters: buildFromFilter(['2@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}; - const ruleB: ApprovalWorkflowRule = {filters: buildFromFilter(['3@example.com']), action: FORWARD_ACTION, nextReceiver: '4@example.com'}; + const [ruleA] = buildApprovalWorkflowRules(buildWorkflow([2], [1])); + const [ruleB] = buildApprovalWorkflowRules(buildWorkflow([3], [4])); it('Should upsert non-null entries and delete null entries', () => { expect(applyApprovalWorkflowRulesDiff({a: ruleA}, {a: null, b: ruleB})).toEqual({b: ruleB}); @@ -1767,36 +1771,34 @@ describe('WorkflowUtils', () => { expect(Object.values(diff)).toEqual(newRules); }); - it('Should merge members into a structurally identical existing rule', () => { - const existingRules: Record = { - existing1: {filters: buildFromFilter(['20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + it('Should merge members into structurally identical existing rules', () => { + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([20], [1]))); const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); const diff = reconcileApprovalWorkflowRulesForCreate(newRules, ['10@example.com'], {existingRules}); - expect(diff).toEqual({existing1: {filters: buildFromFilter(['20@example.com', '10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}}); + // Both rules structurally match, so members are folded into the existing rules (no new IDs). + expect(Object.keys(diff)).toEqual(Object.keys(existingRules)); + expect(Object.values(diff)).toEqual(buildApprovalWorkflowRules(buildWorkflow([20, 10], [1]))); }); }); describe('reconcileApprovalWorkflowRulesForEdit', () => { - it('Should drop the old rule and create the new chain when the approver changes', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + it('Should drop the old rules and create the new chain when the approver changes', () => { + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10], [1]))); const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [2])); const diff = reconcileApprovalWorkflowRulesForEdit(newRules, ['10@example.com'], {existingRules}); - expect(diff.r1).toBeNull(); + for (const ruleID of Object.keys(existingRules)) { + expect(diff[ruleID]).toBeNull(); + } const createdRules = Object.entries(diff) - .filter(([ruleID]) => ruleID !== 'r1') + .filter(([ruleID]) => !(ruleID in existingRules)) .map(([, rule]) => rule); expect(createdRules).toEqual(newRules); }); it('Should leave a structurally identical rule untouched', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10], [1]))); const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); const diff = reconcileApprovalWorkflowRulesForEdit(newRules, ['10@example.com'], {existingRules}); @@ -1805,28 +1807,22 @@ describe('WorkflowUtils', () => { }); describe('reconcileApprovalWorkflowRulesForRemove', () => { - it('Should remove a rule that only contains the workflow members', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + it('Should remove rules that only contain the workflow members', () => { + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10], [1]))); + const diff = reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules}); - expect(reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules})).toEqual({r1: null}); + expect(diff).toEqual(Object.fromEntries(Object.keys(existingRules).map((ruleID) => [ruleID, null]))); }); - it('Should strip only the workflow members from a shared rule', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com', '20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + it('Should strip only the workflow members from shared rules', () => { + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10, 20], [1]))); + const diff = reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules}); - expect(reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules})).toEqual({ - r1: {filters: buildFromFilter(['20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }); + expect(diff).toEqual(keyRules(buildApprovalWorkflowRules(buildWorkflow([20], [1])))); }); it('Should ignore rules that do not contain the members', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['30@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([30], [1]))); expect(reconcileApprovalWorkflowRulesForRemove(['10@example.com'], {existingRules})).toEqual({}); }); @@ -1834,28 +1830,23 @@ describe('WorkflowUtils', () => { describe('reconcileApprovalWorkflowRulesForMembersChange', () => { it('Should add new members and drop removed ones from matching rules', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com', '20@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10, 20], [1]))); const diff = reconcileApprovalWorkflowRulesForMembersChange(['10@example.com', '20@example.com'], ['20@example.com', '30@example.com'], {existingRules}); - expect(diff).toEqual({r1: {filters: buildFromFilter(['20@example.com', '30@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}}); + expect(diff).toEqual(keyRules(buildApprovalWorkflowRules(buildWorkflow([20, 30], [1])))); }); it('Should skip rules with no net change to the submitter list', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10], [1]))); expect(reconcileApprovalWorkflowRulesForMembersChange(['10@example.com'], ['10@example.com'], {existingRules})).toEqual({}); }); - it('Should remove a rule when all of its members are dropped', () => { - const existingRules: Record = { - r1: {filters: buildFromFilter(['10@example.com']), action: FORWARD_ACTION, nextReceiver: '1@example.com'}, - }; + it('Should remove rules when all of their members are dropped', () => { + const existingRules = keyRules(buildApprovalWorkflowRules(buildWorkflow([10], [1]))); + const diff = reconcileApprovalWorkflowRulesForMembersChange(['10@example.com'], [], {existingRules}); - expect(reconcileApprovalWorkflowRulesForMembersChange(['10@example.com'], [], {existingRules})).toEqual({r1: null}); + expect(diff).toEqual(Object.fromEntries(Object.keys(existingRules).map((ruleID) => [ruleID, null]))); }); }); @@ -1868,7 +1859,7 @@ describe('WorkflowUtils', () => { }); describe('convertApprovalWorkflowRulesToWorkflows', () => { - const createPolicyWithRules = (employees: PolicyEmployeeList, rules: Record, defaultApprover: string) => + const createPolicy = (employees: PolicyEmployeeList, defaultApprover: string) => ({ id: 'test-policy', name: 'Test Policy', @@ -1879,15 +1870,14 @@ describe('WorkflowUtils', () => { isPolicyExpenseChatEnabled: true, employeeList: employees, approver: defaultApprover, - rules: {approvalWorkflows: rules}, }) as Policy; it('Should reconstruct a multi-approver chain from rules', () => { const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; - const policy = createPolicyWithRules(employees, rules, '1@example.com'); + const policy = createPolicy(employees, '1@example.com'); - const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare}); + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare, rules}); expect(approvalWorkflows).toHaveLength(1); const workflow = approvalWorkflows.at(0); @@ -1906,9 +1896,9 @@ describe('WorkflowUtils', () => { }; const rules = keyRules(buildApprovalWorkflowRules(workflow)); const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; - const policy = createPolicyWithRules(employees, rules, '1@example.com'); + const policy = createPolicy(employees, '1@example.com'); - const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare}); + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare, rules}); const firstApprover = approvalWorkflows.at(0)?.approvers.at(0); expect(firstApprover?.email).toBe('1@example.com'); @@ -1919,9 +1909,9 @@ describe('WorkflowUtils', () => { it('Should round-trip a workflow through rules and back', () => { const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; - const policy = createPolicyWithRules(employees, rules, '1@example.com'); + const policy = createPolicy(employees, '1@example.com'); - const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare}); + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare, rules}); // Rebuilding rules from the reconstructed workflow should reproduce the original rule set. const workflow = approvalWorkflows.at(0); From 23d18bcb7de227ae9ecaff1e55cbcac9a5f433c2 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 14 Jul 2026 15:35:11 +0200 Subject: [PATCH 21/62] properly group people in the same rules --- src/libs/WorkflowUtils.ts | 62 +++++++++++++--- tests/actions/WorkflowTest.ts | 122 ++++++++++++++++++++++++++++++++ tests/unit/WorkflowUtilsTest.ts | 88 ++++++++++++++++++++++- 3 files changed, 260 insertions(+), 12 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index d964a6d4cb6d..3b391748226f 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -934,10 +934,47 @@ function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { return Array.from(emails); } +/** + * Recursively normalize a value so two logically-equal structures stringify identically: + * - object keys are sorted (order-independent), and + * - index-keyed maps (`{"0":x,"1":y}`) are collapsed to arrays (`[x,y]`). + * + * The array collapse matters because the API decodes the rules JSON to PHP associative arrays, so a + * rule's `triggers`/`actions` come back from the backend as JSON arrays while a freshly-built rule + * uses the `{"0":…}` object form. Without this, the two shapes would never match and the create flow + * would mint a brand-new rule instead of folding the submitter into the existing one. + */ +function canonicalize(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(canonicalize); + } + if (value !== null && typeof value === 'object') { + const entries = Object.entries(value); + // A `{"0":…,"1":…}` map is the object form of a list — collapse it to an array to match the backend. + const isSequentialIndexMap = entries.length > 0 && entries.every(([key], index) => key === String(index)); + if (isSequentialIndexMap) { + return entries.map(([, val]) => canonicalize(val)); + } + // Byte-order sort is intentional: this is a locale-agnostic structural fingerprint, not user-facing text. + const sortedEntries = entries.sort(([a], [b]) => { + if (a === b) { + return 0; + } + return a < b ? -1 : 1; + }); + return Object.fromEntries(sortedEntries.map(([key, val]) => [key, canonicalize(val)])); + } + return value; +} + /** * Return a structural fingerprint of a rule with the `right` values of every `from` leaf * stripped. Two rules with the same fingerprint differ only in their submitter list, which * is what we look for when deciding whether to merge two workflows into a shared rule. + * + * Keys are canonicalized (recursively sorted) so a rule hydrated from the server folds into + * a freshly-built one even when their JSON object-key order differs — otherwise the create + * flow would mint a brand-new rule instead of adding the submitter to the existing rule. */ function structuralFingerprint(rule: ApprovalWorkflowRule): string { const stripFromValues = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): unknown => { @@ -954,11 +991,13 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { return {operator: node.operator, left: stripFromValues(node.left), right: stripFromValues(node.right)}; }; - return JSON.stringify({ - triggers: rule.triggers, - filters: stripFromValues(rule.filters), - actions: rule.actions, - }); + return JSON.stringify( + canonicalize({ + triggers: rule.triggers, + filters: stripFromValues(rule.filters), + actions: rule.actions, + }), + ); } /** Replace the `right` value on every `from` leaf with `newEmails`. */ @@ -1519,11 +1558,14 @@ function convertApprovalWorkflowRulesToWorkflows({ } } - // Group submitters that share the same rules into one workflow. A submitter's "rules" is the - // exact set of ruleIDs whose `from` includes them, so two submitters that belong to the same - // rules land in the same workflow - const submitterRuleIDs = getSubmitterRuleIDs(email, rules); - const fingerprint = submitterRuleIDs.length > 0 ? `r|${submitterRuleIDs.join(',')}` : `l|${approverChainFingerprint(chain)}`; + // Group submitters by their resolved approver chain, so everyone routing through the same chain of + // approvers renders as a single workflow card. Grouping by the exact set of ruleIDs instead would + // split two same-chain workflows whenever their rules happened to be stored as separate pairs (e.g. + // one workflow was created before the other's rules were cached). The `r`/`l` source tag keeps + // rule-based chains separate from legacy employeeList chains, which are expected to disappear on re-save. + const hasRuleBasedChain = getSubmitterRuleIDs(email, rules).length > 0; + const chainKey = approverChainFingerprint(chain); + const fingerprint = hasRuleBasedChain ? `r|${chainKey}` : `l|${chainKey}`; const existingGroup = groupedByFingerprint.get(fingerprint); if (existingGroup) { diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 7c1e64f64b27..941120118eb4 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -918,6 +918,128 @@ describe('actions/Workflow', () => { await mockFetch.resume(); await waitForBatchedUpdates(); }); + + it('folds a new submitter into the existing same-chain rules instead of creating a new pair', async () => { + mockFetch.pause(); + + const policyID = '123456789'; + const policy: Policy = { + ...createRandomPolicy(1), + id: policyID, + owner: ownerEmail, + rules: {}, + }; + + // Existing workflow: employee1 (A) and employee2 (B) submit to owner (C). + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}, + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email, employee2Email]}, + actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}}, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}, + filters: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email, employee2Email]}, + right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: ownerEmail}, + }, + actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}, + }); + + // New workflow: employee3 (D) submits to owner (C) — same chain as the existing workflow. + const approvalWorkflow = { + members: [{email: employee3Email, displayName: employee3Email}], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + availableMembers: [], + usedApproverEmails: [], + isDefault: false, + action: 'create', + originalApprovers: [], + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined}); + await waitForBatchedUpdates(); + + const rules = await getActivePolicyRules(policyID); + // D should be folded into the two existing rules, not create a third/fourth rule. + expect(rules).toHaveLength(2); + for (const rule of rules) { + const fromLeaf = Object.values(rule.actions).some((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO) + ? rule.filters + : (rule.filters as {left: unknown}).left; + expect((fromLeaf as {right: string[]}).right).toEqual([employee1Email, employee2Email, employee3Email]); + } + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); + + it('E2E: creating A,B→C then D→C via two successive create calls folds D into the same rules', async () => { + mockFetch.pause(); + + const policyID = '123456789'; + const policy: Policy = { + ...createRandomPolicy(1), + id: policyID, + owner: ownerEmail, + rules: {}, + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + // First: A and B submit to C. + createApprovalWorkflowRules({ + approvalWorkflow: { + members: [ + {email: employee1Email, displayName: employee1Email}, + {email: employee2Email, displayName: employee2Email}, + ], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + isDefault: false, + }, + policy, + addExpenseApprovalsTaskReport: undefined, + }); + await waitForBatchedUpdates(); + + const rulesAfterFirst = await getActivePolicyRules(policyID); + expect(rulesAfterFirst).toHaveLength(2); + + // Second: D submits to C (same approver chain). + createApprovalWorkflowRules({ + approvalWorkflow: { + members: [{email: employee3Email, displayName: employee3Email}], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + isDefault: false, + }, + policy, + addExpenseApprovalsTaskReport: undefined, + }); + await waitForBatchedUpdates(); + + const rulesAfterSecond = await getActivePolicyRules(policyID); + // Still only two rules, each now listing all three submitters. + expect(rulesAfterSecond).toHaveLength(2); + for (const rule of rulesAfterSecond) { + const fromLeaf = Object.values(rule.actions).some((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO) + ? rule.filters + : (rule.filters as {left: unknown}).left; + expect((fromLeaf as {right: string[]}).right).toEqual([employee1Email, employee2Email, employee3Email]); + } + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); }); describe('updateApprovalWorkflowRules', () => { diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index a85d1c39150f..dc5ddb97b7dd 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -25,7 +25,7 @@ import { import type {Policy} from '@src/types/onyx'; import type {Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; -import type {ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; +import type {ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; import type {BankAccountList} from '@src/types/onyx/BankAccount'; import type {PersonalDetailsList} from '@src/types/onyx/PersonalDetails'; import type {PolicyEmployeeList} from '@src/types/onyx/PolicyEmployee'; @@ -1687,7 +1687,11 @@ describe('WorkflowUtils', () => { const approveActions = {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}; const buildFromFilter = (emails: string[]) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: emails}); const buildToFilter = (email: string) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: email}); - const and = (left: object, right: object) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left, right}); + const and = (left: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison, right: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter => ({ + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left, + right, + }); const keyRules = (rules: ApprovalWorkflowRule[]): Record => Object.fromEntries(rules.map((rule, index) => [`rule${index}`, rule])); describe('buildApprovalWorkflowRules', () => { @@ -1780,6 +1784,56 @@ describe('WorkflowUtils', () => { expect(Object.keys(diff)).toEqual(Object.keys(existingRules)); expect(Object.values(diff)).toEqual(buildApprovalWorkflowRules(buildWorkflow([20, 10], [1]))); }); + + it('Should merge into an existing rule whose triggers/actions are arrays (as the PHP backend stores them)', () => { + // The API decodes the rules JSON to PHP associative arrays, so index-keyed maps like + // {"0":"ReportSubmit"} come back as JSON arrays ["ReportSubmit"]. A freshly-built rule uses the + // object form, so the structural match must treat the two shapes as equivalent to fold the submitter in. + const existingRules: Record = { + r1: { + triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT] as unknown as ApprovalWorkflowRule['triggers'], + filters: buildFromFilter(['20@example.com']), + actions: [{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: '1@example.com'}] as unknown as ApprovalWorkflowRule['actions'], + }, + r2: { + triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE] as unknown as ApprovalWorkflowRule['triggers'], + filters: and(buildFromFilter(['20@example.com']), buildToFilter('1@example.com')), + actions: [{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}] as unknown as ApprovalWorkflowRule['actions'], + }, + }; + const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); + const diff = reconcileApprovalWorkflowRulesForCreate(newRules, ['10@example.com'], {existingRules}); + + // Folds into the two existing rules (r1/r2) instead of creating fresh IDs, and appends the submitter. + expect(Object.keys(diff).sort()).toEqual(['r1', 'r2']); + expect((diff.r1?.filters as {right: string[]}).right).toEqual(['20@example.com', '10@example.com']); + }); + + it('Should merge into an existing rule whose JSON keys are ordered differently (e.g. hydrated from the server)', () => { + // Server-hydrated rules can come back with a different object-key order than a freshly-built rule. + // The structural match must be order-independent so the new submitter folds into the existing rule. + const existingRules: Record = { + r1: { + actions: {'0': {approver: '1@example.com', name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO}}, + filters: {right: ['20@example.com'], left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO}, + triggers: submitTriggers, + }, + r2: { + actions: approveActions, + filters: { + right: {right: '1@example.com', left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO}, + left: {right: ['20@example.com'], left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO}, + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + }, + triggers: approveTriggers, + }, + }; + const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); + const diff = reconcileApprovalWorkflowRulesForCreate(newRules, ['10@example.com'], {existingRules}); + + // Folds into the two existing rules (r1/r2) instead of creating fresh IDs. + expect(Object.keys(diff).sort()).toEqual(['r1', 'r2']); + }); }); describe('reconcileApprovalWorkflowRulesForEdit', () => { @@ -1920,6 +1974,36 @@ describe('WorkflowUtils', () => { expect(buildApprovalWorkflowRules(workflow)).toEqual(Object.values(rules)); } }); + + it('Should group submitters with the same approver chain into one workflow even when stored as separate rule pairs', () => { + // Two workflows that both route to approver 1, but stored under distinct ruleIDs (e.g. created + // before the other one's rules were cached). They must still render as a single workflow card. + const rules: Record = { + subAB: {triggers: submitTriggers, filters: buildFromFilter(['2@example.com', '3@example.com']), actions: forwardActions('1@example.com')}, + appAB: {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com', '3@example.com']), buildToFilter('1@example.com')), actions: approveActions}, + subD: {triggers: submitTriggers, filters: buildFromFilter(['4@example.com']), actions: forwardActions('1@example.com')}, + appD: {triggers: approveTriggers, filters: and(buildFromFilter(['4@example.com']), buildToFilter('1@example.com')), actions: approveActions}, + }; + const employees: PolicyEmployeeList = { + '1@example.com': {email: '1@example.com', submitsTo: '9@example.com'}, + '2@example.com': {email: '2@example.com', submitsTo: '1@example.com'}, + '3@example.com': {email: '3@example.com', submitsTo: '1@example.com'}, + '4@example.com': {email: '4@example.com', submitsTo: '1@example.com'}, + '9@example.com': {email: '9@example.com', submitsTo: '9@example.com'}, + }; + const policy = createPolicy(employees, '9@example.com'); + + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare, rules}); + + const workflowsToApprover1 = approvalWorkflows.filter((workflow) => workflow.approvers.at(0)?.email === '1@example.com'); + expect(workflowsToApprover1).toHaveLength(1); + expect( + workflowsToApprover1 + .at(0) + ?.members.map((member) => member.email) + .sort(), + ).toEqual(['2@example.com', '3@example.com', '4@example.com']); + }); }); }); }); From 9213ee2ae0eba5568efc618f04b2f9341a65a543 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 14 Jul 2026 15:50:41 +0200 Subject: [PATCH 22/62] big cleanup --- src/libs/WorkflowUtils.ts | 50 +++++++++++++++++---------------- tests/unit/WorkflowUtilsTest.ts | 43 ++++++---------------------- 2 files changed, 35 insertions(+), 58 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 3b391748226f..1f43290d2df7 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1035,6 +1035,21 @@ function removeEmails(existingEmails: string[], emailsToRemove: string[]): strin return existingEmails.filter((email) => !removalSet.has(email)); } +/** True when any of `emails` is in `set` — i.e. a rule's submitters overlap a workflow's members. */ +function containsAnyEmail(emails: string[], set: Set): boolean { + return emails.some((email) => set.has(email)); +} + +/** Fold `memberEmails` into a rule's `from` list (union), returning the updated rule. */ +function addMembersToRule(rule: ApprovalWorkflowRule, memberEmails: string[]): ApprovalWorkflowRule { + return replaceSubmitterEmails(rule, mergeEmails(extractSubmitterEmails(rule), memberEmails)); +} + +/** Rewrite a rule's `from` list, or drop the rule entirely (`null`) when no submitters remain. */ +function rewriteOrRemoveRule(rule: ApprovalWorkflowRule, remainingEmails: string[]): ApprovalWorkflowRule | null { + return remainingEmails.length === 0 ? null : replaceSubmitterEmails(rule, remainingEmails); +} + type ReconcileContext = { /** The policy's existing approval-workflow rules (`ruleID -> rule body`), defaulting to `{}`. */ existingRules: Record; @@ -1056,8 +1071,7 @@ function reconcileApprovalWorkflowRulesForCreate(newRules: ApprovalWorkflowRule[ if (match) { const [existingID, existingRule] = match; - const mergedEmails = mergeEmails(extractSubmitterEmails(existingRule), memberEmails); - diff[existingID] = replaceSubmitterEmails(existingRule, mergedEmails); + diff[existingID] = addMembersToRule(existingRule, memberEmails); continue; } @@ -1091,8 +1105,7 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], // Pass 1: walk existing rules that belong (at least partially) to this workflow. for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { const ruleEmails = extractSubmitterEmails(existingRule); - const sharedWithThisWorkflow = ruleEmails.some((email) => memberSet.has(email)); - if (!sharedWithThisWorkflow) { + if (!containsAnyEmail(ruleEmails, memberSet)) { continue; } @@ -1103,14 +1116,8 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], continue; } - const remaining = removeEmails(ruleEmails, memberEmails); - if (remaining.length === 0) { - // No other workflow shares this rule — drop it entirely. - diff[ruleID] = null; - } else { - // Keep the rule for the other workflows that still need it, minus our members. - diff[ruleID] = replaceSubmitterEmails(existingRule, remaining); - } + // Keep the rule (minus our members) for any other workflow that still needs it; drop it otherwise. + diff[ruleID] = rewriteOrRemoveRule(existingRule, removeEmails(ruleEmails, memberEmails)); } // Pass 2: create or extend rules for any new rule that wasn't already covered. @@ -1132,15 +1139,13 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], if (structuralFingerprint(existing) !== fingerprint) { return false; } - const existingEmails = extractSubmitterEmails(existing); // "Different workflow" => no overlap with our members. - return !existingEmails.some((email) => memberSet.has(email)); + return !containsAnyEmail(extractSubmitterEmails(existing), memberSet); }); if (foreignMatch) { const [existingID, existingRule] = foreignMatch; - const mergedEmails = mergeEmails(extractSubmitterEmails(existingRule), memberEmails); - diff[existingID] = replaceSubmitterEmails(existingRule, mergedEmails); + diff[existingID] = addMembersToRule(existingRule, memberEmails); continue; } @@ -1161,13 +1166,11 @@ function reconcileApprovalWorkflowRulesForRemove(memberEmails: string[], context for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { const ruleEmails = extractSubmitterEmails(existingRule); - const sharedWithThisWorkflow = ruleEmails.some((email) => memberSet.has(email)); - if (!sharedWithThisWorkflow) { + if (!containsAnyEmail(ruleEmails, memberSet)) { continue; } - const remaining = removeEmails(ruleEmails, memberEmails); - diff[ruleID] = remaining.length === 0 ? null : replaceSubmitterEmails(existingRule, remaining); + diff[ruleID] = rewriteOrRemoveRule(existingRule, removeEmails(ruleEmails, memberEmails)); } return diff; @@ -1186,19 +1189,18 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { const ruleEmails = extractSubmitterEmails(existingRule); - if (!ruleEmails.some((email) => previousSet.has(email))) { + if (!containsAnyEmail(ruleEmails, previousSet)) { continue; } - const afterRemoval = removeEmails(ruleEmails, removed); - const updatedEmails = mergeEmails(afterRemoval, newMemberEmails); + const updatedEmails = mergeEmails(removeEmails(ruleEmails, removed), newMemberEmails); // No effective change to this rule's `from` — skip the round-trip. if (updatedEmails.length === ruleEmails.length && updatedEmails.every((email, idx) => email === ruleEmails.at(idx))) { continue; } - diff[ruleID] = updatedEmails.length === 0 ? null : replaceSubmitterEmails(existingRule, updatedEmails); + diff[ruleID] = rewriteOrRemoveRule(existingRule, updatedEmails); } return diff; diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index dc5ddb97b7dd..55f4b0f281f8 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1785,20 +1785,21 @@ describe('WorkflowUtils', () => { expect(Object.values(diff)).toEqual(buildApprovalWorkflowRules(buildWorkflow([20, 10], [1]))); }); - it('Should merge into an existing rule whose triggers/actions are arrays (as the PHP backend stores them)', () => { - // The API decodes the rules JSON to PHP associative arrays, so index-keyed maps like - // {"0":"ReportSubmit"} come back as JSON arrays ["ReportSubmit"]. A freshly-built rule uses the - // object form, so the structural match must treat the two shapes as equivalent to fold the submitter in. + it('Should merge into a server-hydrated rule (array-shaped triggers/actions, reordered keys)', () => { + // The API decodes the rules JSON to PHP associative arrays, so a hydrated rule comes back with + // index-keyed maps flattened to arrays (`{"0":"ReportSubmit"}` -> `["ReportSubmit"]`) and its object + // keys in a different order than a freshly-built rule. The structural match must ignore both so the + // new submitter folds into the existing rule instead of minting a fresh pair. const existingRules: Record = { r1: { - triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT] as unknown as ApprovalWorkflowRule['triggers'], + actions: [{approver: '1@example.com', name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO}] as unknown as ApprovalWorkflowRule['actions'], filters: buildFromFilter(['20@example.com']), - actions: [{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: '1@example.com'}] as unknown as ApprovalWorkflowRule['actions'], + triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT] as unknown as ApprovalWorkflowRule['triggers'], }, r2: { - triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE] as unknown as ApprovalWorkflowRule['triggers'], - filters: and(buildFromFilter(['20@example.com']), buildToFilter('1@example.com')), actions: [{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}] as unknown as ApprovalWorkflowRule['actions'], + filters: and(buildFromFilter(['20@example.com']), buildToFilter('1@example.com')), + triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE] as unknown as ApprovalWorkflowRule['triggers'], }, }; const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); @@ -1808,32 +1809,6 @@ describe('WorkflowUtils', () => { expect(Object.keys(diff).sort()).toEqual(['r1', 'r2']); expect((diff.r1?.filters as {right: string[]}).right).toEqual(['20@example.com', '10@example.com']); }); - - it('Should merge into an existing rule whose JSON keys are ordered differently (e.g. hydrated from the server)', () => { - // Server-hydrated rules can come back with a different object-key order than a freshly-built rule. - // The structural match must be order-independent so the new submitter folds into the existing rule. - const existingRules: Record = { - r1: { - actions: {'0': {approver: '1@example.com', name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO}}, - filters: {right: ['20@example.com'], left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO}, - triggers: submitTriggers, - }, - r2: { - actions: approveActions, - filters: { - right: {right: '1@example.com', left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO}, - left: {right: ['20@example.com'], left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO}, - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - }, - triggers: approveTriggers, - }, - }; - const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); - const diff = reconcileApprovalWorkflowRulesForCreate(newRules, ['10@example.com'], {existingRules}); - - // Folds into the two existing rules (r1/r2) instead of creating fresh IDs. - expect(Object.keys(diff).sort()).toEqual(['r1', 'r2']); - }); }); describe('reconcileApprovalWorkflowRulesForEdit', () => { From d14a1976fef1c7b697c6ed2b197d8df9aaaf00ea Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 14:02:00 +0200 Subject: [PATCH 23/62] comment cleanup --- src/libs/WorkflowUtils.ts | 90 +++++++++---------------------- src/libs/actions/Policy/Policy.ts | 5 +- src/libs/actions/Workflow.ts | 12 ++--- 3 files changed, 29 insertions(+), 78 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 1f43290d2df7..1d07d1efc50a 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -738,10 +738,6 @@ function mergeWorkflowMembersWithAvailableMembers(workflowMembers: Member[], all return [...workflowMembers, ...additionalMembers]; } -// These helpers translate the in-app `ApprovalWorkflow` model into the AST rule -// format the backend stores in the `rules` table (mirrored in `ONYXKEYS.COLLECTION.RULE`), -// and handle any changes. - type ApprovalWorkflowRulesDiff = Record; /** Build a comparison filter: ` `. */ @@ -789,18 +785,9 @@ function buildApproveActions(): ApprovalWorkflowActions { } /** - * Build the AST rule chain for a single `ApprovalWorkflow` (members + ordered approvers). - * - * For approvers `[A0, A1, …, A_{n-1}]` and members `M` this produces: - * - a `ReportSubmit` rule: `from ∈ M` → forward to `A0`. - * - for each approver `A_i`, a `ReportApprove` rule gated on `to == A_i` (the approver who just - * approved) describing the next hop: - * - normally forward to `A_{i+1}`, or approve the report if `A_i` is the last approver. - * - if `A_i` has a positive `approvalLimit` and an `overLimitForwardsTo`, the hop splits: - * under the limit → the normal hop above; at/over the limit → forward to `overLimitForwardsTo`, - * who then finalizes the report (a terminal `ApproveReport` rule for `to == overLimitForwardsTo`). - * - * The `from` filter is always the top-level left of the tree so it can be checked cheaply. + * Build the AST rule chain for a single `ApprovalWorkflow`: a `ReportSubmit` rule forwarding members' + * reports to the first approver, plus a `ReportApprove` rule per approver describing the next hop + * (forward to the next approver, approve if last, or split on the approver's over-limit target). */ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): ApprovalWorkflowRule[] { const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); @@ -850,13 +837,12 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva filters: buildAnd(fromComparison, buildAnd(toComparison, underAmount)), actions: nextApproverEmail ? buildForwardActions(nextApproverEmail) : buildApproveActions(), }); - // At/over the limit: escalate to the over-limit approver. + // At/over the limit: escalate to the over-limit approver, who then finalizes the report. rules.push({ triggers: buildApproveTriggers(), filters: buildAnd(fromComparison, buildAnd(toComparison, overAmount)), actions: buildForwardActions(limitSplit.overLimitForwardsTo), }); - // The over-limit approver finalizes the report. rules.push({ triggers: buildApproveTriggers(), filters: buildAnd(fromComparison, buildToComparison(limitSplit.overLimitForwardsTo)), @@ -906,7 +892,6 @@ function forEachSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowF return; } if (isComparisonLeaf(node)) { - // A leaf has no children to recurse into; only `from` leaves are reported. if (isSubmitterFilter(node)) { callback(node); } @@ -935,14 +920,10 @@ function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { } /** - * Recursively normalize a value so two logically-equal structures stringify identically: - * - object keys are sorted (order-independent), and - * - index-keyed maps (`{"0":x,"1":y}`) are collapsed to arrays (`[x,y]`). - * - * The array collapse matters because the API decodes the rules JSON to PHP associative arrays, so a - * rule's `triggers`/`actions` come back from the backend as JSON arrays while a freshly-built rule - * uses the `{"0":…}` object form. Without this, the two shapes would never match and the create flow - * would mint a brand-new rule instead of folding the submitter into the existing one. + * Normalize a value so two logically-equal structures stringify identically: object keys are sorted and + * index-keyed maps (`{"0":x}`) are collapsed to arrays (`[x]`). The array collapse matters because the API + * decodes the rules JSON to PHP arrays, so `triggers`/`actions` come back as JSON arrays while a freshly-built + * rule uses the `{"0":…}` object form — without it the two shapes never match and merging fails. */ function canonicalize(value: unknown): unknown { if (Array.isArray(value)) { @@ -955,7 +936,7 @@ function canonicalize(value: unknown): unknown { if (isSequentialIndexMap) { return entries.map(([, val]) => canonicalize(val)); } - // Byte-order sort is intentional: this is a locale-agnostic structural fingerprint, not user-facing text. + // Byte-order sort (not locale-aware): this is a structural fingerprint, not user-facing text. const sortedEntries = entries.sort(([a], [b]) => { if (a === b) { return 0; @@ -968,13 +949,9 @@ function canonicalize(value: unknown): unknown { } /** - * Return a structural fingerprint of a rule with the `right` values of every `from` leaf - * stripped. Two rules with the same fingerprint differ only in their submitter list, which - * is what we look for when deciding whether to merge two workflows into a shared rule. - * - * Keys are canonicalized (recursively sorted) so a rule hydrated from the server folds into - * a freshly-built one even when their JSON object-key order differs — otherwise the create - * flow would mint a brand-new rule instead of adding the submitter to the existing rule. + * Return a structural fingerprint of a rule with every `from` leaf's `right` (the submitter list) + * stripped and keys canonicalized. Two rules with the same fingerprint differ only in their submitters, + * which is what we look for when deciding whether to merge two workflows into a shared rule. */ function structuralFingerprint(rule: ApprovalWorkflowRule): string { const stripFromValues = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): unknown => { @@ -982,7 +959,6 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { return node; } if (isComparisonLeaf(node)) { - // Drop the `right` (submitter list) from `from` leaves so only the structure remains. if (isSubmitterFilter(node)) { return {operator: node.operator, left: node.left}; } @@ -1082,17 +1058,9 @@ function reconcileApprovalWorkflowRulesForCreate(newRules: ApprovalWorkflowRule[ } /** - * Reconcile an edit to an existing workflow. Returns add/replace/remove instructions to - * morph the existing rule set into the new chain while preserving rules shared with other - * workflows. - * - * Two passes: - * 1. Walk every existing rule that contains any of the workflow's members. If a new rule - * structurally matches, leave it alone; otherwise either drop this workflow's members - * from the rule (when it's shared with other workflows) or remove the rule entirely. - * 2. For every new rule that didn't already exist, look for a structurally matching rule - * under a different membership and fold this workflow into it; failing that, create - * a fresh rule with a new ruleID. + * Reconcile an edit to an existing workflow into add/replace/remove instructions, preserving rules shared + * with other workflows. Pass 1 rewrites/removes existing rules that hold this workflow's members; pass 2 + * folds each new rule into a structurally-matching foreign rule or creates it under a fresh ruleID. */ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], memberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { const diff: ApprovalWorkflowRulesDiff = {}; @@ -1206,9 +1174,7 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st return diff; } -/** - * Apply an `ApprovalWorkflowRulesDiff` to a rule map, returning a new map. A `null` value removes - */ +/** Apply an `ApprovalWorkflowRulesDiff` to a rule map, returning a new map. A `null` value removes the rule. */ function applyApprovalWorkflowRulesDiff(existingRules: Record, diff: ApprovalWorkflowRulesDiff): Record { const result: Record = {...existingRules}; for (const [ruleID, value] of Object.entries(diff)) { @@ -1221,10 +1187,8 @@ function applyApprovalWorkflowRulesDiff(existingRules: Record return result; } -/** - * Map every submitter found in the rules to their workflow's first approver - */ +/** Map every submitter found in the rules to their workflow's first approver. */ function getRulesSubmitterToFirstApprover(rules: Record, employees: PolicyEmployeeList = {}): Record { const submitters = new Set(); for (const rule of Object.values(rules)) { @@ -1471,10 +1433,8 @@ function getRulesSubmitterToFirstApprover(rules: Record 0; const chainKey = approverChainFingerprint(chain); const fingerprint = hasRuleBasedChain ? `r|${chainKey}` : `l|${chainKey}`; diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 6f3e41a7078f..6243e463e953 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -1021,9 +1021,8 @@ function setWorkspaceApprovalMode( failureData.push(...nextStepFailureData); } - // Disabling approvals removes every approval workflow, which now lives in the `rules_` Onyx - // collection. Auth's DisablePolicyApprovals deletes those rows server-side, but we must also clear them - // optimistically so the workflows UI doesn't keep rebuilding stale workflows (e.g. after re-enabling). + // Auth's DisablePolicyApprovals deletes the policy's rule rows server-side; clear them optimistically too + // so the workflows UI doesn't keep rebuilding stale workflows (e.g. after re-enabling). if (approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL && allRules) { for (const [ruleKey, rule] of Object.entries(allRules)) { if (!rule || rule.scope !== CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY || rule.scopeID !== policyID) { diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 9013ae553a64..e35728abe9ac 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -359,9 +359,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetAppro write(WRITE_COMMANDS.SET_APPROVAL_WORKFLOW, parameters, {optimisticData, successData, failureData}); } -/** - * Create an approval workflow using the rules-based backend structure, - */ +/** Create an approval workflow using the rules-based backend structure. */ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport}: CreateApprovalWorkflowParams) { if (!policy) { return; @@ -396,9 +394,7 @@ type UpdateApprovalWorkflowRulesParams = { policy: OnyxEntry; }; -/** - * Update an existing workflow using the rules-based backend structure - */ +/** Update an existing workflow using the rules-based backend structure. */ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}: UpdateApprovalWorkflowRulesParams) { if (!policy) { return; @@ -427,9 +423,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); } -/** - * Delete an approval workflow using the rules-based backend structure, gated behind the `multipleApprovers` beta. - */ +/** Delete an approval workflow using the rules-based backend structure, gated behind the `multipleApprovers` beta. */ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry) { if (!policy) { return; From 0ea1d6a792dc887092a3085412a47d5337e562db Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 14:36:48 +0200 Subject: [PATCH 24/62] better comparison --- src/libs/WorkflowUtils.ts | 27 ++++++++++++++ src/libs/actions/Workflow.ts | 5 ++- .../approvals/ApprovalWorkflowEditor.tsx | 6 ++-- ...paceWorkflowsApprovalsExpensesFromPage.tsx | 25 +++++++++++-- ...aceWorkflowsApprovalsApprovalLimitPage.tsx | 2 +- ...orkspaceWorkflowsApprovalsApproverPage.tsx | 6 ++-- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 2 ++ src/types/onyx/ApprovalWorkflow.ts | 5 +++ tests/unit/WorkflowUtilsTest.ts | 36 +++++++++++++++++++ 9 files changed, 105 insertions(+), 9 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 1d07d1efc50a..080dec06cc43 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1431,6 +1431,31 @@ function getRulesSubmitterToFirstApprover(rules: Record, employees: PolicyEmployeeList = {}): Record { + const submitters = new Set(); + for (const rule of Object.values(rules)) { + for (const email of extractSubmitterEmails(rule)) { + submitters.add(email); + } + } + + const result: Record = {}; + for (const submitter of submitters) { + // The fingerprint ignores display/avatar fields, so personal details aren't needed here. + const chain = buildApproverChainFromRules({submitter, rules, employees, personalDetailsByEmail: {}}); + if (chain.length > 0) { + result[submitter] = approverChainFingerprint(chain); + } + } + return result; +} + /** * Beta-enabled counterpart to `convertPolicyEmployeesToApprovalWorkflows`: rebuild the same * `PolicyConversionResult` from `params.rules`, falling back to `employeeList` for any chain step the @@ -1580,6 +1605,7 @@ function convertApprovalWorkflowRulesToWorkflows({ export { applyApprovalWorkflowRulesDiff, + approverChainFingerprint, buildApprovalWorkflowRules, calculateApprovers, convertApprovalWorkflowRulesToWorkflows, @@ -1588,6 +1614,7 @@ export { getApprovalLimitDescription, getApprovalWorkflowRulesForPolicy, getRulesSubmitterToFirstApprover, + getRulesSubmitterToWorkflowKey, getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, getOverLimitForwardsToDisplayName, diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index e35728abe9ac..9e60e8679d86 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -534,10 +534,12 @@ type SelectApprovalWorkflowForEditParams = { usedApproverEmails: string[]; /** Override for the approvers list (the Edit page uses this to seed an optimistic agent). */ approvers?: Approver[]; + /** Identity anchor of the member whose workflow is being edited, preserved across sub-page back routes. */ + memberEmail?: string; }; /** Commits a workflow to onyx in EDIT mode so any sub-page can be entered directly, skipping the Edit RHP. */ -function selectApprovalWorkflowForEdit({workflow, defaultWorkflowMembers, usedApproverEmails, approvers}: SelectApprovalWorkflowForEditParams) { +function selectApprovalWorkflowForEdit({workflow, defaultWorkflowMembers, usedApproverEmails, approvers, memberEmail}: SelectApprovalWorkflowForEditParams) { setApprovalWorkflow({ ...workflow, approvers: approvers ?? workflow.approvers, @@ -546,6 +548,7 @@ function selectApprovalWorkflowForEdit({workflow, defaultWorkflowMembers, usedAp action: CONST.APPROVAL_WORKFLOW.ACTION.EDIT, errors: null, originalApprovers: workflow.approvers, + memberEmail, }); } diff --git a/src/pages/workspace/workflows/approvals/ApprovalWorkflowEditor.tsx b/src/pages/workspace/workflows/approvals/ApprovalWorkflowEditor.tsx index 9e11be550cb8..27dd3c02b128 100644 --- a/src/pages/workspace/workflows/approvals/ApprovalWorkflowEditor.tsx +++ b/src/pages/workspace/workflows/approvals/ApprovalWorkflowEditor.tsx @@ -148,13 +148,15 @@ function ApprovalWorkflowEditor({approvalWorkflow, removeApprovalWorkflow, polic // Always pass a backTo so that after editing expenses-from (including the invite-a-member detour), // we return to the page we came from. For EDIT that's the edit page; for CREATE we're on the // confirm (new) page, so return there instead of falling through to the Approver step. + // Preserve memberEmail so a fresh edit mount (e.g. after refresh) re-resolves this exact workflow + // instead of the first one sharing firstApproverEmail. const backTo = approvalWorkflow.action === CONST.APPROVAL_WORKFLOW.ACTION.EDIT - ? ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(policyID, firstApproverEmail) + ? ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(policyID, firstApproverEmail, approvalWorkflow.memberEmail) : ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_NEW.getRoute(policyID); Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROM.path, backTo)); - }, [approvalWorkflow.action, approvalWorkflow.originalApprovers, policyID]); + }, [approvalWorkflow.action, approvalWorkflow.originalApprovers, approvalWorkflow.memberEmail, policyID]); // User should be allowed to add additional approver only if they upgraded to Control Plan, otherwise redirected to the Upgrade Page const addAdditionalApprover = useCallback(() => { diff --git a/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx b/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx index 5fc32eba8734..e57884726b4e 100644 --- a/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx +++ b/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx @@ -26,7 +26,7 @@ import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import {addSMSDomainIfPhoneNumber} from '@libs/PhoneNumber'; import {canMemberWrite, getDefaultApprover, getExcludedUsers, getMemberAccountIDsForWorkspace, isPendingDeletePolicy} from '@libs/PolicyUtils'; import type {AvatarSource} from '@libs/UserAvatarUtils'; -import {getApprovalWorkflowRulesForPolicy, getRulesSubmitterToFirstApprover} from '@libs/WorkflowUtils'; +import {approverChainFingerprint, getApprovalWorkflowRulesForPolicy, getRulesSubmitterToFirstApprover, getRulesSubmitterToWorkflowKey} from '@libs/WorkflowUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import MemberRightIcon from '@pages/workspace/MemberRightIcon'; @@ -132,6 +132,18 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe return map; })(); + // Beta only: identity (full approver-chain fingerprint) of each submitter's current workflow, plus the + // identity of the workflow being edited. Comparing these — instead of just first approvers — lets us warn + // before moving a member out of a workflow that merely shares its first approver with this one. + const submitterToWorkflowKey = (() => { + if (!isMultipleApproversBetaEnabled) { + return undefined; + } + const rules = getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID); + return new Map(Object.entries(getRulesSubmitterToWorkflowKey(rules, policy?.employeeList ?? {}))); + })(); + const currentWorkflowKey = approverChainFingerprint(approvalWorkflow?.originalApprovers ?? []); + useEffect(() => { if (!approvalWorkflow?.members) { return; @@ -495,7 +507,14 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe const newMember = members.find((m) => !selectedMembers.some((s) => s.login === m.login)); const existingApproverEmail = newMember?.login ? membersInExistingWorkflows.get(newMember.login) : undefined; - if (newMember && existingApproverEmail && existingApproverEmail !== firstApprover) { + // With the beta on, compare full workflow identities so a member that submits to the same + // first approver but through a different chain is still treated as a cross-workflow move. + // Legacy has no diverging chains here, so first-approver comparison is enough. + const belongsToDifferentWorkflow = isMultipleApproversBetaEnabled + ? !!newMember?.login && !!submitterToWorkflowKey?.get(newMember.login) && submitterToWorkflowKey.get(newMember.login) !== currentWorkflowKey + : !!existingApproverEmail && existingApproverEmail !== firstApprover; + + if (newMember && existingApproverEmail && belongsToDifferentWorkflow) { const memberName = Str.removeSMSDomain(newMember.text ?? newMember.login ?? ''); const approverDetails = getPersonalDetailByEmail(existingApproverEmail); const approverName = Str.removeSMSDomain(approverDetails?.displayName ?? existingApproverEmail); @@ -526,6 +545,8 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe firstApprover, selectedMembers, membersInExistingWorkflows, + submitterToWorkflowKey, + currentWorkflowKey, showConfirmModal, translate, ], diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx index 64c101a157a9..28bb421c26e1 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx @@ -99,7 +99,7 @@ function WorkspaceWorkflowsApprovalsApprovalLimitPage({policy, isLoadingReportDa // screen carries extra seed params, so a strict param match misses it and REPLACE mounts // a fresh edit screen that re-derives the workflow from the policy — wiping the unsaved // draft (the seeded agent and any in-progress edits). POP_TO returns to the live screen. - Navigation.goBack(ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(policyID, firstApprover), {compareParams: false}); + Navigation.goBack(ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(policyID, firstApprover, approvalWorkflow?.memberEmail), {compareParams: false}); return; } // Mark that we've completed the initial wizard flow before navigating to the summary page diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx index d58de1e3e432..66714ef415d7 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx @@ -153,14 +153,14 @@ function WorkspaceWorkflowsApprovalsApproverPage({policy, personalDetails, isLoa backToRoute = createDynamicRoute(DYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROM.path, ROUTES.WORKSPACE_WORKFLOWS.getRoute(route.params.policyID)); clearApprovalWorkflowApprovers(); } else if (approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.EDIT) { - backToRoute = rhpRoutes.length > 1 ? undefined : ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(route.params.policyID, firstApprover); + backToRoute = rhpRoutes.length > 1 ? undefined : ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(route.params.policyID, firstApprover, approvalWorkflow?.memberEmail); } else { backToRoute = ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_NEW.getRoute(route.params.policyID); } // Don't compare params: the edit screen may carry "Add agent" seed params, so a strict param // match would miss it and REPLACE would mount a fresh edit screen that wipes the unsaved draft. Navigation.goBack(backToRoute, {compareParams: false}); - }, [isInitialCreationFlow, approvalWorkflow?.action, route.params.policyID, rhpRoutes.length, firstApprover]); + }, [isInitialCreationFlow, approvalWorkflow?.action, approvalWorkflow?.memberEmail, route.params.policyID, rhpRoutes.length, firstApprover]); const toggleApprover = useCallback( (approvers: SelectionListApprover[]) => { @@ -172,7 +172,7 @@ function WorkspaceWorkflowsApprovalsApproverPage({policy, personalDetails, isLoa clearApprovalWorkflowApprover({approverIndex, currentApprovalWorkflow: approvalWorkflow}); if (isChangeApproverRoute && approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.EDIT) { // Don't compare params — see goBack above. - Navigation.goBack(ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(route.params.policyID, firstApprover), {compareParams: false}); + Navigation.goBack(ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EDIT.getRoute(route.params.policyID, firstApprover, approvalWorkflow?.memberEmail), {compareParams: false}); return; } goBack(); diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index 3ab51e1801f4..fd97efc37254 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -186,6 +186,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true workflow: currentApprovalWorkflow, defaultWorkflowMembers, usedApproverEmails, + memberEmail: route.params.memberEmail, }); // Snapshot for diffing on save; runs alongside selectApprovalWorkflowForEdit above. setInitialApprovalWorkflow(currentApprovalWorkflow); @@ -197,6 +198,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true policy, route.params.policyID, route.params.firstApproverEmail, + route.params.memberEmail, approvalWorkflow?.action, approvalWorkflow?.originalApprovers, isLoadingApprovalWorkflow, diff --git a/src/types/onyx/ApprovalWorkflow.ts b/src/types/onyx/ApprovalWorkflow.ts index 3ce3ee813231..29eb6d727bfe 100644 --- a/src/types/onyx/ApprovalWorkflow.ts +++ b/src/types/onyx/ApprovalWorkflow.ts @@ -162,6 +162,11 @@ type ApprovalWorkflowOnyx = Omit & { */ originalApprovers: Approver[]; + /** + * Email of the member whose workflow this edit session belongs to. + */ + memberEmail?: string; + /** * Whether the user is in the initial creation flow */ diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 55f4b0f281f8..e9d5784a949f 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -15,6 +15,7 @@ import { getOpenConnectedToPolicyBusinessBankAccounts, getOverLimitForwardsToDisplayName, getRulesSubmitterToFirstApprover, + getRulesSubmitterToWorkflowKey, mergeWorkflowMembersWithAvailableMembers, reconcileApprovalWorkflowRulesForCreate, reconcileApprovalWorkflowRulesForEdit, @@ -1887,6 +1888,41 @@ describe('WorkflowUtils', () => { }); }); + describe('getRulesSubmitterToWorkflowKey', () => { + // Submitters 2 and 3 share the full chain 1 -> 8, while 4 shares only the first approver (1) but + // then diverges to 9. The workflow key must group 2 and 3 together and set 4 apart, so callers can + // tell a real cross-workflow move from a same-first-approver re-add. + const rules: Record = { + sub2: {triggers: submitTriggers, filters: buildFromFilter(['2@example.com']), actions: forwardActions('1@example.com')}, + app2at1: {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('1@example.com')), actions: forwardActions('8@example.com')}, + app2at8: {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('8@example.com')), actions: approveActions}, + sub3: {triggers: submitTriggers, filters: buildFromFilter(['3@example.com']), actions: forwardActions('1@example.com')}, + app3at1: {triggers: approveTriggers, filters: and(buildFromFilter(['3@example.com']), buildToFilter('1@example.com')), actions: forwardActions('8@example.com')}, + app3at8: {triggers: approveTriggers, filters: and(buildFromFilter(['3@example.com']), buildToFilter('8@example.com')), actions: approveActions}, + sub4: {triggers: submitTriggers, filters: buildFromFilter(['4@example.com']), actions: forwardActions('1@example.com')}, + app4at1: {triggers: approveTriggers, filters: and(buildFromFilter(['4@example.com']), buildToFilter('1@example.com')), actions: forwardActions('9@example.com')}, + app4at9: {triggers: approveTriggers, filters: and(buildFromFilter(['4@example.com']), buildToFilter('9@example.com')), actions: approveActions}, + }; + + it('Should give submitters with identical chains the same key', () => { + const keys = getRulesSubmitterToWorkflowKey(rules); + + expect(keys['2@example.com']).toBe(keys['3@example.com']); + }); + + it('Should give submitters that share a first approver but diverge later different keys', () => { + const keys = getRulesSubmitterToWorkflowKey(rules); + + // All three route to approver 1 first, so first-approver alone cannot distinguish them. + expect(getRulesSubmitterToFirstApprover(rules)).toEqual({ + '2@example.com': '1@example.com', + '3@example.com': '1@example.com', + '4@example.com': '1@example.com', + }); + expect(keys['4@example.com']).not.toBe(keys['2@example.com']); + }); + }); + describe('convertApprovalWorkflowRulesToWorkflows', () => { const createPolicy = (employees: PolicyEmployeeList, defaultApprover: string) => ({ From d28316ff60db390f181c5d4dabbcc0a2bdbb2709 Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 15:18:58 +0200 Subject: [PATCH 25/62] general cleanup --- src/libs/WorkflowUtils.ts | 22 ++--- src/libs/actions/Policy/Policy.ts | 7 +- src/libs/actions/Workflow.ts | 4 +- .../workflows/WorkspaceWorkflowsPage.tsx | 4 +- ...paceWorkflowsApprovalsExpensesFromPage.tsx | 13 +-- src/types/onyx/ApprovalWorkflowRules.ts | 7 -- tests/actions/WorkflowTest.ts | 96 +++++++------------ tests/unit/WorkflowUtilsTest.ts | 13 ++- 8 files changed, 63 insertions(+), 103 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 080dec06cc43..653575b28b19 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -740,7 +740,6 @@ function mergeWorkflowMembersWithAvailableMembers(workflowMembers: Member[], all type ApprovalWorkflowRulesDiff = Record; -/** Build a comparison filter: ` `. */ function buildComparison( operator: ValueOf, left: ApprovalWorkflowFilterComparison['left'], @@ -749,39 +748,37 @@ function buildComparison( return {operator, left, right}; } -/** Combine two filter nodes with a boolean `AND`. */ function buildAnd(left: ApprovalWorkflowFilter['left'], right: ApprovalWorkflowFilter['right']): ApprovalWorkflowFilter { return {operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left, right}; } -/** Build the `from = [emails]` filter used by every approval-workflow rule. Kept at the top-level left of the tree. */ function buildSubmitterFilter(memberEmails: string[]): ApprovalWorkflowFilterComparison { return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, [...memberEmails]); } -/** Build the `to = email` filter that matches the approver who just approved the report. */ function buildToComparison(email: string): ApprovalWorkflowFilterComparison { return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, email); } -/** A rule that fires when a report is submitted. */ +/** The index-keyed object shape the rules API uses for lists (`['a', 'b'] -> {'0': 'a', '1': 'b'}`). */ +function toIndexMap(values: T[]): Record { + return Object.fromEntries(values.map((value, index) => [String(index), value])); +} + function buildSubmitTriggers(): ApprovalWorkflowTriggers { - return {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}; + return toIndexMap([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT]); } -/** A rule that fires when a report is approved. */ function buildApproveTriggers(): ApprovalWorkflowTriggers { - return {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}; + return toIndexMap([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE]); } -/** Forward the report to `approver`. */ function buildForwardActions(approver: string): ApprovalWorkflowActions { - return {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}}; + return toIndexMap([{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}]); } -/** Approve (finalize) the report. */ function buildApproveActions(): ApprovalWorkflowActions { - return {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}; + return toIndexMap([{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}]); } /** @@ -1611,6 +1608,7 @@ export { convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, convertApprovalWorkflowToPolicyEmployees, + extractSubmitterEmails, getApprovalLimitDescription, getApprovalWorkflowRulesForPolicy, getRulesSubmitterToFirstApprover, diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 6243e463e953..a7803b645de5 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -320,7 +320,7 @@ Onyx.connect({ }); let allRules: OnyxCollection; -Onyx.connect({ +Onyx.connectWithoutView({ key: ONYXKEYS.COLLECTION.RULE, waitForCollectionCallback: true, callback: (val) => (allRules = val), @@ -1028,8 +1028,9 @@ function setWorkspaceApprovalMode( if (!rule || rule.scope !== CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY || rule.scopeID !== policyID) { continue; } - optimisticData.push({onyxMethod: Onyx.METHOD.SET, key: ruleKey as `${typeof ONYXKEYS.COLLECTION.RULE}${string}`, value: null}); - failureData.push({onyxMethod: Onyx.METHOD.SET, key: ruleKey as `${typeof ONYXKEYS.COLLECTION.RULE}${string}`, value: rule}); + const ruleOnyxKey: `${typeof ONYXKEYS.COLLECTION.RULE}${string}` = `${ONYXKEYS.COLLECTION.RULE}${ruleKey.slice(ONYXKEYS.COLLECTION.RULE.length)}`; + optimisticData.push({onyxMethod: Onyx.METHOD.SET, key: ruleOnyxKey, value: null}); + failureData.push({onyxMethod: Onyx.METHOD.SET, key: ruleOnyxKey, value: rule}); } } diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 9e60e8679d86..41c790d41d09 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -37,7 +37,7 @@ import {completeTask} from './Task'; /** Cache of every approval-workflow rule (`ONYXKEYS.COLLECTION.RULE`) so actions can read the current rule set. */ let allRules: OnyxCollection = {}; -Onyx.connect({ +Onyx.connectWithoutView({ key: ONYXKEYS.COLLECTION.RULE, waitForCollectionCallback: true, callback: (value) => { @@ -423,7 +423,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); } -/** Delete an approval workflow using the rules-based backend structure, gated behind the `multipleApprovers` beta. */ +/** Delete an approval workflow using the rules-based backend structure. */ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry) { if (!policy) { return; diff --git a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx index 568979141e6e..752764166d98 100644 --- a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx +++ b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx @@ -570,8 +570,8 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { /> {displayedWorkflows.map((workflow) => { const firstApproverEmail = workflow.approvers.at(0)?.email ?? ''; - // A workflow's first approver isn't unique once rule-based chains diverge, but a member - // belongs to exactly one workflow + // The first approver isn't unique once rule-based chains diverge, so anchor the key/edit route + // on a member too (each member belongs to exactly one workflow). const firstMemberEmail = workflow.members.at(0)?.email ?? ''; return ( diff --git a/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx b/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx index e57884726b4e..d59d3c151cfe 100644 --- a/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx +++ b/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx @@ -107,13 +107,14 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe const isCreateAction = approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.CREATE; const policyMemberEmailsToAccountIDs = getMemberAccountIDsForWorkspace(policy?.employeeList); + const policyRules = isMultipleApproversBetaEnabled ? getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID) : {}; + // Build a map of member emails to their existing workflow's first approver. With the beta on this // is derived from the `ONYXKEYS.COLLECTION.RULE` rules; otherwise it falls back to the legacy // employeeList `submitsTo` (non-default workflows only). const membersInExistingWorkflows = (() => { if (isMultipleApproversBetaEnabled) { - const rules = getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID); - return new Map(Object.entries(getRulesSubmitterToFirstApprover(rules, policy?.employeeList ?? {}))); + return new Map(Object.entries(getRulesSubmitterToFirstApprover(policyRules, policy?.employeeList ?? {}))); } const employees = policy?.employeeList ?? {}; @@ -135,13 +136,7 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe // Beta only: identity (full approver-chain fingerprint) of each submitter's current workflow, plus the // identity of the workflow being edited. Comparing these — instead of just first approvers — lets us warn // before moving a member out of a workflow that merely shares its first approver with this one. - const submitterToWorkflowKey = (() => { - if (!isMultipleApproversBetaEnabled) { - return undefined; - } - const rules = getApprovalWorkflowRulesForPolicy(rulesCollection, route.params.policyID); - return new Map(Object.entries(getRulesSubmitterToWorkflowKey(rules, policy?.employeeList ?? {}))); - })(); + const submitterToWorkflowKey = isMultipleApproversBetaEnabled ? new Map(Object.entries(getRulesSubmitterToWorkflowKey(policyRules, policy?.employeeList ?? {}))) : undefined; const currentWorkflowKey = approverChainFingerprint(approvalWorkflow?.originalApprovers ?? []); useEffect(() => { diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 6d1883ad3981..838baabb4163 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -91,12 +91,6 @@ type ApprovalWorkflowRule = { actions: ApprovalWorkflowActions; }; -/** - * Map of approval-workflow rule bodies keyed by ruleID. Used as the in-memory working shape by the - * rules builder/reconcilers; on disk each rule lives under its own `ONYXKEYS.COLLECTION.RULE` key. - */ -type ApprovalWorkflowRules = Record; - export type { ApprovalWorkflowAction, ApprovalWorkflowActionName, @@ -105,7 +99,6 @@ export type { ApprovalWorkflowFilterComparison, ApprovalWorkflowFilterOperand, ApprovalWorkflowRule, - ApprovalWorkflowRules, ApprovalWorkflowTrigger, ApprovalWorkflowTriggers, }; diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 941120118eb4..15f84ba0bde1 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -14,7 +14,7 @@ import { updateApprovalWorkflow, updateApprovalWorkflowRules, } from '@src/libs/actions/Workflow'; -import {calculateApprovers} from '@src/libs/WorkflowUtils'; +import {calculateApprovers, extractSubmitterEmails} from '@src/libs/WorkflowUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ApprovalWorkflowOnyx, PersonalDetailsList, Policy, Policy as PolicyType, Report} from '@src/types/onyx'; import type {Approver} from '@src/types/onyx/ApprovalWorkflow'; @@ -74,6 +74,33 @@ async function getActivePolicyRules(policyID: string): Promise { ); } +/** Build the index-keyed object shape the rules API uses for lists (`['a'] -> {'0': 'a'}`). */ +function indexMap(...values: T[]): Record { + return Object.fromEntries(values.map((value, index) => [String(index), value])); +} + +/** Seed the two rules (submit -> forward, approve -> finalize) that describe a `submitters -> approver` workflow. */ +async function seedForwardApproveRules(policyID: string, submitters: string[], approver: string) { + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: indexMap(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT), + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: submitters}, + actions: indexMap({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}), + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { + scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scopeID: policyID, + triggers: indexMap(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE), + filters: { + operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, + left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: submitters}, + right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: approver}, + }, + actions: indexMap({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}), + }); +} + describe('actions/Workflow', () => { function getApprovalWorkflowState(): Promise { return new Promise((resolve) => { @@ -931,24 +958,7 @@ describe('actions/Workflow', () => { }; // Existing workflow: employee1 (A) and employee2 (B) submit to owner (C). - await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, - scopeID: policyID, - triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}, - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email, employee2Email]}, - actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}}, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, - scopeID: policyID, - triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}, - filters: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email, employee2Email]}, - right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: ownerEmail}, - }, - actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}, - }); + await seedForwardApproveRules(policyID, [employee1Email, employee2Email], ownerEmail); // New workflow: employee3 (D) submits to owner (C) — same chain as the existing workflow. const approvalWorkflow = { @@ -972,10 +982,7 @@ describe('actions/Workflow', () => { // D should be folded into the two existing rules, not create a third/fourth rule. expect(rules).toHaveLength(2); for (const rule of rules) { - const fromLeaf = Object.values(rule.actions).some((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO) - ? rule.filters - : (rule.filters as {left: unknown}).left; - expect((fromLeaf as {right: string[]}).right).toEqual([employee1Email, employee2Email, employee3Email]); + expect(extractSubmitterEmails(rule)).toEqual([employee1Email, employee2Email, employee3Email]); } await mockFetch.resume(); @@ -1031,10 +1038,7 @@ describe('actions/Workflow', () => { // Still only two rules, each now listing all three submitters. expect(rulesAfterSecond).toHaveLength(2); for (const rule of rulesAfterSecond) { - const fromLeaf = Object.values(rule.actions).some((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO) - ? rule.filters - : (rule.filters as {left: unknown}).left; - expect((fromLeaf as {right: string[]}).right).toEqual([employee1Email, employee2Email, employee3Email]); + expect(extractSubmitterEmails(rule)).toEqual([employee1Email, employee2Email, employee3Email]); } await mockFetch.resume(); @@ -1055,24 +1059,7 @@ describe('actions/Workflow', () => { }; // Seed the existing [employee1] → [owner] workflow as rules in the collection. - await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, - scopeID: policyID, - triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}, - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, - actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}}, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, - scopeID: policyID, - triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}, - filters: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, - right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: ownerEmail}, - }, - actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}, - }); + await seedForwardApproveRules(policyID, [employee1Email], ownerEmail); const initialApprovalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], @@ -1122,24 +1109,7 @@ describe('actions/Workflow', () => { }; // Seed the existing [employee1] → [owner] workflow as rules in the collection. - await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, - scopeID: policyID, - triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}, - filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, - actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}}, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, - scopeID: policyID, - triggers: {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}, - filters: { - operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, - left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}, - right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: ownerEmail}, - }, - actions: {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}, - }); + await seedForwardApproveRules(policyID, [employee1Email], ownerEmail); const approvalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index e9d5784a949f..1ba3f56433cf 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -10,6 +10,7 @@ import { convertApprovalWorkflowRulesToWorkflows, convertApprovalWorkflowToPolicyEmployees, convertPolicyEmployeesToApprovalWorkflows, + extractSubmitterEmails, getApprovalLimitDescription, getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, @@ -1694,6 +1695,8 @@ describe('WorkflowUtils', () => { right, }); const keyRules = (rules: ApprovalWorkflowRule[]): Record => Object.fromEntries(rules.map((rule, index) => [`rule${index}`, rule])); + // Present a list as the array-shaped value the API returns for `triggers`/`actions` (PHP decodes index maps to arrays). + const asServerShape = (value: unknown[]): T => value as unknown as T; describe('buildApprovalWorkflowRules', () => { it('Should return an empty list when there are no members', () => { @@ -1793,14 +1796,14 @@ describe('WorkflowUtils', () => { // new submitter folds into the existing rule instead of minting a fresh pair. const existingRules: Record = { r1: { - actions: [{approver: '1@example.com', name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO}] as unknown as ApprovalWorkflowRule['actions'], + actions: asServerShape([{approver: '1@example.com', name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO}]), filters: buildFromFilter(['20@example.com']), - triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT] as unknown as ApprovalWorkflowRule['triggers'], + triggers: asServerShape([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT]), }, r2: { - actions: [{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}] as unknown as ApprovalWorkflowRule['actions'], + actions: asServerShape([{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}]), filters: and(buildFromFilter(['20@example.com']), buildToFilter('1@example.com')), - triggers: [CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE] as unknown as ApprovalWorkflowRule['triggers'], + triggers: asServerShape([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE]), }, }; const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); @@ -1808,7 +1811,7 @@ describe('WorkflowUtils', () => { // Folds into the two existing rules (r1/r2) instead of creating fresh IDs, and appends the submitter. expect(Object.keys(diff).sort()).toEqual(['r1', 'r2']); - expect((diff.r1?.filters as {right: string[]}).right).toEqual(['20@example.com', '10@example.com']); + expect(diff.r1 ? extractSubmitterEmails(diff.r1) : []).toEqual(['20@example.com', '10@example.com']); }); }); From 3d449edb4977e6caa6f04e77fc1eff9d74a9aba4 Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 15:33:24 +0200 Subject: [PATCH 26/62] renaming --- .../{ApprovalWorkflowParams.ts => SetApprovalWorkflowParams.ts} | 0 src/libs/API/parameters/index.ts | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename src/libs/API/parameters/{ApprovalWorkflowParams.ts => SetApprovalWorkflowParams.ts} (100%) diff --git a/src/libs/API/parameters/ApprovalWorkflowParams.ts b/src/libs/API/parameters/SetApprovalWorkflowParams.ts similarity index 100% rename from src/libs/API/parameters/ApprovalWorkflowParams.ts rename to src/libs/API/parameters/SetApprovalWorkflowParams.ts diff --git a/src/libs/API/parameters/index.ts b/src/libs/API/parameters/index.ts index 66a5c6194c1a..314877754206 100644 --- a/src/libs/API/parameters/index.ts +++ b/src/libs/API/parameters/index.ts @@ -546,7 +546,7 @@ export type {default as DeleteDomainParams} from './DeleteDomainParams'; export type {default as GetDuplicateTransactionDetailsParams} from './GetDuplicateTransactionDetailsParams'; export type {default as SetPolicyCategoryReceiptsAndItemizedReceiptRequiredParams} from './SetPolicyCategoryReceiptsAndItemizedReceiptRequiredParams'; export type {default as SetPolicyCodingRuleParams} from './SetPolicyCodingRuleParams'; -export type {default as SetApprovalWorkflowParams} from './ApprovalWorkflowParams'; +export type {default as SetApprovalWorkflowParams} from './SetApprovalWorkflowParams'; export type {default as RegisterAuthenticationKeyParams} from './RegisterAuthenticationKeyParams'; export type {default as RevokeMultifactorAuthenticationCredentialsParams} from './RevokeMultifactorAuthenticationCredentialsParams'; export type {default as TroubleshootMultifactorAuthenticationParams} from './TroubleshootMultifactorAuthenticationParams'; From ea1de108ca2e11018399bdf999329073baa99fbb Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 15:40:35 +0200 Subject: [PATCH 27/62] small refactor --- src/libs/WorkflowUtils.ts | 7 ++++++- src/libs/actions/Workflow.ts | 9 +++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 653575b28b19..9f8ce6820260 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -786,8 +786,12 @@ function buildApproveActions(): ApprovalWorkflowActions { * reports to the first approver, plus a `ReportApprove` rule per approver describing the next hop * (forward to the next approver, approve if last, or split on the approver's over-limit target). */ +function getWorkflowMemberEmails(members: Member[]): string[] { + return members.map((member) => member.email).filter((email): email is string => !!email); +} + function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): ApprovalWorkflowRule[] { - const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const memberEmails = getWorkflowMemberEmails(approvalWorkflow.members); const approvers = approvalWorkflow.approvers; if (memberEmails.length === 0 || approvers.length === 0) { @@ -1613,6 +1617,7 @@ export { getApprovalWorkflowRulesForPolicy, getRulesSubmitterToFirstApprover, getRulesSubmitterToWorkflowKey, + getWorkflowMemberEmails, getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, getOverLimitForwardsToDisplayName, diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 41c790d41d09..00d4d59b722d 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -11,6 +11,7 @@ import { convertApprovalWorkflowToPolicyEmployees, getApprovalWorkflowRulesForPolicy, getOverLimitForwardsToDisplayName, + getWorkflowMemberEmails, mergeWorkflowMembersWithAvailableMembers, reconcileApprovalWorkflowRulesForCreate, reconcileApprovalWorkflowRulesForEdit, @@ -366,7 +367,7 @@ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprov } const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); - const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const memberEmails = getWorkflowMemberEmails(approvalWorkflow.members); // A submitter can only belong to one workflow, so first drop these members from any OTHER // workflow's rules, then add them to the new workflow. @@ -401,8 +402,8 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, } const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); - const previousMemberEmails = initialApprovalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); - const newMemberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const previousMemberEmails = getWorkflowMemberEmails(initialApprovalWorkflow.members); + const newMemberEmails = getWorkflowMemberEmails(approvalWorkflow.members); // 1. A submitter can only belong to one workflow, so drop joining members (those not previously in // this workflow) from any OTHER workflow's rules first. @@ -430,7 +431,7 @@ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: } const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); - const memberEmails = approvalWorkflow.members.map((member) => member.email).filter((email): email is string => !!email); + const memberEmails = getWorkflowMemberEmails(approvalWorkflow.members); const rulesDiff = reconcileApprovalWorkflowRulesForRemove(memberEmails, {existingRules}); setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); From f879ada7b797c9796fe26110f60c6a9d0561a5f7 Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 16:01:24 +0200 Subject: [PATCH 28/62] Add missing file --- src/types/onyx/Rule.ts | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/types/onyx/Rule.ts diff --git a/src/types/onyx/Rule.ts b/src/types/onyx/Rule.ts new file mode 100644 index 000000000000..65a7e8c0d9ab --- /dev/null +++ b/src/types/onyx/Rule.ts @@ -0,0 +1,39 @@ +import type CONST from '@src/CONST'; + +import type {ValueOf} from 'type-fest'; + +import type {ApprovalWorkflowRule} from './ApprovalWorkflowRules'; +import type {Errors, OnyxValueWithOfflineFeedback} from './OnyxCommon'; + +/** The kind of entity a rule is scoped to (currently only workspace policies). */ +type RuleScope = ValueOf; + +/** + * A rule as stored in the `ONYXKEYS.COLLECTION.RULE` collection under `rules_`. This mirrors a + * row of the server `rules` table: the AST rule body (`triggers`/`filters`/`actions`) plus the + * `scope`/`scopeID` that associate it with an entity (a policy, for approval workflows). + * + * The same collection is intended to hold every kind of AST rule in the future, not just approval + * workflows. + */ +type Rule = OnyxValueWithOfflineFeedback< + ApprovalWorkflowRule & { + /** What kind of entity this rule is scoped to. */ + scope: RuleScope; + + /** ID of the scoped entity (the policyID for `policy`-scoped rules). */ + scopeID: string; + + /** ISO timestamp of when the rule was created. */ + created?: string; + + /** Errors from the latest failed write of this rule. */ + errors?: Errors; + } +>; + +/** A collection of rules keyed by their `ONYXKEYS.COLLECTION.RULE` key (`rules_`). */ +type RuleCollection = Record; + +export default Rule; +export type {RuleCollection, RuleScope}; From 9c651e0d9b6fa114c5ac1b50f68e86c4520c45e2 Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 16:10:50 +0200 Subject: [PATCH 29/62] knip --- src/types/onyx/ApprovalWorkflowRules.ts | 12 +----------- src/types/onyx/Rule.ts | 4 ---- src/types/onyx/index.ts | 2 -- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 838baabb4163..2f78e569e315 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -91,14 +91,4 @@ type ApprovalWorkflowRule = { actions: ApprovalWorkflowActions; }; -export type { - ApprovalWorkflowAction, - ApprovalWorkflowActionName, - ApprovalWorkflowActions, - ApprovalWorkflowFilter, - ApprovalWorkflowFilterComparison, - ApprovalWorkflowFilterOperand, - ApprovalWorkflowRule, - ApprovalWorkflowTrigger, - ApprovalWorkflowTriggers, -}; +export type {ApprovalWorkflowAction, ApprovalWorkflowActions, ApprovalWorkflowFilter, ApprovalWorkflowFilterComparison, ApprovalWorkflowRule, ApprovalWorkflowTriggers}; diff --git a/src/types/onyx/Rule.ts b/src/types/onyx/Rule.ts index 65a7e8c0d9ab..e49d8c58e8ce 100644 --- a/src/types/onyx/Rule.ts +++ b/src/types/onyx/Rule.ts @@ -32,8 +32,4 @@ type Rule = OnyxValueWithOfflineFeedback< } >; -/** A collection of rules keyed by their `ONYXKEYS.COLLECTION.RULE` key (`rules_`). */ -type RuleCollection = Record; - export default Rule; -export type {RuleCollection, RuleScope}; diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index b1e055cad4a0..a05252052bb3 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -161,7 +161,6 @@ import type {AnyRequest} from './Request'; import type Response from './Response'; import type ReviewDuplicates from './ReviewDuplicates'; import type Rule from './Rule'; -import type {RuleCollection} from './Rule'; import type {SavedCSVColumnLayoutData, SavedCSVColumnLayoutList} from './SavedCSVColumnLayout'; import type {SaveSearch} from './SaveSearch'; import type ScheduleCallDraft from './ScheduleCallDraft'; @@ -310,7 +309,6 @@ export type { ReimbursementAccount, Report, Rule, - RuleCollection, ReportNameValuePairs, ReportAction, ReportActionReactions, From ee13b8cfc193ebfb4a256c5171b97b3c6ce3a3a1 Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 15 Jul 2026 16:37:26 +0200 Subject: [PATCH 30/62] fix test --- src/libs/ExportOnyxState/common.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libs/ExportOnyxState/common.ts b/src/libs/ExportOnyxState/common.ts index cf4ad366f553..84fe0d63841a 100644 --- a/src/libs/ExportOnyxState/common.ts +++ b/src/libs/ExportOnyxState/common.ts @@ -334,6 +334,7 @@ const onyxKeysToMaskFragileData = new Set([ ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING, + ONYXKEYS.COLLECTION.RULE, ONYXKEYS.COLLECTION.SAML_METADATA, ONYXKEYS.COLLECTION.SECURITY_GROUP, ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT, From d9602ca2458276f79871cee747a1857344d9f526 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 16 Jul 2026 00:14:55 +0200 Subject: [PATCH 31/62] we gotta do this --- config/eslint/eslint.seatbelt.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index bb50cfc8063d..26debce198be 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -2147,7 +2147,7 @@ "../../tests/unit/VideoRendererTest.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../tests/unit/ViolationUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 20 "../../tests/unit/WhisperContentMentionContextTest.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 -"../../tests/unit/WorkflowUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 7 +"../../tests/unit/WorkflowUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 8 "../../tests/unit/WorkspaceReportFieldUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../tests/unit/WorkspacesSettingsUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 23 "../../tests/unit/awaitStagingDeploysTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 3 From 51d0af1fe98cb7898632922110fbc6b54447899d Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 16 Jul 2026 00:49:36 +0200 Subject: [PATCH 32/62] new rules project --- src/CONST/index.ts | 27 ++++++++++++++----------- src/libs/WorkflowUtils.ts | 18 ++++++++--------- src/libs/actions/Policy/Policy.ts | 2 +- src/libs/actions/Workflow.ts | 4 ++-- src/types/onyx/ApprovalWorkflowRules.ts | 4 ++-- src/types/onyx/Rule.ts | 2 +- tests/actions/WorkflowTest.ts | 27 ++++++++++++------------- tests/unit/WorkflowUtilsTest.ts | 16 +++++++-------- 8 files changed, 51 insertions(+), 49 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index e2d90540fe33..ca828c7cf41a 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -7799,21 +7799,24 @@ const CONST = { }, }, - /** Vocabulary for the AST-based approval-workflow rules stored in the `rules` table / `ONYXKEYS.COLLECTION.RULE`. */ - APPROVAL_WORKFLOW_RULE: { - /** The kind of entity a rule is scoped to. Currently only workspace policies. */ + /** Vocabulary for the AST-based rules stored in the `rules` table / `ONYXKEYS.COLLECTION.RULE`. */ + RULES: { + /** The kind of entity a rule is scoped to. Currently only workspace policies. Shared across all rule types. */ SCOPE: { POLICY: 'policy', }, - /** The report lifecycle event that fires a rule. */ - TRIGGER: { - REPORT_SUBMIT: 'ReportSubmit', - REPORT_APPROVE: 'ReportApprove', - }, - /** The action taken when a rule matches. */ - ACTION: { - FORWARD_TO: 'ForwardTo', - APPROVE_REPORT: 'ApproveReport', + /** Vocabulary specific to approval-workflow rules. */ + APPROVAL_WORKFLOW: { + /** The report lifecycle event that fires a rule. */ + TRIGGER: { + REPORT_SUBMIT: 'ReportSubmit', + REPORT_APPROVE: 'ReportApprove', + }, + /** The action taken when a rule matches. */ + ACTION: { + FORWARD_TO: 'ForwardTo', + APPROVE_REPORT: 'ApproveReport', + }, }, }, diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 9f8ce6820260..b978f5fcc897 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -766,19 +766,19 @@ function toIndexMap(values: T[]): Record { } function buildSubmitTriggers(): ApprovalWorkflowTriggers { - return toIndexMap([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT]); + return toIndexMap([CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT]); } function buildApproveTriggers(): ApprovalWorkflowTriggers { - return toIndexMap([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE]); + return toIndexMap([CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE]); } function buildForwardActions(approver: string): ApprovalWorkflowActions { - return toIndexMap([{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}]); + return toIndexMap([{name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO, approver}]); } function buildApproveActions(): ApprovalWorkflowActions { - return toIndexMap([{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}]); + return toIndexMap([{name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT}]); } /** @@ -1207,7 +1207,7 @@ function findComparisonByLeft(node: ApprovalWorkflowFilter | ApprovalWorkflowFil } /** The triggers of a rule as a flat list. */ -function getRuleTriggers(rule: ApprovalWorkflowRule): Array> { +function getRuleTriggers(rule: ApprovalWorkflowRule): Array> { return Object.values(rule.triggers ?? {}); } @@ -1218,17 +1218,17 @@ function getRuleActions(rule: ApprovalWorkflowRule): ApprovalWorkflowAction[] { /** True when the rule fires on report submission. */ function isSubmitRule(rule: ApprovalWorkflowRule): boolean { - return getRuleTriggers(rule).includes(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT); + return getRuleTriggers(rule).includes(CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT); } /** True when the rule approves (finalizes) the report. */ function isApproveReportRule(rule: ApprovalWorkflowRule): boolean { - return getRuleActions(rule).some((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT); + return getRuleActions(rule).some((action) => action.name === CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT); } /** The approver a `ForwardTo` rule routes to, if any. */ function getForwardApprover(rule: ApprovalWorkflowRule): string | undefined { - return getRuleActions(rule).find((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO)?.approver; + return getRuleActions(rule).find((action) => action.name === CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO)?.approver; } /** @@ -1400,7 +1400,7 @@ function getApprovalWorkflowRulesForPolicy(rulesCollection: OnyxCollection } for (const [onyxKey, rule] of Object.entries(rulesCollection)) { - if (!rule || rule.scope !== CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY || rule.scopeID !== policyID) { + if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { continue; } if (rule.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index a7803b645de5..337dd14e3236 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -1025,7 +1025,7 @@ function setWorkspaceApprovalMode( // so the workflows UI doesn't keep rebuilding stale workflows (e.g. after re-enabling). if (approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL && allRules) { for (const [ruleKey, rule] of Object.entries(allRules)) { - if (!rule || rule.scope !== CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY || rule.scopeID !== policyID) { + if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { continue; } const ruleOnyxKey: `${typeof ONYXKEYS.COLLECTION.RULE}${string}` = `${ONYXKEYS.COLLECTION.RULE}${ruleKey.slice(ONYXKEYS.COLLECTION.RULE.length)}`; diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 00d4d59b722d..3153421e9487 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -332,7 +332,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetAppro ? { onyxMethod: Onyx.METHOD.SET, key: ruleKey, - value: {...previousRule, scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, scopeID: policyID, pendingAction: null, errors: genericError}, + value: {...previousRule, scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, pendingAction: null, errors: genericError}, } : {onyxMethod: Onyx.METHOD.SET, key: ruleKey, value: null}; @@ -346,7 +346,7 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetAppro optimisticData.push({ onyxMethod: Onyx.METHOD.SET, key: ruleKey, - value: {...rule, scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, scopeID: policyID, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, errors: null}, + value: {...rule, scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, errors: null}, }); successData.push({onyxMethod: Onyx.METHOD.MERGE, key: ruleKey, value: {pendingAction: null}}); failureData.push(restore); diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 2f78e569e315..bd99b259e426 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -5,7 +5,7 @@ import type {ValueOf} from 'type-fest'; /** * A report lifecycle event that can fire an approval-workflow rule (`ReportSubmit` or `ReportApprove`). */ -type ApprovalWorkflowTrigger = ValueOf; +type ApprovalWorkflowTrigger = ValueOf; /** * The triggers of a rule, keyed by a string index (e.g. `{"0": "ReportSubmit"}`). A rule fires when @@ -16,7 +16,7 @@ type ApprovalWorkflowTriggers = Record; /** * The name of the action a rule performs when it matches (`ForwardTo` or `ApproveReport`). */ -type ApprovalWorkflowActionName = ValueOf; +type ApprovalWorkflowActionName = ValueOf; /** * A single action a rule performs when it matches. diff --git a/src/types/onyx/Rule.ts b/src/types/onyx/Rule.ts index e49d8c58e8ce..5348ecdcecd7 100644 --- a/src/types/onyx/Rule.ts +++ b/src/types/onyx/Rule.ts @@ -6,7 +6,7 @@ import type {ApprovalWorkflowRule} from './ApprovalWorkflowRules'; import type {Errors, OnyxValueWithOfflineFeedback} from './OnyxCommon'; /** The kind of entity a rule is scoped to (currently only workspace policies). */ -type RuleScope = ValueOf; +type RuleScope = ValueOf; /** * A rule as stored in the `ONYXKEYS.COLLECTION.RULE` collection under `rules_`. This mirrors a diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 15f84ba0bde1..660291d5dc18 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -69,8 +69,7 @@ async function getActivePolicyRules(policyID: string): Promise { }, }); return Object.values(collection).filter( - (rule): rule is Rule => - !!rule && rule.scope === CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY && rule.scopeID === policyID && rule.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + (rule): rule is Rule => !!rule && rule.scope === CONST.RULES.SCOPE.POLICY && rule.scopeID === policyID && rule.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, ); } @@ -82,22 +81,22 @@ function indexMap(...values: T[]): Record { /** Seed the two rules (submit -> forward, approve -> finalize) that describe a `submitters -> approver` workflow. */ async function seedForwardApproveRules(policyID: string, submitters: string[], approver: string) { await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, - triggers: indexMap(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT), + triggers: indexMap(CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT), filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: submitters}, - actions: indexMap({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}), + actions: indexMap({name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO, approver}), }); await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule2`, { - scope: CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY, + scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, - triggers: indexMap(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE), + triggers: indexMap(CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE), filters: { operator: CONST.SEARCH.SYNTAX_OPERATORS.AND, left: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: submitters}, right: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: approver}, }, - actions: indexMap({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}), + actions: indexMap({name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT}), }); } @@ -933,14 +932,14 @@ describe('actions/Workflow', () => { const rules = await getActivePolicyRules(policyID); expect(rules).toHaveLength(2); - const submitRule = rules.find((rule) => Object.values(rule.triggers).includes(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT)); - expect(submitRule?.scope).toBe(CONST.APPROVAL_WORKFLOW_RULE.SCOPE.POLICY); + const submitRule = rules.find((rule) => Object.values(rule.triggers).includes(CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT)); + expect(submitRule?.scope).toBe(CONST.RULES.SCOPE.POLICY); expect(submitRule?.scopeID).toBe(policyID); expect(submitRule?.filters).toEqual({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: [employee1Email]}); - expect(submitRule?.actions[0]).toEqual({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver: ownerEmail}); + expect(submitRule?.actions[0]).toEqual({name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO, approver: ownerEmail}); - const approveRule = rules.find((rule) => Object.values(rule.triggers).includes(CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE)); - expect(approveRule?.actions[0]).toEqual({name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}); + const approveRule = rules.find((rule) => Object.values(rule.triggers).includes(CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE)); + expect(approveRule?.actions[0]).toEqual({name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT}); await mockFetch.resume(); await waitForBatchedUpdates(); @@ -1086,7 +1085,7 @@ describe('actions/Workflow', () => { const rules = await getActivePolicyRules(policyID); const forwardApprovers = rules .flatMap((rule) => Object.values(rule.actions)) - .filter((action) => action.name === CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO) + .filter((action) => action.name === CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO) .map((action) => action.approver); expect(forwardApprovers).toContain(employee2Email); expect(forwardApprovers).not.toContain(ownerEmail); diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 1ba3f56433cf..dce956aa8309 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1683,10 +1683,10 @@ describe('WorkflowUtils', () => { }); describe('rule-based approval workflows', () => { - const submitTriggers = {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT}; - const approveTriggers = {'0': CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE}; - const forwardActions = (approver: string) => ({'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO, approver}}); - const approveActions = {'0': {name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}}; + const submitTriggers = {'0': CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT}; + const approveTriggers = {'0': CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE}; + const forwardActions = (approver: string) => ({'0': {name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO, approver}}); + const approveActions = {'0': {name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT}}; const buildFromFilter = (emails: string[]) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: emails}); const buildToFilter = (email: string) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, right: email}); const and = (left: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison, right: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter => ({ @@ -1796,14 +1796,14 @@ describe('WorkflowUtils', () => { // new submitter folds into the existing rule instead of minting a fresh pair. const existingRules: Record = { r1: { - actions: asServerShape([{approver: '1@example.com', name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.FORWARD_TO}]), + actions: asServerShape([{approver: '1@example.com', name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO}]), filters: buildFromFilter(['20@example.com']), - triggers: asServerShape([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_SUBMIT]), + triggers: asServerShape([CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT]), }, r2: { - actions: asServerShape([{name: CONST.APPROVAL_WORKFLOW_RULE.ACTION.APPROVE_REPORT}]), + actions: asServerShape([{name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT}]), filters: and(buildFromFilter(['20@example.com']), buildToFilter('1@example.com')), - triggers: asServerShape([CONST.APPROVAL_WORKFLOW_RULE.TRIGGER.REPORT_APPROVE]), + triggers: asServerShape([CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE]), }, }; const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); From dfa0c1c966ee1622317ea455facd48e07fc327ef Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 16 Jul 2026 01:22:00 +0200 Subject: [PATCH 33/62] rule handling fix --- src/libs/actions/Policy/Policy.ts | 12 ++---- src/libs/actions/Workflow.ts | 27 ++++++------- .../workflows/WorkspaceWorkflowsPage.tsx | 39 +++++++++++++------ .../WorkspaceWorkflowsApprovalsCreatePage.tsx | 5 ++- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 4 +- tests/actions/WorkflowTest.ts | 19 ++++++--- 6 files changed, 60 insertions(+), 46 deletions(-) diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 337dd14e3236..4dc6aefb09b1 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -319,13 +319,6 @@ Onyx.connect({ callback: (val) => (deprecatedAllPersonalDetails = val), }); -let allRules: OnyxCollection; -Onyx.connectWithoutView({ - key: ONYXKEYS.COLLECTION.RULE, - waitForCollectionCallback: true, - callback: (val) => (allRules = val), -}); - /** * Stores in Onyx the policy ID of the last workspace that was accessed by the user */ @@ -896,6 +889,7 @@ function setWorkspaceApprovalMode( currentUserAccountID: number, currentUserEmail: string, additionalData?: SetWorkspaceApprovalModeAdditionalData, + rules?: OnyxCollection, ) { if (!policy) { return; @@ -1023,8 +1017,8 @@ function setWorkspaceApprovalMode( // Auth's DisablePolicyApprovals deletes the policy's rule rows server-side; clear them optimistically too // so the workflows UI doesn't keep rebuilding stale workflows (e.g. after re-enabling). - if (approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL && allRules) { - for (const [ruleKey, rule] of Object.entries(allRules)) { + if (approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL && rules) { + for (const [ruleKey, rule] of Object.entries(rules)) { if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { continue; } diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 3153421e9487..d3406342dbe7 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -36,16 +36,6 @@ import Onyx from 'react-native-onyx'; import {completeTask} from './Task'; -/** Cache of every approval-workflow rule (`ONYXKEYS.COLLECTION.RULE`) so actions can read the current rule set. */ -let allRules: OnyxCollection = {}; -Onyx.connectWithoutView({ - key: ONYXKEYS.COLLECTION.RULE, - waitForCollectionCallback: true, - callback: (value) => { - allRules = value ?? {}; - }, -}); - type CreateApprovalWorkflowParams = { approvalWorkflow: ApprovalWorkflow; policy: OnyxEntry; @@ -360,13 +350,17 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetAppro write(WRITE_COMMANDS.SET_APPROVAL_WORKFLOW, parameters, {optimisticData, successData, failureData}); } +type CreateApprovalWorkflowRulesParams = CreateApprovalWorkflowParams & { + rules: OnyxCollection; +}; + /** Create an approval workflow using the rules-based backend structure. */ -function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport}: CreateApprovalWorkflowParams) { +function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport, rules}: CreateApprovalWorkflowRulesParams) { if (!policy) { return; } - const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); + const existingRules = getApprovalWorkflowRulesForPolicy(rules, policy.id); const memberEmails = getWorkflowMemberEmails(approvalWorkflow.members); // A submitter can only belong to one workflow, so first drop these members from any OTHER @@ -393,15 +387,16 @@ type UpdateApprovalWorkflowRulesParams = { approvalWorkflow: ApprovalWorkflow; initialApprovalWorkflow: ApprovalWorkflow; policy: OnyxEntry; + rules: OnyxCollection; }; /** Update an existing workflow using the rules-based backend structure. */ -function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}: UpdateApprovalWorkflowRulesParams) { +function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy, rules}: UpdateApprovalWorkflowRulesParams) { if (!policy) { return; } - const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); + const existingRules = getApprovalWorkflowRulesForPolicy(rules, policy.id); const previousMemberEmails = getWorkflowMemberEmails(initialApprovalWorkflow.members); const newMemberEmails = getWorkflowMemberEmails(approvalWorkflow.members); @@ -425,12 +420,12 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, } /** Delete an approval workflow using the rules-based backend structure. */ -function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry) { +function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry, rules: OnyxCollection) { if (!policy) { return; } - const existingRules = getApprovalWorkflowRulesForPolicy(allRules, policy.id); + const existingRules = getApprovalWorkflowRulesForPolicy(rules, policy.id); const memberEmails = getWorkflowMemberEmails(approvalWorkflow.members); const rulesDiff = reconcileApprovalWorkflowRulesForRemove(memberEmails, {existingRules}); diff --git a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx index 752764166d98..605b47a3f972 100644 --- a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx +++ b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx @@ -253,12 +253,20 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { }, []); const confirmDisableApprovals = useCallback(() => { - setWorkspaceApprovalMode(policy, policy?.owner ?? '', CONST.POLICY.APPROVAL_MODE.OPTIONAL, currentUserAccountID, currentUserEmail, { - reportNextSteps: allReportNextSteps, - transactionViolations, - betas, - }); - }, [allReportNextSteps, betas, policy, transactionViolations, currentUserAccountID, currentUserEmail]); + setWorkspaceApprovalMode( + policy, + policy?.owner ?? '', + CONST.POLICY.APPROVAL_MODE.OPTIONAL, + currentUserAccountID, + currentUserEmail, + { + reportNextSteps: allReportNextSteps, + transactionViolations, + betas, + }, + rulesCollection, + ); + }, [allReportNextSteps, betas, policy, transactionViolations, currentUserAccountID, currentUserEmail, rulesCollection]); const navigateToHRSettings = useCallback(() => { Navigation.navigate(ROUTES.WORKSPACE_HR.getRoute(route.params.policyID)); @@ -529,11 +537,19 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { }); return; } - setWorkspaceApprovalMode(policy, policy?.owner ?? '', isEnabled ? updateApprovalMode : CONST.POLICY.APPROVAL_MODE.OPTIONAL, currentUserAccountID, currentUserEmail, { - reportNextSteps: allReportNextSteps, - transactionViolations, - betas, - }); + setWorkspaceApprovalMode( + policy, + policy?.owner ?? '', + isEnabled ? updateApprovalMode : CONST.POLICY.APPROVAL_MODE.OPTIONAL, + currentUserAccountID, + currentUserEmail, + { + reportNextSteps: allReportNextSteps, + transactionViolations, + betas, + }, + rulesCollection, + ); }, subMenuItems: ( <> @@ -902,6 +918,7 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { withPaymentsReadOnlyFallback, withWorkflowsReadOnlyFallback, showReadOnlyModal, + rulesCollection, ]); const renderOptionItem = (item: ToggleSettingOptionRowProps, index: number) => ( diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx index c4acd020f59c..a0c437a6bca0 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx @@ -45,6 +45,7 @@ function WorkspaceWorkflowsApprovalsCreatePage({policy, isLoadingReportData = tr const {translate} = useLocalize(); const {isBetaEnabled} = usePermissions(); const [approvalWorkflow] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW); + const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const addExpenseApprovalsTaskReportID = introSelected?.addExpenseApprovals; const [addExpenseApprovalsTaskReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${addExpenseApprovalsTaskReportID}`); @@ -66,13 +67,13 @@ function WorkspaceWorkflowsApprovalsCreatePage({policy, isLoadingReportData = tr startWithLoading(() => { if (isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS)) { - createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport}); + createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport, rules: rulesCollection}); } else { createApprovalWorkflowAction({approvalWorkflow, policy, addExpenseApprovalsTaskReport}); } Navigation.dismissModal(); }); - }, [approvalWorkflow, policy, addExpenseApprovalsTaskReport, isBetaEnabled, startWithLoading]); + }, [approvalWorkflow, policy, addExpenseApprovalsTaskReport, rulesCollection, isBetaEnabled, startWithLoading]); const submitButtonContainerStyles = useBottomSafeSafeAreaPaddingStyle({addBottomSafeAreaPadding: true, style: [styles.mb5, styles.mh5]}); diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index fd97efc37254..bd0f1b7e1c8f 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -80,7 +80,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true if (isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS)) { Navigation.dismissModal({ afterTransition: () => { - updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}); + updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy, rules: rulesCollection}); }, }); return; @@ -109,7 +109,7 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true afterTransition: () => { // Remove the approval workflow using the initial data as it could be already edited if (useRulesBackend) { - removeApprovalWorkflowRules(initialApprovalWorkflow, policy); + removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection); } else { removeApprovalWorkflow(initialApprovalWorkflow, policy); } diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 660291d5dc18..46388818af33 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -59,7 +59,7 @@ const ownerEmail = 'owner@gmail.com'; * Reads every rule in the `ONYXKEYS.COLLECTION.RULE` collection that belongs to the given policy and is * not optimistically pending deletion. This mirrors what the app treats as the policy's live rule set. */ -async function getActivePolicyRules(policyID: string): Promise { +async function getRulesCollection(): Promise> { let collection: OnyxCollection = {}; await getOnyxData({ key: ONYXKEYS.COLLECTION.RULE, @@ -68,7 +68,12 @@ async function getActivePolicyRules(policyID: string): Promise { collection = value ?? {}; }, }); - return Object.values(collection).filter( + return collection; +} + +async function getActivePolicyRules(policyID: string): Promise { + const collection = await getRulesCollection(); + return Object.values(collection ?? {}).filter( (rule): rule is Rule => !!rule && rule.scope === CONST.RULES.SCOPE.POLICY && rule.scopeID === policyID && rule.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, ); } @@ -925,7 +930,7 @@ describe('actions/Workflow', () => { await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); await waitForBatchedUpdates(); - createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined}); + createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined, rules: await getRulesCollection()}); await waitForBatchedUpdates(); // A one-approver workflow produces a submit rule (forward to the approver) and a terminal approve rule. @@ -974,7 +979,7 @@ describe('actions/Workflow', () => { await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); await waitForBatchedUpdates(); - createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined}); + createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprovalsTaskReport: undefined, rules: await getRulesCollection()}); await waitForBatchedUpdates(); const rules = await getActivePolicyRules(policyID); @@ -1015,6 +1020,7 @@ describe('actions/Workflow', () => { }, policy, addExpenseApprovalsTaskReport: undefined, + rules: await getRulesCollection(), }); await waitForBatchedUpdates(); @@ -1030,6 +1036,7 @@ describe('actions/Workflow', () => { }, policy, addExpenseApprovalsTaskReport: undefined, + rules: await getRulesCollection(), }); await waitForBatchedUpdates(); @@ -1078,7 +1085,7 @@ describe('actions/Workflow', () => { await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); await waitForBatchedUpdates(); - updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy}); + updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy, rules: await getRulesCollection()}); await waitForBatchedUpdates(); // The old rules (forwarding to the owner) are removed and new rules forwarding to employee2 are created. @@ -1124,7 +1131,7 @@ describe('actions/Workflow', () => { await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); await waitForBatchedUpdates(); - removeApprovalWorkflowRules(approvalWorkflow, policy); + removeApprovalWorkflowRules(approvalWorkflow, policy, await getRulesCollection()); await waitForBatchedUpdates(); // Both rules belonged only to the removed member, so no live rules remain for the policy. From 99b9b6f3c6918d8e8f0e14b5c9b421808a1963db Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 30 Jul 2026 15:54:33 +0200 Subject: [PATCH 34/62] typescript --- tests/actions/WorkflowTest.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 46388818af33..449a988431c8 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -63,7 +63,6 @@ async function getRulesCollection(): Promise> { let collection: OnyxCollection = {}; await getOnyxData({ key: ONYXKEYS.COLLECTION.RULE, - waitForCollectionCallback: true, callback: (value) => { collection = value ?? {}; }, From c3730bf75048e0525be630fc595e4a69a08301ee Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 30 Jul 2026 15:58:13 +0200 Subject: [PATCH 35/62] tests --- src/libs/WorkflowUtils.ts | 2 +- src/libs/actions/Workflow.ts | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index e9e3541f4a1f..d6d1cfbf81f1 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -681,7 +681,7 @@ function getEligibleExistingBusinessBankAccounts( account.bankCurrency === policyCurrency && (account.accountData?.state === CONST.BANK_ACCOUNT.STATE.OPEN || (shouldIncludePartiallySetup && isBankAccountPartiallySetup(account.accountData?.state))) && account.accountData?.type === CONST.BANK_ACCOUNT.TYPE.BUSINESS && - account.methodID !== excludeBankAccountID + (excludeBankAccountID === undefined || account.methodID !== excludeBankAccountID) ); }); } diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index d3406342dbe7..8f08ca29bb29 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -298,11 +298,6 @@ type SetApprovalWorkflowRulesParams = { /** * Apply a set of approval-workflow rule changes to a policy via the SetApprovalWorkflow Auth command. - * - * Each rule lives under its own `ONYXKEYS.COLLECTION.RULE` key (`rules_`). Upserts use SET so - * a structurally different replacement doesn't deep-merge stale filters; removals mark the rule as - * pending-delete optimistically and clear it on success (or restore the previous rule on failure). - * Only the rule bodies (no `scope`/`scopeID`) are sent over the wire — the backend derives those. */ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetApprovalWorkflowRulesParams) { if (!policyID || isEmptyObject(rulesDiff)) { From 1aa65ca87137be102752c15431716bf8f2d823cb Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 30 Jul 2026 17:11:35 +0200 Subject: [PATCH 36/62] cleanup for new shape --- src/CONST/index.ts | 5 ----- src/libs/WorkflowUtils.ts | 30 ++++++++++++------------------ src/libs/actions/Policy/Policy.ts | 2 -- src/libs/actions/Workflow.ts | 4 ++-- tests/unit/WorkflowUtilsTest.ts | 20 ++++++++------------ 5 files changed, 22 insertions(+), 39 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index b631b21e33d7..5795a4c53a2b 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -7919,20 +7919,15 @@ const CONST = { }, }, - /** Vocabulary for the AST-based rules stored in the `rules` table / `ONYXKEYS.COLLECTION.RULE`. */ RULES: { - /** The kind of entity a rule is scoped to. Currently only workspace policies. Shared across all rule types. */ SCOPE: { POLICY: 'policy', }, - /** Vocabulary specific to approval-workflow rules. */ APPROVAL_WORKFLOW: { - /** The report lifecycle event that fires a rule. */ TRIGGER: { REPORT_SUBMIT: 'ReportSubmit', REPORT_APPROVE: 'ReportApprove', }, - /** The action taken when a rule matches. */ ACTION: { FORWARD_TO: 'ForwardTo', APPROVE_REPORT: 'ApproveReport', diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index d6d1cfbf81f1..ce8767eeb803 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -134,10 +134,7 @@ type PolicyConversionParams = { /** Current user's login email, used to determine if Expensify team members should be shown */ currentUserLogin?: string; - /** - * The policy's approval-workflow rules keyed by ruleID, read from the `ONYXKEYS.COLLECTION.RULE` - * collection (see `getApprovalWorkflowRulesForPolicy`). Only consumed by the rules-based converter. - */ + /** The policy's approval-workflow rules keyed by ruleID */ rules?: Record; }; @@ -844,7 +841,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva filters: buildAnd(fromComparison, buildAnd(toComparison, underAmount)), actions: nextApproverEmail ? buildForwardActions(nextApproverEmail) : buildApproveActions(), }); - // At/over the limit: escalate to the over-limit approver, who then finalizes the report. + // Over the limit: escalate to the over-limit approver, who then finalizes the report. rules.push({ triggers: buildApproveTriggers(), filters: buildAnd(fromComparison, buildAnd(toComparison, overAmount)), @@ -877,8 +874,11 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva } /** - * A leaf comparison node — its `left` is a primitive field name (or an array of values), unlike a - * boolean filter whose `left` is another node. + * True when this node is a single comparison like `from = alice@expensify.com`, rather than an `AND` that + * joins two other nodes. + * + * Both look the same (`{operator, left, right}`), so the giveaway is `left`: a comparison points at a field + * name, an `AND` points at another node. Arrays count as comparisons too. */ function isComparisonLeaf(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): node is ApprovalWorkflowFilterComparison { if (!node) { @@ -927,24 +927,18 @@ function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { } /** - * Normalize a value so two logically-equal structures stringify identically: object keys are sorted and - * index-keyed maps (`{"0":x}`) are collapsed to arrays (`[x]`). The array collapse matters because the API - * decodes the rules JSON to PHP arrays, so `triggers`/`actions` come back as JSON arrays while a freshly-built - * rule uses the `{"0":…}` object form — without it the two shapes never match and merging fails. + * Rewrite a value so that `JSON.stringify` gives the same string for two structures that mean the same thing. + * + * Only key order needs fixing: a rule that came back from the server can list the same keys in a different + * order than one we just built, and those two would otherwise produce different strings and never match. */ function canonicalize(value: unknown): unknown { if (Array.isArray(value)) { return value.map(canonicalize); } if (value !== null && typeof value === 'object') { - const entries = Object.entries(value); - // A `{"0":…,"1":…}` map is the object form of a list — collapse it to an array to match the backend. - const isSequentialIndexMap = entries.length > 0 && entries.every(([key], index) => key === String(index)); - if (isSequentialIndexMap) { - return entries.map(([, val]) => canonicalize(val)); - } // Byte-order sort (not locale-aware): this is a structural fingerprint, not user-facing text. - const sortedEntries = entries.sort(([a], [b]) => { + const sortedEntries = Object.entries(value).sort(([a], [b]) => { if (a === b) { return 0; } diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 60ea57d14d35..974cfc2a47b9 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -1026,8 +1026,6 @@ function setWorkspaceApprovalMode( failureData.push(...nextStepFailureData); } - // Auth's DisablePolicyApprovals deletes the policy's rule rows server-side; clear them optimistically too - // so the workflows UI doesn't keep rebuilding stale workflows (e.g. after re-enabling). if (approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL && rules) { for (const [ruleKey, rule] of Object.entries(rules)) { if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 8f08ca29bb29..e2996eb040fb 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -287,12 +287,12 @@ type SetApprovalWorkflowRulesParams = { policyID: string; /** - * Diff of rule bodies keyed by ruleID. A value of `ApprovalWorkflowRule` sets/replaces the rule + * Diff of rules keyed by ruleID. A value of `ApprovalWorkflowRule` sets/replaces the rule * under its `ruleID` in the `ONYXKEYS.COLLECTION.RULE` collection; a value of `null` removes it. */ rulesDiff: ApprovalWorkflowRulesDiff; - /** Snapshot of the policy's rules (`ruleID -> rule body`) taken before applying `rulesDiff`. Used to roll back on failure. */ + /** Snapshot of the policy's rules taken before applying `rulesDiff`. Used to roll back on failure. */ previousRules: Record; }; diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 49854a6f0582..e160f46431fe 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1694,9 +1694,6 @@ describe('WorkflowUtils', () => { right, }); const keyRules = (rules: ApprovalWorkflowRule[]): Record => Object.fromEntries(rules.map((rule, index) => [`rule${index}`, rule])); - // Present a list as the array-shaped value the API returns for `triggers`/`actions` (PHP decodes index maps to arrays). - const asServerShape = (value: unknown[]): T => value as unknown as T; - describe('buildApprovalWorkflowRules', () => { it('Should return an empty list when there are no members', () => { expect(buildApprovalWorkflowRules(buildWorkflow([], [1]))).toEqual([]); @@ -1788,21 +1785,20 @@ describe('WorkflowUtils', () => { expect(Object.values(diff)).toEqual(buildApprovalWorkflowRules(buildWorkflow([20, 10], [1]))); }); - it('Should merge into a server-hydrated rule (array-shaped triggers/actions, reordered keys)', () => { - // The API decodes the rules JSON to PHP associative arrays, so a hydrated rule comes back with - // index-keyed maps flattened to arrays (`{"0":"ReportSubmit"}` -> `["ReportSubmit"]`) and its object - // keys in a different order than a freshly-built rule. The structural match must ignore both so the - // new submitter folds into the existing rule instead of minting a fresh pair. + it('Should merge into a server-hydrated rule (reordered keys)', () => { + // A rule hydrated from the server lists its object keys in a different order than a freshly-built + // one. The structural match must ignore key order so the new submitter folds into the existing rule + // instead of minting a fresh pair. const existingRules: Record = { r1: { - actions: asServerShape([{approver: '1@example.com', name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO}]), + actions: forwardActions('1@example.com'), filters: buildFromFilter(['20@example.com']), - triggers: asServerShape([CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT]), + triggers: submitTriggers, }, r2: { - actions: asServerShape([{name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.APPROVE_REPORT}]), + actions: approveActions, filters: and(buildFromFilter(['20@example.com']), buildToFilter('1@example.com')), - triggers: asServerShape([CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE]), + triggers: approveTriggers, }, }; const newRules = buildApprovalWorkflowRules(buildWorkflow([10], [1])); From 838758d7341800ccbbe9af06f4fcc942e13e50f7 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 30 Jul 2026 17:40:41 +0200 Subject: [PATCH 37/62] comment cleanup --- src/libs/WorkflowUtils.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index ce8767eeb803..760f101d46eb 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1060,8 +1060,7 @@ function reconcileApprovalWorkflowRulesForCreate(newRules: ApprovalWorkflowRule[ /** * Reconcile an edit to an existing workflow into add/replace/remove instructions, preserving rules shared - * with other workflows. Pass 1 rewrites/removes existing rules that hold this workflow's members; pass 2 - * folds each new rule into a structurally-matching foreign rule or creates it under a fresh ruleID. + * with other workflows. */ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], memberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { const diff: ApprovalWorkflowRulesDiff = {}; @@ -1126,8 +1125,8 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], /** * Reconcile the deletion of a workflow. Rules that listed only this workflow's members in - * their `from` filter are removed outright; rules shared with other workflows have just - * this workflow's members stripped from `from`. + * their `from` filter are removed outright; rules shared with other workflows have this workflow's members + * stripped from `from`. */ function reconcileApprovalWorkflowRulesForRemove(memberEmails: string[], context: ReconcileContext): ApprovalWorkflowRulesDiff { const diff: ApprovalWorkflowRulesDiff = {}; @@ -1188,9 +1187,6 @@ function applyApprovalWorkflowRulesDiff(existingRules: Record, employees: PolicyEmployeeList): string | undefined { for (const rule of Object.values(rules)) { From 413c56ad3add05aba425edc9d21ca47584dcc619 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 30 Jul 2026 17:50:03 +0200 Subject: [PATCH 38/62] more cleanup of robot quirks --- src/ONYXKEYS.ts | 3 +-- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 3 --- src/types/onyx/ApprovalWorkflowRules.ts | 8 ++------ src/types/onyx/Rule.ts | 7 +------ tests/actions/WorkflowTest.ts | 14 +++++++------- 5 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 2d6e73abb651..47461b291304 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -867,8 +867,7 @@ const ONYXKEYS = { POLICY_HAS_CONNECTIONS_DATA_BEEN_FETCHED: 'policyHasConnectionsDataBeenFetched_', POLICY_CONNECTION_SYNC_PROGRESS: 'policyConnectionSyncProgress_', POLICY_MERGE_HR_INITIAL_SYNC_MODAL_SHOWN: 'policyMergeHRInitialSyncModalShown_', - // AST rules keyed by ruleID (`rules_`). Mirrors a row of the server `rules` table. - // Currently holds approval-workflow rules; intended for all AST rules in the future. + // AST rules keyed by ruleID RULE: 'rules_', WORKSPACE_INVITE_MEMBERS_DRAFT: 'workspaceInviteMembersDraft_', WORKSPACE_INVITE_MESSAGE_DRAFT: 'workspaceInviteMessageDraft_', diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index bd0f1b7e1c8f..b72fe2e00df8 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -135,9 +135,6 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true ? convertApprovalWorkflowRulesToWorkflows(conversionParams) : convertPolicyEmployeesToApprovalWorkflows(conversionParams); - // `firstApproverEmail` isn't unique once rule-based chains diverge, so prefer matching on the - // member that opened this workflow (a member belongs to exactly one workflow). Fall back to the - // first-approver match for the default workflow (no members) and legacy/unspecified cases. const memberEmail = route.params.memberEmail; const currentApprovalWorkflow = (memberEmail ? result.approvalWorkflows.find((workflow) => workflow.members.some((member) => member.email === memberEmail)) : undefined) ?? diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index bd99b259e426..06d5d308d702 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -73,12 +73,8 @@ type ApprovalWorkflowFilter = { }; /** - * The body of a single approval-workflow rule. This is exactly what is stored in the server `rules` - * table `value` column, what is sent over the wire to `SetApprovalWorkflow`, and (extended with - * `scope`/`scopeID`) what is stored in the `ONYXKEYS.COLLECTION.RULE` collection. - * - * When the report event matches one of the `triggers` and the `filters` match the report, the rule's - * `actions` are performed (forward the report to an approver, or approve it). + * The body of a single approval-workflow rule. When the report event matches one of the `triggers` and + * the `filters` match the report, the rule's `actions` are performed */ type ApprovalWorkflowRule = { /** Report lifecycle events that fire this rule. */ diff --git a/src/types/onyx/Rule.ts b/src/types/onyx/Rule.ts index 5348ecdcecd7..a48f1defc989 100644 --- a/src/types/onyx/Rule.ts +++ b/src/types/onyx/Rule.ts @@ -9,12 +9,7 @@ import type {Errors, OnyxValueWithOfflineFeedback} from './OnyxCommon'; type RuleScope = ValueOf; /** - * A rule as stored in the `ONYXKEYS.COLLECTION.RULE` collection under `rules_`. This mirrors a - * row of the server `rules` table: the AST rule body (`triggers`/`filters`/`actions`) plus the - * `scope`/`scopeID` that associate it with an entity (a policy, for approval workflows). - * - * The same collection is intended to hold every kind of AST rule in the future, not just approval - * workflows. + * A rule as stored in the `ONYXKEYS.COLLECTION.RULE` collection under `rules_`. */ type Rule = OnyxValueWithOfflineFeedback< ApprovalWorkflowRule & { diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 449a988431c8..02308bffeee8 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -57,7 +57,7 @@ const ownerEmail = 'owner@gmail.com'; /** * Reads every rule in the `ONYXKEYS.COLLECTION.RULE` collection that belongs to the given policy and is - * not optimistically pending deletion. This mirrors what the app treats as the policy's live rule set. + * not optimistically pending deletion. */ async function getRulesCollection(): Promise> { let collection: OnyxCollection = {}; @@ -77,13 +77,13 @@ async function getActivePolicyRules(policyID: string): Promise { ); } -/** Build the index-keyed object shape the rules API uses for lists (`['a'] -> {'0': 'a'}`). */ +/** Build the index-keyed object shape the rules API uses for lists */ function indexMap(...values: T[]): Record { return Object.fromEntries(values.map((value, index) => [String(index), value])); } -/** Seed the two rules (submit -> forward, approve -> finalize) that describe a `submitters -> approver` workflow. */ -async function seedForwardApproveRules(policyID: string, submitters: string[], approver: string) { +/** Write the two rules (submit -> forward, approve -> finalize) that describe a `submitters -> approver` workflow. */ +async function createForwardApproveRules(policyID: string, submitters: string[], approver: string) { await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}rule1`, { scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, @@ -961,7 +961,7 @@ describe('actions/Workflow', () => { }; // Existing workflow: employee1 (A) and employee2 (B) submit to owner (C). - await seedForwardApproveRules(policyID, [employee1Email, employee2Email], ownerEmail); + await createForwardApproveRules(policyID, [employee1Email, employee2Email], ownerEmail); // New workflow: employee3 (D) submits to owner (C) — same chain as the existing workflow. const approvalWorkflow = { @@ -1064,7 +1064,7 @@ describe('actions/Workflow', () => { }; // Seed the existing [employee1] → [owner] workflow as rules in the collection. - await seedForwardApproveRules(policyID, [employee1Email], ownerEmail); + await createForwardApproveRules(policyID, [employee1Email], ownerEmail); const initialApprovalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], @@ -1114,7 +1114,7 @@ describe('actions/Workflow', () => { }; // Seed the existing [employee1] → [owner] workflow as rules in the collection. - await seedForwardApproveRules(policyID, [employee1Email], ownerEmail); + await createForwardApproveRules(policyID, [employee1Email], ownerEmail); const approvalWorkflow = { members: [{email: employee1Email, displayName: employee1Email}], From b92715cd0945168a0f00a7f7dbdcb7b965ffa6e8 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 3 Aug 2026 13:16:06 +0200 Subject: [PATCH 39/62] add selector --- src/libs/WorkflowUtils.ts | 21 ++++++++++++ .../workflows/WorkspaceWorkflowsPage.tsx | 6 +++- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 9 ++++-- tests/unit/WorkflowUtilsTest.ts | 32 +++++++++++++++++++ 4 files changed, 64 insertions(+), 4 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 760f101d46eb..03082e1f8e72 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1387,6 +1387,26 @@ function getSubmitterRuleIDs(submitter: string, rules: Record, policyID: string | undefined): NonNullable> { + const result: NonNullable> = {}; + if (!rulesCollection || !policyID) { + return result; + } + + for (const [onyxKey, rule] of Object.entries(rulesCollection)) { + if (rule?.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { + continue; + } + result[onyxKey] = rule; + } + + return result; +} + /** * Convert the `ONYXKEYS.COLLECTION.RULE` collection into the `ruleID -> rule body` map used by the * builder, reconcilers and converters, keeping only non-deleted rules scoped to `policyID`. @@ -1613,6 +1633,7 @@ export { extractSubmitterEmails, getApprovalLimitDescription, getApprovalWorkflowRulesForPolicy, + filterRulesForPolicy, getRulesSubmitterToFirstApprover, getRulesSubmitterToWorkflowKey, getWorkflowMemberEmails, diff --git a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx index 5af3d1dfa509..6f92cd740e9b 100644 --- a/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx +++ b/src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx @@ -70,6 +70,7 @@ import tokenizedSearch from '@libs/tokenizedSearch'; import { convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, + filterRulesForPolicy, getApprovalWorkflowRulesForPolicy, getEligibleExistingBusinessBankAccounts, INITIAL_APPROVAL_WORKFLOW, @@ -93,7 +94,9 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; +import type Rule from '@src/types/onyx/Rule'; +import type {OnyxCollection} from 'react-native-onyx'; import type {TupleToUnion, ValueOf} from 'type-fest'; import {hasSeenTourSelector} from '@selectors/Onboarding'; @@ -200,7 +203,8 @@ function WorkspaceWorkflowsPage({policy, route}: WorkspaceWorkflowsPageProps) { const {accountID: currentUserAccountID, email: currentUserEmail = '', login: currentUserLogin = ''} = useCurrentUserPersonalDetails(); const isUserReimburser = account?.primaryLogin !== undefined && (policy?.achAccount?.reimburser ?? policy?.owner) === account?.primaryLogin; const isMultipleApproversBetaEnabled = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS); - const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE); + const policyRulesSelector = useCallback((rules: OnyxCollection) => filterRulesForPolicy(rules, route.params.policyID), [route.params.policyID]); + const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE, {selector: policyRulesSelector}); const {approvalWorkflows, availableMembers, usedApproverEmails} = useMemo(() => { const params = { policy, diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index b72fe2e00df8..d6974250588f 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -19,7 +19,7 @@ import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import {canMemberWrite, goBackFromInvalidPolicy, isPendingDeletePolicy} from '@libs/PolicyUtils'; -import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, getApprovalWorkflowRulesForPolicy} from '@libs/WorkflowUtils'; +import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, filterRulesForPolicy, getApprovalWorkflowRulesForPolicy} from '@libs/WorkflowUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading'; @@ -39,13 +39,15 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; +import type Rule from '@src/types/onyx/Rule'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; // eslint-disable-next-line no-restricted-imports import type {ScrollView} from 'react-native'; +import type {OnyxCollection} from 'react-native-onyx'; -import React, {useEffect, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useRef, useState} from 'react'; import ApprovalWorkflowEditor from './ApprovalWorkflowEditor'; @@ -57,7 +59,8 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true const {translate, localeCompare} = useLocalize(); const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); const [approvalWorkflow, approvalWorkflowMetadata] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW); - const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE); + const policyRulesSelector = useCallback((rules: OnyxCollection) => filterRulesForPolicy(rules, route.params.policyID), [route.params.policyID]); + const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE, {selector: policyRulesSelector}); const isLoadingApprovalWorkflow = isLoadingOnyxValue(approvalWorkflowMetadata); const {login: currentUserLogin = ''} = useCurrentUserPersonalDetails(); const {isBetaEnabled} = usePermissions(); diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index e160f46431fe..47bfe45e728a 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -10,6 +10,7 @@ import { convertApprovalWorkflowToPolicyEmployees, convertPolicyEmployeesToApprovalWorkflows, extractSubmitterEmails, + filterRulesForPolicy, getApprovalLimitDescription, getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, @@ -31,6 +32,7 @@ import type {BankAccountList} from '@src/types/onyx/BankAccount'; import type {PersonalDetailsList} from '@src/types/onyx/PersonalDetails'; import type {PolicyEmployeeList} from '@src/types/onyx/PolicyEmployee'; import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; +import type Rule from '@src/types/onyx/Rule'; import createRandomPolicy from '../utils/collections/policies'; import {buildPersonalDetails, convertToDisplayString, localeCompare, translateLocal} from '../utils/TestHelper'; @@ -2015,4 +2017,34 @@ describe('WorkflowUtils', () => { }); }); }); + + describe('filterRulesForPolicy', () => { + const ruleForPolicy = (scopeID: string, extra: Partial = {}): Rule => ({ + scope: CONST.RULES.SCOPE.POLICY, + scopeID, + triggers: {'0': CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT}, + filters: {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, right: 'a@example.com'}, + actions: {'0': {name: CONST.RULES.APPROVAL_WORKFLOW.ACTION.FORWARD_TO, approver: 'b@example.com'}}, + ...extra, + }); + + it('keeps only the rules scoped to the given policy, preserving the collection keys', () => { + const mine = ruleForPolicy('policy1'); + const collection = {rules_1: mine, rules_2: ruleForPolicy('policy2')}; + + // The value is passed through by reference so callers still see the full rule. + expect(filterRulesForPolicy(collection, 'policy1')).toEqual({rules_1: mine}); + }); + + it('keeps rules pending deletion, leaving that decision to the caller', () => { + const pendingDelete = ruleForPolicy('policy1', {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}); + + expect(filterRulesForPolicy({rules_1: pendingDelete}, 'policy1')).toEqual({rules_1: pendingDelete}); + }); + + it('returns an empty collection when there is no policy or no rules', () => { + expect(filterRulesForPolicy({rules_1: ruleForPolicy('policy1')}, undefined)).toEqual({}); + expect(filterRulesForPolicy(undefined, 'policy1')).toEqual({}); + }); + }); }); From 1b513ce44f26852d584753146a80449a371a96e0 Mon Sep 17 00:00:00 2001 From: alberto Date: Wed, 5 Aug 2026 11:54:16 +0200 Subject: [PATCH 40/62] delete workflow fix --- src/libs/actions/Workflow.ts | 13 ++++-- .../WorkspaceWorkflowsApprovalsEditPage.tsx | 7 ++- tests/actions/WorkflowTest.ts | 45 +++++++++++++++++++ 3 files changed, 58 insertions(+), 7 deletions(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index e2996eb040fb..255a4044c07b 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -414,17 +414,24 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); } -/** Delete an approval workflow using the rules-based backend structure. */ -function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry, rules: OnyxCollection) { +/** + * Delete an approval workflow using the rules-based backend structure. + */ +function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry, rules: OnyxCollection): boolean { if (!policy) { - return; + return false; } const existingRules = getApprovalWorkflowRulesForPolicy(rules, policy.id); const memberEmails = getWorkflowMemberEmails(approvalWorkflow.members); const rulesDiff = reconcileApprovalWorkflowRulesForRemove(memberEmails, {existingRules}); + if (isEmptyObject(rulesDiff)) { + return false; + } + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); + return true; } /** Set the members of the approval workflow that is currently edited */ diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index 97c564cf8a4c..8659b3d2754d 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -112,11 +112,10 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true Navigation.dismissModal({ afterTransition: () => { // Remove the approval workflow using the initial data as it could be already edited - if (useRulesBackend) { - removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection); - } else { - removeApprovalWorkflow(initialApprovalWorkflow, policy); + if (useRulesBackend && removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection)) { + return; } + removeApprovalWorkflow(initialApprovalWorkflow, policy); }, }); }; diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index 02308bffeee8..071888aba243 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -1140,5 +1140,50 @@ describe('actions/Workflow', () => { await mockFetch.resume(); await waitForBatchedUpdates(); }); + + it('returns false when the workflow only exists in the employee list so the caller can fall back', async () => { + mockFetch.pause(); + + const policyID = '987654321'; + const policy: Policy = { + ...createRandomPolicy(2), + id: policyID, + owner: ownerEmail, + approver: ownerEmail, + approvalMode: CONST.POLICY.APPROVAL_MODE.ADVANCED, + employeeList: { + [employee1Email]: {email: employee1Email, forwardsTo: '', role: CONST.POLICY.ROLE.USER, submitsTo: employee2Email}, + [employee2Email]: {email: employee2Email, forwardsTo: '', role: CONST.POLICY.ROLE.USER, submitsTo: ownerEmail}, + }, + rules: {}, + }; + + const approvalWorkflow = { + members: [{email: employee1Email, displayName: employee1Email}], + approvers: [{email: employee2Email, displayName: employee2Email, isCircularReference: false}], + availableMembers: [], + usedApproverEmails: [], + isDefault: false, + action: 'remove', + originalApprovers: [], + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + expect(removeApprovalWorkflowRules(approvalWorkflow, policy, await getRulesCollection())).toBe(false); + await waitForBatchedUpdates(); + + // Falling back to the employee-list command detaches the member from the removed approver. + removeApprovalWorkflow(approvalWorkflow, policy); + await waitForBatchedUpdates(); + + const updatedPolicy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); + expect(updatedPolicy?.employeeList?.[employee1Email]?.submitsTo).not.toBe(employee2Email); + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); }); }); From 0385d1145321f424b4941aaa02b77c21c4c0ce31 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 6 Aug 2026 11:02:54 +0200 Subject: [PATCH 41/62] Better comparison handling --- src/libs/WorkflowUtils.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 03082e1f8e72..9f1a07a4f5c4 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1425,7 +1425,11 @@ function getApprovalWorkflowRulesForPolicy(rulesCollection: OnyxCollection continue; } const ruleID = onyxKey.slice(ONYXKEYS.COLLECTION.RULE.length); - result[ruleID] = {triggers: rule.triggers, filters: rule.filters, actions: rule.actions}; + result[ruleID] = { + triggers: toIndexMap(Object.values(rule.triggers ?? {})), + filters: rule.filters, + actions: toIndexMap(Object.values(rule.actions ?? {})), + }; } return result; From fe6409ca29e8677549609ad0b65a1ea342243252 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 6 Aug 2026 14:01:46 +0200 Subject: [PATCH 42/62] fix for overLimit approver --- src/libs/WorkflowUtils.ts | 264 ++++++++++++++++++-------------- tests/unit/WorkflowUtilsTest.ts | 51 +++++- 2 files changed, 194 insertions(+), 121 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 9f1a07a4f5c4..1cf2109d1c19 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -809,56 +809,72 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva const fromComparison = buildSubmitterFilter(memberEmails); const rules: ApprovalWorkflowRule[] = []; - // On submission, route the report to the first approver. - rules.push({ - triggers: buildSubmitTriggers(), - filters: fromComparison, - actions: buildForwardActions(firstApproverEmail), + /** + * An approver's approval limit decides who holds the report at that position, not where it goes afterwards: a + * report over the limit is received by `overLimitForwardsTo` *instead of* the approver, and then carries on to the + * next approver as normal. So each position has one or two people who can hold it, and the hop into the position + * is what branches on the amount. + */ + const holdersAtPosition = approvers.map((approver) => { + const hasLimitSplit = !!approver.approvalLimit && approver.approvalLimit > 0 && !!approver.overLimitForwardsTo; + return { + underLimitEmail: approver.email, + overLimitEmail: hasLimitSplit ? approver.overLimitForwardsTo : undefined, + limit: hasLimitSplit ? approver.approvalLimit : undefined, + }; }); - // For each approver, describe what happens after THEY approve (gated on `to == approver`). - for (let i = 0; i < approvers.length; i++) { - const approver = approvers.at(i); - if (!approver?.email) { - continue; + /** The rules routing a report into `position`, from either submission or the approvers at the position before. */ + const buildRulesIntoPosition = (position: number): ApprovalWorkflowRule[] => { + const holders = holdersAtPosition.at(position); + if (!holders?.underLimitEmail) { + return []; } - const nextApproverEmail = approvers.at(i + 1)?.email; - const toComparison = buildToComparison(approver.email); + const isFirstPosition = position === 0; + const triggers = isFirstPosition ? buildSubmitTriggers() : buildApproveTriggers(); - const limitSplit = - approver.approvalLimit && approver.approvalLimit > 0 && approver.overLimitForwardsTo - ? {limit: approver.approvalLimit, overLimitForwardsTo: approver.overLimitForwardsTo} - : undefined; + // Everyone who can hold the previous position routes onward the same way, so each of them needs a rule. + const previousHolders = isFirstPosition ? [undefined] : [holdersAtPosition.at(position - 1)?.underLimitEmail, holdersAtPosition.at(position - 1)?.overLimitEmail]; - if (limitSplit) { - const underAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit); - const overAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, limitSplit.limit); + const rulesIntoPosition: ApprovalWorkflowRule[] = []; + for (const previousHolderEmail of previousHolders) { + if (!isFirstPosition && !previousHolderEmail) { + continue; + } - // Under the limit: continue the chain, or approve if this is the last approver. - rules.push({ - triggers: buildApproveTriggers(), - filters: buildAnd(fromComparison, buildAnd(toComparison, underAmount)), - actions: nextApproverEmail ? buildForwardActions(nextApproverEmail) : buildApproveActions(), - }); - // Over the limit: escalate to the over-limit approver, who then finalizes the report. - rules.push({ - triggers: buildApproveTriggers(), - filters: buildAnd(fromComparison, buildAnd(toComparison, overAmount)), - actions: buildForwardActions(limitSplit.overLimitForwardsTo), - }); - rules.push({ - triggers: buildApproveTriggers(), - filters: buildAnd(fromComparison, buildToComparison(limitSplit.overLimitForwardsTo)), - actions: buildApproveActions(), - }); - } else { - rules.push({ - triggers: buildApproveTriggers(), - filters: buildAnd(fromComparison, toComparison), - actions: nextApproverEmail ? buildForwardActions(nextApproverEmail) : buildApproveActions(), - }); + const source = previousHolderEmail ? buildAnd(fromComparison, buildToComparison(previousHolderEmail)) : fromComparison; + + if (holders.overLimitEmail == null || holders.limit == null) { + rulesIntoPosition.push({triggers, filters: source, actions: buildForwardActions(holders.underLimitEmail)}); + continue; + } + + const underAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, holders.limit); + const overAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, holders.limit); + + rulesIntoPosition.push({triggers, filters: buildAnd(source, underAmount), actions: buildForwardActions(holders.underLimitEmail)}); + rulesIntoPosition.push({triggers, filters: buildAnd(source, overAmount), actions: buildForwardActions(holders.overLimitEmail)}); + } + + return rulesIntoPosition; + }; + + for (let position = 0; position < holdersAtPosition.length; position++) { + rules.push(...buildRulesIntoPosition(position)); + } + + // Whoever holds the last position finalizes the report. + const lastHolders = holdersAtPosition.at(-1); + for (const lastHolderEmail of [lastHolders?.underLimitEmail, lastHolders?.overLimitEmail]) { + if (!lastHolderEmail) { + continue; } + rules.push({ + triggers: buildApproveTriggers(), + filters: buildAnd(fromComparison, buildToComparison(lastHolderEmail)), + actions: buildApproveActions(), + }); } // Different approvers may share an `overLimitForwardsTo`, which would emit identical terminal rules. @@ -1235,81 +1251,87 @@ function getForwardApprover(rule: ApprovalWorkflowRule): string | undefined { * we fall back to the older `submitsTo` field on the employee. */ function resolveFirstApprover(submitter: string, rules: Record, employees: PolicyEmployeeList): string | undefined { - for (const rule of Object.values(rules)) { - if (!isSubmitRule(rule) || !extractSubmitterEmails(rule).includes(submitter)) { - continue; - } - const approver = getForwardApprover(rule); - if (approver) { - return approver; - } + const firstPosition = resolvePositionHolders(submitter, rules, undefined); + if (firstPosition?.underLimitEmail) { + return firstPosition.underLimitEmail; } return employees[submitter]?.submitsTo; } -/** What happens after `currentApprover` approves a report from `submitter`. */ -type AfterApproveInfo = { - /** The next approver in the chain, from the normal / under-limit `ForwardTo`. `undefined` means the report is approved (terminal). */ - nextEmail?: string; - /** `currentApprover`'s own approval limit, present only when there is an over-limit split. */ +/** Who can hold one position in a submitter's approval chain. */ +type PositionHolders = { + /** Who holds the position for a report under the limit, or for any report when there is no limit. */ + underLimitEmail?: string; + + /** Who holds it instead once the report reaches the limit. */ + overLimitEmail?: string; + + /** The limit that decides between the two. */ approvalLimit?: number; - /** `currentApprover`'s own over-limit target, present only when there is an over-limit split. */ - overLimitForwardsTo?: string; + + /** True when the routing rules approve the report at this point rather than passing it on. */ + isTerminal: boolean; }; /** - * Resolve what the rules say happens after `currentApprover` approves a report from `submitter`, by - * inspecting every rule gated on `to == currentApprover`. Returns `undefined` when no rule covers - * this approver (so callers can fall back to `employeeList`). + * Read who holds the position a report reaches from `sourceApprover` — or from submission when `sourceApprover` is + * undefined. + * + * An approval limit belongs to the position it guards, not to the approver before it: the rules routing into a + * position carry the amount split, so a report at or over the limit is received by `overLimitEmail` *instead of* + * `underLimitEmail`. Returns undefined when no rule covers this step, so callers can fall back to `employeeList`. */ -function resolveAfterApprove(submitter: string, currentApprover: string, rules: Record): AfterApproveInfo | undefined { - let hasNormalBranch = false; - let normalIsTerminal = false; - let normalNextEmail: string | undefined; - let overLimitForwardsTo: string | undefined; - let approvalLimit: number | undefined; +function resolvePositionHolders(submitter: string, rules: Record, sourceApprover: string | undefined): PositionHolders | undefined { + const holders: PositionHolders = {isTerminal: false}; + let didMatchRule = false; for (const rule of Object.values(rules)) { if (!extractSubmitterEmails(rule).includes(submitter)) { continue; } + + const isFromSubmission = sourceApprover === undefined; + if (isFromSubmission !== isSubmitRule(rule)) { + continue; + } + const toLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.TO); - if (!toLeaf || toLeaf.right !== currentApprover) { + if (isFromSubmission ? !!toLeaf : toLeaf?.right !== sourceApprover) { + continue; + } + + didMatchRule = true; + + if (isApproveReportRule(rule)) { + holders.isTerminal = true; continue; } const amountLeaf = findComparisonByLeft(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT); - const isOverLimit = + const isOverLimitBranch = !!amountLeaf && (amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO || amountLeaf.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN); if (amountLeaf && typeof amountLeaf.right === 'number') { - approvalLimit = approvalLimit ?? amountLeaf.right; + holders.approvalLimit = holders.approvalLimit ?? amountLeaf.right; } - if (isOverLimit) { - overLimitForwardsTo = getForwardApprover(rule) ?? overLimitForwardsTo; - continue; - } - - // Normal branch: either a no-amount rule or the under-limit half of a split. - hasNormalBranch = true; - if (isApproveReportRule(rule)) { - normalIsTerminal = true; + if (isOverLimitBranch) { + holders.overLimitEmail = getForwardApprover(rule) ?? holders.overLimitEmail; } else { - normalNextEmail = getForwardApprover(rule) ?? normalNextEmail; + holders.underLimitEmail = getForwardApprover(rule) ?? holders.underLimitEmail; } } - if (!hasNormalBranch && overLimitForwardsTo === undefined) { + if (!didMatchRule) { return undefined; } - const hasSplit = overLimitForwardsTo !== undefined; - return { - nextEmail: normalIsTerminal ? undefined : normalNextEmail, - approvalLimit: hasSplit ? approvalLimit : undefined, - overLimitForwardsTo, - }; + // A limit only means anything when both halves of the split are known. + if (!holders.overLimitEmail) { + holders.approvalLimit = undefined; + } + + return holders; } type BuildApproverChainFromRulesParams = { @@ -1326,45 +1348,57 @@ type BuildApproverChainFromRulesParams = { * Any step the rules don't cover falls back to the legacy `employeeList` fields. */ function buildApproverChainFromRules({submitter, rules, employees, personalDetailsByEmail}: BuildApproverChainFromRulesParams): Approver[] { - let currentEmail: string | undefined = resolveFirstApprover(submitter, rules, employees); - if (!currentEmail) { - return []; - } - - const chain: Approver[] = []; + // Walk the positions forward first: an approver's own row needs to name the next position's holder, which is only + // known once that position has been read. + const positions: PositionHolders[] = []; const seenEmails = new Set(); + let sourceApprover: string | undefined; + let isFirstPosition = true; - while (currentEmail) { - const isCircularReference = seenEmails.has(currentEmail); - const employee: PolicyEmployee | undefined = employees[currentEmail]; + while (true) { + const holders = resolvePositionHolders(submitter, rules, sourceApprover); - const after = resolveAfterApprove(submitter, currentEmail, rules); - const approvalLimit: number | null = after?.approvalLimit ?? employee?.approvalLimit ?? null; - const overLimitForwardsTo: string | undefined = after?.overLimitForwardsTo ?? employee?.overLimitForwardsTo; - // When a rule covers this approver, trust its next hop (possibly terminal). Otherwise fall back. - const forwardsTo: string | undefined = after ? after.nextEmail : employee?.forwardsTo; + // Nothing covers this step, so fall back to the legacy employeeList fields for it. + const fallbackEmail = isFirstPosition ? employees[submitter]?.submitsTo : employees[sourceApprover ?? '']?.forwardsTo; + const nextEmail = holders?.isTerminal ? undefined : (holders?.underLimitEmail ?? (holders ? undefined : fallbackEmail)); + if (!nextEmail) { + break; + } - chain.push({ - email: currentEmail, - forwardsTo, - avatar: personalDetailsByEmail[currentEmail]?.avatar, - displayName: personalDetailsByEmail[currentEmail]?.displayName ?? currentEmail, - isCircularReference, - approvalLimit, - overLimitForwardsTo, - overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(overLimitForwardsTo, personalDetailsByEmail), - pendingAction: employee?.pendingAction, - errors: employee?.errors, + const fallbackEmployee: PolicyEmployee | undefined = employees[nextEmail]; + positions.push({ + isTerminal: false, + underLimitEmail: nextEmail, + overLimitEmail: holders?.overLimitEmail ?? (holders ? undefined : fallbackEmployee?.overLimitForwardsTo), + approvalLimit: holders?.approvalLimit ?? (holders ? undefined : (fallbackEmployee?.approvalLimit ?? undefined)), }); - if (isCircularReference || !forwardsTo) { + if (seenEmails.has(nextEmail)) { break; } - seenEmails.add(currentEmail); - currentEmail = forwardsTo; + seenEmails.add(nextEmail); + sourceApprover = nextEmail; + isFirstPosition = false; } - return chain; + return positions.map((position, index) => { + const email = position.underLimitEmail ?? ''; + const employee: PolicyEmployee | undefined = employees[email]; + const isCircularReference = positions.findIndex((other) => other.underLimitEmail === email) !== index; + + return { + email, + forwardsTo: isCircularReference ? undefined : positions.at(index + 1)?.underLimitEmail, + avatar: personalDetailsByEmail[email]?.avatar, + displayName: personalDetailsByEmail[email]?.displayName ?? email, + isCircularReference, + approvalLimit: position.approvalLimit ?? null, + overLimitForwardsTo: position.overLimitEmail, + overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(position.overLimitEmail, personalDetailsByEmail), + pendingAction: employee?.pendingAction, + errors: employee?.errors, + }; + }); } /** Structural identity of a chain — used to fold submitters with identical chains into one workflow. */ diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 47bfe45e728a..cc92ca8d728d 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1729,17 +1729,37 @@ describe('WorkflowUtils', () => { const underAmount = {operator: CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; const overAmount = {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 50000}; + // The limit decides who *receives* the report, so the amount split is on the way in. Both possible + // holders then finalize it, because this is the last position. expect(buildApprovalWorkflowRules(workflow)).toEqual([ - {triggers: submitTriggers, filters: buildFromFilter(['2@example.com']), actions: forwardActions('1@example.com')}, - // Under the limit and last approver → approve. - {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), and(buildToFilter('1@example.com'), underAmount)), actions: approveActions}, - // Over the limit → escalate to the over-limit approver. - {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), and(buildToFilter('1@example.com'), overAmount)), actions: forwardActions('3@example.com')}, - // The over-limit approver finalizes the report. + {triggers: submitTriggers, filters: and(buildFromFilter(['2@example.com']), underAmount), actions: forwardActions('1@example.com')}, + {triggers: submitTriggers, filters: and(buildFromFilter(['2@example.com']), overAmount), actions: forwardActions('3@example.com')}, + {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('1@example.com')), actions: approveActions}, {triggers: approveTriggers, filters: and(buildFromFilter(['2@example.com']), buildToFilter('3@example.com')), actions: approveActions}, ]); }); + it('Should route an over-limit report to the over-limit approver instead of the limited one, then continue the chain', () => { + // Hola Dola approves up to 100.00; above that "a a" receives the report instead. Either way it carries + // on to the second approver afterwards. + const workflow: ApprovalWorkflow = { + members: [buildMember(2)], + approvers: [buildApprover(1, {approvalLimit: 10000, overLimitForwardsTo: '3@example.com'}), buildApprover(4)], + isDefault: false, + }; + const underAmount = {operator: CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 10000}; + const overAmount = {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, left: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, right: 10000}; + const from = buildFromFilter(['2@example.com']); + + expect(buildApprovalWorkflowRules(workflow)).toEqual([ + {triggers: submitTriggers, filters: and(from, underAmount), actions: forwardActions('1@example.com')}, + {triggers: submitTriggers, filters: and(from, overAmount), actions: forwardActions('3@example.com')}, + {triggers: approveTriggers, filters: and(from, buildToFilter('1@example.com')), actions: forwardActions('4@example.com')}, + {triggers: approveTriggers, filters: and(from, buildToFilter('3@example.com')), actions: forwardActions('4@example.com')}, + {triggers: approveTriggers, filters: and(from, buildToFilter('4@example.com')), actions: approveActions}, + ]); + }); + it('Should ignore a limit split when the limit is not positive', () => { const workflow: ApprovalWorkflow = { members: [buildMember(2)], @@ -1971,6 +1991,25 @@ describe('WorkflowUtils', () => { expect(firstApprover?.overLimitForwardsTo).toBe('3@example.com'); }); + it('Should round-trip a limited first approver back into the same workflow', () => { + const workflow: ApprovalWorkflow = { + members: [buildMember(2)], + approvers: [buildApprover(1, {approvalLimit: 10000, overLimitForwardsTo: '3@example.com'}), buildApprover(4)], + isDefault: false, + }; + const rules = keyRules(buildApprovalWorkflowRules(workflow)); + const employees: PolicyEmployeeList = {'2@example.com': {email: '2@example.com', submitsTo: '1@example.com'}}; + const policy = createPolicy(employees, '1@example.com'); + + const {approvalWorkflows} = convertApprovalWorkflowRulesToWorkflows({policy, personalDetails, localeCompare, rules}); + + const approvers = approvalWorkflows.at(0)?.approvers ?? []; + expect(approvers.map((approver) => approver.email)).toEqual(['1@example.com', '4@example.com']); + expect(approvers.at(0)?.approvalLimit).toBe(10000); + expect(approvers.at(0)?.overLimitForwardsTo).toBe('3@example.com'); + expect(approvers.at(1)?.approvalLimit).toBeNull(); + }); + it('Should round-trip a workflow through rules and back', () => { const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); const employees: PolicyEmployeeList = {'5@example.com': {email: '5@example.com', submitsTo: '1@example.com'}}; From 9d235ce7e81e98e951611c0e8765b5618b168be0 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 13:14:26 +0200 Subject: [PATCH 43/62] better rollback --- src/libs/actions/Workflow.ts | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 255a4044c07b..dced77e3d366 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -25,7 +25,6 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {ApprovalWorkflowOnyx, PersonalDetailsList, Policy, Report} from '@src/types/onyx'; import type {Approver, Member} from '@src/types/onyx/ApprovalWorkflow'; import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow'; -import type {ApprovalWorkflowRule} from '@src/types/onyx/ApprovalWorkflowRules'; import type Rule from '@src/types/onyx/Rule'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -292,8 +291,8 @@ type SetApprovalWorkflowRulesParams = { */ rulesDiff: ApprovalWorkflowRulesDiff; - /** Snapshot of the policy's rules taken before applying `rulesDiff`. Used to roll back on failure. */ - previousRules: Record; + /** The rules as currently stored in Onyx, which `rulesDiff` is applied on top of. Used to roll back on failure. */ + previousRules: OnyxCollection; }; /** @@ -312,13 +311,9 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetAppro for (const [ruleID, rule] of Object.entries(rulesDiff)) { const ruleKey = `${ONYXKEYS.COLLECTION.RULE}${ruleID}` as const; - const previousRule = previousRules[ruleID]; + const previousRule = previousRules?.[ruleKey]; const restore: OnyxUpdate = previousRule - ? { - onyxMethod: Onyx.METHOD.SET, - key: ruleKey, - value: {...previousRule, scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, pendingAction: null, errors: genericError}, - } + ? {onyxMethod: Onyx.METHOD.SET, key: ruleKey, value: {...previousRule, pendingAction: null, errors: genericError}} : {onyxMethod: Onyx.METHOD.SET, key: ruleKey, value: null}; if (rule === null) { @@ -368,7 +363,7 @@ function createApprovalWorkflowRules({approvalWorkflow, policy, addExpenseApprov const rulesDiff = {...removeDiff, ...createDiff}; - setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: rules}); if ( addExpenseApprovalsTaskReport && @@ -411,7 +406,7 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, const rulesDiff = {...removeFromOthersDiff, ...memberDiff, ...chainDiff}; - setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: rules}); } /** @@ -430,7 +425,7 @@ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: return false; } - setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: existingRules}); + setApprovalWorkflowRules({policyID: policy.id, rulesDiff, previousRules: rules}); return true; } From 581b52eb1dbd39cb5ab49ada64a01e8fee657d3d Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 15:06:15 +0200 Subject: [PATCH 44/62] some simplification --- src/libs/WorkflowUtils.ts | 2 +- tests/unit/WorkflowUtilsTest.ts | 41 --------------------------------- 2 files changed, 1 insertion(+), 42 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 1cf2109d1c19..4d94deb9bf8d 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -678,7 +678,7 @@ function getEligibleExistingBusinessBankAccounts( account.bankCurrency === policyCurrency && (account.accountData?.state === CONST.BANK_ACCOUNT.STATE.OPEN || (shouldIncludePartiallySetup && isBankAccountPartiallySetup(account.accountData?.state))) && account.accountData?.type === CONST.BANK_ACCOUNT.TYPE.BUSINESS && - (excludeBankAccountID === undefined || account.methodID !== excludeBankAccountID) + account.methodID !== excludeBankAccountID ); }); } diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index cc92ca8d728d..8bbbb0a3d3c7 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -12,7 +12,6 @@ import { extractSubmitterEmails, filterRulesForPolicy, getApprovalLimitDescription, - getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts, getOverLimitForwardsToDisplayName, getRulesSubmitterToFirstApprover, @@ -1643,46 +1642,6 @@ describe('WorkflowUtils', () => { }); }); - describe('getEligibleExistingBusinessBankAccounts', () => { - const openBusinessBankAccount = { - bankCurrency: 'USD', - bankCountry: 'US', - accountData: { - state: CONST.BANK_ACCOUNT.STATE.OPEN, - type: CONST.BANK_ACCOUNT.TYPE.BUSINESS, - }, - }; - - it('should return an empty array when the bank account list is undefined', () => { - expect(getEligibleExistingBusinessBankAccounts(undefined, 'USD')).toEqual([]); - }); - - it('should return an empty array when the policy currency is undefined', () => { - expect(getEligibleExistingBusinessBankAccounts({'1': openBusinessBankAccount}, undefined)).toEqual([]); - }); - - it('should return open business accounts matching the policy currency', () => { - expect(getEligibleExistingBusinessBankAccounts({'1': openBusinessBankAccount}, 'USD')).toEqual([openBusinessBankAccount]); - }); - - it('should filter out accounts with a non-matching currency', () => { - const eurAccount = {...openBusinessBankAccount, bankCurrency: 'EUR'}; - expect(getEligibleExistingBusinessBankAccounts({'1': eurAccount}, 'USD')).toEqual([]); - }); - - it('should filter out non-business accounts', () => { - const personalAccount = {...openBusinessBankAccount, accountData: {...openBusinessBankAccount.accountData, type: CONST.BANK_ACCOUNT.TYPE.PERSONAL}}; - expect(getEligibleExistingBusinessBankAccounts({'1': personalAccount}, 'USD')).toEqual([]); - }); - - it('should exclude partially set up accounts by default but include them when requested', () => { - const setupAccount = {...openBusinessBankAccount, accountData: {...openBusinessBankAccount.accountData, state: CONST.BANK_ACCOUNT.STATE.SETUP}}; - - expect(getEligibleExistingBusinessBankAccounts({'1': setupAccount}, 'USD')).toEqual([]); - expect(getEligibleExistingBusinessBankAccounts({'1': setupAccount}, 'USD', true)).toEqual([setupAccount]); - }); - }); - describe('rule-based approval workflows', () => { const submitTriggers = {'0': CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_SUBMIT}; const approveTriggers = {'0': CONST.RULES.APPROVAL_WORKFLOW.TRIGGER.REPORT_APPROVE}; From 059b8ace5a107f39bdad224d142f14891a10c252 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 15:07:46 +0200 Subject: [PATCH 45/62] reorder pieces --- src/libs/WorkflowUtils.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 4d94deb9bf8d..3cb993a092a6 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -744,8 +744,8 @@ function mergeWorkflowMembersWithAvailableMembers(workflowMembers: Member[], all type ApprovalWorkflowRulesDiff = Record; function buildComparison( - operator: ValueOf, left: ApprovalWorkflowFilterComparison['left'], + operator: ValueOf, right: ApprovalWorkflowFilterComparison['right'], ): ApprovalWorkflowFilterComparison { return {operator, left, right}; @@ -756,11 +756,11 @@ function buildAnd(left: ApprovalWorkflowFilter['left'], right: ApprovalWorkflowF } function buildSubmitterFilter(memberEmails: string[]): ApprovalWorkflowFilterComparison { - return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, [...memberEmails]); + return buildComparison(CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, [...memberEmails]); } function buildToComparison(email: string): ApprovalWorkflowFilterComparison { - return buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, email); + return buildComparison(CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, email); } /** The index-keyed object shape the rules API uses for lists (`['a', 'b'] -> {'0': 'a', '1': 'b'}`). */ @@ -850,8 +850,8 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva continue; } - const underAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, holders.limit); - const overAmount = buildComparison(CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, holders.limit); + const underAmount = buildComparison(CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, holders.limit); + const overAmount = buildComparison(CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO, holders.limit); rulesIntoPosition.push({triggers, filters: buildAnd(source, underAmount), actions: buildForwardActions(holders.underLimitEmail)}); rulesIntoPosition.push({triggers, filters: buildAnd(source, overAmount), actions: buildForwardActions(holders.overLimitEmail)}); From f805a3de645d9b74b8532b317feb46c8ad6012ee Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 15:25:01 +0200 Subject: [PATCH 46/62] better fingerprint --- src/libs/WorkflowUtils.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 3cb993a092a6..87faec81af72 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -880,7 +880,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva // Different approvers may share an `overLimitForwardsTo`, which would emit identical terminal rules. const seen = new Set(); return rules.filter((rule) => { - const fingerprint = JSON.stringify(rule); + const fingerprint = canonicalFingerprint(rule); if (seen.has(fingerprint)) { return false; } @@ -970,6 +970,11 @@ function canonicalize(value: unknown): unknown { * stripped and keys canonicalized. Two rules with the same fingerprint differ only in their submitters, * which is what we look for when deciding whether to merge two workflows into a shared rule. */ +/** A string that is equal for two values that mean the same thing, regardless of the order their keys were built in. */ +function canonicalFingerprint(value: unknown): string { + return JSON.stringify(canonicalize(value)); +} + function structuralFingerprint(rule: ApprovalWorkflowRule): string { const stripFromValues = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): unknown => { if (!node) { @@ -984,13 +989,11 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { return {operator: node.operator, left: stripFromValues(node.left), right: stripFromValues(node.right)}; }; - return JSON.stringify( - canonicalize({ - triggers: rule.triggers, - filters: stripFromValues(rule.filters), - actions: rule.actions, - }), - ); + return canonicalFingerprint({ + triggers: rule.triggers, + filters: stripFromValues(rule.filters), + actions: rule.actions, + }); } /** Replace the `right` value on every `from` leaf with `newEmails`. */ From 6ceef53b7bb5d29973cb83cbe10e5dbd4a5488e0 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 15:26:23 +0200 Subject: [PATCH 47/62] remove comment --- src/ONYXKEYS.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 2ddf961928bc..7ee36477683b 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -880,7 +880,6 @@ const ONYXKEYS = { POLICY_HAS_CONNECTIONS_DATA_BEEN_FETCHED: 'policyHasConnectionsDataBeenFetched_', POLICY_CONNECTION_SYNC_PROGRESS: 'policyConnectionSyncProgress_', POLICY_MERGE_HR_INITIAL_SYNC_MODAL_SHOWN: 'policyMergeHRInitialSyncModalShown_', - // AST rules keyed by ruleID RULE: 'rules_', WORKSPACE_INVITE_MEMBERS_DRAFT: 'workspaceInviteMembersDraft_', WORKSPACE_INVITE_MESSAGE_DRAFT: 'workspaceInviteMessageDraft_', From 7c07b85fb1abded79eea44ce5e9d7bdd9acd4b9e Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 15:36:40 +0200 Subject: [PATCH 48/62] reuse generic methods --- src/libs/WorkflowUtils.ts | 79 +++++++++++++-------------------------- 1 file changed, 27 insertions(+), 52 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 87faec81af72..548fa206d764 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -909,37 +909,37 @@ function isSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilter return isComparisonLeaf(node) && node.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && node.left === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM; } -/** Walk a filter tree and call `callback` on every submitter filter (the `from` leaf) in it. */ -function forEachSubmitterFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, callback: (filter: ApprovalWorkflowFilterComparison) => void): void { +/** Return the first comparison leaf in the filter tree whose `left` field matches. */ +function getFilter(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined, leftKey: string): ApprovalWorkflowFilterComparison | undefined { if (!node) { - return; + return undefined; } if (isComparisonLeaf(node)) { - if (isSubmitterFilter(node)) { - callback(node); - } - return; + return node.left === leftKey ? node : undefined; + } + return getFilter(node.left, leftKey) ?? getFilter(node.right, leftKey); +} + +/** Rebuild a filter tree, replacing every comparison leaf with the result of `mapLeaf`. */ +function mapFilters( + node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison, + mapLeaf: (leaf: ApprovalWorkflowFilterComparison) => ApprovalWorkflowFilterComparison, +): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison { + if (isComparisonLeaf(node)) { + return mapLeaf(node); } - forEachSubmitterFilter(node.left, callback); - forEachSubmitterFilter(node.right, callback); + return {...node, left: mapFilters(node.left, mapLeaf), right: mapFilters(node.right, mapLeaf)}; } -/** Extract the union of email values across every `from` leaf in a rule. */ +/** The emails a rule's `from` filter lists. */ function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { - const emails = new Set(); - forEachSubmitterFilter(rule.filters, (filter) => { - const right = filter.right; - if (Array.isArray(right)) { - for (const email of right) { - if (typeof email === 'string') { - emails.add(email); - } - } - } else if (typeof right === 'string') { - emails.add(right); - } - }); - return Array.from(emails); + const submitterFilter = getFilter(rule.filters, CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM); + if (!submitterFilter || !isSubmitterFilter(submitterFilter)) { + return []; + } + + const emails = Array.isArray(submitterFilter.right) ? submitterFilter.right : [submitterFilter.right]; + return Array.from(new Set(emails.filter((email): email is string => typeof email === 'string'))); } /** @@ -998,17 +998,7 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { /** Replace the `right` value on every `from` leaf with `newEmails`. */ function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]): ApprovalWorkflowRule { - const rewrite = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison): ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison => { - if (isComparisonLeaf(node)) { - return isSubmitterFilter(node) ? {...node, right: [...newEmails]} : node; - } - return { - ...node, - left: rewrite(node.left), - right: rewrite(node.right), - }; - }; - return {...rule, filters: rewrite(rule.filters)}; + return {...rule, filters: mapFilters(rule.filters, (leaf) => (isSubmitterFilter(leaf) ? {...leaf, right: [...newEmails]} : leaf))}; } /** Merge `emailsToAdd` into `existingEmails`, preserving the order of `existingEmails` and dropping duplicates. */ @@ -1206,21 +1196,6 @@ function applyApprovalWorkflowRulesDiff(existingRules: Record> { return Object.values(rule.triggers ?? {}); @@ -1298,7 +1273,7 @@ function resolvePositionHolders(submitter: string, rules: Record Date: Mon, 10 Aug 2026 15:37:49 +0200 Subject: [PATCH 49/62] Update src/libs/WorkflowUtils.ts Co-authored-by: Jack Senyitko <49812749+JS00001@users.noreply.github.com> --- src/libs/WorkflowUtils.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 548fa206d764..686041f80efa 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1003,16 +1003,12 @@ function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]) /** Merge `emailsToAdd` into `existingEmails`, preserving the order of `existingEmails` and dropping duplicates. */ function mergeEmails(existingEmails: string[], emailsToAdd: string[]): string[] { - const seen = new Set(existingEmails); - const result = [...existingEmails]; - for (const email of emailsToAdd) { - if (seen.has(email)) { - continue; - } - seen.add(email); - result.push(email); - } - return result; + const seen = new Set(existingEmails); + + return [ + ...existingEmails, + ...emailsToAdd.filter(email => !seen.has(email) && !!seen.add(email)), + ]; } /** Remove everything in `emailsToRemove` from `existingEmails`, preserving the order of `existingEmails`. */ From 6b05cea208afb1e92e69fb8e36b185b6bfdd3a4e Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 16:19:19 +0200 Subject: [PATCH 50/62] better comment --- src/libs/actions/Workflow.ts | 3 +++ .../approvals/WorkspaceWorkflowsApprovalsEditPage.tsx | 4 +++- tests/unit/WorkflowUtilsTest.ts | 4 ++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index dced77e3d366..1ad6322528cc 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -411,6 +411,9 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, /** * Delete an approval workflow using the rules-based backend structure. + * + * Returns false without calling the API when this policy has no rules covering the workflow's members, so the + * caller can fall back to the `employeeList` path. */ function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry, rules: OnyxCollection): boolean { if (!policy) { diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx index b1bea4455930..4b0e251a768e 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx @@ -112,9 +112,11 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = true Navigation.dismissModal({ afterTransition: () => { // Remove the approval workflow using the initial data as it could be already edited - if (useRulesBackend && removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection)) { + const didRemoveRules = useRulesBackend && removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection); + if (didRemoveRules) { return; } + removeApprovalWorkflow(initialApprovalWorkflow, policy); }, }); diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 8bbbb0a3d3c7..a563dd2bee88 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1699,8 +1699,8 @@ describe('WorkflowUtils', () => { }); it('Should route an over-limit report to the over-limit approver instead of the limited one, then continue the chain', () => { - // Hola Dola approves up to 100.00; above that "a a" receives the report instead. Either way it carries - // on to the second approver afterwards. + // 1@example.com approves up to 100.00; above that 3@example.com receives the report instead. Either way + // it carries on to 4@example.com afterwards. const workflow: ApprovalWorkflow = { members: [buildMember(2)], approvers: [buildApprover(1, {approvalLimit: 10000, overLimitForwardsTo: '3@example.com'}), buildApprover(4)], From a24d7a041049320a62a1cbd751f9e0c7a73b45fd Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 16:27:13 +0200 Subject: [PATCH 51/62] uneeded helper function --- src/libs/WorkflowUtils.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 548fa206d764..21e59c1f9975 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1021,11 +1021,6 @@ function removeEmails(existingEmails: string[], emailsToRemove: string[]): strin return existingEmails.filter((email) => !removalSet.has(email)); } -/** True when any of `emails` is in `set` — i.e. a rule's submitters overlap a workflow's members. */ -function containsAnyEmail(emails: string[], set: Set): boolean { - return emails.some((email) => set.has(email)); -} - /** Fold `memberEmails` into a rule's `from` list (union), returning the updated rule. */ function addMembersToRule(rule: ApprovalWorkflowRule, memberEmails: string[]): ApprovalWorkflowRule { return replaceSubmitterEmails(rule, mergeEmails(extractSubmitterEmails(rule), memberEmails)); @@ -1082,7 +1077,7 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], // Pass 1: walk existing rules that belong (at least partially) to this workflow. for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { const ruleEmails = extractSubmitterEmails(existingRule); - if (!containsAnyEmail(ruleEmails, memberSet)) { + if (!ruleEmails.some((email) => memberSet.has(email))) { continue; } @@ -1117,7 +1112,7 @@ function reconcileApprovalWorkflowRulesForEdit(newRules: ApprovalWorkflowRule[], return false; } // "Different workflow" => no overlap with our members. - return !containsAnyEmail(extractSubmitterEmails(existing), memberSet); + return !extractSubmitterEmails(existing).some((email) => memberSet.has(email)); }); if (foreignMatch) { @@ -1143,7 +1138,7 @@ function reconcileApprovalWorkflowRulesForRemove(memberEmails: string[], context for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { const ruleEmails = extractSubmitterEmails(existingRule); - if (!containsAnyEmail(ruleEmails, memberSet)) { + if (!ruleEmails.some((email) => memberSet.has(email))) { continue; } @@ -1166,7 +1161,7 @@ function reconcileApprovalWorkflowRulesForMembersChange(previousMemberEmails: st for (const [ruleID, existingRule] of Object.entries(context.existingRules)) { const ruleEmails = extractSubmitterEmails(existingRule); - if (!containsAnyEmail(ruleEmails, previousSet)) { + if (!ruleEmails.some((email) => previousSet.has(email))) { continue; } From 0c69fc012404763c2dc86a33774a920936a4b9b6 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 10 Aug 2026 16:46:40 +0200 Subject: [PATCH 52/62] fmt --- src/libs/WorkflowUtils.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index eabe40218d55..0b429976aa54 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1003,12 +1003,9 @@ function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]) /** Merge `emailsToAdd` into `existingEmails`, preserving the order of `existingEmails` and dropping duplicates. */ function mergeEmails(existingEmails: string[], emailsToAdd: string[]): string[] { - const seen = new Set(existingEmails); + const seen = new Set(existingEmails); - return [ - ...existingEmails, - ...emailsToAdd.filter(email => !seen.has(email) && !!seen.add(email)), - ]; + return [...existingEmails, ...emailsToAdd.filter((email) => !seen.has(email) && !!seen.add(email))]; } /** Remove everything in `emailsToRemove` from `existingEmails`, preserving the order of `existingEmails`. */ From d9ff9f97e5b06657a082aa800f31619fc57b332b Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:16:03 +0200 Subject: [PATCH 53/62] fix action --- src/libs/actions/Workflow.ts | 8 +++++- tests/actions/WorkflowTest.ts | 48 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts index 1ad6322528cc..91125b9267e8 100644 --- a/src/libs/actions/Workflow.ts +++ b/src/libs/actions/Workflow.ts @@ -326,7 +326,13 @@ function setApprovalWorkflowRules({policyID, rulesDiff, previousRules}: SetAppro optimisticData.push({ onyxMethod: Onyx.METHOD.SET, key: ruleKey, - value: {...rule, scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, errors: null}, + value: { + ...rule, + scope: CONST.RULES.SCOPE.POLICY, + scopeID: policyID, + pendingAction: previousRule ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE : CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, + errors: null, + }, }); successData.push({onyxMethod: Onyx.METHOD.MERGE, key: ruleKey, value: {pendingAction: null}}); failureData.push(restore); diff --git a/tests/actions/WorkflowTest.ts b/tests/actions/WorkflowTest.ts index cb8d62887712..0890fe2b2a19 100644 --- a/tests/actions/WorkflowTest.ts +++ b/tests/actions/WorkflowTest.ts @@ -1101,6 +1101,54 @@ describe('actions/Workflow', () => { await mockFetch.resume(); await waitForBatchedUpdates(); }); + + it('marks rewritten rules as pending update rather than pending add', async () => { + mockFetch.pause(); + + const policyID = '123456789'; + const policy: Policy = { + ...createRandomPolicy(1), + id: policyID, + owner: ownerEmail, + rules: {}, + }; + + // Seed the existing [employee1] → [owner] workflow as rules in the collection. + await createForwardApproveRules(policyID, [employee1Email], ownerEmail); + + const initialApprovalWorkflow = { + members: [{email: employee1Email, displayName: employee1Email}], + approvers: [{email: ownerEmail, displayName: ownerEmail, isCircularReference: false}], + availableMembers: [], + usedApproverEmails: [], + isDefault: false, + action: 'update', + originalApprovers: [], + }; + + // Adding a member keeps the same approver chain, so the seeded rules are rewritten under their own IDs. + const approvalWorkflow = { + ...initialApprovalWorkflow, + members: [ + {email: employee1Email, displayName: employee1Email}, + {email: employee2Email, displayName: employee2Email}, + ], + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policy); + await Onyx.merge(ONYXKEYS.SESSION, {authToken: '123456789'}); + await waitForBatchedUpdates(); + + updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow, policy, rules: await getRulesCollection()}); + await waitForBatchedUpdates(); + + const collection = await getRulesCollection(); + expect(collection?.[`${ONYXKEYS.COLLECTION.RULE}rule1`]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE); + expect(collection?.[`${ONYXKEYS.COLLECTION.RULE}rule2`]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE); + + await mockFetch.resume(); + await waitForBatchedUpdates(); + }); }); describe('removeApprovalWorkflowRules', () => { From 0b480dc290ec566f265b2da041d6c15752098f8b Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:19:23 +0200 Subject: [PATCH 54/62] cleanup --- src/libs/WorkflowUtils.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 0b429976aa54..f5770b355846 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1003,9 +1003,7 @@ function replaceSubmitterEmails(rule: ApprovalWorkflowRule, newEmails: string[]) /** Merge `emailsToAdd` into `existingEmails`, preserving the order of `existingEmails` and dropping duplicates. */ function mergeEmails(existingEmails: string[], emailsToAdd: string[]): string[] { - const seen = new Set(existingEmails); - - return [...existingEmails, ...emailsToAdd.filter((email) => !seen.has(email) && !!seen.add(email))]; + return [...new Set([...existingEmails, ...emailsToAdd])]; } /** Remove everything in `emailsToRemove` from `existingEmails`, preserving the order of `existingEmails`. */ From 09f7dccfde45baaa9f6f65bedb60ba5d81ca1748 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:21:39 +0200 Subject: [PATCH 55/62] simplify tests --- tests/unit/WorkflowUtilsTest.ts | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 1159679c7cf1..d4654850aa7b 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -1904,18 +1904,12 @@ describe('WorkflowUtils', () => { }); describe('convertApprovalWorkflowRulesToWorkflows', () => { - const createPolicy = (employees: PolicyEmployeeList, defaultApprover: string) => - ({ - id: 'test-policy', - name: 'Test Policy', - role: 'admin' as const, - type: 'team' as const, - owner: 'owner@example.com', - outputCurrency: 'USD', - isPolicyExpenseChatEnabled: true, - employeeList: employees, - approver: defaultApprover, - }) as Policy; + const createPolicy = (employees: PolicyEmployeeList, defaultApprover: string): Policy => ({ + ...createRandomPolicy(1), + owner: 'owner@example.com', + employeeList: employees, + approver: defaultApprover, + }); it('Should reconstruct a multi-approver chain from rules', () => { const rules = keyRules(buildApprovalWorkflowRules(buildWorkflow([5], [1, 2]))); From 8158218d2fb75905c7fc20ec548b6825f4e57101 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:25:34 +0200 Subject: [PATCH 56/62] simplify --- src/libs/actions/Policy/Policy.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 8fe6d48bc35e..7cb59f0bf0a0 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -1088,9 +1088,11 @@ function setWorkspaceApprovalMode( if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { continue; } - const ruleOnyxKey: `${typeof ONYXKEYS.COLLECTION.RULE}${string}` = `${ONYXKEYS.COLLECTION.RULE}${ruleKey.slice(ONYXKEYS.COLLECTION.RULE.length)}`; - optimisticData.push({onyxMethod: Onyx.METHOD.SET, key: ruleOnyxKey, value: null}); - failureData.push({onyxMethod: Onyx.METHOD.SET, key: ruleOnyxKey, value: rule}); + // `Object.entries` widens the collection keys to `string`, so rebuild the key from the rule ID to get + // the `rules_${string}` type that an Onyx update needs. + const ruleID = ruleKey.slice(ONYXKEYS.COLLECTION.RULE.length); + optimisticData.push({onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.RULE}${ruleID}`, value: null}); + failureData.push({onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.RULE}${ruleID}`, value: rule}); } } const successData: Array> = [ From f5ac580297c22d12381fff9a60bca9d7691da7e4 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:27:48 +0200 Subject: [PATCH 57/62] cleanup comment --- src/libs/WorkflowUtils.ts | 10 +++++----- src/libs/actions/Policy/Policy.ts | 2 -- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index f5770b355846..fc95abef29a6 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -965,16 +965,16 @@ function canonicalize(value: unknown): unknown { return value; } -/** - * Return a structural fingerprint of a rule with every `from` leaf's `right` (the submitter list) - * stripped and keys canonicalized. Two rules with the same fingerprint differ only in their submitters, - * which is what we look for when deciding whether to merge two workflows into a shared rule. - */ /** A string that is equal for two values that mean the same thing, regardless of the order their keys were built in. */ function canonicalFingerprint(value: unknown): string { return JSON.stringify(canonicalize(value)); } +/** + * Return a structural fingerprint of a rule with every `from` leaf's `right` (the submitter list) + * stripped and keys canonicalized. Two rules with the same fingerprint differ only in their submitters, + * which is what we look for when deciding whether to merge two workflows into a shared rule. + */ function structuralFingerprint(rule: ApprovalWorkflowRule): string { const stripFromValues = (node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): unknown => { if (!node) { diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 7cb59f0bf0a0..d57ecbec3d0f 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -1088,8 +1088,6 @@ function setWorkspaceApprovalMode( if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { continue; } - // `Object.entries` widens the collection keys to `string`, so rebuild the key from the rule ID to get - // the `rules_${string}` type that an Onyx update needs. const ruleID = ruleKey.slice(ONYXKEYS.COLLECTION.RULE.length); optimisticData.push({onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.RULE}${ruleID}`, value: null}); failureData.push({onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.RULE}${ruleID}`, value: rule}); From eda201ba423aa2803ab82970ed7af29ff1cf3224 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:31:51 +0200 Subject: [PATCH 58/62] left can't be an array --- src/libs/WorkflowUtils.ts | 8 ++------ src/types/onyx/ApprovalWorkflowRules.ts | 15 ++++++--------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index fc95abef29a6..006ae77b4b02 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -894,14 +894,10 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva * joins two other nodes. * * Both look the same (`{operator, left, right}`), so the giveaway is `left`: a comparison points at a field - * name, an `AND` points at another node. Arrays count as comparisons too. + * name, an `AND` points at another node. */ function isComparisonLeaf(node: ApprovalWorkflowFilter | ApprovalWorkflowFilterComparison | undefined): node is ApprovalWorkflowFilterComparison { - if (!node) { - return false; - } - const nodeLeft = node.left; - return typeof nodeLeft !== 'object' || nodeLeft === null || Array.isArray(nodeLeft); + return !!node && typeof node.left === 'string'; } /** True when a comparison node targets the `from` field with an equality operator. */ diff --git a/src/types/onyx/ApprovalWorkflowRules.ts b/src/types/onyx/ApprovalWorkflowRules.ts index 06d5d308d702..0072b5628887 100644 --- a/src/types/onyx/ApprovalWorkflowRules.ts +++ b/src/types/onyx/ApprovalWorkflowRules.ts @@ -35,13 +35,10 @@ type ApprovalWorkflowAction = { type ApprovalWorkflowActions = Record; /** - * Operand of a comparison in an approval-workflow filter. - * - * - The left operand is a field identifier — one of the search-syntax filter keys (`from`, `to`, `amount`). - * - The right operand is the literal value the field is compared against. For email-typed fields like - * `from`, the value may be a list of emails to match against. + * The value a comparison's field is compared against. For email-typed fields like `from`, this is a list + * of emails to match against. */ -type ApprovalWorkflowFilterOperand = string | number | string[]; +type ApprovalWorkflowFilterValue = string | number | string[]; /** * A single comparison node: ` `. Both `left` and `right` are always present. @@ -50,11 +47,11 @@ type ApprovalWorkflowFilterComparison = { /** The comparison operator. */ operator: ValueOf; - /** The field identifier being compared. */ - left: ApprovalWorkflowFilterOperand; + /** The field identifier being compared — one of the search-syntax filter keys (`from`, `to`, `amount`). */ + left: string; /** The literal value being compared against. */ - right: ApprovalWorkflowFilterOperand; + right: ApprovalWorkflowFilterValue; }; /** From 2beb6fc3a541c0ecb658366e15e31290bba674a3 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:38:38 +0200 Subject: [PATCH 59/62] rename function --- src/libs/WorkflowUtils.ts | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 006ae77b4b02..0152f742cdd6 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -880,7 +880,7 @@ function buildApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow): Approva // Different approvers may share an `overLimitForwardsTo`, which would emit identical terminal rules. const seen = new Set(); return rules.filter((rule) => { - const fingerprint = canonicalFingerprint(rule); + const fingerprint = JSON.stringify(sortObjectKeysDeep(rule)); if (seen.has(fingerprint)) { return false; } @@ -944,9 +944,9 @@ function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] { * Only key order needs fixing: a rule that came back from the server can list the same keys in a different * order than one we just built, and those two would otherwise produce different strings and never match. */ -function canonicalize(value: unknown): unknown { +function sortObjectKeysDeep(value: unknown): unknown { if (Array.isArray(value)) { - return value.map(canonicalize); + return value.map(sortObjectKeysDeep); } if (value !== null && typeof value === 'object') { // Byte-order sort (not locale-aware): this is a structural fingerprint, not user-facing text. @@ -956,19 +956,14 @@ function canonicalize(value: unknown): unknown { } return a < b ? -1 : 1; }); - return Object.fromEntries(sortedEntries.map(([key, val]) => [key, canonicalize(val)])); + return Object.fromEntries(sortedEntries.map(([key, val]) => [key, sortObjectKeysDeep(val)])); } return value; } -/** A string that is equal for two values that mean the same thing, regardless of the order their keys were built in. */ -function canonicalFingerprint(value: unknown): string { - return JSON.stringify(canonicalize(value)); -} - /** * Return a structural fingerprint of a rule with every `from` leaf's `right` (the submitter list) - * stripped and keys canonicalized. Two rules with the same fingerprint differ only in their submitters, + * stripped and object keys sorted. Two rules with the same fingerprint differ only in their submitters, * which is what we look for when deciding whether to merge two workflows into a shared rule. */ function structuralFingerprint(rule: ApprovalWorkflowRule): string { @@ -985,11 +980,13 @@ function structuralFingerprint(rule: ApprovalWorkflowRule): string { return {operator: node.operator, left: stripFromValues(node.left), right: stripFromValues(node.right)}; }; - return canonicalFingerprint({ - triggers: rule.triggers, - filters: stripFromValues(rule.filters), - actions: rule.actions, - }); + return JSON.stringify( + sortObjectKeysDeep({ + triggers: rule.triggers, + filters: stripFromValues(rule.filters), + actions: rule.actions, + }), + ); } /** Replace the `right` value on every `from` leaf with `newEmails`. */ From 99875d0a49b6f7b1f6c84cea589e1aa21e46a672 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:40:42 +0200 Subject: [PATCH 60/62] reuse filterRulesForPolicy --- src/libs/WorkflowUtils.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 0152f742cdd6..9b4f0c549c0f 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1404,15 +1404,9 @@ function filterRulesForPolicy(rulesCollection: OnyxCollection, policyID: s */ function getApprovalWorkflowRulesForPolicy(rulesCollection: OnyxCollection | undefined, policyID: string | undefined): Record { const result: Record = {}; - if (!rulesCollection || !policyID) { - return result; - } - for (const [onyxKey, rule] of Object.entries(rulesCollection)) { - if (!rule || rule.scope !== CONST.RULES.SCOPE.POLICY || rule.scopeID !== policyID) { - continue; - } - if (rule.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + for (const [onyxKey, rule] of Object.entries(filterRulesForPolicy(rulesCollection, policyID))) { + if (!rule || rule.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { continue; } const ruleID = onyxKey.slice(ONYXKEYS.COLLECTION.RULE.length); From 24b135b1a7fa89e974000cb4d6bb8bd389552a6b Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:42:55 +0200 Subject: [PATCH 61/62] moved to module level --- src/libs/WorkflowUtils.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 9b4f0c549c0f..8b6747b2746a 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -1464,6 +1464,14 @@ function getRulesSubmitterToWorkflowKey(rules: Record(); const usedApproverEmails = new Set(); const availableMembers: Member[] = []; From c85ce361829820d60823f52d243a6eda94f27ace Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 25 Aug 2026 19:56:08 +0200 Subject: [PATCH 62/62] Match Mobile-Expensify submodule to main --- Mobile-Expensify | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mobile-Expensify b/Mobile-Expensify index 7e8bfd0bb953..79674077a3a1 160000 --- a/Mobile-Expensify +++ b/Mobile-Expensify @@ -1 +1 @@ -Subproject commit 7e8bfd0bb95320d73b15d54d20875cf2d86d9891 +Subproject commit 79674077a3a172153b707d139393bffd8bb36bc1