App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Company-card CSV upload reverses UK dates and reports all transactions imported even when most expenses fail to appear.

Open m-natarajan opened this issue 1 week ago • 14 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: Reproducible in staging?: Reproduction blocked Reproducible in production?: Reproduction blocked If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @Leeckhart Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

  1. Open the workspace → Company cards.
  2. Upload a CSV containing 69 transactions with dates in DD/MM/YYYY format.
  3. Assign the CSV card to Michael Munro.
  4. View the imported expenses.
  5. Update the card again.

Expected Result:

All 69 transactions import with the correct dates, or the app clearly identifies failed rows and explains why they failed.

Actual Result:

The app reports 69 transactions imported, but only some expenses are created. Dates such as 03/08/2026 appear as March 8 instead of August 3. Seven rows were interpreted as future dates and excluded. The remaining rows encounter “403 New expense cannot be added to this report”, linked to Instant Submit, optional approval, and the destination report’s status. Each card update creates one additional expense while others continue to fail.

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

  • [ ] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [x] MacOS: Chrome / Safari

Screenshots/Videos

The video, account details and CSV available in Slack thread

View all open jobs on GitHub

Upwork Automation - Do Not Edit

m-natarajan avatar Nov 18 '26 23:11 m-natarajan

@m-natarajan I sent you a Slack DM to connect GitHub. I will continue the original request once you are connected.

melvin-bot[bot] avatar Nov 18 '26 23:11 melvin-bot[bot]

@MelvinBot Proceed without connecting to Slack

m-natarajan avatar Nov 19 '26 13:11 m-natarajan

@m-natarajan Use the Connect GitHub link in our earlier Slack DM. I will continue the original request once you are connected.

melvin-bot[bot] avatar Nov 19 '26 13:11 melvin-bot[bot]

@MelvinBot Proceed without connecting to Slack

m-natarajan avatar Nov 19 '26 13:11 m-natarajan

@m-natarajan Use the Connect GitHub link in our earlier Slack DM. I will continue the original request once you are connected.

melvin-bot[bot] avatar Nov 19 '26 13:11 melvin-bot[bot]

@MelvinBot Connected , Please proceed

m-natarajan avatar Nov 19 '26 16:11 m-natarajan

🤖 Web test steps verification results: ⚠️ partial

The issue could not be reproduced on dev NewDot web because navigation and CSV-upload automation were blocked. No customer data was accessed; these blocked checks do not confirm product defects.

Test workspace overview with Company cards visible in the sidebar
Step Status
1. Open workspace → Company cardsOpened a fresh test workspace. Company cards was visible, but automation could not select it.
Test workspace overview with Company cards visible in the sidebar
❌
2. Upload 69 DD/MM/YYYY transactionsBlocked: Slack-only source materials were unavailable, and the permitted browser interface does not support file uploads. No CSV was imported.
❌
3. Assign CSV card to Michael MunroBlocked: no imported card or verified test identity was available. No real user was invited or assigned.
❌
4. Verify expenses, dates, and import errorsBlocked by the import prerequisites. Transaction count, date interpretation, row-failure explanations, and 403 errors remain unverified.
❌
5. Update the card againBlocked: no CSV card was imported. The reported one-additional-expense-per-update behavior remains unverified.
❌

view run · view recording

MelvinBot avatar Nov 19 '26 16:11 MelvinBot

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

Job added to Upwork: https://www.upwork.com/jobs/~022123477822322434503

Proposal

Confidence: High in the two App-side mechanisms below; the backend cause of missing expenses remains unconfirmed.

What is the root cause of that problem?

The report combines three distinct problems:

  1. Ambiguous dates are parsed month-first. App tries MM/dd/yyyy before dd/MM/yyyy, so 03/08/2026 becomes March 8, not August 3. It then sends the normalized, incorrect date to the server. Unambiguous UK dates can parse correctly, producing inconsistent results within one file.

  2. The success count does not confirm expense creation. App calculates the displayed count from rows passing local validation, before receiving authoritative expense-creation results. Consequently, “69 transactions have been added” can overstate what actually appeared.

  3. The 403 failures and one-expense-per-update behavior require backend confirmation. Reusing a report that becomes ineligible after the first expense is a plausible explanation—not an established root cause. Date parsing alone cannot explain these permission failures.

Code evidence

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

Escalate the missing-expense/report-insertion portion to an internal engineer with backend repository access. An App-only change cannot establish or resolve that failure.

