Skip to content

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

feat(import): one place to import, with history and undo for orders (#651)

Tássio Noronhab817c5330128
diff --git a/backend/alembic/versions/073_import_logs_for_asset_orders.py b/backend/alembic/versions/073_import_logs_for_asset_orders.py
new file mode 100644
index 00000000..3947bc9b
--- /dev/null
+++ b/backend/alembic/versions/073_import_logs_for_asset_orders.py
@@ -0,0 +1,62 @@
+"""let an import log describe an order import, not only a statement import
+
+Revision ID: 073
+Revises: 072
+Create Date: 2026-08-21
+
+`import_logs` was written when the only thing anyone imported was a bank
+statement: every row points at an account, counts transactions and sums
+credits and debits. Investment orders are imported the same way and deserve
+the same record, including the delete that undoes them, but they belong to
+holdings rather than to an account.
+
+So the table grows an `entity` telling the two apart, `account_id` becomes
+nullable because an order import has no account, and `asset_transactions`
+gains the `import_id` that makes an undo possible at all. Existing rows are
+statement imports by definition, which is what the server default records.
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import postgresql
+
+revision: str = "073"
+down_revision: Union[str, None] = "072"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "import_logs",
+ sa.Column("entity", sa.String(20), nullable=False, server_default="transactions"),
+ )
+ op.alter_column("import_logs", "account_id", existing_type=postgresql.UUID(), nullable=True)
+
+ op.add_column(
+ "asset_transactions",
+ sa.Column("import_id", postgresql.UUID(as_uuid=True), nullable=True),
+ )
+ op.create_foreign_key(
+ "fk_asset_transactions_import_id",
+ "asset_transactions",
+ "import_logs",
+ ["import_id"],
+ ["id"],
+ ondelete="SET NULL",
+ )
+ op.create_index("ix_asset_transactions_import_id", "asset_transactions", ["import_id"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_asset_transactions_import_id", table_name="asset_transactions")
+ op.drop_constraint("fk_asset_transactions_import_id", "asset_transactions", type_="foreignkey")
+ op.drop_column("asset_transactions", "import_id")
+
+ # An order import has no account, so its rows cannot satisfy the old NOT
+ # NULL. They are deleted rather than pointed at an arbitrary account.
+ op.execute("DELETE FROM import_logs WHERE entity = 'asset_orders'")
+ op.alter_column("import_logs", "account_id", existing_type=postgresql.UUID(), nullable=False)
+ op.drop_column("import_logs", "entity")
diff --git a/backend/app/api/assets.py b/backend/app/api/assets.py
index 7bc76f92..d520c76f 100644
--- a/backend/app/api/assets.py
+++ b/backend/app/api/assets.py
@@ -305,7 +305,8 @@ async def import_asset_orders(
"""Apply the previewed orders to the workspace's holdings."""
try:
summary = await asset_import_service.import_orders(
- session, ctx.workspace.id, ctx.user_id, data.orders, group_id=data.group_id
+ session, ctx.workspace.id, ctx.user_id, data.orders,
+ group_id=data.group_id, filename=data.filename,
)
except MarketPriceRateLimitedError:
raise HTTPException(
diff --git a/backend/app/api/import_logs.py b/backend/app/api/import_logs.py
index 4e08d0e7..bb96defd 100644
--- a/backend/app/api/import_logs.py
+++ b/backend/app/api/import_logs.py
@@ -12,6 +12,7 @@ from app.core.workspace_context import (
from app.models.import_log import ImportLog
from app.models.transaction import Transaction
from app.schemas.import_log import ImportLogRead
+from app.services import asset_import_service
router = APIRouter(prefix="/api/import-logs", tags=["import-logs"])
@@ -34,6 +35,7 @@ async def list_import_logs(
user_id=log.user_id,
account_id=log.account_id,
account_name=log.account.name if log.account else None,
+ entity=log.entity,
filename=log.filename,
format=log.format,
transaction_count=log.transaction_count,
@@ -63,6 +65,13 @@ async def delete_import_log(
if not log:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Import log not found")
+ if log.entity == "asset_orders":
+ # Orders derive a position, so undoing them is more than a delete:
+ # the service recomputes what is left and drops holdings the import
+ # itself created.
+ await asset_import_service.undo_import(session, ctx.workspace.id, log)
+ return
+
# Clean up attachment files before deleting transactions
from app.services.attachment_service import cleanup_attachment_files
tx_result = await session.execute(
diff --git a/backend/app/models/asset_transaction.py b/backend/app/models/asset_transaction.py
index 086bdddd..76b21b12 100644
--- a/backend/app/models/asset_transaction.py
+++ b/backend/app/models/asset_transaction.py
@@ -40,6 +40,11 @@ class AssetTransaction(Base):
source: Mapped[str] = mapped_column(String(20), default="manual") # manual, import, pluggy
external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
notes: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
+ #: The import that wrote this row, so deleting that import can take it
+ #: back out again.
+ import_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("import_logs.id", ondelete="SET NULL"), nullable=True, index=True
+ )
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
asset: Mapped["Asset"] = relationship(back_populates="transactions")
diff --git a/backend/app/models/import_log.py b/backend/app/models/import_log.py
index 6d8f156f..51e2d417 100644
--- a/backend/app/models/import_log.py
+++ b/backend/app/models/import_log.py
@@ -22,9 +22,15 @@ class ImportLog(Base):
workspace_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
)
- account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))
+ #: Null for an order import: those land on holdings, not on an account.
+ account_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=True
+ )
+ #: What was imported: "transactions" (a bank statement) or "asset_orders".
+ entity: Mapped[str] = mapped_column(String(20), default="transactions", server_default="transactions")
filename: Mapped[str] = mapped_column(String(255))
format: Mapped[str] = mapped_column(String(10))
+ #: Rows written by this import, whichever kind they are.
transaction_count: Mapped[int] = mapped_column(Integer)
total_credit: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))
total_debit: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))
diff --git a/backend/app/schemas/asset_import.py b/backend/app/schemas/asset_import.py
index 0c64848b..2a83f906 100644
--- a/backend/app/schemas/asset_import.py
+++ b/backend/app/schemas/asset_import.py
@@ -56,9 +56,12 @@ class AssetImportPreview(BaseModel):
class AssetImportRequest(BaseModel):
orders: list[AssetOrderImport]
group_id: Optional[UUID] = None
+ #: Only for the history entry, so a past import is recognisable.
+ filename: Optional[str] = None
class AssetImportResult(BaseModel):
+ import_log_id: Optional[UUID] = None
imported: int
skipped: int
holdings_created: int
diff --git a/backend/app/schemas/import_log.py b/backend/app/schemas/import_log.py
index 0dceb1bc..777d477b 100644
--- a/backend/app/schemas/import_log.py
+++ b/backend/app/schemas/import_log.py
@@ -9,8 +9,11 @@ from pydantic import BaseModel, ConfigDict
class ImportLogRead(BaseModel):
id: uuid.UUID
user_id: uuid.UUID
- account_id: uuid.UUID
+ #: Null for an order import, which lands on holdings rather than an account.
+ account_id: Optional[uuid.UUID] = None
account_name: Optional[str] = None
+ #: "transactions" for a bank statement, "asset_orders" for a broker file.
+ entity: str = "transactions"
filename: str
format: str
transaction_count: int
diff --git a/backend/app/services/asset_import_service.py b/backend/app/services/asset_import_service.py
index 6e0a0208..17672574 100644
--- a/backend/app/services/asset_import_service.py
+++ b/backend/app/services/asset_import_service.py
@@ -21,6 +21,7 @@ Two things shape the design:
"""
import csv
import io
+import logging
import uuid
from datetime import date as date_type
from datetime import datetime, timezone
@@ -33,7 +34,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.asset import Asset
from app.models.asset_group import AssetGroup
from app.models.asset_transaction import AssetTransaction
-from app.providers.market_price import MarketPriceProvider, get_market_price_provider
+from app.models.import_log import ImportLog
+from app.providers.market_price import (
+ MarketPriceProvider,
+ MarketPriceRateLimitedError,
+ get_market_price_provider,
+)
from app.schemas.asset_import import (
AssetImportRowError,
AssetImportWarning,
@@ -47,6 +53,12 @@ from app.services.import_service import (
)
from app.services.rule_engine import _strip_accents
+logger = logging.getLogger(__name__)
+
+#: How many tickers the bulk lookup may miss before we stop double-checking
+#: them one by one. Past this the provider is having a bad day, not the file.
+_QUOTE_FALLBACK_LIMIT = 25
+
#: Securo fields a CSV column can be mapped to, and which of them a file cannot
#: do without. Mirrors the transaction importer's `CSV_MAPPABLE_FIELDS`, and
#: drives both the mapping dropdowns and the downloadable template.
@@ -331,19 +343,44 @@ async def resolve_tickers(
) -> dict[str, bool]:
"""Which of these tickers the price provider recognises.
- One batch call for the whole file. A ticker the provider does not know can
- still be imported onto a holding that already exists in the workspace; it
- is only a problem when the holding would have to be created.
+ One batch call answers for the whole file, which is what keeps a 200-row
+ import from making 200 requests. The bulk endpoint is not authoritative
+ though: it answers with an empty result often enough — the same ticker can
+ come back priced and then empty seconds later — that treating a miss as
+ proof would reject real holdings. So the few it did not answer for are
+ confirmed one by one against the quote endpoint, which is.
+
+ A ticker nobody recognises can still be imported onto a holding that
+ already exists in the workspace; it only blocks a holding that would have
+ to be created.
"""
provider = market_provider or get_market_price_provider()
unique = sorted({t.upper() for t in tickers if t})
if not unique:
return {}
+
+ resolved: dict[str, bool] = {}
try:
prices = await provider.get_latest_prices(unique)
- except Exception: # provider down or rate-limited: nothing is resolvable
- return {t: False for t in unique}
- return {t: prices.get(t) is not None for t in unique}
+ resolved = {t: prices.get(t) is not None for t in unique}
+ except MarketPriceRateLimitedError:
+ raise # the endpoint turns this into a 429 the user can act on
+ except Exception:
+ # Swallowing this silently would report every ticker as unknown and
+ # blame the file for the provider's outage.
+ logger.warning("Bulk price lookup failed; falling back to quotes", exc_info=True)
+ resolved = {t: False for t in unique}
+
+ unconfirmed = [t for t in unique if not resolved.get(t)]
+ for ticker in unconfirmed[:_QUOTE_FALLBACK_LIMIT]:
+ try:
+ resolved[ticker] = await provider.get_quote(ticker) is not None
+ except MarketPriceRateLimitedError:
+ raise
+ except Exception:
+ logger.warning("Quote lookup failed for %s", ticker, exc_info=True)
+ resolved[ticker] = False
+ return resolved
async def _existing_holdings(
@@ -424,6 +461,7 @@ async def import_orders(
*,
group_id: Optional[uuid.UUID] = None,
dry_run: bool = False,
+ filename: Optional[str] = None,
market_provider: Optional[MarketPriceProvider] = None,
) -> dict:
"""Apply a file of orders to the workspace's holdings.
@@ -505,6 +543,20 @@ async def import_orders(
if dry_run or not accepted:
return summary
+ # The log exists before the rows so they can point at it, and is removed
+ # again if the run ends up writing nothing.
+ log = ImportLog(
+ user_id=user_id,
+ workspace_id=workspace_id,
+ account_id=None,
+ entity='asset_orders',
+ filename=filename or 'orders.csv',
+ format='csv',
+ transaction_count=0,
+ )
+ session.add(log)
+ await session.flush()
+
quotes = {}
if to_create:
provider = market_provider or get_market_price_provider()
@@ -554,6 +606,7 @@ async def import_orders(
date=order.date,
source='import',
external_id=order.external_id,
+ import_id=log.id,
notes=order.notes,
))
touched[order.ticker] = asset
@@ -563,10 +616,17 @@ async def import_orders(
# Once per holding, not once per row: the recompute walks the whole ledger.
for asset in touched.values():
await asset_transaction_service.recompute_and_cache(session, asset)
+
+ if written:
+ log.transaction_count = written
+ session.add(log)
+ else:
+ await session.delete(log)
await session.commit()
summary['errors'] = errors
summary['imported'] = written
+ summary['import_log_id'] = str(log.id) if written else None
summary['holdings_created'] = len([t for t in to_create if t in touched])
return summary
@@ -579,3 +639,44 @@ def csv_template() -> str:
'AAPL,2026-03-02,-4,178.30,1.20,sell,USD,partial exit\n'
'PETR4.SA,2026-02-10,100,38.50,2.90,buy,BRL,\n'
)
+
+
+async def undo_import(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ log: ImportLog,
+) -> int:
+ """Take back every order an import wrote, and leave the portfolio as it was.
+
+ Deleting the rows is only half of it. A position is derived from its
+ ledger, so each touched holding has to be recomputed, and a holding this
+ import created from nothing has to go with it — otherwise undoing leaves
+ an empty ticker sitting in the wallet. A holding that still has orders
+ after the delete is one the user also fed by hand or by an earlier import,
+ so it stays.
+ """
+ result = await session.execute(
+ select(AssetTransaction).where(AssetTransaction.import_id == log.id)
+ )
+ rows = list(result.scalars().all())
+ asset_ids = {row.asset_id for row in rows}
+
+ for row in rows:
+ await session.delete(row)
+ await session.flush()
+
+ for asset_id in asset_ids:
+ asset = await session.get(Asset, asset_id)
+ if asset is None or asset.workspace_id != workspace_id:
+ continue
+ remaining = await session.execute(
+ select(AssetTransaction.id).where(AssetTransaction.asset_id == asset_id).limit(1)
+ )
+ if remaining.scalar_one_or_none() is None:
+ await session.delete(asset)
+ else:
+ await asset_transaction_service.recompute_and_cache(session, asset)
+
+ await session.delete(log)
+ await session.commit()
+ return len(rows)
diff --git a/backend/tests/test_asset_import_service.py b/backend/tests/test_asset_import_service.py
index ec58a895..af2fa534 100644
--- a/backend/tests/test_asset_import_service.py
+++ b/backend/tests/test_asset_import_service.py
@@ -1,5 +1,6 @@
"""Importing broker orders: reading the file, and applying it to holdings."""
import uuid
+from datetime import date
from decimal import Decimal
import pytest
@@ -373,3 +374,161 @@ async def test_warns_harder_when_the_same_orders_are_already_in_another_wallet(
assert [(w.ticker, w.reason, w.wallet) for w in summary["warnings"]] == [
("AAPL", "orders_already_in_other_wallet", "Corretora B"),
]
+
+
+# ---------------------------------------------------------------------------
+# History and undo
+# ---------------------------------------------------------------------------
+
+
+async def test_import_records_a_history_entry(
+ session: AsyncSession, test_user: User, test_workspace: Workspace, provider
+):
+ from app.models.import_log import ImportLog
+
+ summary = await _import(session, test_workspace, test_user, _csv(
+ "ticker,date,quantity,price",
+ "AAPL,2026-01-15,10,100.00",
+ "AAPL,2026-02-15,5,120.00",
+ ), provider, filename="corretora.csv")
+
+ log = (await session.execute(select(ImportLog))).scalars().one()
+ assert (log.entity, log.filename, log.transaction_count) == ("asset_orders", "corretora.csv", 2)
+ assert log.account_id is None # an order import has no account
+ assert summary["import_log_id"] == str(log.id)
+
+
+async def test_an_import_that_writes_nothing_leaves_no_history(
+ session: AsyncSession, test_user: User, test_workspace: Workspace, provider
+):
+ from app.models.import_log import ImportLog
+
+ content = _csv("ticker,date,quantity,price", "AAPL,2026-01-15,10,100.00")
+ await _import(session, test_workspace, test_user, content, provider)
+ summary = await _import(session, test_workspace, test_user, content, provider) # all duplicates
+
+ assert summary["imported"] == 0
+ assert len((await session.execute(select(ImportLog))).scalars().all()) == 1
+
+
+async def test_undo_removes_the_orders_and_the_holding_it_created(
+ session: AsyncSession, test_user: User, test_workspace: Workspace, provider
+):
+ from app.models.import_log import ImportLog
+
+ await _import(session, test_workspace, test_user, _csv(
+ "ticker,date,quantity,price",
+ "AAPL,2026-01-15,10,100.00",
+ ), provider)
+ log = (await session.execute(select(ImportLog))).scalars().one()
+
+ removed = await asset_import_service.undo_import(session, test_workspace.id, log)
+
+ assert removed == 1
+ assert (await session.execute(select(Asset))).scalars().first() is None
+ assert (await session.execute(select(AssetTransaction))).scalars().first() is None
+ assert (await session.execute(select(ImportLog))).scalars().first() is None
+
+
+async def test_undo_keeps_a_holding_that_has_other_orders_and_recomputes_it(
+ session: AsyncSession, test_user: User, test_workspace: Workspace, provider
+):
+ """A holding the user also fed by hand survives the undo, with the position
+ it would have had if the import had never run."""
+ from app.models.import_log import ImportLog
+
+ await _import(session, test_workspace, test_user, _csv(
+ "ticker,date,quantity,price",
+ "AAPL,2026-01-15,10,100.00",
+ ), provider)
+ asset = await _only_asset(session, test_workspace)
+ session.add(AssetTransaction(
+ asset_id=asset.id, workspace_id=test_workspace.id, kind="buy",
+ quantity=Decimal("4"), price=Decimal("200.00"), fee=Decimal("0"),
+ date=date(2026, 3, 1), source="manual",
+ ))
+ await session.commit()
+
+ log = (await session.execute(select(ImportLog))).scalars().one()
+ await asset_import_service.undo_import(session, test_workspace.id, log)
+
+ survivor = await _only_asset(session, test_workspace)
+ assert survivor.units == Decimal("4") # only the manual buy is left
+ assert survivor.average_price == Decimal("200")
+
+
+async def test_undo_leaves_a_pre_existing_holding_alone(
+ session: AsyncSession, test_user: User, test_workspace: Workspace, provider
+):
+ from app.models.import_log import ImportLog
+
+ existing = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ name="Apple", type="stock", currency="USD", valuation_method="market_price",
+ ticker="AAPL", units=Decimal("0"),
+ )
+ session.add(existing)
+ session.add(AssetTransaction(
+ asset_id=existing.id, workspace_id=test_workspace.id, kind="buy",
+ quantity=Decimal("2"), price=Decimal("50.00"), fee=Decimal("0"),
+ date=date(2025, 1, 1), source="manual",
+ ))
+ await session.commit()
+
+ await _import(session, test_workspace, test_user, _csv(
+ "ticker,date,quantity,price",
+ "AAPL,2026-01-15,10,100.00",
+ ), provider)
+ log = (await session.execute(select(ImportLog))).scalars().one()
+ await asset_import_service.undo_import(session, test_workspace.id, log)
+
+ survivor = await session.get(Asset, existing.id)
+ assert survivor is not None
+ assert survivor.units == Decimal("2")
+
+
+class FlakyBatchProvider(FakeProvider):
+ """The bulk endpoint answers empty even for tickers it knows.
+
+ Not hypothetical: yfinance's bulk download returned a price for AAPL and
+ then nothing for the same ticker seconds later, which used to reject the
+ whole file as unknown tickers.
+ """
+
+ async def get_latest_prices(self, symbols):
+ self.latest_price_calls += 1
+ return {s.upper(): None for s in symbols}
+
+
+async def test_a_bulk_miss_is_confirmed_against_the_quote_endpoint(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ provider = FlakyBatchProvider()
+ summary = await _import(session, test_workspace, test_user, _csv(
+ "ticker,date,quantity,price",
+ "AAPL,2026-01-15,10,100.00",
+ ), provider)
+
+ assert summary["errors"] == []
+ assert summary["imported"] == 1
+ assert provider.quote_calls >= 1 # the bulk miss was double-checked
+
+
+async def test_a_ticker_neither_call_knows_is_still_refused(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ provider = FlakyBatchProvider()
+ summary = await _import(session, test_workspace, test_user, _csv(
+ "ticker,date,quantity,price",
+ "NOSUCH,2026-01-15,10,100.00",
+ ), provider)
+
+ assert [(e.row, e.reason) for e in summary["errors"]] == [(2, "unknown_ticker")]
+ assert summary["imported"] == 0
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 6197daf7..e383aef6 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,6 +1,6 @@
import { lazy, Suspense } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { BrowserRouter, Routes, Route } from 'react-router-dom'
+import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { Toaster } from '@/components/ui/sonner'
import { ThemeProvider } from '@/components/theme-provider'
import { AuthProvider } from '@/contexts/auth-context'
@@ -20,7 +20,6 @@ const TransactionsPage = lazy(() => import('@/pages/transactions'))
const AccountsPage = lazy(() => import('@/pages/accounts'))
const AccountDetailPage = lazy(() => import('@/pages/account-detail'))
const ImportPage = lazy(() => import('@/pages/import'))
-const AssetImportPage = lazy(() => import('@/pages/asset-import'))
const RulesPage = lazy(() => import('@/pages/rules'))
const CategoriesPage = lazy(() => import('@/pages/categories'))
const CollectionsPage = lazy(() => import('@/pages/collections'))
@@ -94,7 +93,8 @@ function App() {
<Route path="/goals" element={<ModuleRoute module="goals"><GoalsPage /></ModuleRoute>} />
<Route path="/recurring" element={<ModuleRoute module="recurring"><RecurringPage /></ModuleRoute>} />
<Route path="/assets" element={<ModuleRoute module="assets"><AssetsPage /></ModuleRoute>} />
- <Route path="/assets/import" element={<ModuleRoute module="assets"><AssetImportPage /></ModuleRoute>} />
+ {/* Kept so links minted before the importers were merged keep working. */}
+ <Route path="/assets/import" element={<Navigate to="/import?tab=investments" replace />} />
<Route path="/reports" element={<ModuleRoute module="reports"><ReportsPage /></ModuleRoute>} />
<Route path="/payees" element={<ModuleRoute module="payees"><PayeesPage /></ModuleRoute>} />
<Route path="/groups" element={<ModuleRoute module="split_groups"><GroupsPage /></ModuleRoute>} />
diff --git a/frontend/src/components/asset-import-panel.tsx b/frontend/src/components/asset-import-panel.tsx
new file mode 100644
index 00000000..ca2de433
--- /dev/null
+++ b/frontend/src/components/asset-import-panel.tsx
@@ -0,0 +1,377 @@
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useNavigate } from 'react-router-dom'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+import { AlertCircle, AlertTriangle, CheckCircle2, Download, FileText, Info, Settings2, Upload, X } from 'lucide-react'
+
+import { assets as assetsApi, assetGroups as assetGroupsApi } from '@/lib/api'
+import type { AssetImportPreview, AssetOrderImport } from '@/types'
+import { ImportHistory } from '@/components/import-history'
+import { Button } from '@/components/ui/button'
+import { Label } from '@/components/ui/label'
+import { useWorkspace } from '@/contexts/workspace-context'
+
+/** The Securo fields a CSV column can be mapped to; `*` marks the required ones. */
+const MAPPABLE_FIELDS = [
+ { key: 'ticker', required: true },
+ { key: 'date', required: true },
+ { key: 'quantity', required: true },
+ { key: 'price', required: true },
+ { key: 'fee', required: false },
+ { key: 'kind', required: false },
+ { key: 'currency', required: false },
+ { key: 'notes', required: false },
+] as const
+
+const SELECT_CLASS =
+ 'border border-border rounded-md px-3 py-2 text-sm bg-card focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]'
+
+/**
+ * The investments half of the import page.
+ *
+ * Deliberately built from the same pieces as the transaction importer: one
+ * dashed drop zone that also carries the template link, then a result card
+ * whose first strip picks the destination — the wallet here, the account
+ * there. Two importers that look different teach the same person two habits.
+ */
+export function AssetImportPanel() {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const queryClient = useQueryClient()
+ const { canWrite } = useWorkspace()
+ const fileInputRef = useRef<HTMLInputElement | null>(null)
+
+ const [file, setFile] = useState<File | null>(null)
+ const [preview, setPreview] = useState<AssetImportPreview | null>(null)
+ const [mapping, setMapping] = useState<Record<string, string>>({})
+ const [groupId, setGroupId] = useState<string>('')
+ const [loading, setLoading] = useState(false)
+ const [importing, setImporting] = useState(false)
+ const [dragOver, setDragOver] = useState(false)
+
+ const { data: wallets } = useQuery({
+ queryKey: ['asset-groups'],
+ queryFn: assetGroupsApi.list,
+ })
+
+ async function runPreview(
+ selected: File,
+ nextMapping: Record<string, string>,
+ nextGroup: string,
+ ) {
+ setLoading(true)
+ try {
+ const result = await assetsApi.previewImport(selected, {
+ column_mapping: nextMapping,
+ group_id: nextGroup || null,
+ })
+ setPreview(result)
+ } catch {
+ toast.error(t('assetImport.previewError'))
+ setPreview(null)
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ function handleFile(selected: File | null) {
+ setFile(selected)
+ setPreview(null)
+ setMapping({})
+ if (selected) runPreview(selected, {}, groupId)
+ }
+
+ function handleReset() {
+ handleFile(null)
+ if (fileInputRef.current) fileInputRef.current.value = ''
+ }
+
+ function handleDrop(e: React.DragEvent) {
+ e.preventDefault()
+ setDragOver(false)
+ const dropped = e.dataTransfer.files?.[0]
+ if (dropped) handleFile(dropped)
+ }
+
+ // Re-preview on every change, so the counts on screen always describe the
+ // import that would actually run.
+ function handleMappingChange(field: string, column: string) {
+ const next = { ...mapping, [field]: column }
+ if (!column) delete next[field]
+ setMapping(next)
+ if (file) runPreview(file, next, groupId)
+ }
+
+ function handleWalletChange(value: string) {
+ setGroupId(value)
+ if (file) runPreview(file, mapping, value)
+ }
+
+ async function handleImport() {
+ if (!preview || preview.orders.length === 0) return
+ setImporting(true)
+ try {
+ const result = await assetsApi.importOrders(
+ preview.orders as AssetOrderImport[],
+ groupId || null,
+ file?.name,
+ )
+ queryClient.invalidateQueries({ queryKey: ['assets'] })
+ queryClient.invalidateQueries({ queryKey: ['asset-groups'] })
+ queryClient.invalidateQueries({ queryKey: ['import-logs'] })
+ toast.success(t('assetImport.imported', { count: result.imported }))
+ navigate('/assets')
+ } catch {
+ toast.error(t('assetImport.importError'))
+ } finally {
+ setImporting(false)
+ }
+ }
+
+ const importable = preview?.orders.length ?? 0
+ const rowErrors = preview?.errors ?? []
+ const walletWarnings = preview?.warnings ?? []
+ const needsMapping = !!preview?.parse_error
+
+ return (
+ <div className="space-y-6">
+ {canWrite && (
+ <div
+ className={`cursor-pointer rounded-xl border-2 border-dashed bg-card transition-all ${
+ dragOver ? 'border-primary bg-primary/5' : 'border-border hover:border-border'
+ }`}
+ onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
+ onDragLeave={() => setDragOver(false)}
+ onDrop={handleDrop}
+ onClick={() => !loading && fileInputRef.current?.click()}
+ >
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".csv,text/csv"
+ className="hidden"
+ onChange={(e) => handleFile(e.target.files?.[0] ?? null)}
+ />
+
+ <div className="flex flex-col items-center justify-center px-6 py-12 text-center">
+ {loading ? (
+ <>
+ <div className="mb-4 flex h-12 w-12 animate-pulse items-center justify-center rounded-full bg-primary/10">
+ <FileText size={22} className="text-primary" />
+ </div>
+ <p className="text-sm font-semibold text-foreground">{t('assetImport.reading')}</p>
+ <p className="mt-1 text-xs text-muted-foreground">{file?.name}</p>
+ </>
+ ) : file && preview && !needsMapping ? (
+ <>
+ <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100">
+ <CheckCircle2 size={22} className="text-emerald-500" />
+ </div>
+ <p className="text-sm font-semibold text-foreground">{file.name}</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t('assetImport.summaryOrders', { count: importable })}
+ </p>
+ <button
+ className="mt-3 flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-rose-500"
+ onClick={(e) => { e.stopPropagation(); handleReset() }}
+ >
+ <X size={12} /> {t('import.removeFile')}
+ </button>
+ </>
+ ) : (
+ <>
+ <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
+ <Upload size={22} className="text-muted-foreground" />
+ </div>
+ <p className="mb-1 text-sm font-semibold text-foreground">{t('import.dragOrClick')}</p>
+ <p className="text-xs text-muted-foreground">{t('assetImport.chooseHint')}</p>
+ <button
+ className="mt-2 flex items-center gap-1 text-xs text-primary transition-colors hover:text-primary/80"
+ onClick={(e) => { e.stopPropagation(); assetsApi.importTemplate() }}
+ >
+ <Download size={12} />
+ {t('assetImport.downloadTemplate')}
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ )}
+
+ {needsMapping && (
+ <div className="overflow-hidden rounded-xl border border-border bg-card shadow-sm">
+ <div className="flex items-center gap-2 border-b border-border bg-muted/30 px-5 py-4">
+ <Settings2 size={14} className="text-muted-foreground" />
+ <p className="text-xs font-medium text-muted-foreground">{t('assetImport.mapPrompt')}</p>
+ </div>
+ <div className="grid gap-3 p-5 sm:grid-cols-2">
+ {MAPPABLE_FIELDS.map(({ key, required }) => (
+ <div key={key} className="grid gap-1">
+ <Label htmlFor={`map-${key}`} className="text-xs">
+ {t(`assetImport.field.${key}`)}{required ? ' *' : ''}
+ </Label>
+ <select
+ id={`map-${key}`}
+ className={SELECT_CLASS}
+ value={mapping[key] ?? ''}
+ onChange={(e) => handleMappingChange(key, e.target.value)}
+ >
+ <option value="">{t('assetImport.ignoreColumn')}</option>
+ {(preview?.csv_columns ?? []).map((col) => (
+ <option key={col} value={col}>{col}</option>
+ ))}
+ </select>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {preview && !needsMapping && (
+ <div className="overflow-hidden rounded-xl border border-border bg-card shadow-sm">
+ <div className="border-b border-border px-4 py-4 sm:px-5">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
+ <span className="font-semibold text-foreground">
+ {t('assetImport.summaryOrders', { count: importable })}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {t('assetImport.summaryHoldings', {
+ created: preview.holdings_created,
+ matched: preview.holdings_matched,
+ })}
+ </span>
+ {preview.skipped > 0 && (
+ <span className="text-xs text-muted-foreground">
+ {t('assetImport.summarySkipped', { count: preview.skipped })}
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Destination strip, in the place the account picker holds on the
+ transactions side. */}
+ <div className="border-b border-border bg-muted/50 px-4 py-4 sm:px-5">
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4">
+ <Label htmlFor="asset-import-wallet" className="shrink-0 whitespace-nowrap text-sm text-muted-foreground">
+ {t('assetImport.importTo')}
+ </Label>
+ <select
+ id="asset-import-wallet"
+ className={`flex-1 ${SELECT_CLASS}`}
+ value={groupId}
+ onChange={(e) => handleWalletChange(e.target.value)}
+ >
+ <option value="">{t('assetImport.noWallet')}</option>
+ {(wallets ?? []).map((w) => (
+ <option key={w.id} value={w.id}>{w.name}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {walletWarnings.length > 0 && (
+ <div className="border-b border-border bg-blue-50 px-4 py-3 dark:bg-blue-950 sm:px-5">
+ <p className="mb-2 flex items-center gap-2 text-sm font-medium text-blue-700 dark:text-blue-300">
+ <Info size={14} />
+ {t('assetImport.walletWarningTitle')}
+ </p>
+ <ul className="space-y-1 text-xs text-blue-600 dark:text-blue-300/80">
+ {walletWarnings.map((w) => (
+ <li key={`${w.ticker}-${w.reason}`}>
+ {t(`assetImport.warning.${w.reason}`, { ticker: w.ticker, wallet: w.wallet ?? '—' })}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {rowErrors.length > 0 && (
+ <div className="border-b border-border bg-amber-500/10 px-4 py-3 sm:px-5">
+ <p className="mb-2 flex items-center gap-2 text-sm font-medium text-amber-700 dark:text-amber-400">
+ <AlertTriangle size={14} />
+ {t('assetImport.rowsSkipped', { count: rowErrors.length })}
+ </p>
+ <ul className="space-y-1 text-xs text-muted-foreground">
+ {rowErrors.slice(0, 8).map((err) => (
+ <li key={`${err.row}-${err.reason}`}>
+ {t('assetImport.rowError', {
+ row: err.row,
+ ticker: err.ticker ?? '—',
+ reason: t(`assetImport.reason.${err.reason}`, err.reason),
+ })}
+ {err.detail ? ` (${err.detail})` : ''}
+ </li>
+ ))}
+ {rowErrors.length > 8 && (
+ <li>{t('assetImport.moreErrors', { count: rowErrors.length - 8 })}</li>
+ )}
+ </ul>
+ </div>
+ )}
+
+ {importable > 0 && (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead className="bg-muted/40 text-xs uppercase text-muted-foreground">
+ <tr>
+ <th className="px-3 py-2 text-left sm:px-5">{t('assetImport.field.ticker')}</th>
+ <th className="px-3 py-2 text-left">{t('assetImport.field.date')}</th>
+ <th className="px-3 py-2 text-left">{t('assetImport.field.kind')}</th>
+ <th className="px-3 py-2 text-right">{t('assetImport.field.quantity')}</th>
+ <th className="px-3 py-2 text-right">{t('assetImport.field.price')}</th>
+ <th className="px-3 py-2 text-right sm:px-5">{t('assetImport.field.fee')}</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-border">
+ {preview.orders.slice(0, 50).map((order) => (
+ <tr key={order.row}>
+ <td className="px-3 py-1.5 font-medium sm:px-5">{order.ticker}</td>
+ <td className="px-3 py-1.5">{order.date}</td>
+ <td className="px-3 py-1.5">
+ <span className={order.kind === 'sell' ? 'text-rose-500' : 'text-emerald-500'}>
+ {t(`assetImport.kind.${order.kind}`)}
+ </span>
+ </td>
+ <td className="px-3 py-1.5 text-right tabular-nums">{order.quantity}</td>
+ <td className="px-3 py-1.5 text-right tabular-nums">{order.price}</td>
+ <td className="px-3 py-1.5 text-right tabular-nums sm:px-5">{order.fee}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {preview.orders.length > 50 && (
+ <p className="border-t border-border px-4 py-2 text-xs text-muted-foreground sm:px-5">
+ {t('assetImport.moreRows', { count: preview.orders.length - 50 })}
+ </p>
+ )}
+ </div>
+ )}
+
+ <div className="flex items-center justify-between gap-3 border-t border-border px-4 py-4 sm:px-5">
+ {importable === 0 ? (
+ <span className="flex items-center gap-1.5 text-xs text-amber-600">
+ <AlertCircle size={12} />
+ {t('assetImport.nothingToImport')}
+ </span>
+ ) : (
+ <span />
+ )}
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={handleReset}>
+ <X size={14} className="mr-1" />
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={handleImport} disabled={importing || importable === 0} className="gap-2">
+ <Upload size={14} />
+ {importing ? t('assetImport.importing') : t('assetImport.confirm', { count: importable })}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <ImportHistory entity="asset_orders" />
+ </div>
+ )
+}
diff --git a/frontend/src/components/import-history.tsx b/frontend/src/components/import-history.tsx
new file mode 100644
index 00000000..9fc92a89
--- /dev/null
+++ b/frontend/src/components/import-history.tsx
@@ -0,0 +1,175 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+import { History, Trash2 } from 'lucide-react'
+
+import { importLogs as importLogsApi } from '@/lib/api'
+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
+import { formatCurrency } from '@/lib/format'
+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
+import { useAuth } from '@/contexts/auth-context'
+import { useWorkspace } from '@/contexts/workspace-context'
+import type { ImportLog } from '@/types'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+
+interface ImportHistoryProps {
+ /** Which importer's runs to list; the two never mix in one table. */
+ entity: 'transactions' | 'asset_orders'
+}
+
+/**
+ * Past imports, newest first, each removable.
+ *
+ * Deleting an entry is the undo: the server takes the rows back out, and for
+ * orders it also recomputes the affected positions. The two entities share
+ * this table but not its columns — an order import has no account and no
+ * credit/debit totals, so those columns only appear for statements.
+ */
+export function ImportHistory({ entity }: ImportHistoryProps) {
+ const { t } = useTranslation()
+ const locale = useDisplayLocale()
+ const dateLocale = useDateLocale()
+ const queryClient = useQueryClient()
+ const { user } = useAuth()
+ const { canWrite } = useWorkspace()
+ const userCurrency = user?.preferences?.currency_display ?? 'USD'
+ const [deleteTarget, setDeleteTarget] = useState<ImportLog | null>(null)
+
+ const { data: logs = [] } = useQuery({
+ queryKey: ['import-logs'],
+ queryFn: importLogsApi.list,
+ })
+
+ const deleteMutation = useMutation({
+ mutationFn: (id: string) => importLogsApi.delete(id),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['import-logs'] })
+ queryClient.invalidateQueries({ queryKey: ['assets'] })
+ invalidateFinancialQueries(queryClient)
+ setDeleteTarget(null)
+ toast.success(t('import.undone'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
+ const rows = logs.filter((log) => (log.entity ?? 'transactions') === entity)
+ const isStatement = entity === 'transactions'
+
+ return (
+ <div className="mt-8">
+ <div className="mb-4 flex items-center gap-2">
+ <History className="h-5 w-5 text-muted-foreground" />
+ <h2 className="text-lg font-semibold text-foreground">{t('import.history')}</h2>
+ </div>
+
+ {rows.length === 0 ? (
+ <div className="rounded-xl border border-border bg-card p-8 text-center text-muted-foreground">
+ {t('import.noHistory')}
+ </div>
+ ) : (
+ <div className="overflow-hidden rounded-xl border border-border bg-card shadow-sm">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-border">
+ <th className="px-3 py-3 text-left font-medium text-muted-foreground sm:px-4">{t('import.historyDate')}</th>
+ <th className="px-3 py-3 text-left font-medium text-muted-foreground sm:px-4">{t('import.historyFile')}</th>
+ <th className="hidden px-4 py-3 text-left font-medium text-muted-foreground lg:table-cell">{t('import.historyFormat')}</th>
+ {isStatement && (
+ <th className="hidden px-4 py-3 text-left font-medium text-muted-foreground md:table-cell">{t('import.historyAccount')}</th>
+ )}
+ <th className="px-3 py-3 text-right font-medium text-muted-foreground sm:px-4">{t('import.historyCount')}</th>
+ {isStatement && (
+ <>
+ <th className="hidden px-4 py-3 text-right font-medium text-muted-foreground sm:table-cell">{t('import.historyCredit')}</th>
+ <th className="hidden px-4 py-3 text-right font-medium text-muted-foreground sm:table-cell">{t('import.historyDebit')}</th>
+ </>
+ )}
+ <th className="px-3 py-3 sm:px-4" aria-label={t('common.more')}></th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-border">
+ {rows.map((log) => (
+ <tr key={log.id} className="hover:bg-muted">
+ <td className="px-3 py-3 text-xs whitespace-nowrap text-muted-foreground sm:px-4 sm:text-sm">
+ {new Date(log.created_at).toLocaleString(dateLocale, { dateStyle: 'short', timeStyle: 'short' })}
+ </td>
+ <td className="max-w-[120px] truncate px-3 py-3 font-mono text-xs text-foreground sm:max-w-none sm:px-4">
+ {log.filename || '—'}
+ </td>
+ <td className="hidden px-4 py-3 lg:table-cell">
+ <span className="rounded bg-muted px-2 py-0.5 font-mono text-xs uppercase text-muted-foreground">
+ {log.format || '—'}
+ </span>
+ </td>
+ {isStatement && (
+ <td className="hidden px-4 py-3 text-muted-foreground md:table-cell">{log.account_name || '—'}</td>
+ )}
+ <td className="px-3 py-3 text-right text-foreground sm:px-4">{log.transaction_count}</td>
+ {isStatement && (
+ <>
+ <td className="hidden px-4 py-3 text-right font-medium text-emerald-600 sm:table-cell">
+ {formatCurrency(log.total_credit, userCurrency, locale)}
+ </td>
+ <td className="hidden px-4 py-3 text-right font-medium text-rose-600 sm:table-cell">
+ {formatCurrency(log.total_debit, userCurrency, locale)}
+ </td>
+ </>
+ )}
+ <td className="px-3 py-3 text-right sm:px-4">
+ {canWrite && (
+ <button
+ onClick={() => setDeleteTarget(log)}
+ className="text-muted-foreground transition-colors hover:text-rose-500"
+ aria-label={t('import.undoImport')}
+ title={t('import.undoImport')}
+ >
+ <Trash2 className="h-4 w-4" />
+ </button>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ <Dialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('import.undoImport')}</DialogTitle>
+ <DialogDescription>
+ {t(isStatement ? 'import.undoDescription' : 'import.undoOrdersDescription', {
+ count: deleteTarget?.transaction_count,
+ filename: deleteTarget?.filename || '—',
+ })}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <button
+ onClick={() => setDeleteTarget(null)}
+ className="px-4 py-2 text-sm text-muted-foreground hover:text-foreground"
+ >
+ {t('common.cancel')}
+ </button>
+ <button
+ onClick={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)}
+ disabled={deleteMutation.isPending}
+ className="rounded-lg bg-rose-500 px-4 py-2 text-sm text-white hover:bg-rose-600 disabled:opacity-50"
+ >
+ {deleteMutation.isPending ? t('import.deleting') : t('import.deleteAll')}
+ </button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 772b7dd9..fb515663 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1160,8 +1160,9 @@ export const assets = {
importOrders: async (
orders: AssetOrderImport[],
group_id?: string | null,
+ filename?: string,
): Promise<AssetImportResult> => {
- const { data } = await api.post('/assets/import', { orders, group_id: group_id || null })
+ const { data } = await api.post('/assets/import', { orders, group_id: group_id || null, filename })
return data
},
importTemplate: async (): Promise<void> => {
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index f1f7e3bb..2b08fbff 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -1003,6 +1003,8 @@
"selectAccountWarning": "Wähle ein Konto aus",
"showingPreview": "Vorschau von {{shown}} von {{total}} Transaktionen",
"importButton": "{{count}} Transaktionen importieren",
+ "tabTransactions": "Transaktionen",
+ "tabInvestments": "Wertpapiere",
"history": "Import-Verlauf",
"noHistory": "Noch keine Importe",
"historyDate": "Datum",
@@ -1013,6 +1015,8 @@
"historyCredit": "Haben",
"historyDebit": "Soll",
"undoImport": "Import rückgängig machen?",
+ "undoOrdersDescription": "Damit werden die {{count}} aus {{filename}} importierten Orders gelöscht und die betroffenen Positionen neu berechnet. Von diesem Import angelegte Werte werden mit entfernt.",
+ "undone": "Import rückgängig gemacht",
"undoDescription": "Dadurch werden {{count}} importierte Transaktionen aus {{filename}} gelöscht. Diese Aktion kann nicht rückgängig gemacht werden.",
"deleting": "Wird gelöscht...",
"deleteAll": "Alle löschen",
@@ -1044,6 +1048,8 @@
"choose": "CSV-Datei auswählen",
"chooseHint": "Ticker, Datum, Stückzahl und Preis sind Pflicht. Eine negative Stückzahl gilt als Verkauf.",
"downloadTemplate": "Vorlage herunterladen",
+ "importTo": "Importieren nach",
+ "nothingToImport": "Aus dieser Datei gibt es nichts zu importieren",
"wallet": "Depot",
"noWallet": "Kein Depot",
"reading": "Datei wird gelesen…",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index ca2dd761..279ad7dd 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -1003,6 +1003,8 @@
"selectAccountWarning": "Select an account",
"showingPreview": "Showing {{shown}} of {{total}} transactions",
"importButton": "Import {{count}} transactions",
+ "tabTransactions": "Transactions",
+ "tabInvestments": "Investments",
"history": "Import History",
"noHistory": "No imports yet",
"historyDate": "Date",
@@ -1013,6 +1015,8 @@
"historyCredit": "Credit",
"historyDebit": "Debit",
"undoImport": "Undo import?",
+ "undoOrdersDescription": "This will delete the {{count}} orders imported from {{filename}} and recalculate the positions they touched. Holdings this import created are removed with them.",
+ "undone": "Import undone",
"undoDescription": "This will delete {{count}} imported transactions from {{filename}}. This action cannot be undone.",
"deleting": "Deleting...",
"deleteAll": "Delete all",
@@ -1044,6 +1048,8 @@
"choose": "Choose a CSV file",
"chooseHint": "Ticker, date, quantity and price are required. A negative quantity is read as a sale.",
"downloadTemplate": "Download template",
+ "importTo": "Import into",
+ "nothingToImport": "Nothing left to import from this file",
"wallet": "Wallet",
"noWallet": "No wallet",
"reading": "Reading the file…",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 1543071d..162391f8 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -1003,6 +1003,8 @@
"selectAccountWarning": "Selecciona una cuenta",
"showingPreview": "Mostrando {{shown}} de {{total}} transacciones",
"importButton": "Importar {{count}} transacciones",
+ "tabTransactions": "Transacciones",
+ "tabInvestments": "Inversiones",
"history": "Historial de importaciones",
"noHistory": "Aún no hay importaciones",
"historyDate": "Fecha",
@@ -1013,6 +1015,8 @@
"historyCredit": "Crédito",
"historyDebit": "Débito",
"undoImport": "¿Deshacer importación?",
+ "undoOrdersDescription": "Esto eliminará las {{count}} órdenes importadas de {{filename}} y recalculará las posiciones afectadas. Los activos creados por esta importación se eliminan con ellas.",
+ "undone": "Importación deshecha",
"undoDescription": "Esto eliminará {{count}} transacciones importadas de {{filename}}. Esta acción no se puede deshacer.",
"deleting": "Eliminando...",
"deleteAll": "Eliminar todo",
@@ -1044,6 +1048,8 @@
"choose": "Elegir un archivo CSV",
"chooseHint": "Ticker, fecha, cantidad y precio son obligatorios. Una cantidad negativa se lee como venta.",
"downloadTemplate": "Descargar plantilla",
+ "importTo": "Importar a",
+ "nothingToImport": "No queda nada para importar de este archivo",
"wallet": "Cartera",
"noWallet": "Sin cartera",
"reading": "Leyendo el archivo…",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index e9679d75..5de8285d 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -1003,6 +1003,8 @@
"selectAccountWarning": "Sélectionnez un compte",
"showingPreview": "Affichage de {{shown}} sur {{total}} transactions",
"importButton": "Importer {{count}} transactions",
+ "tabTransactions": "Transactions",
+ "tabInvestments": "Investissements",
"history": "Historique des imports",
"noHistory": "Aucun import pour l'instant",
"historyDate": "Date",
@@ -1013,6 +1015,8 @@
"historyCredit": "Crédit",
"historyDebit": "Débit",
"undoImport": "Annuler l'import ?",
+ "undoOrdersDescription": "Cela supprimera les {{count}} ordres importés de {{filename}} et recalculera les positions concernées. Les actifs créés par cet import sont supprimés avec eux.",
+ "undone": "Import annulé",
"undoDescription": "Cela supprimera {{count}} transactions importées depuis {{filename}}. Cette action est irréversible.",
"deleting": "Suppression...",
"deleteAll": "Tout supprimer",
@@ -1044,6 +1048,8 @@
"choose": "Choisir un fichier CSV",
"chooseHint": "Ticker, date, quantité et prix sont obligatoires. Une quantité négative est lue comme une vente.",
"downloadTemplate": "Télécharger le modèle",
+ "importTo": "Importer dans",
+ "nothingToImport": "Rien à importer dans ce fichier",
"wallet": "Portefeuille",
"noWallet": "Aucun portefeuille",
"reading": "Lecture du fichier…",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index f0df3536..911b333f 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -1003,6 +1003,8 @@
"selectAccountWarning": "Seleziona un conto",
"showingPreview": "Visualizzazione di {{shown}} su {{total}} transazioni",
"importButton": "Importa {{count}} transazioni",
+ "tabTransactions": "Transazioni",
+ "tabInvestments": "Investimenti",
"history": "Cronologia importazioni",
"noHistory": "Ancora nessuna importazione",
"historyDate": "Data",
@@ -1013,6 +1015,8 @@
"historyCredit": "Accredito",
"historyDebit": "Addebito",
"undoImport": "Annullare l'importazione?",
+ "undoOrdersDescription": "Verranno eliminati i {{count}} ordini importati da {{filename}} e ricalcolate le posizioni interessate. I titoli creati da questa importazione vengono rimossi con essi.",
+ "undone": "Importazione annullata",
"undoDescription": "Questo eliminerà {{count}} transazioni importate da {{filename}}. Questa azione non può essere annullata.",
"deleting": "Eliminazione...",
"deleteAll": "Elimina tutto",
@@ -1044,6 +1048,8 @@
"choose": "Scegli un file CSV",
"chooseHint": "Ticker, data, quantità e prezzo sono obbligatori. Una quantità negativa vale come vendita.",
"downloadTemplate": "Scarica il modello",
+ "importTo": "Importa in",
+ "nothingToImport": "Niente da importare da questo file",
"wallet": "Portafoglio",
"noWallet": "Nessun portafoglio",
"reading": "Lettura del file…",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index e8f11a16..11787002 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -1072,6 +1072,8 @@
"importButton_few": "Importuj {{count}} transakcje",
"importButton_many": "Importuj {{count}} transakcji",
"importButton_other": "Importuj {{count}} transakcji",
+ "tabTransactions": "Transakcje",
+ "tabInvestments": "Inwestycje",
"history": "Historia importów",
"noHistory": "Brak importów",
"historyDate": "Data",
@@ -1081,6 +1083,11 @@
"historyCount": "Liczba",
"historyCredit": "Uznanie",
"historyDebit": "Obciążenie",
+ "undoOrdersDescription_one": "Usunie to {{count}} zlecenie zaimportowane z {{filename}} i przeliczy zmienione pozycje. Walory utworzone przez ten import zostaną usunięte razem z nim.",
+ "undoOrdersDescription_few": "Usunie to {{count}} zlecenia zaimportowane z {{filename}} i przeliczy zmienione pozycje. Walory utworzone przez ten import zostaną usunięte razem z nimi.",
+ "undoOrdersDescription_many": "Usunie to {{count}} zleceń zaimportowanych z {{filename}} i przeliczy zmienione pozycje. Walory utworzone przez ten import zostaną usunięte razem z nimi.",
+ "undoOrdersDescription_other": "Usunie to {{count}} zleceń zaimportowanych z {{filename}} i przeliczy zmienione pozycje. Walory utworzone przez ten import zostaną usunięte razem z nimi.",
+ "undone": "Import cofnięty",
"undoImport": "Cofnąć import?",
"undoDescription_one": "Spowoduje to usunięcie {{count}} zaimportowanej transakcji z pliku {{filename}}. Tej operacji nie można cofnąć.",
"undoDescription_few": "Spowoduje to usunięcie {{count}} zaimportowanych transakcji z pliku {{filename}}. Tej operacji nie można cofnąć.",
@@ -1119,6 +1126,8 @@
"choose": "Wybierz plik CSV",
"chooseHint": "Ticker, data, ilość i cena są wymagane. Ujemna ilość oznacza sprzedaż.",
"downloadTemplate": "Pobierz szablon",
+ "importTo": "Importuj do",
+ "nothingToImport": "Nie ma czego zaimportować z tego pliku",
"wallet": "Portfel",
"noWallet": "Bez portfela",
"reading": "Wczytywanie pliku…",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index fd8e177e..2695b976 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -1003,6 +1003,8 @@
"selectAccountWarning": "Selecione uma conta",
"showingPreview": "Mostrando {{shown}} de {{total}} transações",
"importButton": "Importar {{count}} transações",
+ "tabTransactions": "Transações",
+ "tabInvestments": "Investimentos",
"history": "Histórico de Importações",
"noHistory": "Nenhuma importação ainda",
"historyDate": "Data",
@@ -1013,6 +1015,8 @@
"historyCredit": "Crédito",
"historyDebit": "Débito",
"undoImport": "Desfazer importação?",
+ "undoOrdersDescription": "Isso vai apagar as {{count}} ordens importadas de {{filename}} e recalcular as posições afetadas. Os ativos criados por essa importação são removidos junto.",
+ "undone": "Importação desfeita",
"undoDescription": "Isso vai excluir {{count}} transações importadas de {{filename}}. Esta ação não pode ser desfeita.",
"deleting": "Excluindo...",
"deleteAll": "Excluir tudo",
@@ -1044,6 +1048,8 @@
"choose": "Escolher um arquivo CSV",
"chooseHint": "Ativo, data, quantidade e preço são obrigatórios. Quantidade negativa é lida como venda.",
"downloadTemplate": "Baixar modelo",
+ "importTo": "Importar para",
+ "nothingToImport": "Nada para importar deste arquivo",
"wallet": "Carteira",
"noWallet": "Sem carteira",
"reading": "Lendo o arquivo…",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index eebd2df6..17134dd1 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -1006,6 +1006,8 @@
"selectAccountWarning": "Seleciona uma conta",
"showingPreview": "Mostrando {{shown}} de {{total}} transações",
"importButton": "Importar {{count}} transações",
+ "tabTransactions": "Transações",
+ "tabInvestments": "Investimentos",
"history": "Histórico de Importações",
"noHistory": "Nenhuma importação ainda",
"historyDate": "Data",
@@ -1016,6 +1018,8 @@
"historyCredit": "Crédito",
"historyDebit": "Débito",
"undoImport": "Desfazer importação?",
+ "undoOrdersDescription": "Isto vai apagar as {{count}} ordens importadas de {{filename}} e recalcular as posições afetadas. Os ativos criados por esta importação são removidos com elas.",
+ "undone": "Importação desfeita",
"undoDescription": "Isto vai eliminar {{count}} transações importadas de {{filename}}. Esta ação não pode ser desfeita.",
"deleting": "A eliminar...",
"deleteAll": "Eliminar tudo",
@@ -1044,6 +1048,8 @@
"choose": "Escolher um ficheiro CSV",
"chooseHint": "Ativo, data, quantidade e preço são obrigatórios. Quantidade negativa é lida como venda.",
"downloadTemplate": "Descarregar modelo",
+ "importTo": "Importar para",
+ "nothingToImport": "Nada para importar deste ficheiro",
"wallet": "Carteira",
"noWallet": "Sem carteira",
"reading": "A ler o ficheiro…",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 94722b20..466c74c9 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -1009,6 +1009,8 @@
"selectAccountWarning": "Выберите счёт",
"showingPreview": "Показано {{shown}} из {{total}} транзакций",
"importButton": "Импортировать {{count}} транзакций",
+ "tabTransactions": "Транзакции",
+ "tabInvestments": "Инвестиции",
"history": "История импорта",
"noHistory": "Импортов пока нет",
"historyDate": "Дата",
@@ -1018,6 +1020,8 @@
"historyCount": "Кол-во",
"historyCredit": "Кредит",
"historyDebit": "Дебет",
+ "undoOrdersDescription": "Будут удалены {{count}} заявок, импортированных из {{filename}}, и пересчитаны затронутые позиции. Бумаги, созданные этим импортом, удаляются вместе с ними.",
+ "undone": "Импорт отменён",
"undoImport": "Отменить импорт?",
"undoDescription": "Это удалит {{count}} импортированных транзакций из {{filename}}. Это действие нельзя отменить.",
"deleting": "Удаление...",
@@ -1050,6 +1054,8 @@
"choose": "Выбрать файл CSV",
"chooseHint": "Тикер, дата, количество и цена обязательны. Отрицательное количество читается как продажа.",
"downloadTemplate": "Скачать шаблон",
+ "importTo": "Импортировать в",
+ "nothingToImport": "Из этого файла нечего импортировать",
"wallet": "Портфель",
"noWallet": "Без портфеля",
"reading": "Чтение файла…",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 0ede600b..0395db77 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -1009,6 +1009,8 @@
"selectAccountWarning": "Оберіть рахунок",
"showingPreview": "Показано {{shown}} із {{total}} транзакцій",
"importButton": "Імпортувати {{count}} транзакцій",
+ "tabTransactions": "Транзакції",
+ "tabInvestments": "Інвестиції",
"history": "Історія імпорту",
"noHistory": "Імпортів поки немає",
"historyDate": "Дата",
@@ -1018,6 +1020,8 @@
"historyCount": "К-сть",
"historyCredit": "Кредит",
"historyDebit": "Дебет",
+ "undoOrdersDescription": "Буде видалено {{count}} заявок, імпортованих із {{filename}}, і перераховано зачеплені позиції. Папери, створені цим імпортом, видаляються разом із ними.",
+ "undone": "Імпорт скасовано",
"undoImport": "Скасувати імпорт?",
"undoDescription": "Це видалить {{count}} імпортованих транзакцій із {{filename}}. Цю дію не можна скасувати.",
"deleting": "Видалення...",
@@ -1050,6 +1054,8 @@
"choose": "Обрати файл CSV",
"chooseHint": "Тикер, дата, кількість і ціна обов'язкові. Від'ємна кількість читається як продаж.",
"downloadTemplate": "Завантажити шаблон",
+ "importTo": "Імпортувати до",
+ "nothingToImport": "З цього файлу нічого імпортувати",
"wallet": "Портфель",
"noWallet": "Без портфеля",
"reading": "Читання файлу…",
diff --git a/frontend/src/pages/asset-import.tsx b/frontend/src/pages/asset-import.tsx
deleted file mode 100644
index 8558efa3..00000000
--- a/frontend/src/pages/asset-import.tsx
+++ /dev/null
@@ -1,301 +0,0 @@
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useNavigate } from 'react-router-dom'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { toast } from 'sonner'
-import { AlertTriangle, Download, FileUp, Info, Upload, X } from 'lucide-react'
-
-import { assets as assetsApi, assetGroups as assetGroupsApi } from '@/lib/api'
-import type { AssetImportPreview, AssetOrderImport } from '@/types'
-import { PageHeader } from '@/components/page-header'
-import { Button } from '@/components/ui/button'
-import { Label } from '@/components/ui/label'
-
-/** The Securo fields a CSV column can be mapped to; `*` marks the required ones. */
-const MAPPABLE_FIELDS = [
- { key: 'ticker', required: true },
- { key: 'date', required: true },
- { key: 'quantity', required: true },
- { key: 'price', required: true },
- { key: 'fee', required: false },
- { key: 'kind', required: false },
- { key: 'currency', required: false },
- { key: 'notes', required: false },
-] as const
-
-/** Matches the card the other configuration pages use (see rules.tsx). */
-function SectionCard({ children }: { children: React.ReactNode }) {
- return (
- <div className="bg-card border border-border rounded-xl p-4 sm:p-6">{children}</div>
- )
-}
-
-const SELECT_CLASS =
- 'border border-border rounded-lg px-2 py-1.5 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'
-
-export default function AssetImportPage() {
- const { t } = useTranslation()
- const navigate = useNavigate()
- const queryClient = useQueryClient()
-
- const [file, setFile] = useState<File | null>(null)
- const [preview, setPreview] = useState<AssetImportPreview | null>(null)
- const [mapping, setMapping] = useState<Record<string, string>>({})
- const [groupId, setGroupId] = useState<string>('')
- const [loading, setLoading] = useState(false)
- const [importing, setImporting] = useState(false)
-
- const { data: wallets } = useQuery({
- queryKey: ['asset-groups'],
- queryFn: assetGroupsApi.list,
- })
-
- async function runPreview(
- selected: File,
- nextMapping: Record<string, string>,
- nextGroup: string,
- ) {
- setLoading(true)
- try {
- const result = await assetsApi.previewImport(selected, {
- column_mapping: nextMapping,
- group_id: nextGroup || null,
- })
- setPreview(result)
- } catch {
- toast.error(t('assetImport.previewError'))
- setPreview(null)
- } finally {
- setLoading(false)
- }
- }
-
- function handleFile(selected: File | null) {
- setFile(selected)
- setPreview(null)
- setMapping({})
- if (selected) runPreview(selected, {}, groupId)
- }
-
- // Re-preview on every change, so the counts on screen always describe the
- // import that would actually run.
- function handleMappingChange(field: string, column: string) {
- const next = { ...mapping, [field]: column }
- if (!column) delete next[field]
- setMapping(next)
- if (file) runPreview(file, next, groupId)
- }
-
- function handleWalletChange(value: string) {
- setGroupId(value)
- if (file) runPreview(file, mapping, value)
- }
-
- async function handleImport() {
- if (!preview || preview.orders.length === 0) return
- setImporting(true)
- try {
- const result = await assetsApi.importOrders(preview.orders as AssetOrderImport[], groupId || null)
- queryClient.invalidateQueries({ queryKey: ['assets'] })
- queryClient.invalidateQueries({ queryKey: ['asset-groups'] })
- toast.success(t('assetImport.imported', { count: result.imported }))
- navigate('/assets')
- } catch {
- toast.error(t('assetImport.importError'))
- } finally {
- setImporting(false)
- }
- }
-
- const importable = preview?.orders.length ?? 0
- const rowErrors = preview?.errors ?? []
- const walletWarnings = preview?.warnings ?? []
- const needsMapping = !!preview?.parse_error
-
- return (
- <div>
- <PageHeader
- section={t('assets.title')}
- title={t('assetImport.title')}
- action={
- <Button variant="outline" onClick={() => assetsApi.importTemplate()}>
- <Download size={14} className="mr-1" />
- {t('assetImport.downloadTemplate')}
- </Button>
- }
- />
-
- <SectionCard>
- <div className="mb-4 grid gap-2 sm:max-w-xs">
- <Label htmlFor="asset-import-wallet">{t('assetImport.wallet')}</Label>
- <select
- id="asset-import-wallet"
- className={SELECT_CLASS}
- value={groupId}
- onChange={(e) => handleWalletChange(e.target.value)}
- >
- <option value="">{t('assetImport.noWallet')}</option>
- {(wallets ?? []).map((w) => (
- <option key={w.id} value={w.id}>{w.name}</option>
- ))}
- </select>
- </div>
-
- <label className="flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border px-6 py-10 text-center transition-colors hover:border-primary/50">
- <FileUp size={22} className="text-muted-foreground" />
- <span className="text-sm font-medium">
- {file ? file.name : t('assetImport.choose')}
- </span>
- <span className="text-xs text-muted-foreground">{t('assetImport.chooseHint')}</span>
- <input
- type="file"
- accept=".csv,text/csv"
- className="hidden"
- onChange={(e) => handleFile(e.target.files?.[0] ?? null)}
- />
- </label>
-
- {loading && (
- <p className="mt-4 text-sm text-muted-foreground">{t('assetImport.reading')}</p>
- )}
-
- {needsMapping && (
- <div className="mt-6">
- <p className="mb-3 text-sm text-amber-500">{t('assetImport.mapPrompt')}</p>
- <div className="grid gap-3 sm:grid-cols-2">
- {MAPPABLE_FIELDS.map(({ key, required }) => (
- <div key={key} className="grid gap-1">
- <Label htmlFor={`map-${key}`} className="text-xs">
- {t(`assetImport.field.${key}`)}{required ? ' *' : ''}
- </Label>
- <select
- id={`map-${key}`}
- className={SELECT_CLASS}
- value={mapping[key] ?? ''}
- onChange={(e) => handleMappingChange(key, e.target.value)}
- >
- <option value="">{t('assetImport.ignoreColumn')}</option>
- {(preview?.csv_columns ?? []).map((col) => (
- <option key={col} value={col}>{col}</option>
- ))}
- </select>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {preview && !needsMapping && (
- <div className="mt-6 space-y-4">
- <div className="flex flex-wrap gap-4 text-sm">
- <span>{t('assetImport.summaryOrders', { count: importable })}</span>
- <span className="text-muted-foreground">
- {t('assetImport.summaryHoldings', {
- created: preview.holdings_created,
- matched: preview.holdings_matched,
- })}
- </span>
- {preview.skipped > 0 && (
- <span className="text-muted-foreground">
- {t('assetImport.summarySkipped', { count: preview.skipped })}
- </span>
- )}
- </div>
-
- {walletWarnings.length > 0 && (
- <div className="rounded-md border border-blue-200 bg-blue-50 p-3 dark:border-blue-800 dark:bg-blue-950">
- <p className="mb-2 flex items-center gap-2 text-sm font-medium text-blue-700 dark:text-blue-300">
- <Info size={14} />
- {t('assetImport.walletWarningTitle')}
- </p>
- <ul className="space-y-1 text-xs text-blue-600 dark:text-blue-300/80">
- {walletWarnings.map((w) => (
- <li key={`${w.ticker}-${w.reason}`}>
- {t(`assetImport.warning.${w.reason}`, {
- ticker: w.ticker,
- wallet: w.wallet ?? '—',
- })}
- </li>
- ))}
- </ul>
- </div>
- )}
-
- {rowErrors.length > 0 && (
- <div className="rounded-md border border-amber-500/30 bg-amber-500/10 p-3">
- <p className="mb-2 flex items-center gap-2 text-sm font-medium text-amber-700 dark:text-amber-400">
- <AlertTriangle size={14} />
- {t('assetImport.rowsSkipped', { count: rowErrors.length })}
- </p>
- <ul className="space-y-1 text-xs text-muted-foreground">
- {rowErrors.slice(0, 8).map((err) => (
- <li key={`${err.row}-${err.reason}`}>
- {t('assetImport.rowError', {
- row: err.row,
- ticker: err.ticker ?? '—',
- reason: t(`assetImport.reason.${err.reason}`, err.reason),
- })}
- {err.detail ? ` (${err.detail})` : ''}
- </li>
- ))}
- {rowErrors.length > 8 && (
- <li>{t('assetImport.moreErrors', { count: rowErrors.length - 8 })}</li>
- )}
- </ul>
- </div>
- )}
-
- {importable > 0 && (
- <div className="overflow-x-auto rounded-lg border border-border">
- <table className="w-full text-sm">
- <thead className="bg-muted/40 text-xs uppercase text-muted-foreground">
- <tr>
- <th className="px-3 py-2 text-left">{t('assetImport.field.ticker')}</th>
- <th className="px-3 py-2 text-left">{t('assetImport.field.date')}</th>
- <th className="px-3 py-2 text-left">{t('assetImport.field.kind')}</th>
- <th className="px-3 py-2 text-right">{t('assetImport.field.quantity')}</th>
- <th className="px-3 py-2 text-right">{t('assetImport.field.price')}</th>
- <th className="px-3 py-2 text-right">{t('assetImport.field.fee')}</th>
- </tr>
- </thead>
- <tbody>
- {preview.orders.slice(0, 50).map((order) => (
- <tr key={order.row} className="border-t border-border/60">
- <td className="px-3 py-1.5 font-medium">{order.ticker}</td>
- <td className="px-3 py-1.5">{order.date}</td>
- <td className="px-3 py-1.5">
- <span className={order.kind === 'sell' ? 'text-rose-500' : 'text-emerald-500'}>
- {t(`assetImport.kind.${order.kind}`)}
- </span>
- </td>
- <td className="px-3 py-1.5 text-right tabular-nums">{order.quantity}</td>
- <td className="px-3 py-1.5 text-right tabular-nums">{order.price}</td>
- <td className="px-3 py-1.5 text-right tabular-nums">{order.fee}</td>
- </tr>
- ))}
- </tbody>
- </table>
- {preview.orders.length > 50 && (
- <p className="border-t border-border/60 px-3 py-2 text-xs text-muted-foreground">
- {t('assetImport.moreRows', { count: preview.orders.length - 50 })}
- </p>
- )}
- </div>
- )}
-
- <div className="flex gap-2">
- <Button onClick={handleImport} disabled={importing || importable === 0}>
- <Upload size={14} className="mr-1" />
- {importing ? t('assetImport.importing') : t('assetImport.confirm', { count: importable })}
- </Button>
- <Button variant="outline" onClick={() => handleFile(null)}>
- <X size={14} className="mr-1" />
- {t('common.cancel')}
- </Button>
- </div>
- </div>
- )}
- </SectionCard>
- </div>
- )
-}
diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsx
index d79abd1c..6cbc80ad 100644
--- a/frontend/src/pages/assets.tsx
+++ b/frontend/src/pages/assets.tsx
@@ -1021,7 +1021,7 @@ export default function AssetsPage() {
action={
canWrite ? (
<div className="flex items-center gap-2">
- <Button onClick={() => navigate('/assets/import')} variant="outline" className="gap-1.5">
+ <Button onClick={() => navigate('/import?tab=investments')} variant="outline" className="gap-1.5">
<Upload size={16} />
{t('assetImport.action')}
</Button>
diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsx
index 8de51289..18c10008 100644
--- a/frontend/src/pages/import.tsx
+++ b/frontend/src/pages/import.tsx
@@ -1,20 +1,21 @@
import { useState, useRef, useCallback } from 'react'
+import { useSearchParams } from 'react-router-dom'
import { getAccountName, sortAccountsByDisplayName } from '@/lib/account-utils'
import { useTranslation } from 'react-i18next'
import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { transactions as transactionsApi, accounts as accountsApi, importLogs as importLogsApi, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'
+import { transactions as transactionsApi, accounts as accountsApi, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
-import { formatCurrency } from '@/lib/format'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
-import type { ImportPreviewTransaction, ImportReviewTransaction, ImportLog } from '@/types'
-import { Upload, FileText, X, CheckCircle2, AlertCircle, History, Trash2, Settings2, Download } from 'lucide-react'
-import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
+import type { ImportPreviewTransaction, ImportReviewTransaction } from '@/types'
+import { Upload, FileText, X, CheckCircle2, AlertCircle, Settings2, Download } from 'lucide-react'
import { PageHeader } from '@/components/page-header'
+import { AssetImportPanel } from '@/components/asset-import-panel'
import { ImportSummaryBar } from '@/components/import-summary-bar'
import { ImportReviewTable } from '@/components/import-review-table'
+import { ImportHistory } from '@/components/import-history'
import { useAuth } from '@/contexts/auth-context'
import { useWorkspace } from '@/contexts/workspace-context'
@@ -48,7 +49,7 @@ function toReviewTransactions(txns: ImportPreviewTransaction[]): ImportReviewTra
}))
}
-export default function ImportPage() {
+function TransactionImportPanel() {
const { t } = useTranslation()
const { user } = useAuth()
const { canWrite } = useWorkspace()
@@ -63,7 +64,6 @@ export default function ImportPage() {
const [dragOver, setDragOver] = useState(false)
const [fileName, setFileName] = useState<string | null>(null)
const [currentFile, setCurrentFile] = useState<File | null>(null)
- const [deleteTarget, setDeleteTarget] = useState<ImportLog | null>(null)
const [csvHeaders, setCsvHeaders] = useState<string[]>([])
const [searchQuery, setSearchQuery] = useState('')
@@ -95,11 +95,6 @@ export default function ImportPage() {
queryFn: categoryGroupsApi.list,
})
- const { data: importHistory = [] } = useQuery({
- queryKey: ['import-logs'],
- queryFn: importLogsApi.list,
- })
-
const previewMutation = useMutation({
mutationFn: ({ file, options }: { file: File; options?: { date_format?: string; flip_amount?: boolean; inflow_column?: string; outflow_column?: string; column_mapping?: Record<string, string> } }) =>
transactionsApi.previewImport(file, options),
@@ -170,15 +165,6 @@ export default function ImportPage() {
},
})
- const deleteMutation = useMutation({
- mutationFn: (id: string) => importLogsApi.delete(id),
- onSuccess: () => {
- invalidateFinancialQueries(queryClient)
- queryClient.invalidateQueries({ queryKey: ['import-logs'] })
- setDeleteTarget(null)
- },
- })
-
function resetCsvOptions() {
setCsvDateFormat('')
setCsvFlipAmount(false)
@@ -285,8 +271,6 @@ export default function ImportPage() {
return (
<div className="space-y-6">
- <PageHeader section={t('import.title')} title={t('import.subtitle')} />
-
{/* Upload zone */}
{canWrite && <div
className={`bg-card rounded-xl border-2 border-dashed transition-all cursor-pointer ${
@@ -579,98 +563,51 @@ export default function ImportPage() {
</div>
)}
- {/* Import History */}
- <div className="mt-8">
- <div className="flex items-center gap-2 mb-4">
- <History className="w-5 h-5 text-muted-foreground" />
- <h2 className="text-lg font-semibold text-foreground">{t('import.history')}</h2>
- </div>
+ <ImportHistory entity="transactions" />
- {importHistory.length === 0 ? (
- <div className="bg-card rounded-xl border border-border p-8 text-center text-muted-foreground">
- {t('import.noHistory')}
- </div>
- ) : (
- <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
- <table className="w-full text-sm">
- <thead>
- <tr className="border-b border-border">
- <th className="text-left px-3 sm:px-4 py-3 font-medium text-muted-foreground">{t('import.historyDate')}</th>
- <th className="text-left px-3 sm:px-4 py-3 font-medium text-muted-foreground">{t('import.historyFile')}</th>
- <th className="text-left px-4 py-3 font-medium text-muted-foreground hidden lg:table-cell">{t('import.historyFormat')}</th>
- <th className="text-left px-4 py-3 font-medium text-muted-foreground hidden md:table-cell">{t('import.historyAccount')}</th>
- <th className="text-right px-3 sm:px-4 py-3 font-medium text-muted-foreground">{t('import.historyCount')}</th>
- <th className="text-right px-4 py-3 font-medium text-muted-foreground hidden sm:table-cell">{t('import.historyCredit')}</th>
- <th className="text-right px-4 py-3 font-medium text-muted-foreground hidden sm:table-cell">{t('import.historyDebit')}</th>
- <th className="px-3 sm:px-4 py-3" aria-label={t('common.more')}></th>
- </tr>
- </thead>
- <tbody className="divide-y divide-border">
- {importHistory.map((log) => (
- <tr key={log.id} className="hover:bg-muted">
- <td className="px-3 sm:px-4 py-3 text-xs sm:text-sm text-muted-foreground whitespace-nowrap">
- {new Date(log.created_at).toLocaleString(dateLocale, { dateStyle: 'short', timeStyle: 'short' })}
- </td>
- <td className="px-3 sm:px-4 py-3 font-mono text-xs text-foreground max-w-[120px] sm:max-w-none truncate">{log.filename || '—'}</td>
- <td className="px-4 py-3 hidden lg:table-cell">
- <span className="bg-muted text-muted-foreground text-xs px-2 py-0.5 rounded font-mono uppercase">
- {log.format || '—'}
- </span>
- </td>
- <td className="px-4 py-3 text-muted-foreground hidden md:table-cell">{log.account_name || '—'}</td>
- <td className="px-3 sm:px-4 py-3 text-right text-foreground">{log.transaction_count}</td>
- <td className="px-4 py-3 text-right text-emerald-600 font-medium hidden sm:table-cell">
- {formatCurrency(log.total_credit, userCurrency, locale)}
- </td>
- <td className="px-4 py-3 text-right text-rose-600 font-medium hidden sm:table-cell">
- {formatCurrency(log.total_debit, userCurrency, locale)}
- </td>
- <td className="px-3 sm:px-4 py-3 text-right">
- {canWrite && (
- <button
- onClick={() => setDeleteTarget(log)}
- className="text-muted-foreground hover:text-rose-500 transition-colors"
- aria-label={t('import.undoImport')}
- title={t('import.undoImport')}
- >
- <Trash2 className="w-4 h-4" />
- </button>
- )}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
+ </div>
+ )
+}
+
+/** Both importers live behind one menu entry: someone with a file to upload
+ should not have to know first whether it holds transactions or orders. */
+export default function ImportPage() {
+ const { t } = useTranslation()
+ const [searchParams, setSearchParams] = useSearchParams()
+ const tab = searchParams.get('tab') === 'investments' ? 'investments' : 'transactions'
+
+ function selectTab(next: 'transactions' | 'investments') {
+ const params = new URLSearchParams(searchParams)
+ if (next === 'transactions') params.delete('tab')
+ else params.set('tab', next)
+ setSearchParams(params, { replace: true })
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* The title follows the tab: "Bank statement" is about the file you
+ are uploading, and an order file is not one. */}
+ <PageHeader
+ section={t('import.title')}
+ title={tab === 'investments' ? t('assetImport.title') : t('import.subtitle')}
+ />
+
+ <div className="inline-flex items-center rounded-lg border border-border bg-muted/40 p-0.5">
+ {(['transactions', 'investments'] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() => selectTab(value)}
+ className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
+ tab === value ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'
+ }`}
+ >
+ {t(value === 'transactions' ? 'import.tabTransactions' : 'import.tabInvestments')}
+ </button>
+ ))}
</div>
- {/* Delete confirmation dialog */}
- <Dialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('import.undoImport')}</DialogTitle>
- <DialogDescription>
- {t('import.undoDescription', { count: deleteTarget?.transaction_count, filename: deleteTarget?.filename || '—' })}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <button
- onClick={() => setDeleteTarget(null)}
- className="px-4 py-2 text-sm text-muted-foreground hover:text-foreground"
- >
- {t('common.cancel')}
- </button>
- <button
- onClick={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)}
- disabled={deleteMutation.isPending}
- className="px-4 py-2 text-sm bg-rose-500 text-white rounded-lg hover:bg-rose-600 disabled:opacity-50"
- >
- {deleteMutation.isPending ? t('import.deleting') : t('import.deleteAll')}
- </button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ {tab === 'investments' ? <AssetImportPanel /> : <TransactionImportPanel />}
</div>
)
}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index ad270cd6..9cbe665e 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -484,8 +484,10 @@ export interface RuleImportResponse {
export interface ImportLog {
id: string
user_id: string
- account_id: string
+ /** Null for an order import, which lands on holdings rather than an account. */
+ account_id: string | null
account_name: string | null
+ entity: 'transactions' | 'asset_orders'
filename: string
format: string
transaction_count: number