Open-source personal finance manager. Self-hosted, privacy-first.
fix: preserve transfer categories and clear fx overrides (#16) (#378)
Albert Dolkunf81b0fad5b19
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 023dbb3a..15b81e07 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -923,7 +923,6 @@ async def link_existing_as_transfer(transfer_pair_id = uuid.uuid4()for tx in txns:tx.transfer_pair_id = transfer_pair_id- tx.category_id = None # transfers are excluded from category reportsawait session.commit()for tx in txns:@@ -1002,9 +1001,8 @@ async def create_transfer_counterpart(apply_effective_date(counterpart_tx, to_account)session.add(counterpart_tx)- # Link the anchor into the pair; transfers are excluded from category reports.+ # Link the anchor into the pair; reports exclude transfer_pair_id.anchor.transfer_pair_id = transfer_pair_id- anchor.category_id = Noneawait session.flush()await stamp_primary_amount(session, user_id, counterpart_tx)@@ -1122,9 +1120,9 @@ async def update_transaction(raise ValueError("Cannot move transfer to the same account as its paired transaction")# Pop FX override fields before generic setattr loop+ has_fx_override = "amount_primary" in update_data or "fx_rate_used" in update_dataoverride_amount_primary = update_data.pop("amount_primary", None)override_fx_rate = update_data.pop("fx_rate_used", None)- has_fx_override = override_amount_primary is not None or override_fx_rate is not Nonerestamp_fields = {"amount", "currency", "date"}needs_restamp = bool(restamp_fields & update_data.keys())@@ -1133,12 +1131,17 @@ async def update_transaction(setattr(transaction, key, value)if has_fx_override:- _apply_fx_override(- transaction,- transaction.amount,- override_amount_primary,- override_fx_rate,- )+ if override_amount_primary is None and override_fx_rate is None:+ transaction.amount_primary = None+ transaction.fx_rate_used = None+ await stamp_primary_amount(session, user_id, transaction)+ else:+ _apply_fx_override(+ transaction,+ transaction.amount,+ override_amount_primary,+ override_fx_rate,+ )elif needs_restamp:await stamp_primary_amount(session, user_id, transaction)diff --git a/backend/tests/test_fx_rates.py b/backend/tests/test_fx_rates.pyindex 052c048e..1aef615f 100644--- a/backend/tests/test_fx_rates.py+++ b/backend/tests/test_fx_rates.py@@ -1256,6 +1256,43 @@ class TestManualFxOverride:assert data["amount_primary"] == 550.0assert data["fx_rate_used"] == 5.5+ @pytest.mark.asyncio+ async def test_update_clear_fx_override_restamps(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ usd_account = await _make_account(session, test_user, currency="USD")+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Clear override",+ "amount": "100.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ "amount_primary": "550.00",+ "fx_rate_used": "5.5",+ },+ )+ assert resp.status_code == 201+ txn_id = resp.json()["id"]++ resp2 = await client.patch(+ f"/api/transactions/{txn_id}",+ headers=auth_headers,+ json={"amount_primary": None, "fx_rate_used": None},+ )+ assert resp2.status_code == 200+ data = resp2.json()+ assert data["amount_primary"] == 500.0+ assert data["fx_rate_used"] == 5.0+@pytest.mark.asyncioasync def test_update_without_fx_override_auto_stamps(self,diff --git a/backend/tests/test_transactions_api_coverage.py b/backend/tests/test_transactions_api_coverage.pyindex 86bc67c0..74533188 100644--- a/backend/tests/test_transactions_api_coverage.py+++ b/backend/tests/test_transactions_api_coverage.py@@ -314,6 +314,37 @@ async def test_transfer_candidates_not_found(client: AsyncClient, auth_headers,assert resp.status_code == 404+async def test_link_transfer_preserves_categories(+ client: AsyncClient, auth_headers, test_transactions, test_categories+):+ other = await _manual_account(client, auth_headers, "Destino linkado")+ debit = test_transactions[0]+ credit_resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": other,+ "category_id": str(test_categories[2].id),+ "description": "Linked credit",+ "amount": "25.50",+ "date": date.today().isoformat(),+ "type": "credit",+ },+ )+ assert credit_resp.status_code == 201, credit_resp.text++ resp = await client.post(+ "/api/transactions/link-transfer",+ headers=auth_headers,+ json={"transaction_ids": [str(debit.id), credit_resp.json()["id"]]},+ )+ assert resp.status_code == 200, resp.text+ data = resp.json()+ assert data["debit"]["category_id"] == str(debit.category_id)+ assert data["credit"]["category_id"] == str(test_categories[2].id)++@pytest.mark.asyncioasync def test_create_counterpart(client: AsyncClient, auth_headers, test_account: Account, test_transactions@@ -326,7 +357,9 @@ async def test_create_counterpart(json={"to_account_id": other},)assert resp.status_code == 201, resp.text- assert resp.json()["transfer_pair_id"]+ data = resp.json()+ assert data["transfer_pair_id"]+ assert data["debit"]["category_id"] == str(tx.category_id)@pytest.mark.asynciodiff --git a/backend/tests/test_transfer_api.py b/backend/tests/test_transfer_api.pyindex dfd302af..5416b8e1 100644--- a/backend/tests/test_transfer_api.py+++ b/backend/tests/test_transfer_api.py@@ -875,14 +875,14 @@ async def test_create_counterpart_rejects_already_linked(@pytest.mark.asyncio-async def test_create_counterpart_clears_anchor_category(+async def test_create_counterpart_preserves_anchor_category(client: AsyncClient,auth_headers,test_account: Account,second_account: Account,test_categories,):- """Marking a categorized transaction as a transfer clears its category."""+ """Marking a categorized transaction as a transfer keeps its category."""create_response = await client.post("/api/transactions",json={@@ -910,7 +910,7 @@ async def test_create_counterpart_clears_anchor_category(f"/api/transactions/{anchor['id']}", headers=auth_headers)assert refreshed.status_code == 200- assert refreshed.json()["category_id"] is None+ assert refreshed.json()["category_id"] == str(test_categories[0].id)@pytest.mark.asynciodiff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex 1febfa7f..933ddb84 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -369,6 +369,9 @@ function TransactionForm({const [fxRate, setFxRate] = useState(seed?.fx_rate_used != null ? seed.fx_rate_used.toString() : '')+ const [hadInitialFx] = useState(+ !!transaction && (seed?.amount_primary != null || seed?.fx_rate_used != null)+ )const [isRecurring, setIsRecurring] = useState(false)const [frequency, setFrequency] = useState<'monthly' | 'weekly' | 'yearly'>('monthly')const [endDate, setEndDate] = useState('')@@ -598,6 +601,10 @@ function TransactionForm({if (showConversion && fxRate) {fxFields.fx_rate_used = parseFloat(fxRate)}+ if (showConversion && hadInitialFx && !convertedAmount && !fxRate) {+ fxFields.amount_primary = null+ fxFields.fx_rate_used = null+ }// Active CC account ⇒ surface effective_bill_date in the payload// (sent both for synced and manual edits since the user can hand-// correct the bucketing on either; null clears the override back to