Before choosing a complete fix, obtain through an authorized private channel:

  • The original CSV, selected mappings, and affected App version.
  • A scoped card identifier and upload/update timestamps.
  • Per-row parsed dates, filtering results, insertion responses, and destination-report state transitions.

These are needed to verify the seven reported future-date exclusions and whether rejected rows reuse the same report after its first successful insertion. Production confirmation was blocked by missing identifiers and unavailable authorized log/source access; no production logs were queried.

What alternative solutions did you explore?

Browser locale alone does not explain the explicit month-first parser. Incorrect column mappings, deduplication, feed mismatches, or hidden expenses could explain some discrepancies, but none independently explains confirmed per-row 403 errors. Changing date handling alone would therefore be an incomplete solution.


Next Steps for Contributor+ team: Obtain the scoped evidence and internal backend investigation before accepting an implementation plan.


view run

MelvinBot avatar Nov 19 '26 18:11 MelvinBot

Proposal

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

A company-card CSV with UK dates (DD/MM/YYYY) imports some dates with day and month swapped: 03/08/2026 becomes 8 March, not 3 August. Swapped dates that land in the future are then dropped, so the "69 transactions added" message doesn't match what shows up.

This proposal covers the App-side date problem. The 403 "New expense cannot be added to this report" failures are server-side, as MelvinBot noted, and are out of scope here.

What is the root cause of that problem?

parseCSVDate (src/libs/CSVDateUtils.ts) parses each cell on its own, trying CSV_DATE_FORMATS in order and returning the first valid match. MM/dd/yyyy comes before dd/MM/yyyy, so:

  • 13/08/2026 fails as month-first and correctly falls through to day-first, giving 13 August.
  • 03/08/2026 is valid as month-first, so it becomes 8 March.

As a result, one UK file comes out half-right and half-swapped. Every swapped date where the real day is 12 or less turns into a different day. Rows that become a future date (e.g. 05/12/2026 → 12 May instead of 5 Dec, or 12/11/2026 → 11 Dec instead of 12 Nov) get excluded, which matches the "7 rows treated as future dates".

CompanyCards.ts (around lines 162–182) calls parseCSVDate per row for the posted and original dates and writes the normalized value back into the row it sends. The server therefore receives the wrong date. ImportTransactions.ts uses the same per-cell parser, so personal CSV imports have the same bug.

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

Decide the day/month order once per date column, not once per cell:

  1. In CSVDateUtils.ts, add detectCSVDateOrder(values: string[]). It looks at every numeric a/b/yyyy or a-b-yyyy value in the column:
    • If any value has a > 12, the column is day-first.
    • If any value has b > 12, the column is month-first.
    • If both happen (a mixed file), or neither does (every value is ambiguous), it returns null.
  2. Give parseCSVDate(input, dateOrder?) an optional order. When set, it skips the formats of the other order (dd/MM… vs MM/dd… and their short and dash variants). ISO, month-name and Excel-serial handling stays the same.
  3. In CompanyCards.ts and ImportTransactions.ts, call detectCSVDateOrder on the mapped date column(s) before the row loop and pass the result to every parseCSVDate call.
  4. When the order is still null because the whole column is ambiguous, keep today's behavior. This file had unambiguous rows like 13/08/2026, so it would be detected as day-first without needing that fallback.

Leave parseCSVDate with no order argument behaving exactly as today, so other callers aren't affected.

What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

In tests/unit/CSVDateUtils.test.ts:

  • detectCSVDateOrder(['03/08/2026', '13/08/2026']) returns day-first, and parseCSVDate('03/08/2026', dayFirst) returns 2026-08-03.
  • ['08/13/2026', '03/08/2026'] returns month-first, giving 2026-03-08.
  • A column where every value is ambiguous returns null, and parsing falls back to today's behavior.
  • Day-first short and dash variants (3/8/2026, 03-08-2026) follow the detected order.
  • ISO and month-name dates are unaffected.

Also add a company-card CSV test where a mixed UK file produces the right created values for every row.

What alternative solutions did you explore? (Optional)

  • Just put dd/MM before MM/dd. That breaks US files the same way it breaks UK files today.
  • Add a "Date format" picker to the column-mapping step. It's the most explicit option, and it's a good follow-up for files where every value is ambiguous, but it adds a step to every import. Detecting the order from the file fixes this report with no new UI.

