Skip to content

fix(fx): give the hand-reconcile loan note only when no real currency paid the loan, and stop dropped cash rows passing the loan gate - #463

Merged
GeiserX merged 3 commits into
mainfrom
fix/overdraft-loan-cr460
Nov 18, 2026
Merged

GeiserX merged 3 commits into
mainfrom
fix/overdraft-loan-cr460

Conversation

@GeiserX

@GeiserX GeiserX commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Problem

CodeRabbit reviewed #460 after it shipped in v0.66.9. It found two ways the broker-loan model (#449) could go wrong, plus one wrong line in CLAUDE.md.

  1. Wrong loan note. This applies to «Criterio DGT (multidivisa)». Shares bought on a loan give back that loan's dollars when they are sold. When those dollars repay a loan, the debt's currency change is not in 1633/1637. So the report says «cuadrar a mano» (fx_loan_repayment_manual). In v0.66.9 that exception applied to any loan's dollars, so a loan already paid by a funding could still turn the plain note («lower 1633 by the gain») into the hand-reconcile one. A first fix narrowed it to "only its own loan". Our review then found the reverse case. Two loans, L1 for AAA and L2 for BBB. BBB is sold first and its dollars repay L1. AAA is sold next and its dollars repay L2. No real currency ever paid either loan and 1633 holds 0, yet the report told the user to lower 1633 by 100 €.
  2. The cash gate could be fooled. The gate compared the statement's cash rows with the engine's cash events once per period. The engine drops two kinds of row: a credit with no ECB rate, and an orphan withholding. Two dropped rows of the same size in one period cancelled out. The loan model then ran on cash the engine never saw.
  3. CLAUDE.md overstated a rule. It said a loan-funded fee always has zero gain. That holds only when no commission is allocated to it, as docs/traza-fx.md already says.

Fix

  1. Each loan counts how much of its returned dollars are still borrowed. The count drops when currency in 1633/1637 repays the loan. It also drops when a slice settles on the loan's own day, and when those dollars repay a debt as borrowed currency. Returned dollars count outside 1633/1637 for their own loan. For another loan, they count outside only up to that count. So a chain of loans paid down from one funding gets the plain note, and two loans repaid with each other's dollars get the hand-reconcile note in either sale order.
  2. extractCashFxEvents takes an optional collector and lists every cash row it drops. The gate rejects the currency on any dropped row and reconciles cash per day. A withholding netted into its own dividend that day still passes.
  3. CLAUDE.md now states the commission condition.

What users see

  • No figure changes in any FX method. No committed fixture changes over 1,692 runs. Monodivisa and «Tradicional con divisa» are byte-identical.
  • Over 2,424 generated loan runs, 5 changed, all in the default method and only in the loan note. 4 move from the hand-reconcile note to the plain note with the same gain. 1 stays hand-reconcile with the correct boxGain.
  • An upload with dropped cash rows goes back to the untracked path, the same as an upload with no Cash Report.
  • Migration: none.

Left on purpose

Both cases fail safe, toward the hand-reconcile note or the untracked path:

  • A loan whose dollars first repay another loan as borrowed currency, and that a funding pays only later, keeps the hand-reconcile note. No figure moves. CLAUDE.md documents it.
  • A same-day reversal pair with a blank dateTime and different settle dates is rejected by the per-day gate.

Checks

  • Tests: the new tests fail on v0.66.9's engine, with 12 of 68 red. Mutation controls (any-loan match, omitted-row rule off, per-period sums, a silent extractor) each turn a test red.
  • Suite: vitest, typecheck, typecheck:tests, lint and build:web pass.

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

…'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.
…d-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.
@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

@GeiserX
GeiserX merged commit 0fda3db into main Nov 18, 2026
5 of 6 checks passed
@GeiserX
GeiserX deleted the fix/overdraft-loan-cr460 branch November 18, 2026 21:48
@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.61017% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.07%. Comparing base (f114d6d) to head (db7fec9).
⚠️ Report is 2 commits behind head on main.

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

Impacted file tree graph

@@           Coverage Diff           @@
##             main     #463   +/-   ##
=======================================
  Coverage   94.06%   94.07%           
=======================================
  Files          64       64           
  Lines        8347     8382   +35     
  Branches     2891     2904   +13     
=======================================
+ Hits         7852     7885   +33     
- Misses        407      409    +2     
  Partials       88       88           
Files with missing lines Coverage Δ
src/engine/fx-loan-gate.ts 91.47% <100.00%> (+0.34%) ⬆️
src/generators/report.ts 97.96% <100.00%> (+<0.01%) ⬆️
src/engine/fx-fifo.ts 99.39% <95.00%> (-0.15%) ⬇️
🚀 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 added a commit that referenced this pull request Nov 18, 2026
…concile by hand (#464)

* fix(fx): stop counting loan principal as borrowed after it repaid another loan with a result

The default kept a loan's borrowed-principal count (borrowedLeft) too high
when its returned principal repaid another loan at a nonzero result: only a
gain-0 row took the spent units out. A later pass-on of the paid-for rest
then went outside 1633/1637, and the loan note said `_manual` with too small
a boxGain (PASS: 35 instead of 55 of 75 EUR). Tax figures never changed.

Every repayment now retires the borrowed units it spends from their loan,
borrowed units first; only a gain-0 row still counts them outside the boxes.
docs/casillas.md, docs/traza-fx.md and the #449 Hard Trace now say that a
repayment with a result is always in 1633/1637, and that another loan's
principal is outside only for the part of its loan your currency has not
paid, also when it paid another part (PR #463 review).

* docs(fx): say that a repayment with a result pays its loan even when borrowed principal pays it

docs/casillas.md and docs/traza-fx.md told the user that a loan's principal
stays borrowed until currency of their own pays the loan. The code counts a
loan as paid by any repayment in 1633/1637, also a row with a result paid
with another loan's borrowed principal (P2: L2's principal repays L1 with a
5 EUR result, then L1's principal repays L3 inside the boxes, the plain note
with gain 75; only at gain 0, P2-ZERO, does L1 stay borrowed: `_manual`,
boxGain 15 of 65). The docs now say that, CLAUDE.md #449 pins P2 and
P2-ZERO, and the PASS-ZERO test no longer claims the same split as PASS
(PR #463 review).
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