Skip to content

[Payment due @thelullabyy] Allow setting and displaying approval workflows with the new structure - #94825

Open
Gonals wants to merge 55 commits into
mainfrom
alberto-moreApprovers
Open

[Payment due @thelullabyy] Allow setting and displaying approval workflows with the new structure#94825
Gonals wants to merge 55 commits into
mainfrom
alberto-moreApprovers

Conversation

@Gonals

@Gonals Gonals commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Fixed Issues

$ https://github.com/Expensify/Expensify/issues/651010
PROPOSAL:

Tests

This is where all the testing happens. Get ready because it is fun!

  1. Enable approval workflows:
Screenshot 2026-07-30 at 16 42 31
  1. Create a new workflow for a couple of users. Make it simple for now (a first approver and a second one, no overLimit)
  2. Confirm it displays properly
  3. Confirm it still displays properly after logout-login
  4. Dev only: Check the DB with select * from rules where scopeID='<POLICYID>';. Confirm the rules are in the right shape
  5. Add someone to the workflow. Confirm it gets added properly and gets added to the existing rules in the DB (no new rules)
  6. Change one of the approvers. Confirm it does so and the rules in the DB reflect it properly.
  7. Create a new workflow for a different user, with the same approvers. Confirm the user gets added to the existing flow and rules instead.
  8. Try to create a new workflow for users already in one. You should see this, but be allowed to do so:
Screenshot 2026-07-30 at 16 48 22
  1. Create a new workflow for new users with the same first approver, but a different second one.
  2. Confirm it displays as a different workflow. In the DB, it should share the first approver rule with the other users, but have a new rule for the second approver
  3. Confirm removing users from workflows works properly.
  4. Try adding over limit approvers and try similar things to the ones above. Confirm the behavior and display is the one you'd expect.
  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

Same as tests, but no DB checks

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

@Gonals Gonals self-assigned this Jun 29, 2026
@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/CONST/index.ts 94.81% <ø> (ø)
src/ONYXKEYS.ts 100.00% <ø> (ø)
src/libs/API/types.ts 100.00% <ø> (ø)
src/libs/ExportOnyxState/common.ts 80.35% <ø> (ø)
...ace/workflows/approvals/ApprovalWorkflowEditor.tsx 80.76% <ø> (ø)
...s/WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx 0.00% <ø> (ø)
src/ROUTES.ts 23.31% <0.00%> (ø)
...ges/workspace/workflows/WorkspaceWorkflowsPage.tsx 73.47% <88.88%> (+0.41%) ⬆️
...rovals/WorkspaceWorkflowsApprovalsApproverPage.tsx 0.00% <0.00%> (ø)
...pprovals/WorkspaceWorkflowsApprovalsCreatePage.tsx 0.00% <0.00%> (ø)
... and 5 more
... and 9 files with indirect coverage changes

@Gonals
Gonals marked this pull request as ready for review June 30, 2026 00:15
@Gonals
Gonals requested review from a team as code owners June 30, 2026 00:15
@thelullabyy

Copy link
Copy Markdown
Contributor

@Gonals Changes lgtm, please let me know when the backend PR is available on staging so that I can test and do final round of review

@Gonals

Gonals commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

@Gonals Changes lgtm, please let me know when the backend PR is available on staging so that I can test and do final round of review

You should be good to test

@thelullabyy

Copy link
Copy Markdown
Contributor

@Gonals Could you please check if we need enable any BE flag in order to test? lullabyythe+91063@gmail.com

It doesn't save the data for me in case I apply the workflow with limit

Screen.Recording.2026-08-05.at.06.21.46.mov

@thelullabyy

Copy link
Copy Markdown
Contributor

BUG 1:

  1. Create several workflows
  2. Go to Account -> Delete cache
  3. Go back workflows

Expected: We should be able to see created workflows
Actual: No workflows shown unless we reload the page

Screen.Recording.2026-08-05.at.06.45.47.mov

@thelullabyy

Copy link
Copy Markdown
Contributor

@Gonals sometimes, I cannot delete workflows

Screen.Recording.2026-08-05.at.07.12.16.mov

@thelullabyy

thelullabyy commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@Gonals I think below is the patch to fix this bug

RCA: removeApprovalWorkflowRules has no equivalent fallback to legacy data likeresolveFirstApprover. It can only delete rules that exist in rules. For any workspace whose workflows predate the rules migration (every existing workspace)

diff --git a/src/libs/actions/Workflow.ts b/src/libs/actions/Workflow.ts
index e2996eb040f..ceb87911cee 100644
--- a/src/libs/actions/Workflow.ts
+++ b/src/libs/actions/Workflow.ts
@@ -415,16 +415,21 @@ function updateApprovalWorkflowRules({approvalWorkflow, initialApprovalWorkflow,
 }
 
 /** Delete an approval workflow using the rules-based backend structure. */
-function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry<Policy>, rules: OnyxCollection<Rule>) {
+function removeApprovalWorkflowRules(approvalWorkflow: ApprovalWorkflow, policy: OnyxEntry<Policy>, rules: OnyxCollection<Rule>): 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 97c564cf8a4..3ca83ba9893 100644
--- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx
+++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx
@@ -111,12 +111,10 @@ function WorkspaceWorkflowsApprovalsEditPage({policy, isLoadingReportData = 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
-                if (useRulesBackend) {
-                    removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection);
-                } else {
-                    removeApprovalWorkflow(initialApprovalWorkflow, policy);
+                if (useRulesBackend && removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection)) {
+                    return;
                 }
+                removeApprovalWorkflow(initialApprovalWorkflow, policy);
             },
         });
     };