okiie12-code avatar Nov 23 '26 09:11 okiie12-code

Proposal

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

When importing a company-card CSV containing UK-formatted (DD/MM/YYYY) transaction dates:

  1. Ambiguous dates (where day <= 12, e.g. 03/08/2026) are parsed as US month-first (MM/dd/yyyy → 2026-03-08), while unambiguous rows (e.g. 13/08/2026) fall through to dd/MM/yyyy (2026-08-13). The App writes those normalized dates back into csvDataWithGeneratedIDs before uploading to ImportCSVCompanyCards, corrupting half the file and turning valid past dates (e.g. 12/11/2026 → 2026-12-11) into future dates that get dropped.
  2. Immediately after upload, importCSVCompanyCards displays the optimistic success modal showing the local row count (transactions.length, e.g. "69 transactions have been added"), even though ImportCSVCompanyCards only queues/imports CSV rows into the feed and actual expense creation happens asynchronously after card assignment (where rows can still be dropped or fail).

(Note: As confirmed in the investigation, server-side 403 errors preventing multiple expenses from being added to a report are backend-owned and out of scope for this App PR.)

What is the root cause of that problem?

  1. Cell-by-cell month-first parsing in src/libs/CSVDateUtils.ts:
    • parseCSVDate invokes parseWithKnownFormats, which iterates CSV_DATE_FORMATS with US month-first formats (MM/dd/yyyy, M/d/yyyy, MM-dd-yyyy, MM/dd/yy, MM-dd-yy) ordered before European day-first formats (dd/MM/yyyy, d/M/yyyy, dd-MM-yyyy, dd/MM/yy, dd-MM-yy), independently for each cell.
    • parseCSVDate also has a second parseWithKnownFormats(shortInput) call (for values longer than 10 characters, such as DD/MM/YYYY HH:mm:ss bank timestamps) that likewise defaults to US month-first order.
    • In src/libs/actions/CompanyCards.ts (buildOptimisticCompanyCardCSVTransactions), both POSTED_DATE and ORIGINAL_TRANSACTION_DATE are parsed per row and written directly back into row[postedDateColumnIndex] and row[originalTransactionDateColumnIndex] before serialization to ImportCSVCompanyCards. The same per-cell call occurs in src/libs/actions/ImportTransactions.ts (buildTransactionListFromSpreadsheet) for personal card CSV imports.
  2. Optimistic client-side count in src/libs/actions/CompanyCards.ts:
    • importCSVCompanyCards computes transactionsCount = transactions.length strictly from local CSV parsing and sets successData to display spreadsheet.importCompanyCardTransactionsSuccessfulDescription with that local count as soon as ImportCSVCompanyCards returns 200, without reflecting rows skipped during local validation or distinguishing "uploaded to the feed" from "expenses created on reports".

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

  1. Infer date order at the file/column level in src/libs/CSVDateUtils.ts:

    • Add an exported helper inferCSVDateOrder(dateValues: Array<string | undefined>): CSVDateOrder | undefined ('DMY' | 'MDY' | undefined) that scans all non-empty cells in the column(s) before parsing:
      • Matches delimited numeric dates across both 4-digit and 2-digit years, with slashes or dashes, 1–2 digit day/month, and optional trailing time (HH:mm... / T...), while ignoring ISO yyyy-MM-dd / yyyy/MM/dd, month-name strings, header text, and 5-digit Excel serials.
      • Primary signal (unambiguous component > 12): If any cell has first > 12 (and second <= 12) while no cell has second > 12, infer 'DMY'. Symmetrically, if any cell has second > 12 while no cell has first > 12, infer 'MDY'. If both appear in the same column (genuinely conflicting rows), return undefined.
      • Secondary tie-breaker for small all-ambiguous CSVs (all rows have first <= 12 && second <= 12): Because bank/company-card statement exports contain historical posted transactions rather than future transactions, compare how many rows land in the future (> today + 1 day timezone buffer) under 'MDY' vs 'DMY'. If 'MDY' produces future dates while 'DMY' produces zero future dates, infer 'DMY' (and symmetrically 'MDY' if 'DMY' produces future dates while 'MDY' produces zero). Otherwise return undefined (preserving current default behavior).
    • Update parseCSVDate(input: string, preferredOrder?: CSVDateOrder) and parseWithKnownFormats(input: string, preferredOrder?: CSVDateOrder) so that when preferredOrder is 'DMY', European day-first formats (dd/MM/yyyy, d/M/yyyy, dd-MM-yyyy, dd/MM/yy, dd-MM-yy) are prioritized ahead of (or exclude conflicting) US month-first formats — and pass preferredOrder to both parseWithKnownFormats call sites inside parseCSVDate (including the trimmedInput.length > 10 timestamp-prefix path). Leave calls with no preferredOrder 100% backward-compatible.
  2. Wire file-level date order inference into both CSV import actions:

    • In src/libs/actions/CompanyCards.ts (buildOptimisticCompanyCardCSVTransactions), collect values from postedDateColumnIndex (and originalTransactionDateColumnIndex when mapped, pooling both columns if consistent or inferring per-column if they differ) before the row loop, call inferCSVDateOrder(...), and pass the inferred order to every parseCSVDate call for both posted and original transaction dates.
    • In src/libs/actions/ImportTransactions.ts (buildTransactionListFromSpreadsheet), infer the column's date order from the mapped date column slice (startIndex..numRows) once before the loop and pass it to parseCSVDate(dateValue, preferredDateOrder).
  3. Align post-upload confirmation messaging (optional UX safeguard pending C+/product confirmation):

    • Fixing step 1–2 eliminates the root cause of UK dates flipping into future dates and silently disappearing.
    • In addition, if product/C+ wants the upload modal to avoid overstating downstream expense creation when ImportCSVCompanyCards completes (or when rows are skipped locally due to invalid fields), we can clarify importCompanyCardTransactionsSuccessfulDescription to state that N transactions were uploaded/imported to the card feed (or surface any skipped-row count cleanly) rather than implying all expenses have already been created on reports. Happy to keep the PR scoped strictly to date parsing or include the copy alignment per @thelullabyy's preference.

What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

  1. Unit tests in CSVDateUtils:
    • Mixed UK column ['03/08/2026', '13/08/2026', '01/11/2026'] infers 'DMY' and parses 03/08/2026 → 2026-08-03 and 01/11/2026 → 2026-11-01.
    • Mixed US column ['08/03/2026', '08/13/2026'] infers 'MDY' and parses 08/03/2026 → 2026-08-03.
    • 2-digit year (13/08/26, 03/08/26), dash-separated (13-08-2026, 03-08-2026), single-digit (3/8/2026, 13/8/2026), and timestamped (13/08/2026 14:22:00, 03/08/2026 09:05:00) variants all respect the inferred 'DMY' order.
    • Small all-ambiguous UK column where 'MDY' yields future dates while 'DMY' yields only past dates (using a mocked reference date) infers 'DMY' and prevents future-date flipping.
    • Completely ambiguous past column (both orders produce valid past dates) returns undefined and preserves default US behavior; conflicting mixed rows return undefined.
    • ISO (yyyy-MM-dd), month-name (2 Nov 2025), Excel serial numbers, and header strings (Posted Date) are unaffected.
  2. Company-card & personal CSV import tests:
    • buildOptimisticCompanyCardCSVTransactions with a UK DD/MM/YYYY CSV (including both POSTED_DATE and ORIGINAL_TRANSACTION_DATE, plus a case where only one of the two date columns has a day > 12) writes yyyy-MM-dd day-first dates into both transactions and csvDataWithGeneratedIDs.
    • buildTransactionListFromSpreadsheet in ImportTransactions.ts preserves day-first order for personal UK CSV imports.

What alternative solutions did you explore? (Optional)

  • Only checking a/b/yyyy with 4-digit years and skipping timestamps / 2-digit years: Rejected because bank exports frequently emit dd/MM/yy or dd/MM/yyyy HH:mm:ss (handled by CSVDateUtils.ts lines 23–26 and 93–98), which would fall back to US order and re-introduce the swap.
  • Reordering CSV_DATE_FORMATS globally to put dd/MM/yyyy before MM/dd/yyyy: Rejected because it would reverse US CSV files in the exact same way UK files are currently broken.
  • Adding a mandatory manual date-format dropdown to the import wizard: Rejected for this bug fix because file-level inference solves real UK/EU/US bank exports automatically with zero extra friction; a manual override picker could still be added later as a separate enhancement if needed.

danlopes18-ctrl avatar Nov 23 '26 17:11 danlopes18-ctrl

Reviewing...

thelullabyy avatar Nov 24 '26 04:11 thelullabyy

@thelullabyy Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!