Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix(sync): import shared connections as connection owner (#750)

Leonardo Zanivanf050c6d85ead
diff --git a/backend/alembic/versions/077_asset_external_id_workspace.py b/backend/alembic/versions/077_asset_external_id_workspace.py
new file mode 100644
index 00000000..7bf7b64a
--- /dev/null
+++ b/backend/alembic/versions/077_asset_external_id_workspace.py
@@ -0,0 +1,83 @@
+"""scope asset external IDs to workspaces
+
+Revision ID: 077
+Revises: 076
+Create Date: 2026-08-30
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "077"
+down_revision: Union[str, None] = "076"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def _duplicate_external_id(scope_column: str):
+ queries = {
+ "workspace_id": sa.text(
+ """
+ SELECT workspace_id AS scope_id, source, external_id, count(*) AS row_count
+ FROM assets
+ WHERE external_id IS NOT NULL
+ GROUP BY workspace_id, source, external_id
+ HAVING count(*) > 1
+ LIMIT 1
+ """
+ ),
+ "user_id": sa.text(
+ """
+ SELECT user_id AS scope_id, source, external_id, count(*) AS row_count
+ FROM assets
+ WHERE external_id IS NOT NULL
+ GROUP BY user_id, source, external_id
+ HAVING count(*) > 1
+ LIMIT 1
+ """
+ ),
+ }
+ return (
+ op.get_bind()
+ .execute(queries[scope_column])
+ .mappings()
+ .first()
+ )
+
+
+def _require_unique_external_ids(scope_column: str) -> None:
+ duplicate = _duplicate_external_id(scope_column)
+ if duplicate is None:
+ return
+ raise RuntimeError(
+ "Cannot change the asset external ID index because duplicate records "
+ f"exist for {scope_column}={duplicate['scope_id']}, "
+ f"source={duplicate['source']!r}, external_id={duplicate['external_id']!r} "
+ f"({duplicate['row_count']} rows). Reconcile those assets and rerun the migration."
+ )
+
+
+def upgrade() -> None:
+ _require_unique_external_ids("workspace_id")
+ op.drop_index("ux_assets_user_source_external", table_name="assets")
+ op.create_index(
+ "ux_assets_workspace_source_external",
+ "assets",
+ ["workspace_id", "source", "external_id"],
+ unique=True,
+ postgresql_where=sa.text("external_id IS NOT NULL"),
+ )
+
+
+def downgrade() -> None:
+ _require_unique_external_ids("user_id")
+ op.drop_index("ux_assets_workspace_source_external", table_name="assets")
+ op.create_index(
+ "ux_assets_user_source_external",
+ "assets",
+ ["user_id", "source", "external_id"],
+ unique=True,
+ postgresql_where=sa.text("external_id IS NOT NULL"),
+ )
diff --git a/backend/app/models/asset.py b/backend/app/models/asset.py
index 1fde64c8..bc5d79d1 100644
--- a/backend/app/models/asset.py
+++ b/backend/app/models/asset.py
@@ -3,7 +3,7 @@ from datetime import date, datetime
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional
-from sqlalchemy import JSON, Boolean, Date, DateTime, ForeignKey, Integer, Numeric, String
+from sqlalchemy import JSON, Boolean, Date, DateTime, ForeignKey, Index, Integer, Numeric, String, text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -17,6 +17,17 @@ if TYPE_CHECKING:
class Asset(Base):
__tablename__ = "assets"
+ __table_args__ = (
+ Index(
+ "ux_assets_workspace_source_external",
+ "workspace_id",
+ "source",
+ "external_id",
+ unique=True,
+ postgresql_where=text("external_id IS NOT NULL"),
+ sqlite_where=text("external_id IS NOT NULL"),
+ ),
+ )
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index 28f0657c..aeda752b 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -56,6 +56,8 @@ logger = logging.getLogger(__name__)
settings = get_settings()
+_PROVIDER_SELL_DATE_METADATA_KEY = "_securo_provider_sell_date"
+
def _clean_logo_url(value: object) -> Optional[str]:
"""Normalize a provider-supplied logo to a non-empty string or None.
@@ -246,7 +248,7 @@ async def _sync_holdings(
"""Fetch investment holdings from the provider and upsert them as Assets.
Each holding becomes one Asset (type="investment") keyed by
- (user_id, source, external_id). Every sync appends an AssetValue row
+ (workspace_id, source, external_id). Every sync appends an AssetValue row
dated today; if a row for today already exists (same day re-sync) it
is updated in place rather than creating a duplicate.
@@ -514,19 +516,21 @@ async def _sync_holdings(
# the user's customization with them.
split_group_ids = {row[0] for row in sync_owned if row[1] and "::" in row[1]}
- # Also pull orphans (connection_id IS NULL) with the same source —
- # those are assets archived by a prior disconnect. Re-matching on
- # external_id lets users re-link their investment history when they
- # re-add a connection without creating duplicate rows.
existing_rows = await session.execute(
select(Asset).where(
- Asset.user_id == user_id,
+ Asset.workspace_id == connection.workspace_id,
Asset.source == source,
- or_(Asset.connection_id == connection.id, Asset.connection_id.is_(None)),
)
)
+ existing_assets = list(existing_rows.scalars().all())
existing_by_external: dict[str, Asset] = {
- a.external_id: a for a in existing_rows.scalars().all() if a.external_id
+ asset.external_id: asset for asset in existing_assets if asset.external_id
+ }
+ archive_candidates: dict[str, Asset] = {
+ asset.external_id: asset
+ for asset in existing_assets
+ if asset.external_id
+ and (asset.connection_id == connection.id or asset.connection_id is None)
}
seen: set[str] = set()
@@ -545,19 +549,63 @@ async def _sync_holdings(
if holding.is_withdrawn:
if existing is None:
continue
+ provider_sell_date: Optional[str] = None
if existing.sell_date is None:
existing.sell_date = today
+ provider_sell_date = today.isoformat()
+ else:
+ # Preserve provenance across repeated withdrawn payloads, but
+ # deliberately drop it once the user changes the date.
+ previous_marker = (existing.external_metadata or {}).get(
+ _PROVIDER_SELL_DATE_METADATA_KEY
+ )
+ if previous_marker == existing.sell_date.isoformat():
+ provider_sell_date = previous_marker
# Keep descriptive fields fresh in case the provider still
# updates them post-closure, but don't touch valuation.
existing.name = holding.name
- existing.external_metadata = holding.metadata
+ withdrawn_metadata = dict(holding.metadata or {})
+ if provider_sell_date is not None:
+ withdrawn_metadata[_PROVIDER_SELL_DATE_METADATA_KEY] = provider_sell_date
+ existing.external_metadata = withdrawn_metadata or None
existing.connection_id = connection.id
continue
+ # A provider-reported closure is reversible. The prior raw status is
+ # already persisted in external_metadata, so no separate schema field
+ # is needed to distinguish TOTAL_WITHDRAWAL -> ACTIVE from a manually
+ # entered sell date. Manual dates remain authoritative when there was
+ # no provider withdrawal transition.
+ previous_metadata = existing.external_metadata or {} if existing is not None else {}
+ previous_provider_status = str(previous_metadata.get("status") or "").upper()
+ provider_sell_date = previous_metadata.get(_PROVIDER_SELL_DATE_METADATA_KEY)
+ if (
+ existing is not None
+ and existing.sell_date is not None
+ and previous_provider_status == "TOTAL_WITHDRAWAL"
+ and provider_sell_date == existing.sell_date.isoformat()
+ ):
+ existing.sell_date = None
+
asset = await _upsert_asset_from_holding(
session, existing, holding, user_id, connection.id, source,
workspace_id=connection.workspace_id,
)
+ if asset.group_id is not None:
+ existing_group = await session.get(AssetGroup, asset.group_id)
+ if (
+ existing_group is not None
+ and existing_group.workspace_id == connection.workspace_id
+ and existing_group.source == source
+ and (
+ existing_group.connection_id == connection.id
+ or existing_group.connection_id is None
+ )
+ ):
+ existing_group.user_id = user_id
+ sync_owned_group_ids.add(existing_group.id)
+ if existing_group.external_id and "::" in existing_group.external_id:
+ split_group_ids.add(existing_group.id)
# Attach to its institution's wallet. NOTE this deliberately moves
# holdings between sync-owned wallets, not just out of a null group
# like it used to: re-attribution corrects the sync's own earlier
@@ -589,7 +637,7 @@ async def _sync_holdings(
if asset.sell_date is None:
await _upsert_asset_value_for_today(session, asset, holding.current_value, today)
- for ext_id, asset in existing_by_external.items():
+ for ext_id, asset in archive_candidates.items():
if ext_id not in seen and not asset.is_archived:
asset.is_archived = True
@@ -630,7 +678,7 @@ async def _upsert_asset_from_holding(
user_id: uuid.UUID,
connection_id: uuid.UUID,
source: str,
- workspace_id: Optional[uuid.UUID] = None,
+ workspace_id: uuid.UUID,
) -> Asset:
"""Create or update an Asset from a HoldingData payload.
@@ -643,6 +691,7 @@ async def _upsert_asset_from_holding(
if asset is None:
asset = Asset(
user_id=user_id,
+ workspace_id=workspace_id,
connection_id=connection_id,
source=source,
external_id=holding.external_id,
@@ -665,6 +714,7 @@ async def _upsert_asset_from_holding(
# Fields Pluggy consistently returns — safe to overwrite each sync.
asset.name = holding.name
asset.currency = holding.currency
+ asset.user_id = user_id
# external_metadata is a snapshot blob: we want the latest every time.
asset.external_metadata = holding.metadata
previous_connection_id = asset.connection_id
@@ -676,7 +726,7 @@ async def _upsert_asset_from_holding(
# Re-adopted across workspaces (bank deleted in one, re-added in the
# other): the asset follows its connection; its old wallet stays behind
# in the old workspace, so placement is redone by the caller.
- if workspace_id is not None and asset.workspace_id != workspace_id:
+ if asset.workspace_id != workspace_id:
asset.workspace_id = workspace_id
asset.group_id = None
@@ -1570,7 +1620,7 @@ async def sync_connection(
session: AsyncSession,
connection_id: uuid.UUID,
workspace_id: uuid.UUID,
- user_id: uuid.UUID,
+ requesting_user_id: uuid.UUID,
trigger_provider_refresh: bool = False,
) -> tuple[BankConnection, int]:
connection = await get_connection(session, connection_id, workspace_id)
@@ -1579,6 +1629,20 @@ async def sync_connection(
if not connection.credentials:
raise ValueError("Credentials not found")
+ # Authorization is workspace-scoped and happens before this service is
+ # called. Data imported from a bank connection, however, must always be
+ # owned by the user who owns that connection — not by whichever workspace
+ # member clicked Sync. Mixing those identities creates duplicate holdings
+ # and wallets because provider external IDs are unique per user.
+ if requesting_user_id != connection.user_id:
+ logger.info(
+ "Connection %s sync requested by workspace member %s; importing as owner %s",
+ connection.id,
+ requesting_user_id,
+ connection.user_id,
+ )
+ user_id = connection.user_id
+
conn_settings = connection.settings or {}
payee_source = conn_settings.get("payee_source", "auto")
import_pending = conn_settings.get("import_pending", True)
@@ -1649,6 +1713,23 @@ async def sync_connection(
)
account = result.scalar_one_or_none()
+ if account is not None:
+ account.user_id = user_id
+ account.workspace_id = connection.workspace_id
+ await session.execute(
+ update(Transaction)
+ .where(
+ Transaction.account_id == account.id,
+ Transaction.source == "sync",
+ )
+ .values(user_id=user_id, workspace_id=connection.workspace_id)
+ )
+ await session.execute(
+ update(CreditCardBill)
+ .where(CreditCardBill.account_id == account.id)
+ .values(user_id=user_id, workspace_id=connection.workspace_id)
+ )
+
institution = await _resolve_institution(
session, connection.id, institution_cache, acc_data
)
diff --git a/backend/tests/test_asset_external_id_migration.py b/backend/tests/test_asset_external_id_migration.py
new file mode 100644
index 00000000..f3bfe1cf
--- /dev/null
+++ b/backend/tests/test_asset_external_id_migration.py
@@ -0,0 +1,58 @@
+import importlib.util
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+
+
+_MIGRATION_PATH = (
+ Path(__file__).resolve().parent.parent
+ / "alembic"
+ / "versions"
+ / "077_asset_external_id_workspace.py"
+)
+_SPEC = importlib.util.spec_from_file_location("asset_external_id_migration", _MIGRATION_PATH)
+assert _SPEC is not None and _SPEC.loader is not None
+migration = importlib.util.module_from_spec(_SPEC)
+_SPEC.loader.exec_module(migration)
+
+
+class _Result:
+ def __init__(self, row):
+ self.row = row
+
+ def mappings(self):
+ return self
+
+ def first(self):
+ return self.row
+
+
+ ("direction", "scope_column"),
+ [("upgrade", "workspace_id"), ("downgrade", "user_id")],
+)
+def test_index_change_aborts_before_schema_changes(monkeypatch, direction, scope_column):
+ bind = Mock()
+ bind.execute.return_value = _Result(
+ {
+ "scope_id": "scope-1",
+ "source": "provider",
+ "external_id": "asset-1",
+ "row_count": 2,
+ }
+ )
+ drop_index = Mock()
+ create_index = Mock()
+ monkeypatch.setattr(migration.op, "get_bind", lambda: bind)
+ monkeypatch.setattr(migration.op, "drop_index", drop_index)
+ monkeypatch.setattr(migration.op, "create_index", create_index)
+
+ with pytest.raises(RuntimeError, match=f"{scope_column}=scope-1"):
+ getattr(migration, direction)()
+
+ statement = " ".join(str(bind.execute.call_args.args[0]).lower().split())
+ assert f"select {scope_column} as scope_id" in statement
+ assert f"group by {scope_column}, source, external_id" in statement
+ drop_index.assert_not_called()
+ create_index.assert_not_called()
diff --git a/backend/tests/test_connection_service_coverage.py b/backend/tests/test_connection_service_coverage.py
index 31550112..94854a8c 100644
--- a/backend/tests/test_connection_service_coverage.py
+++ b/backend/tests/test_connection_service_coverage.py
@@ -19,8 +19,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
from app.models.asset import Asset
+from app.models.asset_group import AssetGroup
from app.models.bank_connection import BankConnection
+from app.models.credit_card_bill import CreditCardBill
from app.models.transaction import Transaction
+from app.models.user import User
+from app.models.workspace import WorkspaceMember
from app.providers.base import (
AccountData,
ConnectionData,
@@ -67,6 +71,107 @@ def _patch_helpers():
)
+async def test_shared_workspace_sync_imports_as_connection_owner(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """A workspace member may trigger sync without owning imported rows."""
+ requester = User(
+ id=uuid.uuid4(),
+ hashed_password="not-used",
+ is_active=True,
+ is_superuser=False,
+ is_verified=True,
+ preferences={"currency_display": "BRL"},
+ )
+ session.add(requester)
+ await session.flush()
+
+ conn = await _make_connection(session, test_user.id, "Shared Broker")
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="shared-account",
+ name="Brokerage",
+ type="checking",
+ balance=Decimal("100"),
+ currency="BRL",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="shared-tx",
+ description="DIVIDEND",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="credit",
+ currency="BRL",
+ ),
+ ])
+ mock_provider.get_holdings = AsyncMock(return_value=[
+ HoldingData(
+ external_id="shared-holding",
+ name="Shared Fund",
+ currency="BRL",
+ current_value=Decimal("500"),
+ ),
+ ])
+
+ p1, p2, p3 = _patch_helpers()
+ q1, q2, q3 = _patch_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ q1, q2, q3:
+ await sync_connection(session, conn.id, test_workspace.id, requester.id)
+
+ account = await session.scalar(select(Account).where(Account.external_id == "shared-account"))
+ transaction = await session.scalar(
+ select(Transaction).where(Transaction.external_id == "shared-tx")
+ )
+ asset = await session.scalar(select(Asset).where(Asset.external_id == "shared-holding"))
+ assert asset is not None
+ wallet = await session.get(AssetGroup, asset.group_id)
+
+ assert account is not None and account.user_id == test_user.id
+ assert transaction is not None and transaction.user_id == test_user.id
+ assert asset.user_id == test_user.id
+ assert wallet is not None and wallet.user_id == test_user.id
+
+ account.user_id = requester.id
+ transaction.user_id = requester.id
+ asset.user_id = requester.id
+ wallet.user_id = requester.id
+ bill = CreditCardBill(
+ id=uuid.uuid4(),
+ user_id=requester.id,
+ workspace_id=test_workspace.id,
+ account_id=account.id,
+ external_id="legacy-bill",
+ due_date=date.today(),
+ total_amount=Decimal("100"),
+ currency="BRL",
+ )
+ session.add(bill)
+ await session.commit()
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_workspace.id, requester.id)
+
+ await session.refresh(account)
+ await session.refresh(transaction)
+ await session.refresh(asset)
+ await session.refresh(wallet)
+ await session.refresh(bill)
+ assert account.user_id == test_user.id
+ assert transaction.user_id == test_user.id
+ assert asset.user_id == test_user.id
+ assert wallet.user_id == test_user.id
+ assert bill.user_id == test_user.id
+ assert bill.workspace_id == test_workspace.id
+
+
# ---------------------------------------------------------------------------
# get_oauth_url / get_reauth_url
# ---------------------------------------------------------------------------
@@ -158,6 +263,163 @@ async def test_sync_holdings_creates_asset(session: AsyncSession, test_user):
assert asset.name == "VWCE ETF"
assert asset.type == "investment"
assert asset.connection_id == conn.id
+ assert asset.workspace_id == conn.workspace_id
+
+
+async def test_sync_holdings_matches_asset_across_workspace_members(
+ session: AsyncSession, test_user, test_workspace
+):
+ other_member = User(
+ id=uuid.uuid4(),
+ hashed_password="not-used",
+ is_active=True,
+ is_superuser=False,
+ is_verified=True,
+ )
+ session.add(other_member)
+ await session.flush()
+ session.add(
+ WorkspaceMember(
+ id=uuid.uuid4(),
+ workspace_id=test_workspace.id,
+ user_id=other_member.id,
+ role="editor",
+ )
+ )
+ conn = await _make_connection(session, test_user.id, "Shared Broker")
+ existing = Asset(
+ id=uuid.uuid4(),
+ user_id=other_member.id,
+ workspace_id=test_workspace.id,
+ source="test",
+ external_id="shared-holding-id",
+ name="Existing holding",
+ type="investment",
+ currency="USD",
+ valuation_method="manual",
+ )
+ existing_group = AssetGroup(
+ id=uuid.uuid4(),
+ user_id=other_member.id,
+ workspace_id=test_workspace.id,
+ connection_id=None,
+ source="test",
+ external_id=conn.external_id,
+ name="Legacy wallet",
+ position=0,
+ )
+ session.add(existing_group)
+ await session.flush()
+ existing.group_id = existing_group.id
+ session.add(existing)
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.get_holdings = AsyncMock(
+ return_value=[
+ HoldingData(
+ external_id="shared-holding-id",
+ name="Updated holding",
+ currency="USD",
+ current_value=Decimal("500"),
+ )
+ ]
+ )
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):
+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})
+ await session.commit()
+
+ matching = (
+ await session.execute(
+ select(Asset).where(
+ Asset.workspace_id == test_workspace.id,
+ Asset.source == "test",
+ Asset.external_id == "shared-holding-id",
+ )
+ )
+ ).scalars().all()
+ assert [asset.id for asset in matching] == [existing.id]
+ assert matching[0].connection_id == conn.id
+ assert matching[0].name == "Updated holding"
+ assert matching[0].user_id == test_user.id
+ await session.refresh(existing_group)
+ assert existing_group.user_id == test_user.id
+
+
+async def test_sync_holdings_does_not_adopt_another_connections_wallet(
+ session: AsyncSession, test_user, test_workspace
+):
+ other_member = User(
+ id=uuid.uuid4(),
+ hashed_password="not-used",
+ is_active=True,
+ is_superuser=False,
+ is_verified=True,
+ )
+ session.add(other_member)
+ await session.flush()
+ session.add(
+ WorkspaceMember(
+ id=uuid.uuid4(),
+ workspace_id=test_workspace.id,
+ user_id=other_member.id,
+ role="editor",
+ )
+ )
+ current = await _make_connection(session, test_user.id, "Current Broker")
+ other = await _make_connection(session, other_member.id, "Other Broker")
+ other_group = AssetGroup(
+ id=uuid.uuid4(),
+ user_id=other_member.id,
+ workspace_id=test_workspace.id,
+ connection_id=other.id,
+ source="test",
+ external_id=other.external_id,
+ name="Other connection wallet",
+ position=0,
+ )
+ existing = Asset(
+ id=uuid.uuid4(),
+ user_id=other_member.id,
+ workspace_id=test_workspace.id,
+ connection_id=other.id,
+ group_id=other_group.id,
+ source="test",
+ external_id="shared-provider-holding",
+ name="Existing holding",
+ type="investment",
+ currency="USD",
+ valuation_method="manual",
+ )
+ session.add_all([other_group, existing])
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.get_holdings = AsyncMock(
+ return_value=[
+ HoldingData(
+ external_id="shared-provider-holding",
+ name="Updated holding",
+ currency="USD",
+ current_value=Decimal("500"),
+ )
+ ]
+ )
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):
+ await _sync_holdings(session, test_user.id, current, {"token": "t"})
+ await session.commit()
+
+ await session.refresh(other_group)
+ await session.refresh(existing)
+ assert other_group.user_id == other_member.id
+ assert other_group.connection_id == other.id
+ assert existing.group_id == other_group.id
@pytest.mark.asyncio
diff --git a/backend/tests/test_sync_holdings.py b/backend/tests/test_sync_holdings.py
index f55135c2..25d0b938 100644
--- a/backend/tests/test_sync_holdings.py
+++ b/backend/tests/test_sync_holdings.py
@@ -1,8 +1,9 @@
"""Cover the Asset lifecycle through `_sync_holdings`.
The sync contract is a bit subtle: provider data drives creation *and*
-closure of Assets, but user-set fields are load-bearing — sell_date is
-never overwritten, and group_id is rewritten only between wallets the
+closure of Assets, but user-set fields are load-bearing — manual sell_date
+is never overwritten, while provider closures reopen if the holding returns
+ACTIVE; group_id is rewritten only between wallets the
sync itself owns (per-account re-attribution, issue #345); a wallet the
user chose is never touched (see test_connection_service.py for the
re-attribution matrix). These tests pin the rest: new/existing ×
@@ -134,7 +135,11 @@ def _holding(
purchase_price=purchase_price,
purchase_date=purchase_date,
is_withdrawn=is_withdrawn,
- metadata=metadata or {"status": "ACTIVE"},
+ metadata=(
+ metadata
+ if metadata is not None
+ else {"status": "TOTAL_WITHDRAWAL" if is_withdrawn else "ACTIVE"}
+ ),
)
@@ -239,6 +244,8 @@ async def test_withdrawn_existing_asset_gets_sell_date(
await session.refresh(asset)
assert asset.sell_date == today
+ assert asset.external_metadata is not None
+ assert asset.external_metadata["status"] == "TOTAL_WITHDRAWAL"
values_after = await _values_for(session, asset.id)
# Historical values preserved; no zero appended.
assert len(values_after) == len(values_before)
@@ -314,6 +321,78 @@ async def test_user_sold_active_on_provider_stops_value_updates(
assert values == [] # no new values recorded
+async def test_provider_withdrawn_holding_reopens_when_active_again(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """A transient TOTAL_WITHDRAWAL must not leave an ACTIVE holding sold."""
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("500")),
+ ]
+ assert mock_connection.credentials is not None
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ [asset] = await _assets_for(session, test_user)
+
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("0"), is_withdrawn=True),
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+ assert asset.sell_date == date.today()
+ assert asset.external_metadata is not None
+ assert asset.external_metadata["status"] == "TOTAL_WITHDRAWAL"
+
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("525")),
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.sell_date is None
+ assert asset.external_metadata is not None
+ assert asset.external_metadata["status"] == "ACTIVE"
+ values = await _values_for(session, asset.id)
+ assert any(v.date == date.today() and v.amount == Decimal("525") for v in values)
+
+
+async def test_active_holding_preserves_sell_date_edited_after_provider_withdrawal(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """A user correction after withdrawal must survive provider reactivation."""
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("500")),
+ ]
+ assert mock_connection.credentials is not None
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ [asset] = await _assets_for(session, test_user)
+
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("0"), is_withdrawn=True),
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ corrected_sell_date = date.today() - timedelta(days=14)
+ asset.sell_date = corrected_sell_date
+ await session.commit()
+
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("525")),
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.sell_date == corrected_sell_date
+ assert asset.external_metadata is not None
+ assert asset.external_metadata["status"] == "ACTIVE"
+
+
@pytest.mark.asyncio
async def test_same_day_resync_updates_asset_value_in_place(
session: AsyncSession, test_user: User, mock_connection: BankConnection