@thelullabyy

Copy link
Copy Markdown
Contributor

This issue was false alarm, it works fine now after I got the beta flag enabled in BE

Screen.Recording.2026-08-05.at.16.04.50.mov

@thelullabyy

Copy link
Copy Markdown
Contributor

We can ignore this issue as it is very edge case which normal user won't reach

@thelullabyy

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2b7f1a9262

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/WorkflowUtils.ts
@thelullabyy

Copy link
Copy Markdown
Contributor

@Gonals Could you please check the AI bot comments?

@Gonals

Gonals commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@Gonals Could you please check the AI bot comments?

Done

@thelullabyy

thelullabyy commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@Gonals I found another issue is that when I try to update an existing Approvals by adding additional (second) approver, the optimistic data is showing correctly, but after getting response from BE, it the newly added approver is removed

Screen.Recording.2026-08-05.at.22.41.21.mov

@Gonals

Gonals commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

@Gonals I found another issue is that when I try to update an existing Approvals by adding additional (second) approver, the optimistic data is showing correctly, but after getting response from BE, it the newly added approver is removed

Screen.Recording.2026-08-05.at.22.41.21.mov

I haven't been able to reproduce this one, but found a related bug and fixed it. Can you give this one a try again? Maybe that fixed it too.

@thelullabyy thelullabyy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@melvin-bot melvin-bot Bot changed the title Allow setting and displaying approval workflows with the new structure [Payment due @thelullabyy] Allow setting and displaying approval workflows with the new structure Aug 6, 2026
@melvin-bot

melvin-bot Bot commented Aug 6, 2026

Copy link
Copy Markdown

🎯 @thelullabyy, thanks for reviewing and testing this PR! 🎉

A payment issue will be created for your review once this PR is deployed to production.
E/E issue linked to the PR - https://www.github.com/Expensify/Expensify/issues/651010.

If payment is not needed (e.g., regression PR review fix etc), react with 👎 to this comment to prevent the payment issue from being created.

@Gonals
Gonals requested a review from JS00001 August 6, 2026 13:31
@Gonals

Gonals commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

@mountiny, @luacmartins, @tgolen, @JS00001, all yours! Let's push this!

? {
onyxMethod: Onyx.METHOD.SET,
key: ruleKey,
value: {...previousRule, scope: CONST.RULES.SCOPE.POLICY, scopeID: policyID, pendingAction: null, errors: genericError},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to add scope/scopeID here? Shouldn't the previous rule already have that?

Comment on lines +361 to +364
// 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we show any warning to the user that we're doing this? I'd think that the admin wouldn't be able to select a user that is currently in another workflow to begin with.

Comment thread src/libs/WorkflowUtils.ts
(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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this change?

Comment thread src/libs/WorkflowUtils.ts
return [...workflowMembers, ...additionalMembers];
}

type ApprovalWorkflowRulesDiff = Record<string, ApprovalWorkflowRule | null>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NAB but this file seems over-engineered. We only have fixed shapes for these rules as of now, so it seems like we could simplify this quite a bit.

Comment thread src/ONYXKEYS.ts
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// AST rules keyed by ruleID

"../../tests/unit/VideoRendererTest.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1
"../../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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we be adding to the unsafe assertion count?

Comment thread src/libs/WorkflowUtils.ts
Comment on lines +746 to +752
function buildComparison(
operator: ValueOf<typeof CONST.SEARCH.SYNTAX_OPERATORS>,
left: ApprovalWorkflowFilterComparison['left'],
right: ApprovalWorkflowFilterComparison['right'],
): ApprovalWorkflowFilterComparison {
return {operator, left, right};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NAB can we make this take params as left, operator, right so it reads like an equation?

Comment thread src/libs/WorkflowUtils.ts
// Different approvers may share an `overLimitForwardsTo`, which would emit identical terminal rules.
const seen = new Set<string>();
return rules.filter((rule) => {
const fingerprint = JSON.stringify(rule);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to sort this? E.g {a: '', b: ''} wont equal {b: '', a: ''}

Comment thread src/libs/WorkflowUtils.ts
}

/** Extract the union of email values across every `from` leaf in a rule. */
function extractSubmitterEmails(rule: ApprovalWorkflowRule): string[] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'd be helpful to use common AST methods for this (e.g getFilter(rule.filters) rather than parsing the ast in a one off method)

Comment thread src/libs/WorkflowUtils.ts
Comment on lines +996 to +1007
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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;
}
function mergeEmails(existingEmails: string[], emailsToAdd: string[]): string[] {
const seen = new Set(existingEmails);
return [
...existingEmails,
...emailsToAdd.filter(email => !seen.has(email) && !!seen.add(email)),
];
}

Comment thread src/libs/WorkflowUtils.ts
}

/** 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<string>): boolean {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it'd be a bit overengineered, will we reuse this method? Its one line either way, right?

containsAnyEmails(emails, set)

vs

emails.some(email => set.has(email))

Navigation.dismissModal({
afterTransition: () => {
// Remove the approval workflow using the initial data as it could be already edited
if (useRulesBackend && removeApprovalWorkflowRules(initialApprovalWorkflow, policy, rulesCollection)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This confused me, are we calling the API in the if statement?

*/
type ApprovalWorkflowFilterComparison = {
/** The comparison operator. */
operator: ValueOf<typeof CONST.SEARCH.SYNTAX_OPERATORS>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should standardize the operators to no longer live in 'Search'. Maybe thats something we can handle separately

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants