Skip to content

fix(fx): stop the broker-loan model trusting unproven Cash Reports and repaying in the wrong order - #460

Merged
GeiserX merged 5 commits into
mainfrom
fix/overdraft-loan-cr456
Nov 18, 2026
Merged

GeiserX merged 5 commits into
mainfrom
fix/overdraft-loan-cr456

Conversation

@GeiserX

@GeiserX GeiserX commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Problem

#456 shipped the broker-loan model (#449) in v0.66.7 before CodeRabbit finished. Its late review, and a second review of this fix, found three groups of problems:

  • the gate accepted Cash Report evidence it could not prove;
  • the ledger spent and repaid dollars in the wrong order;
  • the report gave advice that did not match where the numbers were booked.

All of them only affect uploads whose IBKR Cash Report passes the gate.

Gate

It now rejects a currency in these cases:

  • a Cash Report row whose dates are not real calendar dates, or whose start comes after its end;
  • rows with no account id (blank matched blank);
  • a row with no endingCash (the parser's default 0 reconciled by accident; Modelo 720 still reads 0);
  • the same row from two brokers (the dedupe key now includes the broker);
  • an opening short sale, or cash rows that do not add up to the cash events the engine sees. Before, a short sale's inflow could cancel an orphan withholding's debit.

Ledger

These apply to loan currencies only:

  • The opening balance is spent first, before later lots. Before, 1000 of opening cash plus a newer lot at 0.80 booked 100 € in 2025, instead of 0 in 2025 and 50 € in 2026.
  • Opening cash that a same-day sale returns repays that day's loan first. With 500 of opening cash, a buy of 1000 and a sale of 400, the account owes 100, not 500.
  • A same-day payback repays only what the loan still owes. Before, in «Tradicional con divisa», a second same-day sale paid a loan that was already settled and lost 500 USD.
  • Opening cash lost in a same-day loss sale is lost principal at once. Before, it became a phantom debt that a later trade "repaid", and then a loan that was never repaid: 80 instead of 50, in both FX methods. This was already in v0.66.7.
  • The default method now sees a sale with proceeds of 0 or less, as the gate already did. Before, a worthless sale's commission stayed in the pool.

Report

  • There is one untracked-currency note per currency and kind. So the IBKR Cash Report hint covers only IBKR's amount.
  • In the default method, the shares bought with the loan can repay it, and the debt's change then sits in the stock result. In that case a new note, report.fx_loan_repayment_manual, gives the part that is in 1633/1637 and asks the user to reconcile the rest by hand. Before, it said to lower box 1633 by 50 € when 1633 was 0. Everywhere else, the plain note stays.
  • All 5 locales are updated, along with docs/traza-fx.md, docs/casillas.md and the CLAUDE.md Hard Trace.

What users see

  • No committed fixture changes. The output is byte-identical in all three FX methods: 38 fixtures, 7 option sets.
  • An IBKR upload merged with another broker in «Tradicional con divisa» can show two untracked notes instead of one combined note. The numbers stay the same.
  • Uploads that pass the gate get the corrected figures above.
  • Fail-closed side effect: an IBKR long sale with no openCloseIndicator (which the parser defaults to O) turns the loan model off for that currency.

Checks

  • 100 loan tests, each fix with a mutation that goes red.
  • Seeded generator cases for second same-day sales, worthless sales and opening balances.
  • vitest, typecheck, typecheck:tests, lint and build:web are green on the branch merged with main.

Follow-up to #456, from the CodeRabbit review of its exact head on the fork mirror.

… repaying loans in the wrong order

Follow-up to the late review of #456 (issue #449).

The gate now fails closed. It turned the loan model on for a CashReport
row with dates like "2025-00-01" .. "2025-99-31" (they held every date of
2025), for rows with no account id (blank matched blank), for a row with
no endingCash (the parser's "0" reconciled REPRO, whose dollars end at 0),
for the same row stamped by two brokers (deduplicated to one before the
one-broker check), and when an opening short sale's inflow cancelled an
orphan withholding's debit (the FX engine sees neither). The parser still
gives Modelo 720 "0" for a missing endingCash and flags it.

The ledger spends and repays in the account's order:
- the CashReport's opening balance is the oldest currency, so it goes
  before later tracked lots (a conversion of 1000 on 1000 of opening and a
  newer 0.80 lot booked 100 in 2025 instead of 0, and 50 in 2026);
- opening balance a same-day sale returns repays that day's loan first
  (500 of opening, a buy of 1000, a sale of 400: the account owes 100, not
  500, and a later inflow of 500 repays 100);
- a same-day payback repays only what the loan still owes (in «Tradicional
  con divisa», two same-day sales after a repayment threw 500 USD away and
  left the pool at 60 instead of 560);
- in a loan currency the default now sees a sale with proceeds of 0 or
  less, as the gate counted it (a worthless sale's 5 USD commission stayed
  in the default's pool).

The report gives one untracked note per currency and kind (an IBKR note
no longer covers another broker's dollars), and when part of the debt's
change is outside 1633/1637 (the default's stock line), the new
report.fx_loan_repayment_manual note gives the part in 1633/1637 and asks
to reconcile the rest by hand, in the 5 locales.

No fixture changes in any FX method (38 fixtures, 7 option sets, JSON
identical): none passes the gate. A merged IBKR + Degiro upload now gets
two untracked notes (76.31 IBKR, 452.75 other) instead of one IBKR note of
529.07; its numbers do not change.
… needs a manual check

traza-fx.md, casillas.md and the CLAUDE.md #449 Hard Trace now say that
the opening balance goes before later lots, that only the shortfall after
the available cash and an accepted late cover becomes a loan, which rows
the gate rejects (invalid dates, blank accounts, no endingCash, the same
row from two brokers, an opening short sale, an orphan withholding), how
a same-day sale repays a loan that day, that a LOAN row's gain is the
debit's commission share, and when the report asks to reconcile the debt
part by hand. The review's traps and controls are recorded.
… a phantom broker loan

In a loan currency every untracked parked slice is the Cash Report's
opening balance, which the account really held. When a same-day loss
sale did not return all of it, repayBorrowed still pushed the lost part
as a #447 same-day debt. A later round trip that day paid it with real
dollars, and the final conversion opened a loan nothing repaid (D2: 80
on a true 50; Z1: 160 on 145; both methods).

The lost part is now discarded at once with the row closeDebts writes,
counted in fx_traditional_opening. Untracked currencies outside the
gate keep the #447 rule. New generator mode `loss` with 1500 of opening
balance pins it: no LOAN row on the final conversion, pool 0.
…an's rate by coincidence

The _manual loan note fired for every repayment row that netted to 0.
Shares bought with dollars funded at the loan's rate on the loan's day
repaid it with a zero row. The note then said the debt's change sat in
the sale of shares bought with the loan, which repaid nothing. Lowering
1633 by the debt part was right there, as it was for the same loan with
funding at another rate.

A zero row now counts as in 1633/1637. The exception is the default
repaying with the loan's own borrowed principal that the shares' sale
re-added at the loan's rate: there the stock line holds the change.
«Tradicional con divisa» had the same mirror case (a shifted cost equal
to the loan's rate) and now gets the plain note too.
@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.38710% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.06%. Comparing base (3569621) to head (4f130f3).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/engine/fx-fifo.ts 98.34% 2 Missing ⚠️
src/engine/fx-loan-gate.ts 96.77% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #460      +/-   ##
==========================================
+ Coverage   93.96%   94.06%   +0.09%     
==========================================
  Files          64       64              
  Lines        8201     8338     +137     
  Branches     2838     2889      +51     
==========================================
+ Hits         7706     7843     +137     
- Misses        406      407       +1     
+ Partials       89       88       -1     
Files with missing lines Coverage Δ
src/generators/report.ts 97.95% <100.00%> (+0.10%) ⬆️
src/i18n/locales/ca.ts 100.00% <ø> (ø)
src/i18n/locales/en.ts 100.00% <ø> (ø)
src/i18n/locales/es.ts 100.00% <ø> (ø)
src/i18n/locales/eu.ts 100.00% <ø> (ø)
src/i18n/locales/gl.ts 100.00% <ø> (ø)
src/parsers/ibkr.ts 99.18% <100.00%> (+<0.01%) ⬆️
src/engine/fx-loan-gate.ts 91.12% <96.77%> (+1.65%) ⬆️
src/engine/fx-fifo.ts 99.53% <98.34%> (+0.11%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@GeiserX
GeiserX merged commit c168b6c into main Nov 18, 2026
7 of 8 checks passed
@GeiserX
GeiserX deleted the fix/overdraft-loan-cr456 branch November 18, 2026 20:20
GeiserX added a commit that referenced this pull request Nov 18, 2026
… paid the loan, and stop dropped cash rows passing the loan gate (#463)

* fix(fx): stop unseen cash rows passing the loan gate and another loan's principal hiding a debt change

Follow-up to #460 (the #449 broker-loan gate and ledger), from the review
of its exact diff.

- A lot that carries returned loan principal now remembers which loan it
  came from. The default's "the sale pays its own loan" exception applies
  only when that loan is the one being repaid. Before, principal of a loan
  already repaid by a funding (L1) that repaid a second loan at the same
  rate (L2) took L2's debt change out of 1633/1637 and sent the user to
  reconcile by hand (fx_loan_repayment_manual) instead of the plain note.
  No figure moves, only the note.
- extractCashFxEvents can now list the cash rows it leaves out (no ECB
  rate, an orphan withholding, a refund or reversal it cannot emit). The
  loan gate rejects a currency with any such row, and it reconciles the
  cash rows per day instead of per period, so two unseen rows on two days
  can no longer cancel. A withholding netted into its income that day
  still passes.
- CLAUDE.md: a loan-funded debit has zero gain only when no commission is
  allocated to it, as docs/traza-fx.md says.

* fix(fx): keep two loans repaid with each other's principal on the hand-reconcile note

The previous fix counted returned loan principal outside 1633/1637 only when
it repaid its own loan. When BBB's sale repaid L1 with L2's principal and
AAA's sale then repaid L2 with L1's, no currency ever paid for either
principal, yet the report gave the plain note and told the user to lower
1633 (0) by 100 €, while the other sale order gave fx_loan_repayment_manual
on the same figures.

Each buy's loan now counts how much of its principal is still borrowed
(borrowedLeft): it drops when currency in 1633/1637 repays the loan, when a
slice stops being the loan's on its own day (same-day sale, same-day cover,
opening balance), and when the principal pays a debt as borrowed currency.
Returned principal counts outside the boxes for its own loan, and for
another loan up to that count, borrowed units first. OTHER and CHAIN keep
the plain note; CROSS matches OWN in both sale orders. No figure changes,
only the note.
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.

1 participant