Skip to content

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

feat/transaction attachments (#37)

Tássio Noronhade54d9c7ea44
diff --git a/backend/alembic/versions/018_transaction_attachments.py b/backend/alembic/versions/018_transaction_attachments.py
new file mode 100644
index 00000000..adc4907e
--- /dev/null
+++ b/backend/alembic/versions/018_transaction_attachments.py
@@ -0,0 +1,46 @@
+"""add transaction attachments table
+
+Revision ID: 018
+Revises: 017
+Create Date: 2026-03-25
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects.postgresql import UUID
+
+revision: str = "018"
+down_revision: Union[str, None] = "017"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "transaction_attachments",
+ sa.Column("id", UUID(as_uuid=True), primary_key=True),
+ sa.Column(
+ "transaction_id",
+ UUID(as_uuid=True),
+ sa.ForeignKey("transactions.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
+ sa.Column("filename", sa.String(255), nullable=False),
+ sa.Column("storage_key", sa.String(500), nullable=False),
+ sa.Column("content_type", sa.String(100), nullable=False),
+ sa.Column("size", sa.BigInteger, nullable=False),
+ sa.Column(
+ "created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False
+ ),
+ )
+ op.create_index("ix_transaction_attachments_transaction_id", "transaction_attachments", ["transaction_id"])
+ op.create_index("ix_transaction_attachments_user_id", "transaction_attachments", ["user_id"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_transaction_attachments_user_id", table_name="transaction_attachments")
+ op.drop_index("ix_transaction_attachments_transaction_id", table_name="transaction_attachments")
+ op.drop_table("transaction_attachments")
diff --git a/backend/app/api/attachments.py b/backend/app/api/attachments.py
new file mode 100644
index 00000000..dbe18b96
--- /dev/null
+++ b/backend/app/api/attachments.py
@@ -0,0 +1,103 @@
+import uuid
+
+from fastapi import APIRouter, Depends, HTTPException, UploadFile, status
+from fastapi.responses import Response
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.auth import current_active_user
+from app.core.database import get_async_session
+from app.models.user import User
+from app.schemas.attachment import AttachmentRead, AttachmentRename
+from app.services import attachment_service
+
+router = APIRouter(
+ prefix="/api/transactions/{transaction_id}/attachments",
+ tags=["attachments"],
+)
+
+
[email protected]("", response_model=AttachmentRead, status_code=status.HTTP_201_CREATED)
+async def upload_attachment(
+ transaction_id: uuid.UUID,
+ file: UploadFile,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ data = await file.read()
+ try:
+ attachment = await attachment_service.upload_attachment(
+ session=session,
+ user_id=user.id,
+ transaction_id=transaction_id,
+ filename=file.filename or "unnamed",
+ content_type=file.content_type or "application/octet-stream",
+ data=data,
+ )
+ except LookupError:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ return attachment
+
+
[email protected]("", response_model=list[AttachmentRead])
+async def list_attachments(
+ transaction_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ try:
+ return await attachment_service.list_attachments(session, user.id, transaction_id)
+ except LookupError:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")
+
+
[email protected]("/{attachment_id}")
+async def download_attachment(
+ transaction_id: uuid.UUID,
+ attachment_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ try:
+ attachment, data = await attachment_service.download_attachment(
+ session, attachment_id, user.id
+ )
+ except LookupError:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")
+ return Response(
+ content=data,
+ media_type=attachment.content_type,
+ headers={"Content-Disposition": f'inline; filename="{attachment.filename}"'},
+ )
+
+
[email protected]("/{attachment_id}", response_model=AttachmentRead)
+async def rename_attachment(
+ transaction_id: uuid.UUID,
+ attachment_id: uuid.UUID,
+ body: AttachmentRename,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ try:
+ return await attachment_service.rename_attachment(
+ session, attachment_id, user.id, body.filename
+ )
+ except LookupError:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+
+
[email protected]("/{attachment_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_attachment(
+ transaction_id: uuid.UUID,
+ attachment_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ try:
+ await attachment_service.delete_attachment(session, attachment_id, user.id)
+ except LookupError:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")
diff --git a/backend/app/api/import_logs.py b/backend/app/api/import_logs.py
index 240eb74e..d0911970 100644
--- a/backend/app/api/import_logs.py
+++ b/backend/app/api/import_logs.py
@@ -58,6 +58,23 @@ async def delete_import_log(
if not log:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Import log not found")
+ # Clean up attachment files before deleting transactions
+ from app.services.attachment_service import cleanup_attachment_files
+ tx_result = await session.execute(
+ select(Transaction.id).where(Transaction.import_id == log_id)
+ )
+ tx_ids = [row[0] for row in tx_result.all()]
+ await cleanup_attachment_files(session, tx_ids)
+
+ # Also delete attachment DB records (raw SQL delete bypasses ORM cascade)
+ from app.models.transaction_attachment import TransactionAttachment
+ if tx_ids:
+ await session.execute(
+ delete(TransactionAttachment).where(
+ TransactionAttachment.transaction_id.in_(tx_ids)
+ )
+ )
+
# Delete all transactions from this import
await session.execute(
delete(Transaction).where(Transaction.import_id == log_id)
diff --git a/backend/app/api/settings.py b/backend/app/api/settings.py
new file mode 100644
index 00000000..6d1a6aca
--- /dev/null
+++ b/backend/app/api/settings.py
@@ -0,0 +1,17 @@
+from fastapi import APIRouter
+
+from app.core.config import get_settings
+
+router = APIRouter(prefix="/api/settings", tags=["settings"])
+
+
[email protected]("/attachments")
+async def get_attachment_settings():
+ """Return attachment configuration for this instance."""
+ settings = get_settings()
+ allowed = [ext.strip().lower() for ext in settings.storage_allowed_extensions.split(",") if ext.strip()]
+ return {
+ "allowed_extensions": allowed,
+ "max_file_size_mb": settings.storage_max_file_size_mb,
+ "max_attachments_per_transaction": settings.storage_max_attachments_per_transaction,
+ }
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 5179a49a..29837283 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -31,6 +31,20 @@ class Settings(BaseSettings):
supported_currencies: str = "USD,EUR,GBP,BRL,CAD,AUD,CHF,ARS,JPY,MXN,INR,SEK" # comma-separated list
fx_sync_mode: str = "on_demand" # "on_demand" or "scheduled"
+ # Storage
+ storage_provider: str = "local" # "local" or "s3"
+ storage_local_path: str = "./data/attachments"
+ storage_max_file_size_mb: int = 10
+ storage_allowed_extensions: str = "jpg,jpeg,png,webp,gif,heic,pdf"
+ storage_max_attachments_per_transaction: int = 10
+
+ # S3 Storage (for future use)
+ storage_s3_bucket: str = ""
+ storage_s3_region: str = ""
+ storage_s3_access_key: str = ""
+ storage_s3_secret_key: str = ""
+ storage_s3_endpoint_url: str = "" # for S3-compatible services (MinIO, DigitalOcean Spaces)
+
# Celery
redis_url: str = "redis://localhost:6379/0"
diff --git a/backend/app/main.py b/backend/app/main.py
index 4558d41e..06a98148 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -20,6 +20,8 @@ from app.api.setup import router as setup_router
from app.api.currencies import router as currencies_router
from app.api.export import router as export_router
from app.api.fx_rates import router as fx_rates_router
+from app.api.attachments import router as attachments_router
+from app.api.settings import router as settings_router
from app.api.transactions import router as transactions_router
from app.core.auth import auth_backend, fastapi_users
from app.core.config import get_settings
@@ -97,6 +99,8 @@ app.include_router(setup_router)
app.include_router(currencies_router)
app.include_router(fx_rates_router)
app.include_router(export_router)
+app.include_router(attachments_router)
+app.include_router(settings_router)
@app.get("/api/health")
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index a081c9ab..0671c0fa 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -11,6 +11,7 @@ from app.models.import_log import ImportLog
from app.models.asset import Asset
from app.models.asset_value import AssetValue
from app.models.fx_rate import FxRate
+from app.models.transaction_attachment import TransactionAttachment
__all__ = [
"User",
@@ -26,4 +27,5 @@ __all__ = [
"Asset",
"AssetValue",
"FxRate",
+ "TransactionAttachment",
]
diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.py
index edbcfbc7..3dc20d2c 100644
--- a/backend/app/models/transaction.py
+++ b/backend/app/models/transaction.py
@@ -13,6 +13,7 @@ if TYPE_CHECKING:
from app.models.account import Account
from app.models.category import Category
from app.models.import_log import ImportLog
+ from app.models.transaction_attachment import TransactionAttachment
class Transaction(Base):
@@ -42,3 +43,6 @@ class Transaction(Base):
account: Mapped["Account"] = relationship(back_populates="transactions")
category: Mapped[Optional["Category"]] = relationship()
import_log: Mapped[Optional["ImportLog"]] = relationship(back_populates="transactions")
+ attachments: Mapped[list["TransactionAttachment"]] = relationship(
+ back_populates="transaction", cascade="all, delete-orphan"
+ )
diff --git a/backend/app/models/transaction_attachment.py b/backend/app/models/transaction_attachment.py
new file mode 100644
index 00000000..7289c154
--- /dev/null
+++ b/backend/app/models/transaction_attachment.py
@@ -0,0 +1,31 @@
+import uuid
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING
+
+from sqlalchemy import BigInteger, DateTime, ForeignKey, String
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from app.core.database import Base
+
+if TYPE_CHECKING:
+ from app.models.transaction import Transaction
+
+
+class TransactionAttachment(Base):
+ __tablename__ = "transaction_attachments"
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ transaction_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="CASCADE")
+ )
+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))
+ filename: Mapped[str] = mapped_column(String(255))
+ storage_key: Mapped[str] = mapped_column(String(500))
+ content_type: Mapped[str] = mapped_column(String(100))
+ size: Mapped[int] = mapped_column(BigInteger)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
+ )
+
+ transaction: Mapped["Transaction"] = relationship(back_populates="attachments")
diff --git a/backend/app/providers/__init__.py b/backend/app/providers/__init__.py
index 245bbf03..1b7d0afb 100644
--- a/backend/app/providers/__init__.py
+++ b/backend/app/providers/__init__.py
@@ -57,6 +57,28 @@ def _auto_register_providers() -> None:
_auto_register_providers()
+_storage_provider = None
+
+
+def get_storage_provider():
+ """Get the configured storage provider (singleton)."""
+ global _storage_provider
+ if _storage_provider is None:
+ from app.core.config import get_settings
+
+ settings = get_settings()
+ if settings.storage_provider == "local":
+ from app.providers.local_storage import LocalStorageProvider
+
+ _storage_provider = LocalStorageProvider()
+ else:
+ raise NotImplementedError(
+ f"Storage provider '{settings.storage_provider}' is not yet implemented. "
+ "Supported: 'local'"
+ )
+ return _storage_provider
+
+
__all__ = [
"BankProvider",
"AccountData",
@@ -67,4 +89,5 @@ __all__ = [
"get_provider",
"list_providers",
"all_known_providers",
+ "get_storage_provider",
]
diff --git a/backend/app/providers/local_storage.py b/backend/app/providers/local_storage.py
new file mode 100644
index 00000000..44dc0a4e
--- /dev/null
+++ b/backend/app/providers/local_storage.py
@@ -0,0 +1,44 @@
+import os
+from pathlib import Path
+
+import aiofiles
+
+from app.core.config import get_settings
+from app.providers.storage import StorageProvider, StoredFile
+
+
+class LocalStorageProvider(StorageProvider):
+ """Store files on the local filesystem."""
+
+ @property
+ def name(self) -> str:
+ return "local"
+
+ def _base_path(self) -> Path:
+ return Path(get_settings().storage_local_path)
+
+ def _full_path(self, storage_key: str) -> Path:
+ base = self._base_path().resolve()
+ full = (base / storage_key).resolve()
+ if not str(full).startswith(str(base)):
+ raise ValueError("Invalid storage key")
+ return full
+
+ async def upload(self, storage_key: str, data: bytes, content_type: str) -> StoredFile:
+ path = self._full_path(storage_key)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ async with aiofiles.open(path, "wb") as f:
+ await f.write(data)
+ return StoredFile(storage_key=storage_key, size=len(data), content_type=content_type)
+
+ async def download(self, storage_key: str) -> bytes:
+ path = self._full_path(storage_key)
+ if not path.exists():
+ raise FileNotFoundError(f"File not found: {storage_key}")
+ async with aiofiles.open(path, "rb") as f:
+ return await f.read()
+
+ async def delete(self, storage_key: str) -> None:
+ path = self._full_path(storage_key)
+ if path.exists():
+ os.remove(path)
diff --git a/backend/app/providers/storage.py b/backend/app/providers/storage.py
new file mode 100644
index 00000000..4096ed39
--- /dev/null
+++ b/backend/app/providers/storage.py
@@ -0,0 +1,38 @@
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+
+
+@dataclass
+class StoredFile:
+ storage_key: str
+ size: int
+ content_type: str
+
+
+class StorageProvider(ABC):
+ """Abstract interface for file storage backends."""
+
+ @property
+ @abstractmethod
+ def name(self) -> str:
+ """Unique provider identifier (e.g. 'local', 's3')."""
+ ...
+
+ @abstractmethod
+ async def upload(self, storage_key: str, data: bytes, content_type: str) -> StoredFile:
+ """Upload file data and return metadata."""
+ ...
+
+ @abstractmethod
+ async def download(self, storage_key: str) -> bytes:
+ """Download and return file contents."""
+ ...
+
+ @abstractmethod
+ async def delete(self, storage_key: str) -> None:
+ """Delete a file from storage."""
+ ...
+
+ def get_url(self, storage_key: str) -> str | None:
+ """Return a direct URL (e.g. presigned S3 URL). None for local storage."""
+ return None
diff --git a/backend/app/schemas/attachment.py b/backend/app/schemas/attachment.py
new file mode 100644
index 00000000..135bbdc6
--- /dev/null
+++ b/backend/app/schemas/attachment.py
@@ -0,0 +1,19 @@
+import uuid
+from datetime import datetime
+
+from pydantic import BaseModel, ConfigDict
+
+
+class AttachmentRead(BaseModel):
+ id: uuid.UUID
+ transaction_id: uuid.UUID
+ filename: str
+ content_type: str
+ size: int
+ created_at: datetime
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class AttachmentRename(BaseModel):
+ filename: str
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index a8645ba0..710d6028 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -54,6 +54,7 @@ class TransactionRead(TransactionBase):
amount_primary: Optional[float] = None
fx_rate_used: Optional[float] = None
fx_fallback: bool = False
+ attachment_count: int = 0
model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index af1582b8..e61d32ee 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -197,6 +197,14 @@ async def delete_account(session: AsyncSession, account_id: uuid.UUID, user_id:
if account.connection_id is not None:
raise ValueError("Cannot delete bank-connected accounts")
+ # Clean up attachment files for all transactions in this account
+ from app.services.attachment_service import cleanup_attachment_files
+ tx_result = await session.execute(
+ select(Transaction.id).where(Transaction.account_id == account_id)
+ )
+ tx_ids = [row[0] for row in tx_result.all()]
+ await cleanup_attachment_files(session, tx_ids)
+
await session.delete(account)
await session.commit()
return True
diff --git a/backend/app/services/attachment_service.py b/backend/app/services/attachment_service.py
new file mode 100644
index 00000000..9ad73671
--- /dev/null
+++ b/backend/app/services/attachment_service.py
@@ -0,0 +1,202 @@
+import re
+import uuid
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import get_settings
+from app.models.transaction import Transaction
+from app.models.transaction_attachment import TransactionAttachment
+from app.providers import get_storage_provider
+
+
+def sanitize_filename(filename: str) -> str:
+ """Strip special characters from a filename, preserving the extension."""
+ if "." in filename:
+ name, ext = filename.rsplit(".", 1)
+ ext = re.sub(r"[^a-zA-Z0-9]", "", ext).lower()
+ else:
+ name = filename
+ ext = ""
+ # Replace non-alphanumeric (except hyphens/underscores) with underscores, collapse runs
+ name = re.sub(r"[^a-zA-Z0-9_-]", "_", name)
+ name = re.sub(r"_+", "_", name).strip("_")
+ if not name:
+ name = "file"
+ return f"{name}.{ext}" if ext else name
+
+
+def _validate_file(filename: str, content_type: str, size: int) -> None:
+ settings = get_settings()
+
+ max_bytes = settings.storage_max_file_size_mb * 1024 * 1024
+ if size > max_bytes:
+ raise ValueError(f"File too large. Maximum size is {settings.storage_max_file_size_mb} MB.")
+
+ allowed = {ext.strip().lower() for ext in settings.storage_allowed_extensions.split(",")}
+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
+ if ext not in allowed:
+ raise ValueError(f"File type '.{ext}' is not allowed. Allowed: {', '.join(sorted(allowed))}")
+
+
+async def _verify_transaction_ownership(
+ session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID
+) -> Transaction:
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.id == transaction_id, Transaction.user_id == user_id
+ )
+ )
+ transaction = result.scalar_one_or_none()
+ if not transaction:
+ raise LookupError("Transaction not found")
+ return transaction
+
+
+async def upload_attachment(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ transaction_id: uuid.UUID,
+ filename: str,
+ content_type: str,
+ data: bytes,
+) -> TransactionAttachment:
+ filename = sanitize_filename(filename)
+ _validate_file(filename, content_type, len(data))
+ await _verify_transaction_ownership(session, transaction_id, user_id)
+
+ settings = get_settings()
+ count_result = await session.execute(
+ select(func.count()).where(
+ TransactionAttachment.transaction_id == transaction_id,
+ TransactionAttachment.user_id == user_id,
+ )
+ )
+ current_count = count_result.scalar_one()
+ if current_count >= settings.storage_max_attachments_per_transaction:
+ raise ValueError(
+ f"Maximum of {settings.storage_max_attachments_per_transaction} attachments per transaction reached."
+ )
+
+ prefix = uuid.uuid4().hex[:8]
+ storage_key = f"{user_id}/{transaction_id}/{prefix}_{filename}"
+
+ storage = get_storage_provider()
+ stored = await storage.upload(storage_key, data, content_type)
+
+ attachment = TransactionAttachment(
+ user_id=user_id,
+ transaction_id=transaction_id,
+ filename=filename,
+ storage_key=stored.storage_key,
+ content_type=stored.content_type,
+ size=stored.size,
+ )
+ session.add(attachment)
+ await session.commit()
+ await session.refresh(attachment)
+ return attachment
+
+
+async def list_attachments(
+ session: AsyncSession, user_id: uuid.UUID, transaction_id: uuid.UUID
+) -> list[TransactionAttachment]:
+ await _verify_transaction_ownership(session, transaction_id, user_id)
+ result = await session.execute(
+ select(TransactionAttachment)
+ .where(
+ TransactionAttachment.transaction_id == transaction_id,
+ TransactionAttachment.user_id == user_id,
+ )
+ .order_by(TransactionAttachment.created_at)
+ )
+ return list(result.scalars().all())
+
+
+async def download_attachment(
+ session: AsyncSession, attachment_id: uuid.UUID, user_id: uuid.UUID
+) -> tuple[TransactionAttachment, bytes]:
+ result = await session.execute(
+ select(TransactionAttachment).where(
+ TransactionAttachment.id == attachment_id, TransactionAttachment.user_id == user_id
+ )
+ )
+ attachment = result.scalar_one_or_none()
+ if not attachment:
+ raise LookupError("Attachment not found")
+
+ storage = get_storage_provider()
+ data = await storage.download(attachment.storage_key)
+ return attachment, data
+
+
+async def rename_attachment(
+ session: AsyncSession, attachment_id: uuid.UUID, user_id: uuid.UUID, new_filename: str
+) -> TransactionAttachment:
+ new_filename = sanitize_filename(new_filename)
+ if not new_filename:
+ raise ValueError("Filename cannot be empty.")
+
+ result = await session.execute(
+ select(TransactionAttachment).where(
+ TransactionAttachment.id == attachment_id, TransactionAttachment.user_id == user_id
+ )
+ )
+ attachment = result.scalar_one_or_none()
+ if not attachment:
+ raise LookupError("Attachment not found")
+
+ # Preserve the original extension
+ original_ext = attachment.filename.rsplit(".", 1)[-1].lower() if "." in attachment.filename else ""
+ new_ext = new_filename.rsplit(".", 1)[-1].lower() if "." in new_filename else ""
+
+ if original_ext and new_ext != original_ext:
+ # Strip any wrong extension the user may have typed, re-append original
+ name_part = new_filename.rsplit(".", 1)[0] if "." in new_filename else new_filename
+ new_filename = f"{name_part}.{original_ext}"
+
+ attachment.filename = new_filename
+ await session.commit()
+ await session.refresh(attachment)
+ return attachment
+
+
+async def cleanup_attachment_files(
+ session: AsyncSession, transaction_ids: list[uuid.UUID]
+) -> None:
+ """Delete storage files for all attachments belonging to the given transactions."""
+ if not transaction_ids:
+ return
+ result = await session.execute(
+ select(TransactionAttachment.storage_key).where(
+ TransactionAttachment.transaction_id.in_(transaction_ids)
+ )
+ )
+ storage_keys = [row[0] for row in result.all()]
+ if not storage_keys:
+ return
+ storage = get_storage_provider()
+ for key in storage_keys:
+ try:
+ await storage.delete(key)
+ except Exception:
+ pass # best-effort cleanup; file may already be gone
+
+
+async def delete_attachment(
+ session: AsyncSession, attachment_id: uuid.UUID, user_id: uuid.UUID
+) -> None:
+ result = await session.execute(
+ select(TransactionAttachment).where(
+ TransactionAttachment.id == attachment_id, TransactionAttachment.user_id == user_id
+ )
+ )
+ attachment = result.scalar_one_or_none()
+ if not attachment:
+ raise LookupError("Attachment not found")
+
+ storage = get_storage_provider()
+ await storage.delete(attachment.storage_key)
+
+ await session.delete(attachment)
+ await session.commit()
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index 9178e75a..f8d9c5b6 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models.transaction import Transaction
+from app.models.transaction_attachment import TransactionAttachment
from app.models.account import Account
from app.models.bank_connection import BankConnection
from app.schemas.transaction import TransactionCreate, TransactionUpdate
@@ -111,6 +112,21 @@ async def get_transactions(
result = await session.execute(query)
transactions = list(result.scalars().all())
+ # Batch-load attachment counts in a single query
+ if transactions:
+ tx_ids = [tx.id for tx in transactions]
+ count_rows = await session.execute(
+ select(
+ TransactionAttachment.transaction_id,
+ func.count(TransactionAttachment.id),
+ )
+ .where(TransactionAttachment.transaction_id.in_(tx_ids))
+ .group_by(TransactionAttachment.transaction_id)
+ )
+ counts = dict(count_rows.all())
+ for tx in transactions:
+ tx.attachment_count = counts.get(tx.id, 0)
+
return transactions, total or 0
@@ -130,7 +146,15 @@ async def get_transaction(
)
.options(selectinload(Transaction.category))
)
- return result.scalar_one_or_none()
+ transaction = result.scalar_one_or_none()
+ if transaction:
+ count_result = await session.execute(
+ select(func.count(TransactionAttachment.id)).where(
+ TransactionAttachment.transaction_id == transaction.id
+ )
+ )
+ transaction.attachment_count = count_result.scalar_one()
+ return transaction
async def create_transaction(
@@ -245,6 +269,10 @@ async def delete_transaction(
if not transaction:
return False
+ # Clean up attachment files from storage before ORM cascade deletes DB records
+ from app.services.attachment_service import cleanup_attachment_files
+ await cleanup_attachment_files(session, [transaction_id])
+
await session.delete(transaction)
await session.commit()
return True
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index f9f22af5..88a22134 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -18,6 +18,7 @@ dependencies = [
"python-multipart>=0.0.6",
"ofxparse>=0.21",
"celery[redis]>=5.3.0",
+ "aiofiles>=24.0",
]
[project.optional-dependencies]
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index c9aa4ebd..828f39ec 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -18,6 +18,7 @@ from app.models.transaction import Transaction
from app.models.rule import Rule
from app.models.asset import Asset # noqa: F401
from app.models.asset_value import AssetValue # noqa: F401
+from app.models.transaction_attachment import TransactionAttachment # noqa: F401
# Use SQLite for tests — fast, no external dependency
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
diff --git a/backend/tests/test_attachments_api.py b/backend/tests/test_attachments_api.py
new file mode 100644
index 00000000..f8f8208f
--- /dev/null
+++ b/backend/tests/test_attachments_api.py
@@ -0,0 +1,448 @@
+from unittest.mock import AsyncMock, patch
+from dataclasses import dataclass
+
+import pytest
+from httpx import AsyncClient
+
+from app.models.transaction import Transaction
+from app.services.attachment_service import sanitize_filename
+
+
+@dataclass
+class FakeStoredFile:
+ storage_key: str
+ size: int
+ content_type: str
+
+
+def _make_mock_storage():
+ """Create a mock storage provider for tests."""
+ mock = AsyncMock()
+ mock.name = "mock"
+ mock.upload.side_effect = lambda key, data, ct: FakeStoredFile(
+ storage_key=key, size=len(data), content_type=ct
+ )
+ mock.download.return_value = b"fake-file-content"
+ mock.delete.return_value = None
+ return mock
+
+
+STORAGE_PATCH = "app.services.attachment_service.get_storage_provider"
+
+TINY_PNG = (
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01"
+ b"\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00"
+ b"\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00"
+ b"\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
+)
+
+
+# ── Filename sanitization ──────────────────────────────────
+
+
+def test_sanitize_filename_basic():
+ assert sanitize_filename("receipt.png") == "receipt.png"
+
+
+def test_sanitize_filename_special_chars():
+ assert sanitize_filename("my file (1).png") == "my_file_1.png"
+
+
+def test_sanitize_filename_unicode():
+ assert sanitize_filename("café résumé.pdf") == "caf_r_sum.pdf"
+
+
+def test_sanitize_filename_collapse_underscores():
+ assert sanitize_filename("a---b___c d.jpg") == "a---b_c_d.jpg"
+
+
+def test_sanitize_filename_no_extension():
+ assert sanitize_filename("README") == "README"
+
+
+def test_sanitize_filename_empty_name():
+ assert sanitize_filename("....pdf") == "file.pdf"
+
+
+# ── Upload ──────────────────────────────────────────────────
+
+
+async def test_upload_attachment(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("receipt.png", TINY_PNG, "image/png")},
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["filename"] == "receipt.png"
+ assert data["content_type"] == "image/png"
+ assert data["size"] == len(TINY_PNG)
+ assert data["transaction_id"] == str(txn.id)
+
+
+async def test_upload_sanitizes_filename(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("my file (1).png", TINY_PNG, "image/png")},
+ )
+ assert response.status_code == 201
+ assert response.json()["filename"] == "my_file_1.png"
+
+
+async def test_upload_pdf(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("invoice.pdf", b"%PDF-1.4 fake", "application/pdf")},
+ )
+ assert response.status_code == 201
+ assert response.json()["filename"] == "invoice.pdf"
+
+
+async def test_upload_rejected_file_type(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("malware.exe", b"MZ...", "application/octet-stream")},
+ )
+ assert response.status_code == 400
+ assert "not allowed" in response.json()["detail"].lower()
+
+
+async def test_upload_file_too_large(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ huge = b"x" * (11 * 1024 * 1024) # 11 MB > 10 MB limit
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("big.png", huge, "image/png")},
+ )
+ assert response.status_code == 400
+ assert "too large" in response.json()["detail"].lower()
+
+
+async def test_upload_transaction_not_found(
+ client: AsyncClient, auth_headers, test_transactions
+):
+ fake_id = "00000000-0000-0000-0000-000000000000"
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.post(
+ f"/api/transactions/{fake_id}/attachments",
+ headers=auth_headers,
+ files={"file": ("receipt.png", TINY_PNG, "image/png")},
+ )
+ assert response.status_code == 404
+
+
+# ── List ────────────────────────────────────────────────────
+
+
+async def test_list_attachments_empty(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ response = await client.get(
+ f"/api/transactions/{txn.id}/attachments", headers=auth_headers
+ )
+ assert response.status_code == 200
+ assert response.json() == []
+
+
+async def test_list_attachments(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ mock_storage = _make_mock_storage()
+ with patch(STORAGE_PATCH, return_value=mock_storage):
+ # Upload two files
+ await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("a.png", TINY_PNG, "image/png")},
+ )
+ await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("b.jpg", TINY_PNG, "image/jpeg")},
+ )
+
+ response = await client.get(
+ f"/api/transactions/{txn.id}/attachments", headers=auth_headers
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data) == 2
+ filenames = {a["filename"] for a in data}
+ assert filenames == {"a.png", "b.jpg"}
+
+
+async def test_list_attachments_transaction_not_found(
+ client: AsyncClient, auth_headers, test_transactions
+):
+ fake_id = "00000000-0000-0000-0000-000000000000"
+ response = await client.get(
+ f"/api/transactions/{fake_id}/attachments", headers=auth_headers
+ )
+ assert response.status_code == 404
+
+
+# ── Download ────────────────────────────────────────────────
+
+
+async def test_download_attachment(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ mock_storage = _make_mock_storage()
+ with patch(STORAGE_PATCH, return_value=mock_storage):
+ upload_resp = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("photo.png", TINY_PNG, "image/png")},
+ )
+ attachment_id = upload_resp.json()["id"]
+
+ response = await client.get(
+ f"/api/transactions/{txn.id}/attachments/{attachment_id}",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.headers["content-type"] == "image/png"
+ assert "photo.png" in response.headers.get("content-disposition", "")
+ assert response.content == b"fake-file-content"
+
+
+async def test_download_attachment_not_found(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ fake_id = "00000000-0000-0000-0000-000000000000"
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.get(
+ f"/api/transactions/{txn.id}/attachments/{fake_id}",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+# ── Delete ──────────────────────────────────────────────────
+
+
+async def test_delete_attachment(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ mock_storage = _make_mock_storage()
+ with patch(STORAGE_PATCH, return_value=mock_storage):
+ upload_resp = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("delete-me.png", TINY_PNG, "image/png")},
+ )
+ attachment_id = upload_resp.json()["id"]
+
+ # Delete
+ response = await client.delete(
+ f"/api/transactions/{txn.id}/attachments/{attachment_id}",
+ headers=auth_headers,
+ )
+ assert response.status_code == 204
+
+ # Verify gone
+ list_resp = await client.get(
+ f"/api/transactions/{txn.id}/attachments", headers=auth_headers
+ )
+ assert all(a["id"] != attachment_id for a in list_resp.json())
+
+ # Verify storage.delete was called
+ mock_storage.delete.assert_called_once()
+
+
+async def test_delete_attachment_not_found(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ fake_id = "00000000-0000-0000-0000-000000000000"
+ with patch(STORAGE_PATCH, return_value=_make_mock_storage()):
+ response = await client.delete(
+ f"/api/transactions/{txn.id}/attachments/{fake_id}",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+# ── Auth ────────────────────────────────────────────────────
+
+
+# ── Rename ─────────────────────────────────────────────────
+
+
+async def test_rename_attachment(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ mock_storage = _make_mock_storage()
+ with patch(STORAGE_PATCH, return_value=mock_storage):
+ upload_resp = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("receipt.png", TINY_PNG, "image/png")},
+ )
+ attachment_id = upload_resp.json()["id"]
+
+ response = await client.patch(
+ f"/api/transactions/{txn.id}/attachments/{attachment_id}",
+ headers=auth_headers,
+ json={"filename": "grocery store receipt"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ # Should sanitize and preserve original extension
+ assert data["filename"] == "grocery_store_receipt.png"
+
+
+async def test_rename_preserves_extension(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ mock_storage = _make_mock_storage()
+ with patch(STORAGE_PATCH, return_value=mock_storage):
+ upload_resp = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("invoice.pdf", b"%PDF-1.4 fake", "application/pdf")},
+ )
+ attachment_id = upload_resp.json()["id"]
+
+ # Try renaming with wrong extension — should keep .pdf
+ response = await client.patch(
+ f"/api/transactions/{txn.id}/attachments/{attachment_id}",
+ headers=auth_headers,
+ json={"filename": "my-invoice.jpg"},
+ )
+ assert response.status_code == 200
+ assert response.json()["filename"] == "my-invoice.pdf"
+
+
+async def test_rename_attachment_not_found(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ fake_id = "00000000-0000-0000-0000-000000000000"
+ response = await client.patch(
+ f"/api/transactions/{txn.id}/attachments/{fake_id}",
+ headers=auth_headers,
+ json={"filename": "new-name"},
+ )
+ assert response.status_code == 404
+
+
+# ── Settings ───────────────────────────────────────────────
+
+
+async def test_get_attachment_settings(client: AsyncClient):
+ response = await client.get("/api/settings/attachments")
+ assert response.status_code == 200
+ data = response.json()
+ assert data["allowed_extensions"] == ["jpg", "jpeg", "png", "webp", "gif", "heic", "pdf"]
+ assert data["max_file_size_mb"] == 10
+ assert data["max_attachments_per_transaction"] == 10
+
+
+# ── Max attachments ────────────────────────────────────────
+
+
+async def test_upload_rejected_max_attachments(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ mock_storage = _make_mock_storage()
+ with (
+ patch(STORAGE_PATCH, return_value=mock_storage),
+ patch("app.services.attachment_service.get_settings") as mock_settings,
+ ):
+ settings = mock_settings.return_value
+ settings.storage_max_file_size_mb = 10
+ settings.storage_allowed_extensions = "jpg,jpeg,png,webp,gif,heic,pdf"
+ settings.storage_max_attachments_per_transaction = 2
+
+ # Upload two files (at the limit)
+ for i in range(2):
+ resp = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": (f"file{i}.png", TINY_PNG, "image/png")},
+ )
+ assert resp.status_code == 201
+
+ # Third upload should be rejected
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ headers=auth_headers,
+ files={"file": ("file3.png", TINY_PNG, "image/png")},
+ )
+ assert response.status_code == 400
+ assert "maximum" in response.json()["detail"].lower()
+
+
+# ── Auth ────────────────────────────────────────────────────
+
+
+async def test_attachments_unauthenticated(
+ client: AsyncClient, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ response = await client.get(f"/api/transactions/{txn.id}/attachments")
+ assert response.status_code == 401
+
+
+async def test_upload_unauthenticated(
+ client: AsyncClient, test_transactions: list[Transaction]
+):
+ txn = test_transactions[0]
+ response = await client.post(
+ f"/api/transactions/{txn.id}/attachments",
+ files={"file": ("receipt.png", TINY_PNG, "image/png")},
+ )
+ assert response.status_code == 401
diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml
index 3b9a361d..5c3781ef 100644
--- a/docker-compose.prod.yml
+++ b/docker-compose.prod.yml
@@ -9,6 +9,7 @@ x-backend-env: &backend-env
PLUGGY_CLIENT_SECRET: ${PLUGGY_CLIENT_SECRET:-}
PLUGGY_OAUTH_REDIRECT_URI: ${PLUGGY_OAUTH_REDIRECT_URI:-http://localhost:3000/oauth/callback}
REDIS_URL: redis://redis:6379/0
+ STORAGE_LOCAL_PATH: /app/data/attachments
x-backend-base: &backend-base
image: ghcr.io/securo-finance/securo-backend:latest
@@ -16,6 +17,8 @@ x-backend-base: &backend-base
depends_on:
db: { condition: service_healthy }
redis: { condition: service_healthy }
+ volumes:
+ - attachments:/app/data/attachments
restart: unless-stopped
services:
@@ -66,3 +69,4 @@ services:
volumes:
pgdata:
+ attachments:
diff --git a/docker-compose.yml b/docker-compose.yml
index 6d037b82..bce49f72 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -11,6 +11,7 @@ x-backend-env: &backend-env
REDIS_URL: redis://redis:6379/0
OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}
FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}
+ STORAGE_LOCAL_PATH: /app/data/attachments
x-backend-base: &backend-base
build: ./backend
@@ -20,6 +21,7 @@ x-backend-base: &backend-base
redis: { condition: service_healthy }
volumes:
- ./backend:/app
+ - attachments:/app/data/attachments
restart: unless-stopped
services:
@@ -77,3 +79,4 @@ services:
volumes:
pgdata:
+ attachments:
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 8d5f7ee9..c1014973 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -18,6 +18,7 @@
"i18next-browser-languagedetector": "^8.2.1",
"lucide-react": "^0.575.0",
"next-themes": "^0.4.6",
+ "pdfjs-dist": "^5.5.207",
"radix-ui": "^1.4.3",
"react": "^19.2.0",
"react-dom": "^19.2.0",
@@ -102,7 +103,6 @@
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
@@ -1662,13 +1662,262 @@
"node": ">=18"
}
},
+ "node_modules/@napi-rs/canvas": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.97.tgz",
+ "integrity": "sha512-8cFniXvrIEnVwuNSRCW9wirRZbHvrD3JVujdS2P5n5xiJZNZMOZcfOvJ1pb66c7jXMKHHglJEDVJGbm8XWFcXQ==",
+ "license": "MIT",
+ "optional": true,
+ "workspaces": [
+ "e2e/*"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "optionalDependencies": {
+ "@napi-rs/canvas-android-arm64": "0.1.97",
+ "@napi-rs/canvas-darwin-arm64": "0.1.97",
+ "@napi-rs/canvas-darwin-x64": "0.1.97",
+ "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.97",
+ "@napi-rs/canvas-linux-arm64-gnu": "0.1.97",
+ "@napi-rs/canvas-linux-arm64-musl": "0.1.97",
+ "@napi-rs/canvas-linux-riscv64-gnu": "0.1.97",
+ "@napi-rs/canvas-linux-x64-gnu": "0.1.97",
+ "@napi-rs/canvas-linux-x64-musl": "0.1.97",
+ "@napi-rs/canvas-win32-arm64-msvc": "0.1.97",
+ "@napi-rs/canvas-win32-x64-msvc": "0.1.97"
+ }
+ },
+ "node_modules/@napi-rs/canvas-android-arm64": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.97.tgz",
+ "integrity": "sha512-V1c/WVw+NzH8vk7ZK/O8/nyBSCQimU8sfMsB/9qeSvdkGKNU7+mxy/bIF0gTgeBFmHpj30S4E9WHMSrxXGQuVQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-darwin-arm64": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.97.tgz",
+ "integrity": "sha512-ok+SCEF4YejcxuJ9Rm+WWunHHpf2HmiPxfz6z1a/NFQECGXtsY7A4B8XocK1LmT1D7P174MzwPF9Wy3AUAwEPw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-darwin-x64": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.97.tgz",
+ "integrity": "sha512-PUP6e6/UGlclUvAQNnuXCcnkpdUou6VYZfQOQxExLp86epOylmiwLkqXIvpFmjoTEDmPmXrI+coL/9EFU1gKPA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.97.tgz",
+ "integrity": "sha512-XyXH2L/cic8eTNtbrXCcvqHtMX/nEOxN18+7rMrAM2XtLYC/EB5s0wnO1FsLMWmK+04ZSLN9FBGipo7kpIkcOw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm64-gnu": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.97.tgz",
+ "integrity": "sha512-Kuq/M3djq0K8ktgz6nPlK7Ne5d4uWeDxPpyKWOjWDK2RIOhHVtLtyLiJw2fuldw7Vn4mhw05EZXCEr4Q76rs9w==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm64-musl": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.97.tgz",
+ "integrity": "sha512-kKmSkQVnWeqg7qdsiXvYxKhAFuHz3tkBjW/zyQv5YKUPhotpaVhpBGv5LqCngzyuRV85SXoe+OFj+Tv0a0QXkQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.97.tgz",
+ "integrity": "sha512-Jc7I3A51jnEOIAXeLsN/M/+Z28LUeakcsXs07FLq9prXc0eYOtVwsDEv913Gr+06IRo34gJJVgT0TXvmz+N2VA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-x64-gnu": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.97.tgz",
+ "integrity": "sha512-iDUBe7AilfuBSRbSa8/IGX38Mf+iCSBqoVKLSQ5XaY2JLOaqz1TVyPFEyIck7wT6mRQhQt5sN6ogfjIDfi74tg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-x64-musl": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.97.tgz",
+ "integrity": "sha512-AKLFd/v0Z5fvgqBDqhvqtAdx+fHMJ5t9JcUNKq4FIZ5WH+iegGm8HPdj00NFlCSnm83Fp3Ln8I2f7uq1aIiWaA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-win32-arm64-msvc": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.97.tgz",
+ "integrity": "sha512-u883Yr6A6fO7Vpsy9YE4FVCIxzzo5sO+7pIUjjoDLjS3vQaNMkVzx5bdIpEL+ob+gU88WDK4VcxYMZ6nmnoX9A==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@napi-rs/canvas-win32-x64-msvc": {
+ "version": "0.1.97",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.97.tgz",
+ "integrity": "sha512-sWtD2EE3fV0IzN+iiQUqr/Q1SwqWhs2O1FKItFlxtdDkikpEj5g7DKQpY3x55H/MAOnL8iomnlk3mcEeGiUMoQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": "^14.21.3 || >=16"
},
@@ -4168,7 +4417,6 @@
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -4179,7 +4427,6 @@
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -4190,7 +4437,6 @@
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -4260,7 +4506,6 @@
"integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.56.1",
"@typescript-eslint/types": "8.56.1",
@@ -4579,7 +4824,6 @@
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"dev": true,
"license": "MIT",
- "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -4854,7 +5098,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -5845,7 +6088,6 @@
"integrity": "sha512-VmQ+sifHUbI/IcSopBCF/HO3YiHQx/AVd3UVyYL6weuwW+HvON9VYn5l6Zl1WZzPWXPNZrSQpxwkkZ/VuvJZzg==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -6791,7 +7033,6 @@
"integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=16.9.0"
}
@@ -6869,7 +7110,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/runtime": "^7.28.4"
},
@@ -8006,6 +8246,13 @@
"url": "https://opencollective.com/node-fetch"
}
},
+ "node_modules/node-readable-to-web-readable-stream": {
+ "version": "0.4.2",
+ "resolved": "https://registry.npmjs.org/node-readable-to-web-readable-stream/-/node-readable-to-web-readable-stream-0.4.2.tgz",
+ "integrity": "sha512-/cMZNI34v//jUTrI+UIo4ieHAB5EZRY/+7OmXZgBxaWBMcW2tGdceIw06RFxWxrKZ5Jp3sI2i5TsRo+CBhtVLQ==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/node-releases": {
"version": "2.0.27",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
@@ -8326,6 +8573,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/pdfjs-dist": {
+ "version": "5.5.207",
+ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.5.207.tgz",
+ "integrity": "sha512-WMqqw06w1vUt9ZfT0gOFhMf3wHsWhaCrxGrckGs5Cci6ybDW87IvPaOd2pnBwT6BJuP/CzXDZxjFgmSULLdsdw==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=20.19.0 || >=22.13.0 || >=24"
+ },
+ "optionalDependencies": {
+ "@napi-rs/canvas": "^0.1.95",
+ "node-readable-to-web-readable-stream": "^0.4.2"
+ }
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -8666,7 +8926,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
"integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -8676,7 +8935,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -8689,7 +8947,6 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.2.tgz",
"integrity": "sha512-1CHvcDYzuRUNOflt4MOq3ZM46AronNJtQ1S7tnX6YN4y72qhgiUItpacZUAQ0TyWYci3yz1X+rXaSxiuEm86PA==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -8759,7 +9016,6 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT",
- "peer": true,
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
@@ -8946,8 +9202,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
@@ -9851,7 +10106,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
- "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -10087,7 +10341,6 @@
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"esbuild": "^0.27.0",
"fdir": "^6.5.0",
@@ -10426,7 +10679,6 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
- "peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
diff --git a/frontend/package.json b/frontend/package.json
index 892b13a6..28d7f49a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -21,6 +21,7 @@
"i18next-browser-languagedetector": "^8.2.1",
"lucide-react": "^0.575.0",
"next-themes": "^0.4.6",
+ "pdfjs-dist": "^5.5.207",
"radix-ui": "^1.4.3",
"react": "^19.2.0",
"react-dom": "^19.2.0",
diff --git a/frontend/src/components/transaction-attachments.tsx b/frontend/src/components/transaction-attachments.tsx
new file mode 100644
index 00000000..57c47e9e
--- /dev/null
+++ b/frontend/src/components/transaction-attachments.tsx
@@ -0,0 +1,590 @@
+import { useRef, useState, useEffect, useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { transactions as transactionsApi, settings as settingsApi } from '@/lib/api'
+import { toast } from 'sonner'
+import { GlobalWorkerOptions, getDocument } from 'pdfjs-dist'
+import { Paperclip, Upload, Download, Trash2, X, Loader2, FileText, Eye, Plus, Pencil, Check } from 'lucide-react'
+import { Skeleton } from '@/components/ui/skeleton'
+import type { Attachment } from '@/types'
+
+GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.mjs', import.meta.url).href
+
+export interface AttachmentPreview {
+ attachmentId: string
+ url: string
+ contentType: string
+ filename: string
+}
+
+function formatFileSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+function getFileExtension(filename: string): string {
+ return filename.includes('.') ? filename.split('.').pop()!.toLowerCase() : ''
+}
+
+function isImageType(contentType: string): boolean {
+ return contentType.startsWith('image/')
+}
+
+function sanitizeFilename(filename: string): string {
+ const dotIdx = filename.lastIndexOf('.')
+ let name = dotIdx > 0 ? filename.slice(0, dotIdx) : filename
+ const ext = dotIdx > 0 ? filename.slice(dotIdx + 1).toLowerCase().replace(/[^a-z0-9]/g, '') : ''
+ name = name.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '')
+ if (!name) name = 'file'
+ return ext ? `${name}.${ext}` : name
+}
+
+interface OptimisticAttachment {
+ id: string
+ filename: string
+ content_type: string
+ size: number
+ isUploading: true
+}
+
+export function TransactionAttachments({
+ transactionId,
+ onPreviewChange,
+ activePreviewId,
+}: {
+ transactionId: string
+ onPreviewChange?: (preview: AttachmentPreview | null) => void
+ activePreviewId?: string | null
+}) {
+ const { t, i18n } = useTranslation()
+ const queryClient = useQueryClient()
+ const fileInputRef = useRef<HTMLInputElement>(null)
+ const lastClickedRef = useRef<string | null>(null)
+ const [dragOver, setDragOver] = useState(false)
+ const [deletingId, setDeletingId] = useState<string | null>(null)
+ const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null)
+ const [renamingId, setRenamingId] = useState<string | null>(null)
+ const [renameValue, setRenameValue] = useState('')
+ const renameInputRef = useRef<HTMLInputElement>(null)
+ const [thumbnails, setThumbnails] = useState<Record<string, string>>({})
+ const [optimisticFiles, setOptimisticFiles] = useState<OptimisticAttachment[]>([])
+
+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language
+ const queryKey = ['attachments', transactionId]
+
+ const { data: attachmentSettings } = useQuery({
+ queryKey: ['settings', 'attachments'],
+ queryFn: () => settingsApi.attachments(),
+ staleTime: 5 * 60 * 1000,
+ })
+
+ const allowedExtensions = attachmentSettings?.allowed_extensions ?? ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'pdf']
+ const maxFileSize = (attachmentSettings?.max_file_size_mb ?? 10) * 1024 * 1024
+ const maxAttachments = attachmentSettings?.max_attachments_per_transaction ?? 10
+
+ const { data: attachments, isLoading } = useQuery({
+ queryKey,
+ queryFn: () => transactionsApi.attachments.list(transactionId),
+ })
+
+ // Load thumbnails for image and PDF attachments
+ useEffect(() => {
+ if (!attachments) return
+ let cancelled = false
+ const urls: string[] = []
+
+ const renderPdfThumbnail = async (blobUrl: string): Promise<string> => {
+ const pdf = await getDocument(blobUrl).promise
+ const page = await pdf.getPage(1)
+ const scale = 200 / page.getViewport({ scale: 1 }).width
+ const viewport = page.getViewport({ scale })
+ const canvas = document.createElement('canvas')
+ canvas.width = viewport.width
+ canvas.height = viewport.height
+ await page.render({ canvas, canvasContext: canvas.getContext('2d')!, viewport }).promise
+ const dataUrl = canvas.toDataURL('image/png')
+ pdf.destroy()
+ return dataUrl
+ }
+
+ const loadThumbnails = async () => {
+ const newThumbnails: Record<string, string> = {}
+ for (const att of attachments) {
+ if (thumbnails[att.id]) continue
+ const isImage = isImageType(att.content_type)
+ const isPdf = att.content_type === 'application/pdf'
+ if (!isImage && !isPdf) continue
+
+ try {
+ const blobUrl = await transactionsApi.attachments.downloadUrl(transactionId, att.id)
+ if (cancelled) {
+ URL.revokeObjectURL(blobUrl)
+ return
+ }
+
+ if (isImage) {
+ newThumbnails[att.id] = blobUrl
+ urls.push(blobUrl)
+ } else {
+ // PDF: render first page to canvas, then revoke the blob
+ const dataUrl = await renderPdfThumbnail(blobUrl)
+ URL.revokeObjectURL(blobUrl)
+ if (cancelled) return
+ newThumbnails[att.id] = dataUrl
+ }
+ } catch {
+ // skip failed thumbnail
+ }
+ }
+ if (!cancelled && Object.keys(newThumbnails).length > 0) {
+ setThumbnails(prev => ({ ...prev, ...newThumbnails }))
+ }
+ }
+
+ loadThumbnails()
+ return () => {
+ cancelled = true
+ urls.forEach(URL.revokeObjectURL)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [attachments?.map(a => a.id).join(',')])
+
+ // Cleanup thumbnails on unmount
+ useEffect(() => {
+ return () => {
+ Object.values(thumbnails).forEach(URL.revokeObjectURL)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ const uploadMutation = useMutation({
+ mutationFn: ({ file }: { file: File; optimisticId: string }) =>
+ transactionsApi.attachments.upload(transactionId, file),
+ onMutate: ({ file, optimisticId }) => {
+ const optimistic: OptimisticAttachment = {
+ id: optimisticId,
+ filename: sanitizeFilename(file.name),
+ content_type: file.type || 'application/octet-stream',
+ size: file.size,
+ isUploading: true,
+ }
+ // Generate a local thumbnail for images
+ if (isImageType(file.type)) {
+ const url = URL.createObjectURL(file)
+ setThumbnails(prev => ({ ...prev, [optimisticId]: url }))
+ }
+ setOptimisticFiles(prev => [...prev, optimistic])
+ },
+ onSuccess: (_data, { optimisticId }) => {
+ setOptimisticFiles(prev => prev.filter(f => f.id !== optimisticId))
+ if (thumbnails[optimisticId]) {
+ URL.revokeObjectURL(thumbnails[optimisticId])
+ setThumbnails(prev => {
+ const next = { ...prev }
+ delete next[optimisticId]
+ return next
+ })
+ }
+ queryClient.invalidateQueries({ queryKey })
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ toast.success(t('transactions.attachmentUploaded'))
+ },
+ onError: (error: unknown, { optimisticId }) => {
+ setOptimisticFiles(prev => prev.filter(f => f.id !== optimisticId))
+ if (thumbnails[optimisticId]) {
+ URL.revokeObjectURL(thumbnails[optimisticId])
+ setThumbnails(prev => {
+ const next = { ...prev }
+ delete next[optimisticId]
+ return next
+ })
+ }
+ const msg = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
+ toast.error(msg || t('common.error'))
+ },
+ })
+
+ const deleteMutation = useMutation({
+ mutationFn: (attachmentId: string) => transactionsApi.attachments.delete(transactionId, attachmentId),
+ onSuccess: (_data, attachmentId) => {
+ if (activePreviewId === attachmentId) {
+ onPreviewChange?.(null)
+ }
+ if (thumbnails[attachmentId]) {
+ URL.revokeObjectURL(thumbnails[attachmentId])
+ setThumbnails(prev => {
+ const next = { ...prev }
+ delete next[attachmentId]
+ return next
+ })
+ }
+ queryClient.invalidateQueries({ queryKey })
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ toast.success(t('transactions.attachmentDeleted'))
+ setDeletingId(null)
+ setConfirmDeleteId(null)
+ },
+ onError: () => {
+ toast.error(t('common.error'))
+ setDeletingId(null)
+ },
+ })
+
+ const renameMutation = useMutation({
+ mutationFn: ({ attachmentId, filename }: { attachmentId: string; filename: string }) =>
+ transactionsApi.attachments.rename(transactionId, attachmentId, filename),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey })
+ setRenamingId(null)
+ toast.success(t('transactions.attachmentRenamed'))
+ },
+ onError: () => {
+ toast.error(t('common.error'))
+ },
+ })
+
+ const startRename = (att: Attachment) => {
+ // Pre-fill with name without extension
+ const dotIdx = att.filename.lastIndexOf('.')
+ const nameWithoutExt = dotIdx > 0 ? att.filename.slice(0, dotIdx) : att.filename
+ setRenameValue(nameWithoutExt)
+ setRenamingId(att.id)
+ setConfirmDeleteId(null)
+ setTimeout(() => renameInputRef.current?.select(), 0)
+ }
+
+ const submitRename = (attachmentId: string) => {
+ const trimmed = renameValue.trim()
+ if (!trimmed) {
+ setRenamingId(null)
+ return
+ }
+ renameMutation.mutate({ attachmentId, filename: trimmed })
+ }
+
+ const validateAndUpload = useCallback((files: FileList | File[]) => {
+ const currentCount = (attachments?.length ?? 0) + optimisticFiles.length
+ let uploaded = 0
+ for (const file of Array.from(files)) {
+ if (currentCount + uploaded >= maxAttachments) {
+ toast.error(t('transactions.attachmentMaxReached'))
+ break
+ }
+ const ext = getFileExtension(file.name)
+ if (!allowedExtensions.includes(ext)) {
+ toast.error(t('transactions.attachmentTypeNotAllowed'))
+ continue
+ }
+ if (file.size > maxFileSize) {
+ toast.error(t('transactions.attachmentTooLarge'))
+ continue
+ }
+ const optimisticId = `optimistic-${crypto.randomUUID()}`
+ uploadMutation.mutate({ file, optimisticId })
+ uploaded++
+ }
+ }, [uploadMutation, t, attachments?.length, optimisticFiles.length, maxAttachments, allowedExtensions, maxFileSize])
+
+ const handleDrop = (e: React.DragEvent) => {
+ e.preventDefault()
+ setDragOver(false)
+ if (e.dataTransfer.files?.length) {
+ validateAndUpload(e.dataTransfer.files)
+ }
+ }
+
+ const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files?.length) {
+ validateAndUpload(e.target.files)
+ e.target.value = ''
+ }
+ }
+
+ const handlePreview = async (attachment: Attachment) => {
+ if (activePreviewId === attachment.id) {
+ onPreviewChange?.(null)
+ return
+ }
+
+ lastClickedRef.current = attachment.id
+ try {
+ const url = await transactionsApi.attachments.downloadUrl(transactionId, attachment.id)
+ if (lastClickedRef.current !== attachment.id) {
+ URL.revokeObjectURL(url)
+ return
+ }
+ onPreviewChange?.({
+ attachmentId: attachment.id,
+ url,
+ contentType: attachment.content_type,
+ filename: attachment.filename,
+ })
+ } catch {
+ toast.error(t('common.error'))
+ }
+ }
+
+ const handleDownload = async (attachment: Attachment) => {
+ try {
+ const url = await transactionsApi.attachments.downloadUrl(transactionId, attachment.id)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = attachment.filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+ } catch {
+ toast.error(t('common.error'))
+ }
+ }
+
+ const handleDelete = (attachmentId: string) => {
+ setDeletingId(attachmentId)
+ deleteMutation.mutate(attachmentId)
+ }
+
+ const allItems = [
+ ...(attachments ?? []).map(att => ({ ...att, isUploading: false as const })),
+ ...optimisticFiles,
+ ]
+ const hasAttachments = allItems.length > 0
+ const atMaxAttachments = allItems.length >= maxAttachments
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2 text-sm font-medium">
+ <Paperclip size={14} />
+ {t('transactions.attachments')}
+ {hasAttachments && (
+ <span className="text-xs text-muted-foreground font-normal">({attachments!.length})</span>
+ )}
+ </div>
+
+ {/* Attachment grid */}
+ {isLoading ? (
+ <div className="grid grid-cols-3 gap-2">
+ <Skeleton className="aspect-square w-full rounded-xl" />
+ <Skeleton className="aspect-square w-full rounded-xl" />
+ </div>
+ ) : hasAttachments ? (
+ <>
+ <div className="grid grid-cols-3 gap-2">
+ {allItems.map((att) => {
+ const isUploading = att.isUploading
+ const isActive = !isUploading && activePreviewId === att.id
+ const isPdf = att.content_type === 'application/pdf'
+ const ext = getFileExtension(att.filename).toUpperCase()
+ const isConfirming = confirmDeleteId === att.id
+
+ return (
+ <div
+ key={att.id}
+ className={`group relative rounded-xl overflow-hidden transition-all duration-200 ${
+ isUploading
+ ? 'ring-1 ring-border opacity-60'
+ : isActive
+ ? 'ring-2 ring-primary shadow-md shadow-primary/10 cursor-pointer'
+ : 'ring-1 ring-border hover:ring-border/80 hover:shadow-md hover:shadow-black/5 cursor-pointer'
+ }`}
+ onClick={() => !isUploading && !isConfirming && handlePreview(att as Attachment)}
+ >
+ {/* Thumbnail */}
+ <div className="aspect-square bg-muted/50 flex items-center justify-center overflow-hidden relative">
+ {thumbnails[att.id] ? (
+ <img
+ src={thumbnails[att.id]}
+ alt={att.filename}
+ className={`w-full h-full object-cover transition-transform duration-300 ${isUploading ? '' : 'group-hover:scale-[1.03]'}`}
+ />
+ ) : (
+ <div className="flex flex-col items-center gap-2">
+ <div className={`w-12 h-14 rounded-lg flex items-center justify-center ${
+ isPdf ? 'bg-red-500/10' : 'bg-muted'
+ }`}>
+ <FileText size={24} className={isPdf ? 'text-red-500' : 'text-muted-foreground'} />
+ </div>
+ <span className="text-[10px] font-semibold tracking-widest text-muted-foreground/70 uppercase">
+ {ext || 'FILE'}
+ </span>
+ </div>
+ )}
+ {isUploading && (
+ <div className="absolute inset-0 flex items-center justify-center bg-background/40">
+ <Loader2 size={20} className="animate-spin text-primary" />
+ </div>
+ )}
+ </div>
+
+ {/* Hover action bar — floats over bottom of thumbnail */}
+ {!isUploading && (
+ <div className={`absolute left-0 right-0 bottom-[44px] flex items-center justify-center gap-1 px-2 py-1.5 transition-all duration-200 ${
+ isConfirming
+ ? 'opacity-100 translate-y-0'
+ : 'opacity-0 translate-y-1 group-hover:opacity-100 group-hover:translate-y-0'
+ }`}>
+ <div className="flex items-center gap-1 bg-background/90 dark:bg-card/90 backdrop-blur-sm rounded-lg ring-1 ring-border/50 shadow-lg shadow-black/10 px-1 py-0.5">
+ {isConfirming ? (
+ <>
+ <button
+ type="button"
+ className="flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-medium bg-destructive text-destructive-foreground hover:bg-destructive/90 cursor-pointer transition-colors"
+ onClick={(e) => { e.stopPropagation(); handleDelete(att.id) }}
+ disabled={deletingId === att.id}
+ >
+ {deletingId === att.id ? <Loader2 size={12} className="animate-spin" /> : t('common.delete')}
+ </button>
+ <button
+ type="button"
+ className="p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer transition-colors"
+ onClick={(e) => { e.stopPropagation(); setConfirmDeleteId(null) }}
+ >
+ <X size={13} />
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ type="button"
+ className={`p-1.5 rounded-md cursor-pointer transition-colors ${
+ isActive
+ ? 'text-primary bg-primary/10'
+ : 'text-muted-foreground hover:text-foreground hover:bg-accent'
+ }`}
+ onClick={(e) => { e.stopPropagation(); handlePreview(att as Attachment) }}
+ title="Preview"
+ >
+ <Eye size={14} />
+ </button>
+ <button
+ type="button"
+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer transition-colors"
+ onClick={(e) => { e.stopPropagation(); startRename(att as Attachment) }}
+ title={t('transactions.attachmentRename')}
+ >
+ <Pencil size={14} />
+ </button>
+ <button
+ type="button"
+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer transition-colors"
+ onClick={(e) => { e.stopPropagation(); handleDownload(att as Attachment) }}
+ title="Download"
+ >
+ <Download size={14} />
+ </button>
+ <button
+ type="button"
+ className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 cursor-pointer transition-colors"
+ onClick={(e) => { e.stopPropagation(); setConfirmDeleteId(att.id) }}
+ title={t('common.delete')}
+ >
+ <Trash2 size={14} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Info bar — always visible, clean */}
+ <div className="px-3 py-2.5 bg-card">
+ {!isUploading && renamingId === att.id ? (
+ <div
+ className="flex items-center gap-1"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <input
+ ref={renameInputRef}
+ type="text"
+ value={renameValue}
+ onChange={(e) => setRenameValue(e.target.value)}
+ onBlur={() => submitRename(att.id)}
+ onKeyDown={(e) => {
+ e.stopPropagation()
+ if (e.key === 'Enter') { e.preventDefault(); submitRename(att.id) }
+ if (e.key === 'Escape') setRenamingId(null)
+ }}
+ className="flex-1 min-w-0 text-[12px] font-medium bg-transparent border-b border-primary outline-none leading-tight py-0.5"
+ autoFocus
+ />
+ <button
+ type="button"
+ className="p-0.5 text-primary hover:text-primary/80 cursor-pointer"
+ onClick={(e) => { e.stopPropagation(); submitRename(att.id) }}
+ >
+ {renameMutation.isPending ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}
+ </button>
+ </div>
+ ) : (
+ <p
+ className={`text-[12px] font-medium truncate leading-tight ${!isUploading ? 'cursor-text hover:text-primary/80' : ''}`}
+ title={att.filename}
+ onClick={(e) => { if (!isUploading) { e.stopPropagation(); startRename(att as Attachment) } }}
+ >
+ {att.filename}
+ </p>
+ )}
+ <p className="text-[10px] text-muted-foreground mt-1 leading-tight">
+ {isUploading
+ ? t('transactions.attachmentsUploading')
+ : `${formatFileSize(att.size)} · ${new Date((att as Attachment).created_at).toLocaleDateString(locale, { month: 'short', day: 'numeric' })}`
+ }
+ </p>
+ </div>
+ </div>
+ )
+ })}
+
+ </div>
+
+ {/* Add more button */}
+ {!atMaxAttachments && (
+ <button
+ type="button"
+ className={`w-full mt-2 rounded-lg border-2 border-dashed py-3 flex items-center justify-center gap-2 cursor-pointer transition-all duration-200 ${
+ dragOver
+ ? 'border-primary bg-primary/5'
+ : 'border-border hover:border-muted-foreground/40 hover:bg-muted/30'
+ }`}
+ onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
+ onDragLeave={() => setDragOver(false)}
+ onDrop={handleDrop}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <Plus size={14} className="text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">{t('transactions.attachmentsUpload')}</span>
+ </button>
+ )}
+ </>
+ ) : (
+ /* Empty state with drop zone */
+ <div
+ className={`rounded-xl border-2 border-dashed py-6 px-4 text-center transition-all cursor-pointer ${
+ dragOver ? 'border-primary bg-primary/5' : 'border-border hover:border-muted-foreground/40'
+ }`}
+ onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
+ onDragLeave={() => setDragOver(false)}
+ onDrop={handleDrop}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <div className="flex flex-col items-center gap-2">
+ <div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center">
+ <Upload size={14} className="text-muted-foreground" />
+ </div>
+ <span className="text-xs text-muted-foreground">{t('transactions.attachmentsUpload')}</span>
+ </div>
+ </div>
+ )}
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={allowedExtensions.map(ext => `.${ext}`).join(',')}
+ onChange={handleFileChange}
+ className="hidden"
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 776b9951..e5f0c945 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -1,8 +1,9 @@
-import { useState } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { useAuth } from '@/contexts/auth-context'
-import { currencies as currenciesApi } from '@/lib/api'
+import { currencies as currenciesApi, transactions as transactionsApi } from '@/lib/api'
+import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@@ -14,8 +15,11 @@ import {
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
-import { AlertTriangle } from 'lucide-react'
+import { AlertTriangle, ChevronLeft, Download } from 'lucide-react'
+import { TransactionAttachments } from '@/components/transaction-attachments'
+import type { AttachmentPreview } from '@/components/transaction-attachments'
import type { Transaction, RecurringTransaction } from '@/types'
+import { toast } from 'sonner'
export function extractApiError(error: unknown): string {
if (
@@ -41,6 +45,10 @@ export function extractApiError(error: unknown): string {
return 'An unexpected error occurred'
}
+function isImageType(contentType: string): boolean {
+ return contentType.startsWith('image/')
+}
+
export function TransactionDialog({
open,
onClose,
@@ -67,28 +75,167 @@ export function TransactionDialog({
isSynced?: boolean
}) {
const { t } = useTranslation()
+ const [preview, setPreview] = useState<AttachmentPreview | null>(null)
+
+ const handlePreviewChange = useCallback((newPreview: AttachmentPreview | null) => {
+ setPreview(prev => {
+ if (prev?.url) URL.revokeObjectURL(prev.url)
+ return newPreview
+ })
+ }, [])
+
+ // Clean up preview when dialog closes
+ useEffect(() => {
+ if (!open) {
+ setPreview(prev => {
+ if (prev?.url) URL.revokeObjectURL(prev.url)
+ return null
+ })
+ }
+ }, [open])
+
+ const handleDownloadPreview = async () => {
+ if (!preview || !transaction) return
+ try {
+ const url = await transactionsApi.attachments.downloadUrl(transaction.id, preview.attachmentId)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = preview.filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+ } catch {
+ toast.error(t('common.error'))
+ }
+ }
+
+ const isEditing = !!transaction
+ const hasPreview = isEditing && !!preview
return (
<Dialog open={open} onOpenChange={onClose}>
- <DialogContent className="max-w-2xl">
- <DialogHeader>
- <DialogTitle>
- {transaction ? t('common.edit') : t('transactions.addManual')}
- </DialogTitle>
- </DialogHeader>
- <TransactionForm
- key={transaction?.id ?? 'new'}
- transaction={transaction}
- categories={categories}
- accounts={accounts}
- recurringMatch={recurringMatch}
- onSave={onSave}
- onDelete={onDelete}
- onCancel={onClose}
- loading={loading}
- error={error}
- isSynced={isSynced}
- />
+ <DialogContent className={cn(
+ 'transition-[max-width] duration-300',
+ hasPreview ? 'sm:max-w-5xl max-w-2xl' : 'sm:max-w-2xl max-w-2xl'
+ )}>
+ <div className={isEditing ? 'sm:flex sm:gap-0 sm:h-[80vh]' : ''}>
+ {/* Left column: form */}
+ <div className={isEditing ? 'sm:flex-1 sm:min-w-0 sm:flex sm:flex-col sm:overflow-hidden sm:pr-6' : ''}>
+ <DialogHeader className="mb-4">
+ <DialogTitle>
+ {transaction ? t('common.edit') : t('transactions.addManual')}
+ </DialogTitle>
+ </DialogHeader>
+ <TransactionForm
+ key={transaction?.id ?? 'new'}
+ transaction={transaction}
+ categories={categories}
+ accounts={accounts}
+ recurringMatch={recurringMatch}
+ onSave={onSave}
+ onDelete={onDelete}
+ onCancel={onClose}
+ loading={loading}
+ error={error}
+ isSynced={isSynced}
+ onPreviewChange={handlePreviewChange}
+ activePreviewId={preview?.attachmentId ?? null}
+ hasPreview={hasPreview}
+ />
+ </div>
+
+ {/* Desktop: side panel */}
+ <div
+ className={cn(
+ 'hidden sm:flex shrink-0 border-l flex-col overflow-hidden transition-[width] duration-300 ease-in-out',
+ hasPreview ? 'w-[420px]' : 'w-0 border-l-0'
+ )}
+ >
+ {preview && (
+ <>
+ <div className="flex-1 overflow-hidden">
+ {preview.contentType === 'application/pdf' ? (
+ <iframe
+ src={`${preview.url}#toolbar=0&navpanes=0`}
+ title={preview.filename}
+ className="w-full h-full border-0 bg-white"
+ />
+ ) : isImageType(preview.contentType) ? (
+ <div className="flex items-center justify-center h-full p-4 bg-muted/30">
+ <img
+ src={preview.url}
+ alt={preview.filename}
+ className="max-h-full max-w-full rounded object-contain"
+ />
+ </div>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2 px-4 py-3 border-t text-sm shrink-0">
+ <button
+ type="button"
+ className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer"
+ onClick={() => handlePreviewChange(null)}
+ title="Close preview"
+ >
+ <ChevronLeft size={16} />
+ </button>
+ <span className="flex-1 truncate font-medium">{preview.filename}</span>
+ <button
+ type="button"
+ className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer"
+ onClick={handleDownloadPreview}
+ title="Download"
+ >
+ <Download size={14} />
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Mobile: full-screen overlay */}
+ {hasPreview && (
+ <div className="sm:hidden fixed inset-0 z-[100] bg-background flex flex-col animate-in slide-in-from-right duration-200">
+ <div className="flex-1 overflow-hidden">
+ {preview.contentType === 'application/pdf' ? (
+ <iframe
+ src={`${preview.url}#toolbar=0&navpanes=0`}
+ title={preview.filename}
+ className="w-full h-full border-0 bg-white"
+ />
+ ) : isImageType(preview.contentType) ? (
+ <div className="flex items-center justify-center h-full p-4 bg-muted/30">
+ <img
+ src={preview.url}
+ alt={preview.filename}
+ className="max-h-full max-w-full rounded object-contain"
+ />
+ </div>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2 px-4 py-3 border-t text-sm shrink-0">
+ <button
+ type="button"
+ className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer"
+ onClick={() => handlePreviewChange(null)}
+ title="Close preview"
+ >
+ <ChevronLeft size={18} />
+ </button>
+ <span className="flex-1 truncate font-medium">{preview.filename}</span>
+ <button
+ type="button"
+ className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer"
+ onClick={handleDownloadPreview}
+ title="Download"
+ >
+ <Download size={16} />
+ </button>
+ </div>
+ </div>
+ )}
</DialogContent>
</Dialog>
)
@@ -105,6 +252,9 @@ function TransactionForm({
loading,
error,
isSynced,
+ onPreviewChange,
+ activePreviewId,
+ hasPreview,
}: {
transaction: Transaction | null
categories: { id: string; name: string; icon: string }[]
@@ -116,6 +266,9 @@ function TransactionForm({
loading: boolean
error: string | null
isSynced: boolean
+ onPreviewChange: (preview: AttachmentPreview | null) => void
+ activePreviewId: string | null
+ hasPreview: boolean
}) {
const { t, i18n } = useTranslation()
const { user } = useAuth()
@@ -217,8 +370,13 @@ function TransactionForm({
: undefined
onSave(txData, recurringData)
}}
- className="space-y-4"
+ className={cn(
+ 'flex flex-col',
+ !isCreating ? 'flex-1 min-h-0' : 'max-h-[85vh]',
+ hasPreview && 'mt-4'
+ )}
>
+ <div className="space-y-4 overflow-y-auto flex-1 min-h-0 pb-2">
{error && (
<div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
{error}
@@ -374,6 +532,14 @@ function TransactionForm({
/>
</div>
+ {!isCreating && transaction && (
+ <TransactionAttachments
+ transactionId={transaction.id}
+ onPreviewChange={onPreviewChange}
+ activePreviewId={activePreviewId}
+ />
+ )}
+
{/* Recurring toggle — only shown when creating non-synced */}
{isCreating && !isSynced && (
<div className="space-y-3 border rounded-md p-3">
@@ -414,7 +580,12 @@ function TransactionForm({
</div>
)}
- <DialogFooter className={onDelete ? 'flex justify-between sm:justify-between' : ''}>
+ </div>
+
+ <DialogFooter className={cn(
+ 'shrink-0 border-t pt-4 mt-2',
+ onDelete ? 'flex justify-between sm:justify-between' : ''
+ )}>
{onDelete && (
<Button type="button" variant="destructive" onClick={onDelete} disabled={loading}>
{t('common.delete')}
diff --git a/frontend/src/components/transaction-drill-down.tsx b/frontend/src/components/transaction-drill-down.tsx
index 34805bca..391ce48f 100644
--- a/frontend/src/components/transaction-drill-down.tsx
+++ b/frontend/src/components/transaction-drill-down.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { transactions as transactionsApi, dashboard } from '@/lib/api'
-import { AlertTriangle, X } from 'lucide-react'
+import { AlertTriangle, Paperclip, X } from 'lucide-react'
import { CategoryIcon } from '@/components/category-icon'
import { useAuth } from '@/contexts/auth-context'
import type { Transaction } from '@/types'
@@ -29,6 +29,7 @@ type DisplayItem = {
categoryName: string | null
categoryColor: string | null
isProjected: boolean
+ attachmentCount: number
transaction: Transaction | null
}
@@ -92,6 +93,7 @@ export function TransactionDrillDown({
categoryName: tx.category?.name ?? null,
categoryColor: tx.category?.color ?? null,
isProjected: false,
+ attachmentCount: tx.attachment_count ?? 0,
transaction: tx,
})
}
@@ -116,6 +118,7 @@ export function TransactionDrillDown({
categoryName: pt.category_name,
categoryColor: pt.category_color ?? null,
isProjected: true,
+ attachmentCount: 0,
transaction: null,
})
}
@@ -226,6 +229,9 @@ export function TransactionDrillDown({
{t('transactions.recurringBadge')}
</span>
)}
+ {item.attachmentCount > 0 && (
+ <Paperclip size={12} className="text-muted-foreground shrink-0" />
+ )}
</div>
<p className="text-xs text-muted-foreground">
{new Date(item.date + 'T00:00:00').toLocaleDateString(locale)}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 47da0d8d..0653d57d 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -16,6 +16,7 @@ import type {
ImportLog,
Asset,
AssetValue,
+ Attachment,
DashboardSummary,
SpendingByCategory,
MonthlyTrend,
@@ -284,6 +285,31 @@ export const transactions = {
document.body.removeChild(a)
URL.revokeObjectURL(url)
},
+ attachments: {
+ list: async (transactionId: string): Promise<Attachment[]> => {
+ const { data } = await api.get(`/transactions/${transactionId}/attachments`)
+ return data
+ },
+ upload: async (transactionId: string, file: File): Promise<Attachment> => {
+ const formData = new FormData()
+ formData.append('file', file)
+ const { data } = await api.post(`/transactions/${transactionId}/attachments`, formData)
+ return data
+ },
+ downloadUrl: async (transactionId: string, attachmentId: string): Promise<string> => {
+ const { data } = await api.get(`/transactions/${transactionId}/attachments/${attachmentId}`, {
+ responseType: 'blob',
+ })
+ return URL.createObjectURL(data)
+ },
+ rename: async (transactionId: string, attachmentId: string, filename: string): Promise<Attachment> => {
+ const { data } = await api.patch(`/transactions/${transactionId}/attachments/${attachmentId}`, { filename })
+ return data
+ },
+ delete: async (transactionId: string, attachmentId: string): Promise<void> => {
+ await api.delete(`/transactions/${transactionId}/attachments/${attachmentId}`)
+ },
+ },
}
// Categorization Rules
@@ -474,6 +500,14 @@ export const importLogs = {
},
}
+// Settings
+export const settings = {
+ attachments: async (): Promise<{ allowed_extensions: string[]; max_file_size_mb: number; max_attachments_per_transaction: number }> => {
+ const { data } = await api.get('/settings/attachments')
+ return data
+ },
+}
+
// Backup
export const backup = {
download: async (): Promise<void> => {
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 758ce599..71193b14 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -137,7 +137,19 @@
"exchangeRate": "Exchange rate",
"autoCalculated": "auto",
"fxFallbackTooltip": "Rate unavailable — using 1:1 fallback. Edit to set manually.",
- "fxFallbackBanner": "Exchange rate unavailable — using fallback (1:1). Set the rate manually or check your FX provider settings."
+ "fxFallbackBanner": "Exchange rate unavailable — using fallback (1:1). Set the rate manually or check your FX provider settings.",
+ "attachments": "Attachments",
+ "attachmentsUpload": "Drop files here or click to upload",
+ "attachmentsUploading": "Uploading...",
+ "attachmentsEmpty": "No attachments yet",
+ "attachmentUploaded": "Attachment uploaded",
+ "attachmentDeleted": "Attachment deleted",
+ "attachmentDeleteConfirm": "Delete this attachment?",
+ "attachmentTooLarge": "File is too large. Maximum size is 10 MB.",
+ "attachmentTypeNotAllowed": "File type not supported. Allowed: jpg, jpeg, png, webp, gif, heic, pdf",
+ "attachmentMaxReached": "Maximum number of attachments reached",
+ "attachmentRenamed": "Attachment renamed",
+ "attachmentRename": "Rename"
},
"accounts": {
"title": "Accounts",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index eceb7406..af189913 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -137,7 +137,19 @@
"exchangeRate": "Taxa de câmbio",
"autoCalculated": "automático",
"fxFallbackTooltip": "Taxa indisponível — usando fallback 1:1. Edite para definir manualmente.",
- "fxFallbackBanner": "Taxa de câmbio indisponível — usando fallback (1:1). Defina manualmente ou verifique as configurações do provedor de câmbio."
+ "fxFallbackBanner": "Taxa de câmbio indisponível — usando fallback (1:1). Defina manualmente ou verifique as configurações do provedor de câmbio.",
+ "attachments": "Anexos",
+ "attachmentsUpload": "Arraste arquivos aqui ou clique para enviar",
+ "attachmentsUploading": "Enviando...",
+ "attachmentsEmpty": "Nenhum anexo ainda",
+ "attachmentUploaded": "Anexo enviado",
+ "attachmentDeleted": "Anexo excluído",
+ "attachmentDeleteConfirm": "Excluir este anexo?",
+ "attachmentTooLarge": "Arquivo muito grande. Tamanho máximo: 10 MB.",
+ "attachmentTypeNotAllowed": "Tipo de arquivo não suportado. Permitidos: jpg, jpeg, png, webp, gif, heic, pdf",
+ "attachmentMaxReached": "Número máximo de anexos atingido",
+ "attachmentRenamed": "Anexo renomeado",
+ "attachmentRename": "Renomear"
},
"accounts": {
"title": "Contas",
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index 3871ead9..e7f36d51 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -8,7 +8,7 @@ import { toast } from 'sonner'
import type { Transaction } from '@/types'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
-import { ArrowLeft, ArrowLeftRight, Clock, X } from 'lucide-react'
+import { ArrowLeft, ArrowLeftRight, Clock, Paperclip, X } from 'lucide-react'
import { CategoryIcon } from '@/components/category-icon'
import { TransactionDialog, extractApiError } from '@/components/transaction-dialog'
import { DatePickerInput } from '@/components/ui/date-picker-input'
@@ -413,6 +413,9 @@ export default function AccountDetailPage() {
{t('transactions.pending')}
</span>
)}
+ {(tx.attachment_count ?? 0) > 0 && (
+ <Paperclip size={12} className="ml-2 inline text-muted-foreground" />
+ )}
</div>
{tx.payee && tx.payee !== tx.description && (
<p className="text-xs text-muted-foreground mt-0.5">{tx.payee}</p>
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index 8c54aad7..1b89c89c 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -25,7 +25,7 @@ import {
Tooltip,
ResponsiveContainer,
} from 'recharts'
-import { CheckCircle2, CalendarIcon } from 'lucide-react'
+import { CheckCircle2, CalendarIcon, Paperclip } from 'lucide-react'
import { PageHeader } from '@/components/page-header'
import { CategoryIcon } from '@/components/category-icon'
import { TransactionDrillDown, type DrillDownFilter } from '@/components/transaction-drill-down'
@@ -258,6 +258,7 @@ export default function DashboardPage() {
categoryName: string | null
categoryColor: string | null
isProjected: boolean
+ attachmentCount: number
}
const TX_PER_PAGE = 10
@@ -276,6 +277,7 @@ export default function DashboardPage() {
categoryName: tx.category?.name ?? null,
categoryColor: tx.category?.color ?? null,
isProjected: false,
+ attachmentCount: tx.attachment_count ?? 0,
})
}
for (const pt of projectedTxs ?? []) {
@@ -291,6 +293,7 @@ export default function DashboardPage() {
categoryName: pt.category_name,
categoryColor: pt.category_color ?? null,
isProjected: true,
+ attachmentCount: 0,
})
}
rows.sort((a, b) => a.date.localeCompare(b.date))
@@ -766,6 +769,9 @@ export default function DashboardPage() {
{t('transactions.recurringBadge')}
</span>
)}
+ {row.attachmentCount > 0 && (
+ <Paperclip size={12} className="text-muted-foreground shrink-0" />
+ )}
</div>
<p className="text-xs text-muted-foreground">{formatDate(row.date, locale)}</p>
</div>
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index 062f6f9d..2f0c13d8 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -14,7 +14,7 @@ import {
} from '@/components/ui/table'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
-import { AlertTriangle, Check, Download, Search, X } from 'lucide-react'
+import { AlertTriangle, Check, Download, Paperclip, Search, X } from 'lucide-react'
import type { Transaction } from '@/types'
import { PageHeader } from '@/components/page-header'
import { CategoryIcon } from '@/components/category-icon'
@@ -375,6 +375,9 @@ export default function TransactionsPage() {
{t('transactions.recurringBadge')}
</span>
)}
+ {(tx.attachment_count ?? 0) > 0 && (
+ <Paperclip size={12} className="text-muted-foreground shrink-0" />
+ )}
</div>
<p className="text-xs text-muted-foreground mt-0.5">{new Date(tx.date + 'T00:00:00').toLocaleDateString(locale)}</p>
{tx.notes && (
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 66f63a8a..35ed1c22 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -94,6 +94,7 @@ export interface Transaction {
amount_primary: number | null
fx_rate_used: number | null
fx_fallback: boolean
+ attachment_count?: number
}
export interface RuleCondition {
@@ -313,6 +314,15 @@ export interface CategoryTrendItem {
series: ReportDataPoint[]
}
+export interface Attachment {
+ id: string
+ transaction_id: string
+ filename: string
+ content_type: string
+ size: number
+ created_at: string
+}
+
export interface ReportResponse {
summary: ReportSummary
trend: ReportDataPoint[]