Open-source personal finance manager. Self-hosted, privacy-first.
fix(assets): keep the cost basis when editing a tracked holding (#999)
Tássio Noronha448e42322b07
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex 7a1f6459..79e89ad7 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -619,6 +619,17 @@ async def create_asset(return _asset_to_read(asset, latest, count, tx_count or 0)+# Fields a ledger-backed holding derives from its transactions (see+# asset_transaction_service.recompute_and_cache); an asset update ignores them.+_LEDGER_DERIVED_FIELDS = (+ "units",+ "purchase_price",+ "purchase_date",+ "sell_date",+ "sell_price",+)++async def update_asset(session: AsyncSession,asset_id: uuid.UUID,@@ -638,6 +649,19 @@ async def update_asset(update_data = data.model_dump(exclude_unset=True)# Prevent changing valuation_method on existing assetsupdate_data.pop("valuation_method", None)++ tx_count = await session.scalar(+ select(func.count()).select_from(AssetTransaction).where(AssetTransaction.asset_id == asset.id)+ ) or 0+ # Ledger-backed holdings derive their position (units, cost basis, buy and+ # sell dates) from the transactions ledger. Editing the holding itself+ # (e.g. renaming it) must never overwrite those cached values, or the cost+ # basis is lost and the holding looks like it has no buys (issue #965).+ is_ledger = asset.average_price is not None or tx_count > 0+ if is_ledger:+ for key in _LEDGER_DERIVED_FIELDS:+ update_data.pop(key, None)+for key, value in update_data.items():setattr(asset, key, value)@@ -699,7 +723,7 @@ async def update_asset(await session.refresh(asset)latest = await _get_latest_value(session, asset.id)count = await _get_value_count(session, asset.id)- return _asset_to_read(asset, latest, count)+ return _asset_to_read(asset, latest, count, tx_count)async def delete_asset(diff --git a/backend/tests/test_asset_transactions_api.py b/backend/tests/test_asset_transactions_api.pyindex 5ae616dc..e83775e0 100644--- a/backend/tests/test_asset_transactions_api.py+++ b/backend/tests/test_asset_transactions_api.py@@ -211,3 +211,60 @@ async def test_oversell_rejected_via_api(client: AsyncClient, auth_headers: dict@pytest.mark.asyncioasync def test_transactions_require_auth(client: AsyncClient):assert (await client.get("/api/assets/transactions")).status_code == 401+++async def test_editing_ledger_backed_holding_keeps_cost_basis(+ client: AsyncClient, auth_headers: dict, market_asset_api: Asset+):+ """Renaming a tracked holding must not wipe its ledger-derived position (issue #965)."""+ await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 10, "price": 20, "date": "2026-01-01"},+ )++ # Same shape the edit dialog used to send: cleared cost and form units.+ resp = await client.patch(+ f"/api/assets/{market_asset_api.id}",+ headers=auth_headers,+ json={+ "name": "Petrobras PN",+ "purchase_price": None,+ "purchase_date": None,+ "sell_date": None,+ "sell_price": None,+ "units": 3,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["name"] == "Petrobras PN"+ assert body["units"] == 10+ assert body["purchase_price"] == 200+ assert body["total_invested"] == 200+ assert round(body["average_price"], 2) == 20.00+ assert body["purchase_date"] == "2026-01-01"+ assert body["transaction_count"] == 1++ listed = await client.get("/api/assets", headers=auth_headers)+ holding = next(a for a in listed.json() if a["id"] == str(market_asset_api.id))+ assert holding["total_invested"] == 200+ assert holding["units"] == 10+++async def test_editing_legacy_market_asset_without_ledger_updates_units(+ client: AsyncClient, auth_headers: dict, market_asset_api: Asset+):+ """A market holding with no transactions keeps its units editable."""+ resp = await client.patch(+ f"/api/assets/{market_asset_api.id}",+ headers=auth_headers,+ json={"units": 5},+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["units"] == 5+ assert body["average_price"] is None+ assert body["transaction_count"] == 0diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex 87f5131e..81e91322 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -623,21 +623,41 @@ export default function AssetsPage() {setDialogOpen(true)}+ // Holdings driven by the transactions ledger: quantity, buy date and cost+ // basis come from the transactions, not from this form.+ const editingIsLedgerBacked = !!editingAsset+ && editingAsset.valuation_method === 'market_price'+ && (editingAsset.average_price != null || (editingAsset.transaction_count ?? 0) > 0)+function buildPayload() {const isMarket = formMethod === 'market_price'+ const ledgerBacked = editingIsLedgerBackedconst payload: Record<string, unknown> = {name: formName,type: formType,currency: formCurrency,group_id: formGroupId || null,valuation_method: formMethod,- purchase_date: formPurchaseDate || null,- // Tickers have no total purchase price — the cost basis is derived from- // the unit-price buy (and then the ledger). Only manual/growth assets- // carry a total purchase price.- purchase_price: isMarket ? null : (formPurchasePrice ? parseFloat(formPurchasePrice) : null),- sell_date: isMarket ? null : (formSellDate || null),- sell_price: isMarket ? null : (formSellPrice ? parseFloat(formSellPrice) : null),+ }++ // A ledger-backed holding derives its buy date, quantity and cost basis+ // from its transactions, so an edit must not overwrite them.+ if (!ledgerBacked) {+ payload.purchase_date = formPurchaseDate || null+ }++ // Tickers have no total purchase price: the cost basis is derived from+ // the unit-price buy (and then the ledger). Only manual/growth assets+ // carry a total purchase price and sale info. On edit a ticker leaves+ // these fields untouched instead of clearing them.+ if (!isMarket) {+ payload.purchase_price = formPurchasePrice ? parseFloat(formPurchasePrice) : null+ payload.sell_date = formSellDate || null+ payload.sell_price = formSellPrice ? parseFloat(formSellPrice) : null+ } else if (!editingAsset) {+ payload.purchase_price = null+ payload.sell_date = null+ payload.sell_price = null}if (formMethod === 'growth_rule') {@@ -650,7 +670,9 @@ export default function AssetsPage() {if (isMarket) {payload.ticker = (selectedQuote?.symbol || formTickerQuery || '').toUpperCase()payload.ticker_exchange = selectedQuote?.exchange ?? null- payload.units = formUnits ? parseFloat(formUnits) : null+ if (!ledgerBacked) {+ payload.units = formUnits ? parseFloat(formUnits) : null+ }// Opening buy price per unit (defaults to the live quote on the server// when omitted). Only meaningful on create.if (!editingAsset) {@@ -1354,7 +1376,7 @@ export default function AssetsPage() {) : (<div className="space-y-2"><Label>{t('assets.quantity')}</Label>- <Input type="number" step="any" min="0" value={formUnits} onChange={e => setFormUnits(e.target.value)} placeholder="10" />+ <Input type="number" step="any" min="0" value={formUnits} onChange={e => setFormUnits(e.target.value)} placeholder="10" disabled={editingIsLedgerBacked} /></div>)}@@ -1435,7 +1457,7 @@ export default function AssetsPage() {<div className="grid grid-cols-2 gap-4"><div className="space-y-2"><Label>{t('assets.purchaseDate')}</Label>- <DatePickerInput value={formPurchaseDate} onChange={setFormPurchaseDate} />+ <DatePickerInput value={formPurchaseDate} onChange={setFormPurchaseDate} disabled={editingIsLedgerBacked} /></div>{formMethod !== 'market_price' && (<div className="space-y-2">