Skip to content

[Due for payment 2026-01-29] Optimistically compute report names on creation #76855

Closed

Description

@neil-marcellini

Problem

We have a thorough function for computing report names, and we were going to build a system to optimistically compute report names whenever a dependency of the report name formula updated, but scrapped that idea. Now report names will not be optimistically computed at all.

Solution

It will be sufficient to optimistically compute the report name when reports are created, so that they use the proper name right away.

Replace the call to populateOptimisticReportFormula with a call to compute, or otherwise merge the logic together. Verify various report formulas compute correctly optimistically when reports are created.

Issue OwnerCurrent Issue Owner: @
Issue OwnerCurrent Issue Owner: @NicMendonca

Activity

  1. added
    External
    Daily
    on Dec 5, 2025
  2. added
    Help Wanted
    on Dec 5, 2025
  3. melvin-bot commented on Dec 5, 2025

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (External)

  4. PiyushChandra17 commented on Dec 5, 2025

    @PiyushChandra17
    Contributor

    I can work on this

  5. neil-marcellini commented on Dec 5, 2025

    @neil-marcellini
    ContributorAuthor

    Please post a proposal since this one is a little more involved than similar issues.

  6. abbasifaizan70 commented on Dec 5, 2025

    @abbasifaizan70
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2025-12-09 21:51:06 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    We have a thorough function (compute) for computing report names from formula templates, and we were going to build a system to optimistically compute report names whenever a dependency of the report name formula updated, but scrapped that idea. Now report names will not be optimistically computed at all. When reports are created, they use a simpler function (populateOptimisticReportFormula) that uses basic regex replacements, which may not handle all formula cases correctly and is inconsistent with the more comprehensive compute function used elsewhere in the codebase.

    What is the root cause of that problem?

    The current implementation uses populateOptimisticReportFormula in three places when creating optimistic reports:

    1. buildOptimisticExpenseReport in App/src/libs/ReportUtils.ts (line 6875)
    2. buildOptimisticEmptyReport in App/src/libs/ReportUtils.ts (line 6907)
    3. convertIOUReportToExpenseReport in App/src/libs/actions/Report.ts (line 5459)

    The populateOptimisticReportFormula function uses simple regex replacements (e.g., .replaceAll(/\{report:total\}/gi, ...)) which:

    • May not handle all formula edge cases correctly
    • Doesn't support all formula features that compute supports (e.g., functions, field references, proper parsing)
    • Is inconsistent with the more thorough compute function that's already used in OptimisticReportNames.ts for computing report names when dependencies update
    • May not handle complex formulas with nested braces or special formatting correctly

    The compute function in App/src/libs/Formula.ts is a more comprehensive solution that:

    • Properly parses formulas into parts
    • Handles all formula types (report, field, user, freetext)
    • Supports functions and formatting
    • Is already used successfully in OptimisticReportNames.ts
    • Requires allTransactions to be passed in the FormulaContext for proper computation of fields like {report:expensescount}, {report:startdate}, and {report:enddate}

    What changes do you think we should make in order to solve the problem?

    1. Add transactions parameter to build functions

    Add an optional allTransactions parameter to buildOptimisticExpenseReport and buildOptimisticEmptyReport functions so transactions can be passed from call sites when available. The transactions should be in the format Record<string, Transaction> where the key is the transaction ID.

    2. Replace populateOptimisticReportFormula with compute in report creation functions

    Update the three locations where populateOptimisticReportFormula is called to use compute instead, building the appropriate FormulaContext with the provided transactions.

    App/src/libs/ReportUtils.ts - buildOptimisticExpenseReport function (around line 6874-6883):

    Update the function signature to accept transactions:

    function buildOptimisticExpenseReport(
        chatReportID: string | undefined,
        policyID: string | undefined,
        payeeAccountID: number,
        total: number,
        currency: string,
        nonReimbursableTotal = 0,
        parentReportActionID?: string,
        optimisticIOUReportID?: string,
        allTransactions?: Record<string, Transaction>,
    ): OptimisticExpenseReport {

    Add imports at the top of the file:

    import {compute} from './Formula';
    import type {FormulaContext} from './Formula';

    Update the report name computation (around line 6873-6876):

    const titleReportField = getTitleReportField(getReportFieldsByPolicyID(policyID) ?? {});
    if (!!titleReportField && isGroupPolicy(policy?.type ?? '')) {
        const formulaContext: FormulaContext = {
            report: expenseReport,
            policy,
            allTransactions: allTransactions ?? {},
        };
        const computedName = compute(titleReportField.defaultValue, formulaContext);
        expenseReport.reportName = computedName || expenseReport.reportName;
    }

    App/src/libs/ReportUtils.ts - buildOptimisticEmptyReport function (around line 6883-6919):

    Update the function signature to accept transactions:

    function buildOptimisticEmptyReport(
        reportID: string,
        accountID: number,
        parentReport: OnyxEntry<Report>,
        parentReportActionID: string,
        policy: OnyxEntry<Policy>,
        timeOfCreation: string,
        allTransactions?: Record<string, Transaction>,
    ) {

    Update the report name computation (around line 6907-6908):

    const titleReportField = getTitleReportField(getReportFieldsByPolicyID(policy?.id) ?? {});
    const formula = titleReportField?.defaultValue ?? CONST.POLICY.DEFAULT_REPORT_NAME_PATTERN;
    const formulaContext: FormulaContext = {
        report: optimisticEmptyReport,
        policy,
        allTransactions: allTransactions ?? {},
    };
    const optimisticReportName = compute(formula, formulaContext);
    optimisticEmptyReport.reportName = optimisticReportName || '';

    App/src/libs/actions/Report.ts - convertIOUReportToExpenseReport function (around line 5440-5464):

    Add imports at the top of the file:

    import {compute} from '@libs/Formula';
    import type {FormulaContext} from '@libs/Formula';

    Get transactions for the report and update the report name computation (around line 5462-5464):

    const titleReportField = getTitleReportField(getReportFieldsByPolicyID(policyID) ?? {});
    if (!!titleReportField && isPaidGroupPolicy(policy)) {
        // Get transactions for this report to pass to compute
        const reportTransactions = getReportTransactions(iouReport.reportID);
        const allTransactions: Record<string, Transaction> = {};
        reportTransactions.forEach((transaction) => {
            if (transaction?.transactionID) {
                allTransactions[transaction.transactionID] = transaction;
            }
        });
        
        const formulaContext: FormulaContext = {
            report: expenseReport,
            policy,
            allTransactions,
        };
        const computedName = compute(titleReportField.defaultValue, formulaContext);
        expenseReport.reportName = computedName || expenseReport.reportName;
    }

    3. Update call sites to pass transactions when available

    Update call sites of buildOptimisticExpenseReport and buildOptimisticEmptyReport to pass transactions when they are available. For example, in App/src/libs/actions/IOU.ts where buildOptimisticExpenseReport is called (around line 3867), if there are optimistic transactions available, they should be converted to the Record<string, Transaction> format and passed to the function.

    4. Remove or deprecate populateOptimisticReportFormula function

    After replacing all usages, we can either:

    • Remove the populateOptimisticReportFormula function entirely (if it's not used elsewhere)
    • Mark it as deprecated and remove it in a future cleanup

    5. Update tests

    Update the tests in App/tests/unit/ReportUtilsTest.ts that test populateOptimisticReportFormula to instead test the compute function with appropriate FormulaContext objects, or remove those tests if they're no longer relevant.

    6. Verify various report formulas compute correctly

    Test that various report formula patterns work correctly when reports are created:

    • {report:id} - Should show base62 report ID
    • {report:total} - Should show formatted total amount
    • {report:type} - Should show "Expense Report"
    • {report:startdate} - Should show formatted start date (requires transactions)
    • {report:enddate} - Should show formatted end date (requires transactions)
    • {report:expensescount} - Should show count of expenses (requires transactions)
    • {report:status} - Should show human-readable status
    • {report:policyname} or {report:workspacename} - Should show policy name
    • {report:created} - Should show creation date/time
    • {user:email} - Should show user email
    • Complex formulas with multiple fields and free text (e.g., Report {report:id} - {report:total})
    • Formulas with functions (e.g., {user:email|frontPart})

    What alternative solutions did you explore? (Optional)

    1. Keep both functions: We could keep populateOptimisticReportFormula for simple cases and use compute for complex ones, but this adds unnecessary complexity and inconsistency.

    2. Enhance populateOptimisticReportFormula: We could improve populateOptimisticReportFormula to handle more cases, but this would duplicate logic that already exists in compute and would be harder to maintain.

    3. Use compute only for complex formulas: We could detect if a formula is "complex" and only use compute in those cases, but this adds complexity and the simpler approach of always using compute is cleaner.

    4. Pass empty transactions object: We initially considered passing an empty {} for allTransactions, but this would cause incorrect computation of formula fields that depend on transactions (like {report:expensescount}, {report:startdate}, {report:enddate}). The Formula.ts functions need access to actual transactions to compute these values correctly.

    The chosen solution (replacing populateOptimisticReportFormula with compute and passing transactions) is the cleanest approach because:

    • It uses the existing, well-tested compute function
    • It ensures consistency across the codebase
    • It handles all formula cases correctly, including those that depend on transactions
    • It's easier to maintain (one function instead of two)
    • It properly supports all formula features that depend on transaction data
  7. Nodebrute commented on Dec 5, 2025

    @Nodebrute
    Contributor

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Optimistically compute report names on creation

    What is the root cause of that problem?

    Feature request

    What changes do you think we should make in order to solve the problem?

    Replace the deprecated populateOptimisticReportFormula function with the comprehensive compute function from Formula.ts to enable full formula support when optimistically computing report names during report creation.

    1. We should replace this with
      expenseReport.reportName = populateOptimisticReportFormula(titleReportField.defaultValue, expenseReport, policy);
      const formulaContext = {
          report: expenseReport,
          policy,
      };
      expenseReport.reportName = computeFormula(titleReportField.defaultValue, formulaContext) || titleReportField.defaultValue;
    

    2.We should replace this with

    expenseReport.reportName = populateOptimisticReportFormula(titleReportField.defaultValue, expenseReport, policy);

    const formulaContext = {
          report: expenseReport,
          policy,
      };
      expenseReport.reportName = computeFormula(titleReportField.defaultValue, formulaContext) || titleReportField.defaultValue;
    

    3.And here we should replce it with

      const formulaContext = {
          report: optimisticEmptyReport,
          policy,
      };
      const optimisticReportName = computeFormula(titleReportField?.defaultValue ?? CONST.POLICY.DEFAULT_REPORT_NAME_PATTERN, formulaContext) 
    

    const optimisticReportName = populateOptimisticReportFormula(titleReportField?.defaultValue ?? CONST.POLICY.DEFAULT_REPORT_NAME_PATTERN, optimisticEmptyReport, policy);

    **Testing branch:**https://github.com/Nodebrute/App/tree/replace-optimistic-formula-with-compute. Incase we decide we can also keep populateOptimisticReportFormula function

    Works as expected

    https://github.com/user-attachments/assets/b48bbb46-661b-4c82-9fdd-24629548515d
    Tests

    We can add different types of tests to test complex scenarios

       test('should compute report name with type and total', () => {
                    const result = compute('{report:type} - Total: {report:total}', mockContext);
                    expect(result).toBe('Expense Report - Total: $100.00');
                });
    
      test('should preserve free text in report names', () => {
                    const result = compute('Expense Report for {report:policyname}', mockContext);
                    expect(result).toBe('Expense Report for Test Policy');
                });
    

    What alternative solutions did you explore? (Optional)

  8. eVoloshchak commented on Dec 7, 2025

    @eVoloshchak
    Contributor

    @abbasifaizan70's proposal looks good to me!

    🎀👀🎀 C+ reviewed!

  9. melvin-bot commented on Dec 7, 2025

    @melvin-bot

    Current assignee @neil-marcellini is eligible for the choreEngineerContributorManagement assigner, not assigning anyone new.

  10. neil-marcellini commented on Dec 9, 2025

    @neil-marcellini
    ContributorAuthor

    @abbasifaizan70's proposal looks good to me!

    🎀👀🎀 C+ reviewed!

    Yes it mostly looks good. One problem is that you pass allTransactions as empty. It is needed in various places within Formula.ts. We should pass the report transactions as a collection from the UI component(s) to these "buildOptimistic" functions and pass that in for the context.

    Note: We need to check if isMoneyRequestConfirmation is passed to buildOptimisticEmptyReport. If not, we may need to add it as a parameter or handle it differently. Currently, buildOptimisticEmptyReport doesn't accept this parameter, so we may need to add it or handle the money request confirmation case at the call site.

    I also don't really understand the problem / solution behind this note.

    Please let me know when your proposal is updated @abbasifaizan70

  11. abbasifaizan70 commented on Dec 9, 2025

    @abbasifaizan70
    Contributor

    @neil-marcellini updated proposal. Please have a look thanks.

  12. 27 remaining items

  13. melvin-bot commented on Jan 24, 2026

    @melvin-bot

    @eVoloshchak, @neil-marcellini, @abbasifaizan70 Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

  14. added
    Bug
    on Jan 27, 2026
  15. melvin-bot commented on Jan 27, 2026

    @melvin-bot

    Triggered auto assignment to @NicMendonca (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  16. NicMendonca commented on Jan 28, 2026

    @NicMendonca
    Contributor

    This was deployed 5 days ago, so issuing payment on Thursday Jan 29th

  17. changed the title [-][Due for payment 2026-01-21] Optimistically compute report names on creation[/-] [+][Due for payment 2026-01-29] Optimistically compute report names on creation[/+] on Jan 28, 2026
  18. eVoloshchak commented on Jan 29, 2026

    @eVoloshchak
    Contributor

    BugZero Checklist:

    • [Contributor] The offending PR has been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to comment: N/A, this is a new feature

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion: regression wasn't critical

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    Regression Test Proposal Template
    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue:

    Regression Test Proposal

    Precondition:

    • Create or use an existing Team or Corporate workspace (not a personal workspace)
    • Go to Settings > Workspaces > [Your Workspace] > Report Fields
    • Set up a custom Report Title formula. Examples to test:
    {report:type} - {report:total}
    Report {report:id} - {report:policyname}
    {report:status} Report for {report:workspacename}
    
    Formula Expected Optimistic Result
    {report:type} "Expense Report"
    {report:id} Base62 encoded report ID (e.g., "R0000008M0kX")
    {report:total} Formatted amount (e.g., "25.00")
    {report:policyname} Workspace name
    {report:workspacename} Workspace name
    {report:status} "Open" or "Submitted"
    {report:currency} Currency code (e.g., "USD")

    Test:

    Test Case 1: Create New Expense in Workspace

    1. Open the Expensify app
    2. Click the + button (FAB)
    3. Select Submit Expense
    4. Choose a workspace that has a custom report title formula
    5. Fill in the expense details (amount, merchant, etc.)
    6. Submit the expense
    7. The expense report should be created with the optimistic report name computed using the formula (e.g., "Expense Report - $25.00" instead of the default "[Workspace] owes $25.00")

    Test Case 2: Offline Mode

    1. Turn on Airplane mode / disconnect from internet
    2. Create a new expense in a workspace with custom report title formula
    3. The report name should still be computed optimistically using the formula
    4. Reconnect to internet
    5. The report name should remain correct after sync

    Do we agree 👍 or 👎

  19. melvin-bot commented on Jan 29, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@NicMendonca)

    • (if NewFeature) I have created a PR for any necessary HelpDot updates, or I confirmed no updates are necessary.
    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants//hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  20. NicMendonca commented on Jan 30, 2026

    @NicMendonca
    Contributor

    Payment Summary

    Contributor: @abbasifaizan70 paid $250 via Upwork (✅ )
    Contributor+: @eVoloshchak due $250 via NewDot

  21. trjExpensify commented on Mar 4, 2026

    @trjExpensify
    Contributor

    approved $250 for @eVoloshchak.

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

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions