Skip to content

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

feat: repeat manual transactions as installment series (#524)

Leonardo Zanivana28b34745096
diff --git a/backend/alembic/versions/069_transaction_installment_series_id.py b/backend/alembic/versions/069_transaction_installment_series_id.py
new file mode 100644
index 00000000..7e33d025
--- /dev/null
+++ b/backend/alembic/versions/069_transaction_installment_series_id.py
@@ -0,0 +1,46 @@
+"""add stable ids to manual installment series
+
+Revision ID: 069
+Revises: 068
+Create Date: 2026-08-12
+
+Manual installment rows created by the series endpoint share one UUID. The
+existing installment metadata remains available for provider sync deduplication
+and for legacy rows that predate this migration.
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import postgresql
+
+
+revision: str = "069"
+down_revision: Union[str, None] = "068"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "transactions",
+ sa.Column(
+ "installment_series_id",
+ postgresql.UUID(as_uuid=True),
+ nullable=True,
+ ),
+ )
+ op.create_index(
+ "ix_transactions_installment_series_id",
+ "transactions",
+ ["installment_series_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index(
+ "ix_transactions_installment_series_id",
+ table_name="transactions",
+ )
+ op.drop_column("transactions", "installment_series_id")
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 6bbaf462..eea4fb25 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -15,7 +15,7 @@ from app.core.workspace_context import (
current_workspace,
current_writable_workspace,
)
-from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, BulkTagsRequest, CreateCounterpartRequest, LinkTransferRequest, TransactionBulkDeleteRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead
+from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, BulkTagsRequest, CreateCounterpartRequest, InstallmentSeriesCreate, LinkTransferRequest, TransactionBulkDeleteRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead
from app.schemas.transaction_calendar import TransactionCalendarResponse
from app.services import transaction_service
from app.services.admin_service import get_credit_card_accounting_mode
@@ -420,6 +420,27 @@ async def get_transaction(
return _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)
[email protected]("/installments", response_model=list[TransactionRead], status_code=status.HTTP_201_CREATED)
+async def create_installment_series(
+ data: InstallmentSeriesCreate,
+ ctx: WorkspaceContext = Depends(current_writable_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Create a manual installment series: repeats the base transaction
+ N times, each parcel carrying the shared installment fingerprint."""
+ try:
+ created = await transaction_service.create_installment_series(
+ session, ctx.workspace.id, ctx.user_id, data
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ primary_currency = ctx.user.primary_currency
+ return [
+ _tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency)
+ for tx in created
+ ]
+
+
@router.post("", response_model=TransactionRead, status_code=status.HTTP_201_CREATED)
async def create_transaction(
data: TransactionCreate,
@@ -493,11 +514,12 @@ async def unlink_recurring_transaction(
@router.delete("/{transaction_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_transaction(
transaction_id: uuid.UUID,
+ apply_to: str = Query("this", regex="^(this|future|all)$", description="Installment-series scope: this row only (default), this + later installments, or the whole series. Ignored for non-installment transactions."),
ctx: WorkspaceContext = Depends(current_writable_workspace),
session: AsyncSession = Depends(get_async_session),
):
deleted = await transaction_service.delete_transaction(
- session, transaction_id, ctx.workspace.id
+ session, transaction_id, ctx.workspace.id, apply_to
)
if not deleted:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")
diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.py
index 2e39b8eb..3a85e553 100644
--- a/backend/app/models/transaction.py
+++ b/backend/app/models/transaction.py
@@ -68,6 +68,12 @@ class Transaction(Base):
Numeric(precision=15, scale=2), nullable=True
)
installment_purchase_date: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)
+ # Stable identity for rows created by the manual installment-series
+ # endpoint. Provider-synced installment rows leave this null because their
+ # metadata is only a deduplication fingerprint, not a series identifier.
+ installment_series_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), nullable=True, index=True
+ )
# User-set manual override for which bill cycle this tx belongs to. Null
# by default; only meaningful for credit-card accounts. When set, beats
# both Pluggy's billId and the cycle-math fallback (issue #92, the
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index f6bf5d34..fc76f640 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -39,6 +39,52 @@ class TransactionCreate(TransactionBase):
# (not yet settled) to record an entry that isn't settled yet. Only
# posted/pending are valid.
status: Optional[Literal["posted", "pending"]] = None
+ # Manual installment metadata. When present, this transaction is one
+ # installment of a manually-created series (created via the regular
+ # endpoint, e.g. a single installment, or via the series endpoint
+ # which fans out a payload into N rows). All four fields must be set
+ # together (validated below).
+ installment_number: Optional[int] = Field(default=None, ge=1)
+ total_installments: Optional[int] = Field(default=None, ge=1)
+ installment_total_amount: Optional[Decimal] = None
+ installment_purchase_date: Optional[_Date] = None
+
+ @model_validator(mode="after")
+ def validate_installment_fields(self):
+ installment_number = self.installment_number
+ total_installments = self.total_installments
+ installment_total_amount = self.installment_total_amount
+ installment_purchase_date = self.installment_purchase_date
+ provided = [
+ installment_number is not None,
+ total_installments is not None,
+ installment_total_amount is not None,
+ installment_purchase_date is not None,
+ ]
+ if any(provided) and not all(provided):
+ raise ValueError(
+ "installment_number, total_installments, installment_total_amount and "
+ "installment_purchase_date must be provided together"
+ )
+ if (
+ installment_number is not None
+ and total_installments is not None
+ and installment_total_amount is not None
+ and installment_purchase_date is not None
+ ):
+ if installment_number > total_installments:
+ raise ValueError(
+ "installment_number must be between 1 and total_installments"
+ )
+ if installment_total_amount <= 0:
+ raise ValueError("installment_total_amount must be positive")
+ # The purchase date is the date of the first installment, so a
+ # given installment can never predate it.
+ if installment_purchase_date > self.date:
+ raise ValueError(
+ "installment_purchase_date cannot be after the transaction date"
+ )
+ return self
class TransactionUpdate(BaseModel):
@@ -65,6 +111,31 @@ class TransactionUpdate(BaseModel):
# When provided, replaces the transaction's splits wholesale. Pass
# an object with an empty `splits` list to clear them.
splits: Optional[TransactionSplitsInput] = None
+ # Installment-series scope for edits. "this" (default) only touches the
+ # target row; "future" touches it plus all later installments of the
+ # same series; "all" touches every row in the series. Ignored when the
+ # transaction has no installment fingerprint.
+ apply_to: Literal["this", "future", "all"] = "this"
+
+
+class InstallmentSeriesCreate(BaseModel):
+ """Payload for POST /api/transactions/installments — repeats a purchase
+ as ``installments`` equal payments."""
+
+ base: TransactionCreate
+ installments: int = Field(ge=2, le=360, description="Number of parcels (>= 2)")
+ # Status of the first installment; subsequent ones are created "pending".
+ first_installment_status: Literal["posted", "pending"] = "posted"
+ # Period between installments. Defaults to monthly. Matches the
+ # recurring-transaction frequencies so "repeat as installments" offers
+ # the same cadence choices as a recurring bill.
+ frequency: Literal["monthly", "quarterly", "weekly", "yearly"] = "monthly"
+
+ @model_validator(mode="after")
+ def validate_amounts(self):
+ if self.base.amount <= 0:
+ raise ValueError("amount must be positive")
+ return self
class TransactionRead(TransactionBase):
@@ -89,6 +160,7 @@ class TransactionRead(TransactionBase):
total_installments: Optional[int] = None
installment_total_amount: Optional[float] = None
installment_purchase_date: Optional[_Date] = None
+ installment_series_id: Optional[uuid.UUID] = None
bill_id: Optional[uuid.UUID] = None
effective_bill_date: Optional[_Date] = None
recurring_transaction_id: Optional[uuid.UUID] = None
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index 13084f07..261294ad 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -15,13 +15,19 @@ from app.models.bank_connection import BankConnection
from app.models.category import Category
from app.models.group import Group, GroupMember
from app.models.payee import Payee
-from app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate
+from app.schemas.transaction import (
+ InstallmentSeriesCreate,
+ TransactionCreate,
+ TransactionUpdate,
+ TransferCreate,
+)
from app.schemas.transaction_split import TransactionSplitInput, TransactionSplitsInput
from app.services import split_service
from app.services.credit_card_service import apply_effective_date
from app.services.rule_service import apply_rules_to_transaction
from app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert
from app.services._query_filters import counts_as_pnl, counts_as_user_pnl, reporting_date_col
+from app.services.recurring_transaction_service import _advance_date
async def _ensure_category_in_workspace(
@@ -710,6 +716,10 @@ async def create_transaction(
status=data.status or "posted",
notes=data.notes,
effective_bill_date=data.effective_bill_date,
+ installment_number=data.installment_number,
+ total_installments=data.total_installments,
+ installment_total_amount=data.installment_total_amount,
+ installment_purchase_date=data.installment_purchase_date,
)
if data.effective_bill_date is not None:
await _resync_bill_link_from_override(session, transaction, account)
@@ -735,6 +745,108 @@ async def create_transaction(
return transaction
+async def create_installment_series(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ data: InstallmentSeriesCreate,
+) -> list[Transaction]:
+ """Create a manual installment series.
+
+ Repeats ``data.base`` ``data.installments`` times: every parcel stores
+ the base amount, date advanced by the given frequency (monthly/quarterly/
+ weekly/yearly, matching recurring transactions), and the shared
+ installment fingerprint (account, installment_purchase_date,
+ total_installments, installment_total_amount = amount * installments)
+ plus its 1-based installment_number, so the existing sync dedup matches
+ bank-synced installments against these rows. The first parcel uses the
+ requested status ("posted" by default); subsequent ones are created
+ "pending". Month-end clamping is handled by the shared recurrence helper.
+ """
+ base = data.base
+ n = data.installments
+
+ # Verify account belongs to the workspace (mirrors create_transaction)
+ account_result = await session.execute(
+ select(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Account.id == base.account_id,
+ or_(
+ Account.workspace_id == workspace_id,
+ BankConnection.workspace_id == workspace_id,
+ ),
+ )
+ )
+ account = account_result.scalar_one_or_none()
+ if not account:
+ raise ValueError("Account not found")
+
+ await _ensure_category_in_workspace(session, workspace_id, base.category_id)
+ await _ensure_payee_in_workspace(session, workspace_id, base.payee_id)
+
+ total = base.amount * n
+ currency = base.currency or account.currency
+ purchase_date = base.date
+ intended_day = base.date.day
+ series_id = uuid.uuid4()
+
+ created: list[Transaction] = []
+ installment_date = base.date
+ for i in range(1, n + 1):
+ if i > 1:
+ installment_date = _advance_date(
+ installment_date, data.frequency, intended_day=intended_day
+ )
+
+ tx = Transaction(
+ user_id=user_id,
+ workspace_id=workspace_id,
+ account_id=base.account_id,
+ category_id=base.category_id,
+ payee_id=base.payee_id,
+ description=base.description,
+ amount=base.amount,
+ currency=currency,
+ date=installment_date,
+ type=base.type,
+ source="manual",
+ status=data.first_installment_status if i == 1 else "pending",
+ notes=base.notes,
+ effective_bill_date=base.effective_bill_date,
+ installment_number=i,
+ total_installments=n,
+ installment_total_amount=total,
+ installment_purchase_date=purchase_date,
+ installment_series_id=series_id,
+ )
+ if base.effective_bill_date is not None:
+ await _resync_bill_link_from_override(session, tx, account)
+ apply_effective_date(tx, account)
+ session.add(tx)
+ await session.flush() # get ID without committing
+ created.append(tx)
+
+ # Rules, FX stamping and splits run after every row has an ID so each
+ # parcel is finalized exactly like a single manual transaction.
+ for tx in created:
+ if not base.category_id:
+ await apply_rules_to_transaction(session, user_id, tx)
+ if base.fx_rate_used is not None:
+ _apply_fx_override(tx, tx.amount, None, base.fx_rate_used)
+ elif base.amount_primary is not None:
+ _apply_fx_override(tx, tx.amount, base.amount_primary, None)
+ else:
+ await stamp_primary_amount(session, user_id, tx)
+ if base.splits is not None:
+ await split_service.replace_splits(session, tx, base.splits, user_id)
+
+ await session.commit()
+ for tx in created:
+ await session.refresh(tx, ["category", "splits"])
+ return created
+
+
async def create_transfer(
session: AsyncSession,
workspace_id: uuid.UUID,
@@ -1171,123 +1283,153 @@ async def _resync_bill_link_from_override(
transaction.bill_id = None
-async def update_transaction(
+def _is_installment(tx: Transaction) -> bool:
+ """Whether a row carries a manual/synced installment fingerprint."""
+ return (
+ tx.installment_number is not None
+ and tx.total_installments is not None
+ and tx.installment_purchase_date is not None
+ )
+
+
+async def _get_series_transactions(
session: AsyncSession,
- transaction_id: uuid.UUID,
workspace_id: uuid.UUID,
- user_id: uuid.UUID,
- data: TransactionUpdate,
-) -> Optional[Transaction]:
- transaction = await get_transaction(session, transaction_id, workspace_id)
- if not transaction:
- return None
+ tx: Transaction,
+ apply_to: str,
+) -> list[Transaction]:
+ """Return the sibling installments of ``tx``'s series, ordered by number.
- update_data = data.model_dump(exclude_unset=True)
- apply_to_transfer_pair = update_data.pop("apply_to_transfer_pair", False)
+ Manual series identity is the stable ``installment_series_id`` assigned
+ when the series is created. Legacy/provider-synced rows without that ID
+ retain the historical fingerprint fallback used by sync deduplication.
+ For "future" only rows with installment_number >= the anchor's are
+ returned.
+ """
+ if tx.installment_series_id is not None:
+ conditions = [
+ Transaction.workspace_id == workspace_id,
+ Transaction.installment_series_id == tx.installment_series_id,
+ ]
+ else:
+ conditions = [
+ Transaction.workspace_id == workspace_id,
+ Transaction.account_id == tx.account_id,
+ Transaction.installment_purchase_date == tx.installment_purchase_date,
+ Transaction.total_installments == tx.total_installments,
+ ]
+ if apply_to == "future":
+ conditions.append(Transaction.installment_number >= tx.installment_number)
+ result = await session.execute(
+ select(Transaction).where(*conditions).order_by(Transaction.installment_number)
+ )
+ return list(result.scalars().all())
- # Splits are processed separately after column updates land so the
- # service can validate against the new amount.
- splits_payload = data.splits if "splits" in update_data else None
- update_data.pop("splits", None)
- # Verify the new account belongs to the workspace before touching the
- # row. When changing the account on one side of a transfer pair,
- # refuse to collide with the paired transaction's account (a transfer
- # must have two distinct accounts).
- new_account_id = update_data.get("account_id")
- if new_account_id is not None and new_account_id != transaction.account_id:
- account_result = await session.execute(
- select(Account)
- .outerjoin(BankConnection)
- .where(
- Account.id == new_account_id,
- or_(
- Account.workspace_id == workspace_id,
- BankConnection.workspace_id == workspace_id,
- ),
- )
+async def _resync_installment_series_total(
+ session: AsyncSession, workspace_id: uuid.UUID, tx: Transaction
+) -> None:
+ """Keep ``installment_total_amount`` equal to the sum of the parcels.
+
+ Editing a parcel's amount (with any scope) changes what the series is
+ worth, and the stored total is what the transaction list renders in its
+ installment tooltip. Only series carrying a series id are recomputed:
+ for provider-synced rows the total is the bank's own figure and must
+ stay as reported.
+ """
+ if tx.installment_series_id is None:
+ return
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.workspace_id == workspace_id,
+ Transaction.installment_series_id == tx.installment_series_id,
)
- if account_result.scalar_one_or_none() is None:
- raise ValueError("Account not found")
+ )
+ siblings = list(result.scalars().all())
+ if not siblings:
+ return
+ total = sum((row.amount for row in siblings), Decimal("0"))
+ for row in siblings:
+ row.installment_total_amount = total
- if transaction.transfer_pair_id:
- paired_result = await session.execute(
- select(Transaction).where(
- Transaction.transfer_pair_id == transaction.transfer_pair_id,
- Transaction.id != transaction.id,
- )
- )
- paired_tx = paired_result.scalar_one_or_none()
- if paired_tx and paired_tx.account_id == new_account_id:
- raise ValueError("Cannot move transfer to the same account as its paired transaction")
- if "category_id" in update_data:
- await _ensure_category_in_workspace(session, workspace_id, update_data["category_id"])
- if "payee_id" in update_data:
- await _ensure_payee_in_workspace(session, workspace_id, update_data["payee_id"])
+async def _apply_update_to_row(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ tx: Transaction,
+ update_data: dict,
+ apply_to_transfer_pair: bool,
+ splits_payload: Optional[TransactionSplitsInput],
+) -> None:
+ """Apply a parsed TransactionUpdate payload to a single row.
- # Pop FX override fields before generic setattr loop
+ Shared by single-row edits and installment-series scoped edits so both
+ paths behave identically (FX restamp, bill re-link, transfer cascade,
+ splits replacement).
+ """
has_fx_override = "amount_primary" in update_data or "fx_rate_used" in update_data
- override_amount_primary = update_data.pop("amount_primary", None)
- override_fx_rate = update_data.pop("fx_rate_used", None)
+ override_amount_primary = update_data.get("amount_primary")
+ override_fx_rate = update_data.get("fx_rate_used")
+
+ fx_keys = {"amount_primary", "fx_rate_used"}
+ for key, value in update_data.items():
+ if key in fx_keys:
+ continue
+ setattr(tx, key, value)
restamp_fields = {"amount", "currency", "date"}
needs_restamp = bool(restamp_fields & update_data.keys())
- for key, value in update_data.items():
- setattr(transaction, key, value)
-
if has_fx_override:
if override_amount_primary is None and override_fx_rate is None:
- transaction.amount_primary = None
- transaction.fx_rate_used = None
- await stamp_primary_amount(session, user_id, transaction)
+ tx.amount_primary = None
+ tx.fx_rate_used = None
+ await stamp_primary_amount(session, user_id, tx)
else:
_apply_fx_override(
- transaction,
- transaction.amount,
+ tx,
+ tx.amount,
override_amount_primary,
override_fx_rate,
)
elif needs_restamp:
- await stamp_primary_amount(session, user_id, transaction)
+ await stamp_primary_amount(session, user_id, tx)
# Refresh effective_date when the purchase date, account, or the manual
# bill-cycle override changed. Also re-link bill_id when the override
# changed so the tx moves into the right cycle (issue #92 manual override).
if "date" in update_data or "account_id" in update_data or "effective_bill_date" in update_data:
- account_for_tx = await session.get(Account, transaction.account_id)
+ account_for_tx = await session.get(Account, tx.account_id)
if "effective_bill_date" in update_data:
- await _resync_bill_link_from_override(session, transaction, account_for_tx)
- apply_effective_date(transaction, account_for_tx)
+ await _resync_bill_link_from_override(session, tx, account_for_tx)
+ apply_effective_date(tx, account_for_tx)
# Cascade changes to paired transfer transaction
cascade_fields = {"amount", "date", "description", "notes"}
should_cascade_category = apply_to_transfer_pair and "category_id" in update_data
- if transaction.transfer_pair_id and ((cascade_fields & update_data.keys()) or should_cascade_category):
+ if tx.transfer_pair_id and ((cascade_fields & update_data.keys()) or should_cascade_category):
paired = await session.execute(
select(Transaction).where(
- Transaction.transfer_pair_id == transaction.transfer_pair_id,
- Transaction.id != transaction.id,
+ Transaction.transfer_pair_id == tx.transfer_pair_id,
+ Transaction.id != tx.id,
)
)
paired_tx = paired.scalar_one_or_none()
if paired_tx:
if should_cascade_category:
- paired_tx.category_id = transaction.category_id
+ paired_tx.category_id = tx.category_id
# When the user typed both amounts, neither is a conversion of the
# other: correcting one leg leaves the amount that actually landed
# on the other account untouched. Re-converting here would throw
# away the number the user entered (issue #529).
- keeps_own_amount = transaction.transfer_amount_explicit or paired_tx.transfer_amount_explicit
+ keeps_own_amount = tx.transfer_amount_explicit or paired_tx.transfer_amount_explicit
for key in cascade_fields & update_data.keys():
- if key == "amount" and paired_tx.currency != transaction.currency:
+ if key == "amount" and paired_tx.currency != tx.currency:
if keeps_own_amount:
continue
- from decimal import Decimal
converted, _ = await fx_convert(
- session, Decimal(str(transaction.amount)),
- transaction.currency, paired_tx.currency, transaction.date,
+ session, Decimal(str(tx.amount)),
+ tx.currency, paired_tx.currency, tx.date,
)
paired_tx.amount = converted
elif key != "amount":
@@ -1300,7 +1442,126 @@ async def update_transaction(
apply_effective_date(paired_tx, paired_account)
if splits_payload is not None:
- await split_service.replace_splits(session, transaction, splits_payload, user_id)
+ await split_service.replace_splits(session, tx, splits_payload, user_id)
+
+
+async def update_transaction(
+ session: AsyncSession,
+ transaction_id: uuid.UUID,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ data: TransactionUpdate,
+) -> Optional[Transaction]:
+ transaction = await get_transaction(session, transaction_id, workspace_id)
+ if not transaction:
+ return None
+
+ update_data = data.model_dump(exclude_unset=True)
+ apply_to_transfer_pair = update_data.pop("apply_to_transfer_pair", False)
+ apply_to = update_data.pop("apply_to", "this")
+
+ # Splits are processed separately after column updates land so the
+ # service can validate against the new amount.
+ splits_payload = data.splits if "splits" in update_data else None
+ update_data.pop("splits", None)
+
+ # Verify the new account belongs to the workspace before touching the
+ # row. When changing the account on one side of a transfer pair,
+ # refuse to collide with the paired transaction's account (a transfer
+ # must have two distinct accounts).
+ new_account_id = update_data.get("account_id")
+ if new_account_id is not None and new_account_id != transaction.account_id:
+ account_result = await session.execute(
+ select(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Account.id == new_account_id,
+ or_(
+ Account.workspace_id == workspace_id,
+ BankConnection.workspace_id == workspace_id,
+ ),
+ )
+ )
+ if account_result.scalar_one_or_none() is None:
+ raise ValueError("Account not found")
+
+ if transaction.transfer_pair_id:
+ paired_result = await session.execute(
+ select(Transaction).where(
+ Transaction.transfer_pair_id == transaction.transfer_pair_id,
+ Transaction.id != transaction.id,
+ )
+ )
+ paired_tx = paired_result.scalar_one_or_none()
+ if paired_tx and paired_tx.account_id == new_account_id:
+ raise ValueError("Cannot move transfer to the same account as its paired transaction")
+
+ if "category_id" in update_data:
+ await _ensure_category_in_workspace(session, workspace_id, update_data["category_id"])
+ if "payee_id" in update_data:
+ await _ensure_payee_in_workspace(session, workspace_id, update_data["payee_id"])
+
+ # Series scope. "future"/"all" expand the edit to sibling installments;
+ # ignored entirely for rows without an installment fingerprint.
+ #
+ # Scoped edits only repeat the fields that make sense across a series:
+ # description, amount, currency (+FX override), category, type, payee,
+ # account, and notes. Everything else — date, status, ignore flag,
+ # bill-cycle override, splits — stays untouched on sibling installments
+ # so editing one parcel's bookkeeping never bleeds into the rest.
+ # Account moves ride along so the whole series lands on the new
+ # account together (the fingerprint stays coherent across the rows).
+ installment_scoped_fields = frozenset(
+ {
+ "description",
+ "amount",
+ "currency",
+ "amount_primary",
+ "fx_rate_used",
+ "category_id",
+ "type",
+ "payee_id",
+ "account_id",
+ "notes",
+ }
+ )
+ rows = [transaction]
+ scoped_update = None
+ if apply_to != "this" and _is_installment(transaction):
+ rows = await _get_series_transactions(session, workspace_id, transaction, apply_to)
+ scoped_update = {
+ k: v for k, v in update_data.items() if k in installment_scoped_fields
+ }
+
+ for row in rows:
+ # The edited transaction itself reflects the full form payload; the
+ # sibling installments only receive the whitelisted fields (and keep
+ # their own date, status, bill-cycle, and split bookkeeping).
+ is_anchor = row.id == transaction.id
+ if is_anchor:
+ row_update = update_data
+ row_splits = splits_payload
+ else:
+ # Non-anchor rows only exist in the scoped branch above, where
+ # scoped_update is always built.
+ assert scoped_update is not None
+ row_update = scoped_update
+ row_splits = None
+ await _apply_update_to_row(
+ session,
+ user_id,
+ row,
+ row_update,
+ apply_to_transfer_pair,
+ row_splits,
+ )
+
+ # A changed parcel amount makes the stored series total stale, whatever
+ # the scope was: "this" reprices one parcel, "future"/"all" reprice
+ # several. Recompute from the rows themselves so the two always agree.
+ if "amount" in update_data and _is_installment(transaction):
+ await session.flush()
+ await _resync_installment_series_total(session, workspace_id, transaction)
await session.commit()
await session.refresh(transaction, ["category", "payee_entity", "splits"])
@@ -1554,34 +1815,47 @@ async def delete_transaction(
session: AsyncSession,
transaction_id: uuid.UUID,
workspace_id: uuid.UUID,
+ apply_to: str = "this",
) -> bool:
+ """Delete a transaction. For rows in an installment series, ``apply_to``
+ may be "future" (this row + all later installments) or "all" (every row
+ in the series); otherwise only the single row is removed. Paired transfer
+ legs are cascade-deleted as before. Returns False when not found."""
transaction = await get_transaction(session, transaction_id, workspace_id)
if not transaction:
return False
+ # Expand to sibling installments when the caller asked for a scoped
+ # delete and the row is part of a series.
+ rows: list[Transaction] = [transaction]
+ if apply_to != "this" and _is_installment(transaction):
+ rows = await _get_series_transactions(session, workspace_id, transaction, apply_to)
+
# Clean up attachment files from storage before ORM cascade deletes DB records
from app.services.attachment_service import cleanup_attachment_files
- tx_ids_to_cleanup = [transaction_id]
-
- # Cascade delete paired transfer transaction
- paired_tx = None
- if transaction.transfer_pair_id:
- paired_result = await session.execute(
- select(Transaction).where(
- Transaction.transfer_pair_id == transaction.transfer_pair_id,
- Transaction.id != transaction.id,
+ tx_ids_to_cleanup: list[uuid.UUID] = []
+ paired_txs: list[Transaction] = []
+ for row in rows:
+ tx_ids_to_cleanup.append(row.id)
+ if row.transfer_pair_id:
+ paired_result = await session.execute(
+ select(Transaction).where(
+ Transaction.transfer_pair_id == row.transfer_pair_id,
+ Transaction.id != row.id,
+ )
)
- )
- paired_tx = paired_result.scalar_one_or_none()
- if paired_tx:
- tx_ids_to_cleanup.append(paired_tx.id)
+ paired_tx = paired_result.scalar_one_or_none()
+ if paired_tx and paired_tx.id not in tx_ids_to_cleanup:
+ tx_ids_to_cleanup.append(paired_tx.id)
+ paired_txs.append(paired_tx)
await cleanup_attachment_files(session, tx_ids_to_cleanup)
- if paired_tx:
+ for paired_tx in paired_txs:
await session.delete(paired_tx)
- await session.delete(transaction)
+ for row in rows:
+ await session.delete(row)
await session.commit()
return True
diff --git a/backend/tests/test_transaction_installments.py b/backend/tests/test_transaction_installments.py
new file mode 100644
index 00000000..c994ed69
--- /dev/null
+++ b/backend/tests/test_transaction_installments.py
@@ -0,0 +1,879 @@
+"""Tests for manual installment transactions.
+
+Covers the series creation helper, the single-installment create path, and
+the this/future/all scoped update + delete behavior.
+"""
+
+import uuid
+from datetime import date, datetime, timezone
+from decimal import Decimal
+
+import pytest
+import pytest_asyncio
+from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+from app.models.transaction_split import TransactionSplit
+from app.schemas.group import GroupCreate, GroupMemberCreate
+from app.schemas.transaction import (
+ InstallmentSeriesCreate,
+ TransactionCreate,
+ TransactionUpdate,
+)
+from app.schemas.transaction_split import TransactionSplitInput, TransactionSplitsInput
+from app.services import group_service
+from app.services.transaction_service import (
+ create_installment_series,
+ create_transaction,
+ delete_transaction,
+ get_transaction,
+ update_transaction,
+)
+
+
+@pytest_asyncio.fixture
+async def installment_account(session: AsyncSession, test_user) -> Account:
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Installment Acc",
+ type="checking",
+ balance=Decimal("10000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+def _series_payload(account: Account, **overrides) -> InstallmentSeriesCreate:
+ base = {
+ "description": "Notebook",
+ "amount": Decimal("100.00"),
+ "date": date(2026, 1, 15),
+ "type": "debit",
+ "account_id": account.id,
+ }
+ base.update(overrides.pop("base", {}))
+ return InstallmentSeriesCreate(base=base, **overrides)
+
+
+def _transaction(account: Account, **overrides) -> Transaction:
+ data = dict(
+ id=uuid.uuid4(),
+ user_id=account.user_id,
+ account_id=account.id,
+ description="Parcela",
+ amount=Decimal("100.00"),
+ date=date(2026, 1, 15),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ data.update(overrides)
+ return Transaction(**data)
+
+
+# ---------------------------------------------------------------------------
+# create_installment_series — helper behavior
+# ---------------------------------------------------------------------------
+
+
+async def test_create_installment_series_monthly_defaults(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+
+ assert len(created) == 3
+ numbers = [t.installment_number for t in created]
+ assert numbers == [1, 2, 3]
+ assert all(t.installment_series_id is not None for t in created)
+ assert len({t.installment_series_id for t in created}) == 1
+ for tx in created:
+ assert tx.total_installments == 3
+ assert tx.installment_total_amount == Decimal("300.00")
+ assert tx.installment_purchase_date == date(2026, 1, 15)
+ assert tx.account_id == installment_account.id
+ assert tx.description == "Notebook"
+ assert tx.source == "manual"
+
+ # Default total = amount * n, so equal split keeps per-parcel == typed amount.
+ assert [t.amount for t in created] == [
+ Decimal("100.00"),
+ Decimal("100.00"),
+ Decimal("100.00"),
+ ]
+ # First installment posted, later ones pending.
+ assert created[0].status == "posted"
+ assert created[1].status == "pending"
+ assert created[2].status == "pending"
+ # Dates advance monthly.
+ assert [t.date for t in created] == [
+ date(2026, 1, 15),
+ date(2026, 2, 15),
+ date(2026, 3, 15),
+ ]
+
+
+async def test_create_installment_series_repeats_amount_for_every_parcel(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ # "Repeat as installments": no total is split — every parcel stores the
+ # base amount as-is, even for a large count where rounding a split total
+ # could otherwise produce a negative or zero last parcel.
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(
+ installment_account,
+ installments=360,
+ base={"amount": Decimal("100.00")},
+ ),
+ )
+
+ assert len(created) == 360
+ assert all(t.amount == Decimal("100.00") for t in created)
+ assert sum(t.amount for t in created) == Decimal("36000.00")
+ assert all(t.installment_total_amount == Decimal("36000.00") for t in created)
+
+
+async def test_create_installment_series_repeats_amount_primary_per_parcel(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ # FX override rides along on the series base: every parcel stores the
+ # base amount_primary as-is and derives the same rate, matching the
+ # single-transaction create path.
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(
+ installment_account,
+ installments=3,
+ base={"amount_primary": Decimal("200.00")},
+ ),
+ )
+
+ assert len(created) == 3
+ for tx in created:
+ assert tx.amount == Decimal("100.00")
+ assert tx.amount_primary == Decimal("200.00")
+ assert tx.fx_rate_used == Decimal("2")
+ # Identical across parcels, not re-derived proportionally per parcel.
+ assert len({t.fx_rate_used for t in created}) == 1
+
+
+async def test_create_installment_series_weekly(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(installment_account, installments=3, frequency="weekly"),
+ )
+ assert [t.date for t in created] == [
+ date(2026, 1, 15),
+ date(2026, 1, 22),
+ date(2026, 1, 29),
+ ]
+
+
+async def test_create_installment_series_yearly(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(installment_account, installments=2, frequency="yearly"),
+ )
+ assert [t.date for t in created] == [date(2026, 1, 15), date(2027, 1, 15)]
+
+
+async def test_create_installment_series_quarterly(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(installment_account, installments=4, frequency="quarterly"),
+ )
+ # Matches the recurring-transaction cadence so "repeat as installments"
+ # offers the same frequencies as a recurring bill.
+ assert [t.date for t in created] == [
+ date(2026, 1, 15),
+ date(2026, 4, 15),
+ date(2026, 7, 15),
+ date(2026, 10, 15),
+ ]
+
+
+async def test_create_installment_series_month_end_clamping(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(
+ installment_account,
+ base={"date": date(2026, 1, 31)},
+ installments=3,
+ ),
+ )
+ # Jan 31 -> Feb 28 (clamped) -> Mar 31 (recovers to intended day).
+ assert [t.date for t in created] == [
+ date(2026, 1, 31),
+ date(2026, 2, 28),
+ date(2026, 3, 31),
+ ]
+
+
+async def test_create_installment_series_first_status_pending(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(
+ installment_account, installments=2, first_installment_status="pending"
+ ),
+ )
+ assert created[0].status == "pending"
+ assert created[1].status == "pending"
+
+
+async def test_create_installment_series_applies_splits_per_parcel(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ # Split-with-group rides along on the series base; every parcel must be
+ # split the same way the single-transaction path does.
+ group = await group_service.create_group(
+ session, test_workspace.id, test_user.id, GroupCreate(name="Raid")
+ )
+ member_a = await group_service.create_member(
+ session, group.id, test_workspace.id, GroupMemberCreate(name="A")
+ )
+ member_b = await group_service.create_member(
+ session, group.id, test_workspace.id, GroupMemberCreate(name="B")
+ )
+ assert member_a is not None and member_b is not None
+ members = [member_a, member_b]
+
+ created = await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ _series_payload(
+ installment_account,
+ installments=2,
+ base={
+ "splits": TransactionSplitsInput(
+ share_type="equal",
+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],
+ )
+ },
+ ),
+ )
+ assert len(created) == 2
+ for tx in created:
+ rows = (
+ await session.execute(
+ select(TransactionSplit).where(TransactionSplit.transaction_id == tx.id)
+ )
+ ).scalars().all()
+ assert len(rows) == 2
+ by_member = {r.group_member_id: r.share_amount for r in rows}
+ # base.amount is the per-parcel amount (100.00); split equally into
+ # two members = 50.00 each, matching the single-transaction path.
+ assert by_member[members[0].id] == Decimal("50.00")
+ assert by_member[members[1].id] == Decimal("50.00")
+
+
+async def test_create_installment_series_invalid_account(
+ session: AsyncSession, test_user, test_workspace
+):
+ with pytest.raises(ValueError, match="Account not found"):
+ await create_installment_series(
+ session,
+ test_workspace.id,
+ test_user.id,
+ InstallmentSeriesCreate(
+ base=TransactionCreate(
+ description="Orphan",
+ amount=Decimal("10"),
+ date=date(2026, 1, 15),
+ type="debit",
+ account_id=uuid.uuid4(),
+ ),
+ installments=2,
+ ),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Single installment create via the regular endpoint
+# ---------------------------------------------------------------------------
+
+
+async def test_create_single_installment_persists_fingerprint(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ txn = await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ description="Parcela avulsa",
+ amount=Decimal("50.00"),
+ date=date(2026, 2, 10),
+ type="debit",
+ account_id=installment_account.id,
+ installment_number=3,
+ total_installments=6,
+ installment_total_amount=Decimal("300.00"),
+ installment_purchase_date=date(2025, 12, 10),
+ ),
+ )
+ assert txn.installment_number == 3
+ assert txn.total_installments == 6
+ assert txn.installment_total_amount == Decimal("300.00")
+ assert txn.installment_purchase_date == date(2025, 12, 10)
+
+
+# ---------------------------------------------------------------------------
+# update_transaction — installment scope
+# ---------------------------------------------------------------------------
+
+
+async def test_update_installment_this_only(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ await update_transaction(
+ session, series[1].id, test_workspace.id, test_user.id,
+ TransactionUpdate(description="Only this one", apply_to="this"),
+ )
+ untouched = await get_transaction(session, series[0].id, test_workspace.id)
+ edited = await get_transaction(session, series[1].id, test_workspace.id)
+ later = await get_transaction(session, series[2].id, test_workspace.id)
+ assert untouched is not None and edited is not None and later is not None
+ assert untouched.description == "Notebook"
+ assert edited.description == "Only this one"
+ assert later.description == "Notebook"
+
+
+async def test_update_installment_future(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ await update_transaction(
+ session, series[1].id, test_workspace.id, test_user.id,
+ TransactionUpdate(description="Future ones", apply_to="future"),
+ )
+ untouched = await get_transaction(session, series[0].id, test_workspace.id)
+ edited = await get_transaction(session, series[1].id, test_workspace.id)
+ later = await get_transaction(session, series[2].id, test_workspace.id)
+ assert untouched is not None and edited is not None and later is not None
+ assert untouched.description == "Notebook"
+ assert edited.description == "Future ones"
+ assert later.description == "Future ones"
+
+
+async def test_update_installment_all(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ await update_transaction(
+ session, series[2].id, test_workspace.id, test_user.id,
+ TransactionUpdate(description="All parcels", apply_to="all"),
+ )
+ for tx in series:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ assert reloaded.description == "All parcels"
+
+
+async def test_update_installment_amount_all_resyncs_series_total(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Repricing the whole series updates the stored total on every parcel."""
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ assert all(t.installment_total_amount == Decimal("300.00") for t in series)
+
+ await update_transaction(
+ session, series[0].id, test_workspace.id, test_user.id,
+ TransactionUpdate(amount=Decimal("150.00"), apply_to="all"),
+ )
+
+ for tx in series:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ assert reloaded.amount == Decimal("150.00")
+ assert reloaded.installment_total_amount == Decimal("450.00")
+
+
+async def test_update_installment_amount_this_only_resyncs_series_total(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Repricing a single parcel still changes what the series is worth."""
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+
+ await update_transaction(
+ session, series[1].id, test_workspace.id, test_user.id,
+ TransactionUpdate(amount=Decimal("200.00")),
+ )
+
+ amounts = []
+ for tx in series:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ amounts.append(reloaded.amount)
+ # 100 + 200 + 100
+ assert reloaded.installment_total_amount == Decimal("400.00")
+ assert amounts == [Decimal("100.00"), Decimal("200.00"), Decimal("100.00")]
+
+
+async def test_update_installment_amount_leaves_synced_total_alone(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Provider-synced rows have no series id: their total is the bank's
+ figure and must not be recomputed from our side."""
+ rows = [
+ _transaction(
+ installment_account,
+ workspace_id=test_workspace.id,
+ source="sync",
+ installment_number=i,
+ total_installments=2,
+ installment_total_amount=Decimal("200.00"),
+ installment_purchase_date=date(2026, 1, 15),
+ )
+ for i in (1, 2)
+ ]
+ session.add_all(rows)
+ await session.commit()
+
+ await update_transaction(
+ session, rows[0].id, test_workspace.id, test_user.id,
+ TransactionUpdate(amount=Decimal("175.00")),
+ )
+
+ for tx in rows:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ assert reloaded.installment_total_amount == Decimal("200.00")
+
+
+async def test_update_installment_scope_repeats_only_whitelist_fields(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Scoped edits only repeat the whitelisted fields (description, amount,
+ currency, category, type, payee, account, notes) to sibling installments.
+ Date and status changes land on the edited row only; siblings keep their
+ own dates and statuses."""
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ # Parcel 2 starts as: Feb 15, 100.00, pending (i > 1).
+ await update_transaction(
+ session, series[1].id, test_workspace.id, test_user.id,
+ TransactionUpdate(
+ description="Renamed",
+ amount=Decimal("250.00"),
+ date=date(2026, 4, 10),
+ status="posted",
+ apply_to="future",
+ ),
+ )
+ # The edited row reflects the full payload, including its own date/status.
+ anchor = await get_transaction(session, series[1].id, test_workspace.id)
+ assert anchor is not None
+ assert anchor.description == "Renamed"
+ assert anchor.amount == Decimal("250.00")
+ assert anchor.date == date(2026, 4, 10)
+ assert anchor.status == "posted"
+ # Sibling gets the whitelisted fields but keeps its own date and status.
+ sibling = await get_transaction(session, series[2].id, test_workspace.id)
+ assert sibling is not None
+ assert sibling.description == "Renamed"
+ assert sibling.amount == Decimal("250.00")
+ assert sibling.date == date(2026, 3, 15)
+ assert sibling.status == "pending"
+ # Earlier parcel is outside the "future" scope entirely.
+ earlier = await get_transaction(session, series[0].id, test_workspace.id)
+ assert earlier is not None
+ assert earlier.description == "Notebook"
+ assert earlier.amount == Decimal("100.00")
+ assert earlier.date == date(2026, 1, 15)
+
+
+async def test_update_installment_scope_moves_account_for_whole_series(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Scoped edits apply an account move to every row of the series so the
+ whole series lands on the new account together."""
+ other = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Other Acc",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
+ )
+ session.add(other)
+ await session.commit()
+
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=2),
+ )
+ await update_transaction(
+ session, series[0].id, test_workspace.id, test_user.id,
+ TransactionUpdate(account_id=other.id, apply_to="all"),
+ )
+ for tx in series:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ assert reloaded.account_id == other.id
+
+
+async def test_update_installment_scope_ignored_for_non_installment(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ txn = _transaction(installment_account)
+ session.add(txn)
+ await session.commit()
+
+ await update_transaction(
+ session, txn.id, test_workspace.id, test_user.id,
+ TransactionUpdate(description="Scoped but plain", apply_to="all"),
+ )
+ plain = await get_transaction(session, txn.id, test_workspace.id)
+ assert plain is not None
+ assert plain.description == "Scoped but plain"
+
+
+async def test_update_installment_scope_is_account_scoped(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Two series with identical purchase date/count on different accounts
+ must NOT be treated as the same series."""
+ other = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Other Acc",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
+ )
+ session.add(other)
+ await session.commit()
+
+ series_a = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=2),
+ )
+ series_b = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(other, installments=2),
+ )
+
+ await update_transaction(
+ session, series_a[0].id, test_workspace.id, test_user.id,
+ TransactionUpdate(description="Account A only", apply_to="all"),
+ )
+ a_later = await get_transaction(session, series_a[1].id, test_workspace.id)
+ b_first = await get_transaction(session, series_b[0].id, test_workspace.id)
+ assert a_later is not None and b_first is not None
+ assert a_later.description == "Account A only"
+ assert b_first.description == "Notebook"
+
+
+async def test_update_installment_scope_uses_series_id_for_same_account_and_date(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ """Two same-day purchases on one account must remain separate series."""
+ series_a = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ series_b = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+
+ assert series_a[0].installment_series_id != series_b[0].installment_series_id
+
+ await update_transaction(
+ session, series_a[0].id, test_workspace.id, test_user.id,
+ TransactionUpdate(description="Series A only", apply_to="all"),
+ )
+
+ for tx in series_a:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ assert reloaded.description == "Series A only"
+ for tx in series_b:
+ reloaded = await get_transaction(session, tx.id, test_workspace.id)
+ assert reloaded is not None
+ assert reloaded.description == "Notebook"
+
+
+# ---------------------------------------------------------------------------
+# delete_transaction — installment scope
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_installment_this_only(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ assert await delete_transaction(session, series[1].id, test_workspace.id) is True
+ assert await get_transaction(session, series[0].id, test_workspace.id) is not None
+ assert await get_transaction(session, series[1].id, test_workspace.id) is None
+ assert await get_transaction(session, series[2].id, test_workspace.id) is not None
+
+
+async def test_delete_installment_future(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ assert await delete_transaction(session, series[1].id, test_workspace.id, apply_to="future") is True
+ assert await get_transaction(session, series[0].id, test_workspace.id) is not None
+ assert await get_transaction(session, series[1].id, test_workspace.id) is None
+ assert await get_transaction(session, series[2].id, test_workspace.id) is None
+
+
+async def test_delete_installment_all(
+ session: AsyncSession, test_user, test_workspace, installment_account
+):
+ series = await create_installment_series(
+ session, test_workspace.id, test_user.id,
+ _series_payload(installment_account, installments=3),
+ )
+ assert await delete_transaction(session, series[0].id, test_workspace.id, apply_to="all") is True
+ for tx in series:
+ assert await get_transaction(session, tx.id, test_workspace.id) is None
+
+
+# ---------------------------------------------------------------------------
+# API endpoint
+# ---------------------------------------------------------------------------
+
+
+async def test_api_create_installments(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ response = await client.post(
+ "/api/transactions/installments",
+ headers=auth_headers,
+ json={
+ "base": {
+ "account_id": str(test_account.id),
+ "description": "Cadeira gamer",
+ "amount": "150.00",
+ "date": "2026-03-05",
+ "type": "debit",
+ },
+ "installments": 3,
+ "first_installment_status": "posted",
+ "frequency": "monthly",
+ },
+ )
+ assert response.status_code == 201
+ items = response.json()
+ assert len(items) == 3
+ series_ids = {item["installment_series_id"] for item in items}
+ assert len(series_ids) == 1
+ assert next(iter(series_ids)) is not None
+ for i, item in enumerate(items, start=1):
+ assert item["installment_number"] == i
+ assert item["total_installments"] == 3
+ assert item["installment_total_amount"] == 450.00
+ assert item["installment_purchase_date"] == "2026-03-05"
+ assert item["source"] == "manual"
+ assert items[0]["status"] == "posted"
+ assert items[1]["status"] == "pending"
+ assert [it["date"] for it in items] == ["2026-03-05", "2026-04-05", "2026-05-05"]
+
+
+async def test_api_create_installments_validation(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ response = await client.post(
+ "/api/transactions/installments",
+ headers=auth_headers,
+ json={
+ "base": {
+ "account_id": str(test_account.id),
+ "description": "Single",
+ "amount": "150.00",
+ "date": "2026-03-05",
+ "type": "debit",
+ },
+ "installments": 1,
+ },
+ )
+ assert response.status_code == 422
+
+
+async def test_api_patch_installments_scope_all(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ response = await client.post(
+ "/api/transactions/installments",
+ headers=auth_headers,
+ json={
+ "base": {
+ "account_id": str(test_account.id),
+ "description": "Sofa",
+ "amount": "100.00",
+ "date": "2026-03-05",
+ "type": "debit",
+ },
+ "installments": 2,
+ },
+ )
+ assert response.status_code == 201
+ items = response.json()
+ second = items[1]["id"]
+
+ response = await client.patch(
+ f"/api/transactions/{second}",
+ headers=auth_headers,
+ json={"description": "Sofa novo", "apply_to": "all"},
+ )
+ assert response.status_code == 200
+ assert response.json()["description"] == "Sofa novo"
+
+ listing = await client.get("/api/transactions", headers=auth_headers)
+ descs = {t["description"] for t in listing.json()["items"]}
+ assert "Sofa novo" in descs
+ assert "Sofa" not in descs
+
+
+async def test_api_delete_installments_scope_all(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ response = await client.post(
+ "/api/transactions/installments",
+ headers=auth_headers,
+ json={
+ "base": {
+ "account_id": str(test_account.id),
+ "description": "Delete me",
+ "amount": "50.00",
+ "date": "2026-03-05",
+ "type": "debit",
+ },
+ "installments": 3,
+ },
+ )
+ items = response.json()
+ target = items[1]["id"]
+
+ response = await client.delete(
+ f"/api/transactions/{target}",
+ headers=auth_headers,
+ params={"apply_to": "all"},
+ )
+ assert response.status_code == 204
+
+ listing = await client.get("/api/transactions", headers=auth_headers)
+ assert all(t["description"] != "Delete me" for t in listing.json()["items"])
+
+
+async def test_api_delete_installments_scope_this(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ response = await client.post(
+ "/api/transactions/installments",
+ headers=auth_headers,
+ json={
+ "base": {
+ "account_id": str(test_account.id),
+ "description": "Keep others",
+ "amount": "50.00",
+ "date": "2026-03-05",
+ "type": "debit",
+ },
+ "installments": 3,
+ },
+ )
+ items = response.json()
+ target = items[1]["id"]
+
+ response = await client.delete(
+ f"/api/transactions/{target}", headers=auth_headers
+ )
+ assert response.status_code == 204
+
+ listing = await client.get("/api/transactions", headers=auth_headers)
+ remaining = [t for t in listing.json()["items"] if t["description"] == "Keep others"]
+ assert len(remaining) == 2
diff --git a/backend/tests/test_transaction_schemas.py b/backend/tests/test_transaction_schemas.py
index 60967568..a5915e53 100644
--- a/backend/tests/test_transaction_schemas.py
+++ b/backend/tests/test_transaction_schemas.py
@@ -5,13 +5,19 @@ does not resurface. See: Pydantic V2 metaclass resolves the `date` type annotati
to NoneType when the field name is also `date` and the type is Optional.
"""
+import uuid
from datetime import date
from decimal import Decimal
import pytest
from pydantic import ValidationError
-from app.schemas.transaction import TransactionCreate, TransactionRead, TransactionUpdate
+from app.schemas.transaction import (
+ InstallmentSeriesCreate,
+ TransactionCreate,
+ TransactionRead,
+ TransactionUpdate,
+)
class TestTransactionUpdateDateField:
@@ -88,16 +94,19 @@ class TestTransactionReadInstallmentFields:
return data
def test_all_installment_fields_round_trip(self):
+ series_id = uuid.uuid4()
data = TransactionRead.model_validate(self._base(
installment_number=3,
total_installments=12,
installment_total_amount="1446.00",
installment_purchase_date="2026-02-10",
+ installment_series_id=series_id,
))
assert data.installment_number == 3
assert data.total_installments == 12
assert data.installment_total_amount == 1446.00
assert data.installment_purchase_date == date(2026, 2, 10)
+ assert data.installment_series_id == series_id
def test_installment_fields_default_none(self):
data = TransactionRead.model_validate(self._base())
@@ -105,6 +114,7 @@ class TestTransactionReadInstallmentFields:
assert data.total_installments is None
assert data.installment_total_amount is None
assert data.installment_purchase_date is None
+ assert data.installment_series_id is None
def test_installment_fields_serialize_in_api_response(self):
data = TransactionRead.model_validate(self._base(
@@ -132,3 +142,136 @@ class TestTransactionCreateDateField:
"account_id": "11111111-1111-1111-1111-111111111111",
})
assert data.date == date(2026, 2, 25)
+
+
+class TestTransactionCreateInstallmentFields:
+ """Verify installment metadata on TransactionCreate."""
+
+ BASE = {
+ "description": "TV 55",
+ "amount": "1000.00",
+ "date": "2026-03-10",
+ "type": "debit",
+ "account_id": "11111111-1111-1111-1111-111111111111",
+ }
+
+ def test_accepts_all_four_installment_fields(self):
+ data = TransactionCreate.model_validate({
+ **self.BASE,
+ "installment_number": 2,
+ "total_installments": 10,
+ "installment_total_amount": "10000.00",
+ "installment_purchase_date": "2026-01-10",
+ })
+ assert data.installment_number == 2
+ assert data.total_installments == 10
+ assert data.installment_total_amount == Decimal("10000.00")
+ assert data.installment_purchase_date == date(2026, 1, 10)
+
+ def test_omitting_installment_fields_is_fine(self):
+ data = TransactionCreate.model_validate(self.BASE)
+ assert data.installment_number is None
+
+ def test_rejects_partial_installment_set(self):
+ with pytest.raises(ValidationError, match="must be provided together"):
+ TransactionCreate.model_validate({
+ **self.BASE,
+ "installment_number": 1,
+ "total_installments": 10,
+ })
+
+ def test_rejects_installment_number_out_of_range(self):
+ with pytest.raises(ValidationError, match="between 1 and total_installments"):
+ TransactionCreate.model_validate({
+ **self.BASE,
+ "installment_number": 11,
+ "total_installments": 10,
+ "installment_total_amount": "10000.00",
+ "installment_purchase_date": "2026-01-10",
+ })
+
+ def test_rejects_negative_installment_total(self):
+ with pytest.raises(ValidationError, match="must be positive"):
+ TransactionCreate.model_validate({
+ **self.BASE,
+ "installment_number": 1,
+ "total_installments": 2,
+ "installment_total_amount": "-1.00",
+ "installment_purchase_date": "2026-03-10",
+ })
+
+ def test_rejects_purchase_date_after_transaction_date(self):
+ with pytest.raises(ValidationError, match="cannot be after"):
+ TransactionCreate.model_validate({
+ **self.BASE,
+ "installment_number": 1,
+ "total_installments": 2,
+ "installment_total_amount": "2000.00",
+ "installment_purchase_date": "2026-03-11",
+ })
+
+
+class TestTransactionUpdateApplyTo:
+ """Verify the installment-series edit scope field."""
+
+ def test_defaults_to_this(self):
+ data = TransactionUpdate.model_validate({"description": "x"})
+ assert data.apply_to == "this"
+
+ def test_accepts_all_scopes(self):
+ for scope in ("this", "future", "all"):
+ data = TransactionUpdate.model_validate({"apply_to": scope})
+ assert data.apply_to == scope
+
+ def test_rejects_unknown_scope(self):
+ with pytest.raises(ValidationError):
+ TransactionUpdate.model_validate({"apply_to": "yesterday"})
+
+
+class TestInstallmentSeriesCreate:
+ """Validate the series payload for POST /api/transactions/installments."""
+
+ BASE = {
+ "description": "Notebook",
+ "amount": "500.00",
+ "date": "2026-04-01",
+ "type": "debit",
+ "account_id": "11111111-1111-1111-1111-111111111111",
+ }
+
+ def test_accepts_minimal_payload(self):
+ data = InstallmentSeriesCreate.model_validate(
+ {"base": self.BASE, "installments": 3}
+ )
+ assert data.installments == 3
+ assert data.first_installment_status == "posted"
+ assert data.frequency == "monthly"
+
+ def test_accepts_all_options(self):
+ data = InstallmentSeriesCreate.model_validate({
+ "base": self.BASE,
+ "installments": 12,
+ "first_installment_status": "pending",
+ "frequency": "yearly",
+ })
+ assert data.first_installment_status == "pending"
+ assert data.frequency == "yearly"
+
+ def test_rejects_single_installment(self):
+ with pytest.raises(ValidationError):
+ InstallmentSeriesCreate.model_validate(
+ {"base": self.BASE, "installments": 1}
+ )
+
+ def test_rejects_too_many_installments(self):
+ with pytest.raises(ValidationError):
+ InstallmentSeriesCreate.model_validate(
+ {"base": self.BASE, "installments": 361}
+ )
+
+ def test_rejects_negative_base_amount(self):
+ with pytest.raises(ValidationError, match="amount must be positive"):
+ InstallmentSeriesCreate.model_validate({
+ "base": {**self.BASE, "amount": "-5.00"},
+ "installments": 2,
+ })
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 05d582d8..91a18b41 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -42,12 +42,25 @@ import { CategorySelect } from '@/components/category-select'
import { TransactionAttachments } from '@/components/transaction-attachments'
import type { AttachmentPreview } from '@/components/transaction-attachments'
import { TransactionSplitsSection } from '@/components/transaction-splits-section'
+import { buildInstallmentSeriesInput, hasNonStatusChange, isManualInstallmentSeriesRow } from '@/lib/installment-series'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
-import type { Transaction, RecurringTransaction, TransactionSplitsInput, CategoryGroup, Category, Rule, RuleCondition } from '@/types'
+import type { Transaction, RecurringTransaction, TransactionSplitsInput, TransactionEditPayload, InstallmentSeriesInput, TransactionApplyScope, CategoryGroup, Category, Rule, RuleCondition } from '@/types'
import { toast } from 'sonner'
export type SaveAction = 'save' | 'saveAndNew' | 'saveAndDuplicate'
+export type TransactionSavePayload = TransactionEditPayload & {
+ apply_to?: TransactionApplyScope
+}
+
+type PendingInstallmentEdit = {
+ data: TransactionEditPayload
+ recurringData?: { frequency: string; end_date?: string }
+ installmentData?: InstallmentSeriesInput
+ pendingFiles?: File[]
+ action?: SaveAction
+}
+
export function extractApiError(error: unknown): string {
if (
error &&
@@ -110,7 +123,7 @@ export function TransactionDialog({
categoryGroups: CategoryGroup[]
accounts: { id: string; name: string; display_name?: string | null; type?: string }[]
recurringMatch?: RecurringTransaction
- onSave: (data: Partial<Transaction>, recurringData?: { frequency: string; end_date?: string }, pendingFiles?: File[], action?: SaveAction) => void
+ onSave: (data: TransactionSavePayload, recurringData?: { frequency: string; end_date?: string }, installmentData?: InstallmentSeriesInput, pendingFiles?: File[], action?: SaveAction) => void
onDelete?: () => void
onUnlinkTransfer?: (pairId: string) => void
onIgnoreChanged?: () => void
@@ -118,11 +131,13 @@ export function TransactionDialog({
loading: boolean
error: string | null
isSynced?: boolean
- duplicateDraft?: Partial<Transaction> | null
+ duplicateDraft?: TransactionEditPayload | null
formResetKey?: number
}) {
const { t } = useTranslation()
const [preview, setPreview] = useState<AttachmentPreview | null>(null)
+ const [pendingInstallmentEdit, setPendingInstallmentEdit] =
+ useState<PendingInstallmentEdit | null>(null)
const handlePreviewChange = useCallback((newPreview: AttachmentPreview | null) => {
setPreview(prev => {
@@ -160,8 +175,39 @@ export function TransactionDialog({
const isEditing = !!transaction
const hasPreview = isEditing && !!preview
+ const handleClose = () => {
+ setPendingInstallmentEdit(null)
+ onClose()
+ }
+
+ const handleSave = (
+ data: TransactionEditPayload,
+ recurringData?: { frequency: string; end_date?: string },
+ installmentData?: InstallmentSeriesInput,
+ pendingFiles?: File[],
+ action?: SaveAction,
+ ) => {
+ if (
+ transaction &&
+ isManualInstallmentSeriesRow(transaction) &&
+ hasNonStatusChange(data, transaction)
+ ) {
+ setPendingInstallmentEdit({ data, recurringData, installmentData, pendingFiles, action })
+ return
+ }
+ onSave(data, recurringData, installmentData, pendingFiles, action)
+ }
+
+ const submitInstallmentEdit = (scope: TransactionApplyScope) => {
+ if (!pendingInstallmentEdit) return
+ const { data, recurringData, installmentData, pendingFiles, action } = pendingInstallmentEdit
+ onSave({ ...data, apply_to: scope }, recurringData, installmentData, pendingFiles, action)
+ setPendingInstallmentEdit(null)
+ }
+
return (
- <Dialog open={open} onOpenChange={onClose}>
+ <>
+ <Dialog open={open} onOpenChange={handleClose}>
<DialogContent className={cn(
// Bound the dialog to the viewport (dvh accounts for mobile browser
// chrome) and make it a flex column so the inner scroll region works
@@ -189,12 +235,12 @@ export function TransactionDialog({
categoryGroups={categoryGroups}
accounts={accounts}
recurringMatch={recurringMatch}
- onSave={onSave}
+ onSave={handleSave}
onDelete={onDelete}
onUnlinkTransfer={onUnlinkTransfer}
onIgnoreChanged={onIgnoreChanged}
onCreateRule={onCreateRule}
- onCancel={onClose}
+ onCancel={handleClose}
loading={loading}
error={error}
isSynced={isSynced}
@@ -297,6 +343,49 @@ export function TransactionDialog({
)}
</DialogContent>
</Dialog>
+
+ <Dialog
+ open={!!pendingInstallmentEdit}
+ onOpenChange={(scopeOpen) => {
+ if (!scopeOpen) setPendingInstallmentEdit(null)
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('transactions.installmentScopeTitle')}</DialogTitle>
+ </DialogHeader>
+ <p className="text-sm text-muted-foreground">
+ {t('transactions.installmentScopeEditDesc')}
+ </p>
+ <DialogFooter className="flex-col sm:flex-row sm:justify-end gap-2">
+ <Button
+ autoFocus
+ onClick={() => submitInstallmentEdit('this')}
+ disabled={loading}
+ className="justify-center"
+ >
+ {loading ? t('common.loading') : t('transactions.installmentScopeThis')}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => submitInstallmentEdit('future')}
+ disabled={loading}
+ className="justify-center"
+ >
+ {t('transactions.installmentScopeFuture')}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => submitInstallmentEdit('all')}
+ disabled={loading}
+ className="justify-center"
+ >
+ {t('transactions.installmentScopeAll')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
)
}
@@ -321,12 +410,12 @@ function TransactionForm({
hasPreview,
}: {
transaction: Transaction | null
- duplicateDraft: Partial<Transaction> | null
+ duplicateDraft: TransactionEditPayload | null
categories: Category[]
categoryGroups: CategoryGroup[]
accounts: { id: string; name: string; display_name?: string | null; type?: string }[]
recurringMatch?: RecurringTransaction
- onSave: (data: Partial<Transaction>, recurringData?: { frequency: string; end_date?: string }, pendingFiles?: File[], action?: SaveAction) => void
+ onSave: (data: TransactionEditPayload, recurringData?: { frequency: string; end_date?: string }, installmentData?: InstallmentSeriesInput, pendingFiles?: File[], action?: SaveAction) => void
onDelete?: () => void
onUnlinkTransfer?: (pairId: string) => void
onIgnoreChanged?: () => void
@@ -381,6 +470,13 @@ function TransactionForm({
const [isRecurring, setIsRecurring] = useState(false)
const [frequency, setFrequency] = useState<RecurringTransaction['frequency']>('monthly')
const [endDate, setEndDate] = useState('')
+ // Manual installment series: when checked, the save handler
+ // builds an InstallmentSeriesInput payload that repeats the transaction
+ // as N parcels. Only count and frequency are asked for: each parcel uses
+ // the transaction's own amount and status.
+ const [isInstallment, setIsInstallment] = useState(false)
+ const [installmentCount, setInstallmentCount] = useState('2')
+ const [installmentFrequency, setInstallmentFrequency] = useState<RecurringTransaction['frequency']>('monthly')
// Optional split-with-group payload. `null` = leave splits as-is on
// update, or no splits on create. The dedicated section component
// owns its own UI state and surfaces a normalized payload here.
@@ -662,7 +758,7 @@ function TransactionForm({
is_ignored: isIgnored,
...overridePayload,
...splitsPayload,
- } as Partial<Transaction>
+ } as TransactionEditPayload
: {
description,
amount: parseFloat(amount),
@@ -680,11 +776,29 @@ function TransactionForm({
...fxFields,
...overridePayload,
...splitsPayload,
- } as Partial<Transaction>
+ } as TransactionEditPayload
const recurringData = isCreating && isRecurring
? { frequency, end_date: endDate || undefined }
: undefined
- onSave(txData, recurringData, isCreating && pendingFiles.length > 0 ? pendingFiles : undefined, action)
+ const installmentData = isCreating && isInstallment && !isSynced
+ ? buildInstallmentSeriesInput({
+ accountId,
+ categoryId,
+ payeeId,
+ description,
+ amount,
+ date,
+ type,
+ currency,
+ notes,
+ fxFields,
+ splits,
+ installmentCount,
+ installmentFrequency,
+ status,
+ })
+ : undefined
+ onSave(txData, recurringData, installmentData, isCreating && pendingFiles.length > 0 ? pendingFiles : undefined, action)
}}
className={cn(
// Always a bounded flex column; the DialogContent caps the overall
@@ -1057,18 +1171,37 @@ function TransactionForm({
/>
)}
- {/* Recurring toggle — only shown when creating non-synced */}
+ {/* Create options — recurring and installment toggles share one row
+ when creating non-synced transactions. "Repeat as installments"
+ mirrors the transaction N times for debits and receivables. */}
{isCreating && !isSynced && (
<div className="space-y-3 border rounded-md p-3">
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={isRecurring}
- onChange={(e) => setIsRecurring(e.target.checked)}
- className="rounded border-gray-300"
- />
- <span className="text-sm font-medium">{t('transactions.makeRecurring')}</span>
- </label>
+ <div className="flex items-center gap-6">
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={isRecurring}
+ onChange={(e) => {
+ setIsRecurring(e.target.checked)
+ if (e.target.checked) setIsInstallment(false)
+ }}
+ className="rounded border-gray-300"
+ />
+ <span className="text-sm font-medium">{t('transactions.makeRecurring')}</span>
+ </label>
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={isInstallment}
+ onChange={(e) => {
+ setIsInstallment(e.target.checked)
+ if (e.target.checked) setIsRecurring(false)
+ }}
+ className="rounded border-gray-300"
+ />
+ <span className="text-sm font-medium">{t('transactions.makeInstallment')}</span>
+ </label>
+ </div>
{isRecurring && (
<div className="grid grid-cols-2 gap-4 pt-1">
<div className="space-y-2">
@@ -1095,6 +1228,34 @@ function TransactionForm({
</div>
</div>
)}
+ {isInstallment && (
+ <div className="grid grid-cols-2 gap-4 pt-1">
+ <div className="space-y-2">
+ <Label>{t('transactions.installmentFrequency')}</Label>
+ <select
+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-card focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
+ value={installmentFrequency}
+ onChange={(e) => setInstallmentFrequency(e.target.value as RecurringTransaction['frequency'])}
+ >
+ <option value="monthly">{t('recurring.monthly')}</option>
+ <option value="quarterly">{t('recurring.quarterly')}</option>
+ <option value="weekly">{t('recurring.weekly')}</option>
+ <option value="yearly">{t('recurring.yearly')}</option>
+ </select>
+ </div>
+ <div className="space-y-2">
+ <Label>{t('transactions.installmentCount')}</Label>
+ <input
+ type="number"
+ min={2}
+ max={360}
+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-card focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
+ value={installmentCount}
+ onChange={(e) => setInstallmentCount(e.target.value)}
+ />
+ </div>
+ </div>
+ )}
</div>
)}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 19094d25..e6f22360 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -53,6 +53,9 @@ import type {
GroupSettlement,
GroupBalances,
TransactionSplitsInput,
+ TransactionEditPayload,
+ InstallmentSeriesInput,
+ TransactionApplyScope,
} from '@/types'
const api = axios.create({
@@ -471,19 +474,26 @@ export const transactions = {
const { data } = await api.get(`/transactions/${id}`)
return data
},
- create: async (transaction: Partial<Transaction>): Promise<Transaction> => {
+ create: async (transaction: TransactionEditPayload): Promise<Transaction> => {
const { data } = await api.post('/transactions', transaction)
return data
},
+ createInstallments: async (payload: InstallmentSeriesInput): Promise<Transaction[]> => {
+ const { data } = await api.post('/transactions/installments', payload)
+ return data
+ },
update: async (
id: string,
- transaction: Partial<Transaction> & { apply_to_transfer_pair?: boolean },
+ transaction: TransactionEditPayload & {
+ apply_to_transfer_pair?: boolean
+ apply_to?: TransactionApplyScope
+ },
): Promise<Transaction> => {
const { data } = await api.patch(`/transactions/${id}`, transaction)
return data
},
- delete: async (id: string): Promise<void> => {
- await api.delete(`/transactions/${id}`)
+ delete: async (id: string, applyTo: TransactionApplyScope = 'this'): Promise<void> => {
+ await api.delete(`/transactions/${id}`, { params: { apply_to: applyTo } })
},
toggleIgnore: async (id: string): Promise<Transaction> => {
const { data } = await api.patch(`/transactions/${id}/ignore`)
diff --git a/frontend/src/lib/installment-series.test.ts b/frontend/src/lib/installment-series.test.ts
new file mode 100644
index 00000000..99ca6bc4
--- /dev/null
+++ b/frontend/src/lib/installment-series.test.ts
@@ -0,0 +1,263 @@
+import { describe, expect, it } from 'vitest'
+import {
+ buildInstallmentSeriesInput,
+ hasNonStatusChange,
+ isManualInstallmentSeriesRow,
+} from './installment-series'
+import type { InstallmentSeriesFormInput } from './installment-series'
+import type { Transaction, TransactionEditPayload } from '../types'
+
+const base: InstallmentSeriesFormInput = {
+ accountId: 'acct-1',
+ categoryId: 'cat-1',
+ payeeId: null,
+ description: 'Notebook',
+ amount: '150.00',
+ date: '2026-08-06',
+ type: 'debit',
+ currency: 'BRL',
+ notes: '',
+ fxFields: { amount_primary: 150, fx_rate_used: 1 },
+ splits: null,
+ installmentCount: '3',
+ installmentFrequency: 'monthly',
+ status: 'posted',
+}
+
+describe('buildInstallmentSeriesInput', () => {
+ it('builds the base payload with per-parcel amount', () => {
+ const payload = buildInstallmentSeriesInput(base)
+ expect(payload.base).toMatchObject({
+ account_id: 'acct-1',
+ category_id: 'cat-1',
+ payee_id: null,
+ description: 'Notebook',
+ amount: 150,
+ date: '2026-08-06',
+ type: 'debit',
+ currency: 'BRL',
+ notes: null,
+ })
+ expect(payload.installments).toBe(3)
+ expect(payload.first_installment_status).toBe('posted')
+ expect(payload.frequency).toBe('monthly')
+ })
+
+ it('clamps installments to the backend [2, 360] range', () => {
+ expect(buildInstallmentSeriesInput({ ...base, installmentCount: '1' }).installments).toBe(2)
+ expect(buildInstallmentSeriesInput({ ...base, installmentCount: '500' }).installments).toBe(360)
+ expect(buildInstallmentSeriesInput({ ...base, installmentCount: 'abc' }).installments).toBe(2)
+ expect(buildInstallmentSeriesInput({ ...base, installmentCount: '' }).installments).toBe(2)
+ expect(buildInstallmentSeriesInput({ ...base, installmentCount: '7' }).installments).toBe(7)
+ })
+
+ it('uses the transaction status for the first installment', () => {
+ expect(buildInstallmentSeriesInput({ ...base, status: 'posted' }).first_installment_status).toBe('posted')
+ expect(buildInstallmentSeriesInput({ ...base, status: 'pending' }).first_installment_status).toBe('pending')
+ })
+
+ it('rides the transaction type through, including credit receivables', () => {
+ const payload = buildInstallmentSeriesInput({ ...base, type: 'credit' })
+ expect(payload.base.type).toBe('credit')
+ })
+
+ it('supports the same frequencies as recurring, including quarterly', () => {
+ expect(buildInstallmentSeriesInput({ ...base, installmentFrequency: 'monthly' }).frequency).toBe('monthly')
+ expect(buildInstallmentSeriesInput({ ...base, installmentFrequency: 'quarterly' }).frequency).toBe('quarterly')
+ expect(buildInstallmentSeriesInput({ ...base, installmentFrequency: 'weekly' }).frequency).toBe('weekly')
+ expect(buildInstallmentSeriesInput({ ...base, installmentFrequency: 'yearly' }).frequency).toBe('yearly')
+ })
+
+ it('omits currency when not set', () => {
+ const payload = buildInstallmentSeriesInput({ ...base, currency: undefined })
+ expect(payload.base.currency).toBeUndefined()
+ })
+
+ it('rides FX overrides through to the base', () => {
+ const payload = buildInstallmentSeriesInput({
+ ...base,
+ fxFields: { amount_primary: 120, fx_rate_used: 0.8 },
+ })
+ expect(payload.base.amount_primary).toBe(120)
+ expect(payload.base.fx_rate_used).toBe(0.8)
+ })
+
+ it('rides split-with-group through to the base', () => {
+ const splits = {
+ share_type: 'equal' as const,
+ splits: [{ group_member_id: 'member-1' }],
+ }
+ const payload = buildInstallmentSeriesInput({ ...base, splits })
+ expect(payload.base.splits).toEqual(splits)
+ })
+
+ it('normalizes whitespace-only notes to null', () => {
+ const payload = buildInstallmentSeriesInput({ ...base, notes: ' ' })
+ expect(payload.base.notes).toBeNull()
+ })
+})
+
+describe('isManualInstallmentSeriesRow', () => {
+ it('recognizes multi-installment rows created by the series endpoint', () => {
+ expect(isManualInstallmentSeriesRow({
+ installment_series_id: 'series-1',
+ installment_number: 2,
+ total_installments: 3,
+ })).toBe(true)
+ })
+
+ it('does not recognize bank-synced installment rows', () => {
+ expect(isManualInstallmentSeriesRow({
+ installment_series_id: null,
+ installment_number: 2,
+ total_installments: 3,
+ })).toBe(false)
+ })
+
+ it('keeps recognizing a parcel that bank sync absorbed', () => {
+ // The fuzzy manual match flips `source` to "sync" but leaves the series
+ // id, so the scope prompt must not vanish for that parcel.
+ expect(isManualInstallmentSeriesRow({
+ installment_series_id: 'series-1',
+ installment_number: 1,
+ total_installments: 3,
+ })).toBe(true)
+ })
+
+ it('does not recognize single-parcel or incomplete installment metadata', () => {
+ expect(isManualInstallmentSeriesRow({
+ installment_series_id: 'series-1',
+ installment_number: 1,
+ total_installments: 1,
+ })).toBe(false)
+ expect(isManualInstallmentSeriesRow({
+ installment_series_id: 'series-1',
+ installment_number: null,
+ total_installments: 3,
+ })).toBe(false)
+ })
+})
+
+// The backend serializes Decimal-backed fields as strings, so the original
+// row arrives with amount/amount_primary/fx_rate_used as strings while the
+// dialog sends parsed numbers. The comparison must treat those as equal.
+const original = {
+ id: 'tx-1',
+ account_id: 'acct-1',
+ category_id: 'cat-1',
+ payee_id: null,
+ description: 'Notebook',
+ amount: '150.00',
+ currency: 'BRL',
+ date: '2026-08-06',
+ type: 'debit',
+ status: 'pending',
+ notes: null,
+ amount_primary: '150.00',
+ fx_rate_used: '1',
+ effective_bill_date: null,
+ is_ignored: false,
+ splits: [],
+} as unknown as Transaction
+
+// The form dialog always sends a full payload, with status toggled.
+const statusOnlyPayload: TransactionEditPayload = {
+ description: 'Notebook',
+ amount: 150,
+ date: '2026-08-06',
+ type: 'debit',
+ currency: 'BRL',
+ category_id: 'cat-1',
+ payee_id: null,
+ account_id: 'acct-1',
+ notes: null,
+ is_ignored: false,
+ status: 'posted',
+}
+
+describe('hasNonStatusChange', () => {
+ it('returns false when only the status changed', () => {
+ expect(hasNonStatusChange(statusOnlyPayload, original)).toBe(false)
+ })
+
+ it('returns true when the amount changed', () => {
+ expect(hasNonStatusChange({ ...statusOnlyPayload, amount: 200 }, original)).toBe(true)
+ })
+
+ it('returns true when the description changed', () => {
+ expect(hasNonStatusChange({ ...statusOnlyPayload, description: 'Renamed' }, original)).toBe(true)
+ })
+
+ it('returns true when the currency changed', () => {
+ expect(hasNonStatusChange({ ...statusOnlyPayload, currency: 'USD' }, original)).toBe(true)
+ })
+
+ it('treats untouched FX overrides as unchanged', () => {
+ expect(hasNonStatusChange({
+ ...statusOnlyPayload,
+ amount_primary: 150,
+ fx_rate_used: 1,
+ }, original)).toBe(false)
+ })
+
+ it('treats null vs undefined ids as unchanged', () => {
+ const data = {
+ ...statusOnlyPayload,
+ payee_id: undefined,
+ account_id: undefined,
+ }
+ expect(hasNonStatusChange(data, { ...original, payee_id: null, account_id: null })).toBe(false)
+ })
+
+ it('treats an untouched split group as unchanged', () => {
+ const splitOriginal = {
+ ...original,
+ splits: [
+ {
+ id: 's1',
+ transaction_id: 'tx-1',
+ group_member_id: 'member-1',
+ share_amount: '50.00',
+ share_pct: 33.3333,
+ share_type: 'equal',
+ notes: null,
+ created_at: '2026-08-06T00:00:00Z',
+ },
+ ],
+ } as unknown as Transaction
+ const splitPayload = {
+ ...statusOnlyPayload,
+ splits: {
+ share_type: 'equal' as const,
+ splits: [{ group_member_id: 'member-1', share_amount: 50, share_pct: 33.3333 }],
+ },
+ }
+ expect(hasNonStatusChange(splitPayload, splitOriginal)).toBe(false)
+ })
+
+ it('detects a changed split group', () => {
+ const splitOriginal = {
+ ...original,
+ splits: [
+ {
+ id: 's1',
+ transaction_id: 'tx-1',
+ group_member_id: 'member-1',
+ share_amount: '50.00',
+ share_pct: 33.3333,
+ share_type: 'equal',
+ notes: null,
+ created_at: '2026-08-06T00:00:00Z',
+ },
+ ],
+ } as unknown as Transaction
+ const splitPayload = {
+ ...statusOnlyPayload,
+ splits: {
+ share_type: 'equal' as const,
+ splits: [{ group_member_id: 'member-1', share_amount: 100, share_pct: 66.6666 }],
+ },
+ }
+ expect(hasNonStatusChange(splitPayload, splitOriginal)).toBe(true)
+ })
+})
diff --git a/frontend/src/lib/installment-series.ts b/frontend/src/lib/installment-series.ts
new file mode 100644
index 00000000..2f254ba8
--- /dev/null
+++ b/frontend/src/lib/installment-series.ts
@@ -0,0 +1,159 @@
+import type {
+ InstallmentSeriesInput,
+ Transaction,
+ TransactionEditPayload,
+ TransactionSplitsInput,
+} from '../types'
+
+/**
+ * Form-level inputs that the installment section of TransactionForm collects.
+ * Mirrors the backend's InstallmentSeriesCreate contract so the payload the
+ * UI sends is testable without a DOM.
+ */
+export interface InstallmentSeriesFormInput {
+ accountId: string
+ categoryId: string | null
+ payeeId: string | null
+ description: string
+ amount: string
+ date: string
+ type: 'debit' | 'credit'
+ currency?: string
+ notes: string
+ fxFields: Pick<Partial<Transaction>, 'amount_primary' | 'fx_rate_used'>
+ splits: TransactionSplitsInput | null
+ installmentCount: string
+ installmentFrequency: 'monthly' | 'quarterly' | 'weekly' | 'yearly'
+ status: 'posted' | 'pending'
+}
+
+/**
+ * Scope prompts are only meaningful for installment series created by the
+ * manual installment endpoint. Provider-synced rows may carry installment
+ * metadata, but they are independent bank transactions and must be edited
+ * or deleted one at a time.
+ *
+ * The series id is the signal, not `source`: bank sync absorbs a matching
+ * manual row by flipping its `source` to "sync" (connection_service's fuzzy
+ * manual match), which would otherwise make the prompt disappear from part
+ * of a series after the first sync. The series id survives that merge.
+ */
+export function isManualInstallmentSeriesRow(
+ tx:
+ | Pick<Transaction, 'installment_series_id' | 'installment_number' | 'total_installments'>
+ | null
+ | undefined,
+): boolean {
+ return (
+ tx?.installment_series_id != null &&
+ tx.installment_number != null &&
+ tx.total_installments != null &&
+ tx.total_installments > 1
+ )
+}
+
+/**
+ * Build the POST /api/transactions/installments payload from the form.
+ *
+ * "Repeat as installments": the transaction is repeated N times, so
+ * `base.amount` is the per-parcel amount and the backend derives the series
+ * total as `amount * installments` (no separate total is sent). The first
+ * parcel carries the transaction's own status; subsequent ones are "pending".
+ *
+ * - `installments` is clamped to the backend's [2, 360] range (empty or
+ * invalid input falls back to 2).
+ * - Split-with-group and FX overrides ride along on the base so every parcel
+ * is finalized exactly like a single manual transaction.
+ */
+export function buildInstallmentSeriesInput(
+ input: InstallmentSeriesFormInput,
+): InstallmentSeriesInput {
+ const installments = Math.min(
+ Math.max(parseInt(input.installmentCount, 10) || 2, 2),
+ 360,
+ )
+ return {
+ base: {
+ account_id: input.accountId,
+ category_id: input.categoryId || null,
+ payee_id: input.payeeId || null,
+ description: input.description,
+ amount: parseFloat(input.amount),
+ date: input.date,
+ type: input.type,
+ ...(input.currency ? { currency: input.currency } : {}),
+ notes: input.notes.trim() || null,
+ ...input.fxFields,
+ ...(input.splits ? { splits: input.splits } : {}),
+ },
+ installments,
+ first_installment_status: input.status,
+ frequency: input.installmentFrequency,
+ }
+}
+
+/**
+ * True when an edit payload touches any field beyond the status toggle.
+ *
+ * The dialog sends a full form payload on save, while the backend
+ * serializes Decimal-backed fields (amount, amount_primary, fx_rate_used)
+ * as strings, so values are compared leniently: numeric fields are coerced
+ * and splits are normalized before comparison. Status-only edits skip the
+ * installment-series scope prompt.
+ */
+export function hasNonStatusChange(
+ data: TransactionEditPayload,
+ original: Transaction,
+): boolean {
+ const numericKeys = new Set([
+ 'amount',
+ 'amount_primary',
+ 'fx_rate_used',
+ 'installment_total_amount',
+ ])
+ const toNumber = (v: unknown): number | null => {
+ if (v == null || v === '') return null
+ const n = Number(v)
+ return Number.isFinite(n) ? n : null
+ }
+ const normalizeSplits = (v: TransactionSplitsInput | null | undefined) => {
+ if (!v || v.splits.length === 0) return null
+ return {
+ share_type: v.share_type,
+ splits: v.splits.map((s) => ({
+ group_member_id: s.group_member_id,
+ share_amount: toNumber(s.share_amount),
+ share_pct: toNumber(s.share_pct),
+ })),
+ }
+ }
+ const originalSplits: TransactionSplitsInput | null = original.splits?.length
+ ? {
+ share_type: (original.splits[0].share_type as TransactionSplitsInput['share_type']) ?? 'equal',
+ splits: original.splits.map((s) => ({
+ group_member_id: s.group_member_id,
+ share_amount: s.share_amount,
+ share_pct: s.share_pct,
+ })),
+ }
+ : null
+
+ return Object.entries(data).some(([key, value]) => {
+ if (key === 'status' || key === 'apply_to' || key === 'apply_to_transfer_pair') {
+ return false
+ }
+ const originalValue = original[key as keyof Transaction]
+ if (numericKeys.has(key)) {
+ return toNumber(value) !== toNumber(originalValue)
+ }
+ if (value === originalValue) return false
+ if (value == null && originalValue == null) return false
+ if (key === 'splits') {
+ return (
+ JSON.stringify(normalizeSplits(value as TransactionSplitsInput | null)) !==
+ JSON.stringify(normalizeSplits(originalSplits))
+ )
+ }
+ return true
+ })
+}
diff --git a/frontend/src/lib/transaction-status.test.ts b/frontend/src/lib/transaction-status.test.ts
new file mode 100644
index 00000000..aa442b64
--- /dev/null
+++ b/frontend/src/lib/transaction-status.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+
+import { shouldShowPendingBadge } from './transaction-status'
+
+describe('shouldShowPendingBadge', () => {
+ it('shows pending for transactions managed by Securo', () => {
+ expect(shouldShowPendingBadge({ status: 'pending', source: 'manual' })).toBe(true)
+ expect(shouldShowPendingBadge({ status: 'pending', source: 'recurring' })).toBe(true)
+ })
+
+ it('hides pending for bank-synced transactions', () => {
+ expect(shouldShowPendingBadge({ status: 'pending', source: 'sync' })).toBe(false)
+ })
+
+ it('hides the badge for posted transactions', () => {
+ expect(shouldShowPendingBadge({ status: 'posted', source: 'manual' })).toBe(false)
+ })
+})
diff --git a/frontend/src/lib/transaction-status.ts b/frontend/src/lib/transaction-status.ts
new file mode 100644
index 00000000..f35ce510
--- /dev/null
+++ b/frontend/src/lib/transaction-status.ts
@@ -0,0 +1,9 @@
+type PendingBadgeTransaction = {
+ source: string | null
+ status: string | null
+}
+
+/** Bank-sync pending state already matches the provider and needs no UI badge. */
+export function shouldShowPendingBadge(transaction: PendingBadgeTransaction): boolean {
+ return transaction.status === 'pending' && transaction.source !== 'sync'
+}
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index c954e9e2..6bd83d12 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -324,6 +324,15 @@
"deleted": "Transaktion gelöscht",
"confirmDelete": "Möchtest du diese Transaktion wirklich löschen?",
"makeRecurring": "Als wiederkehrend einrichten",
+ "makeInstallment": "Als Raten wiederholen",
+ "installmentCount": "Anzahl der Raten",
+ "installmentFrequency": "Häufigkeit",
+ "installmentScopeTitle": "Auf welche Raten anwenden?",
+ "installmentScopeEditDesc": "Diese Transaktion gehört zu einer Ratenzahlungsreihe. Wie weit soll diese Änderung angewendet werden?",
+ "installmentScopeDeleteDesc": "Diese Transaktion gehört zu einer Ratenzahlungsreihe. Welche Raten sollen gelöscht werden?",
+ "installmentScopeThis": "Nur diese",
+ "installmentScopeFuture": "Diese und zukünftige",
+ "installmentScopeAll": "Alle Raten",
"recurringBadge": "Wiederkehrend",
"recurringLinkedTooltip": "Mit einer wiederkehrenden Rechnung verknüpft",
"recurringLinkedInfo": "Diese Transaktion ist mit einer wiederkehrenden Rechnung verknüpft.",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 985ce235..a7a67fc0 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -324,6 +324,15 @@
"deleted": "Transaction deleted",
"confirmDelete": "Are you sure you want to delete this transaction?",
"makeRecurring": "Make recurring",
+ "makeInstallment": "Repeat as installments",
+ "installmentCount": "Number of installments",
+ "installmentFrequency": "Frequency",
+ "installmentScopeTitle": "Apply to which installments?",
+ "installmentScopeEditDesc": "This transaction is part of an installment series. How far should this change apply?",
+ "installmentScopeDeleteDesc": "This transaction is part of an installment series. Which installments should be deleted?",
+ "installmentScopeThis": "This one",
+ "installmentScopeFuture": "This and future",
+ "installmentScopeAll": "All installments",
"recurringBadge": "Recurring",
"recurringLinkedTooltip": "Linked to a recurring bill",
"recurringLinkedInfo": "This transaction is linked to a recurring bill.",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index de6dd308..c8ce594a 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -324,6 +324,15 @@
"deleted": "Transacción eliminada",
"confirmDelete": "¿Estás seguro de que quieres eliminar esta transacción?",
"makeRecurring": "Hacer recurrente",
+ "makeInstallment": "Repetir en cuotas",
+ "installmentCount": "Número de cuotas",
+ "installmentFrequency": "Frecuencia",
+ "installmentScopeTitle": "¿Aplicar a qué cuotas?",
+ "installmentScopeEditDesc": "Esta transacción forma parte de una serie de cuotas. ¿Hasta dónde debe aplicarse este cambio?",
+ "installmentScopeDeleteDesc": "Esta transacción forma parte de una serie de cuotas. ¿Qué cuotas deben eliminarse?",
+ "installmentScopeThis": "Solo esta",
+ "installmentScopeFuture": "Esta y futuras",
+ "installmentScopeAll": "Todas las cuotas",
"recurringBadge": "Recurrente",
"recurringLinkedTooltip": "Vinculada a una factura recurrente",
"recurringLinkedInfo": "Esta transacción está vinculada a una factura recurrente.",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 92375888..14bf2482 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -324,6 +324,15 @@
"deleted": "Transaction supprimée",
"confirmDelete": "Êtes-vous sûr de vouloir supprimer cette transaction ?",
"makeRecurring": "Rendre récurrente",
+ "makeInstallment": "Répéter en versements",
+ "installmentCount": "Nombre de versements",
+ "installmentFrequency": "Fréquence",
+ "installmentScopeTitle": "Appliquer à quels versements ?",
+ "installmentScopeEditDesc": "Cette transaction fait partie d'une série de versements. Jusqu'où ce changement doit-il s'appliquer ?",
+ "installmentScopeDeleteDesc": "Cette transaction fait partie d'une série de versements. Quels versements doivent être supprimés ?",
+ "installmentScopeThis": "Celui-ci uniquement",
+ "installmentScopeFuture": "Celui-ci et les suivants",
+ "installmentScopeAll": "Tous les versements",
"recurringBadge": "Récurrente",
"recurringLinkedTooltip": "Liée à une facture récurrente",
"recurringLinkedInfo": "Cette transaction est liée à une facture récurrente.",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 7c0c8d66..146bf7e7 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -324,6 +324,15 @@
"deleted": "Transazione eliminata",
"confirmDelete": "Sei sicuro di voler eliminare questa transazione?",
"makeRecurring": "Rendi ricorrente",
+ "makeInstallment": "Ripeti a rate",
+ "installmentCount": "Numero di rate",
+ "installmentFrequency": "Frequenza",
+ "installmentScopeTitle": "A quali rate applicare?",
+ "installmentScopeEditDesc": "Questa transazione fa parte di una serie di rate. Fino a dove deve essere applicata questa modifica?",
+ "installmentScopeDeleteDesc": "Questa transazione fa parte di una serie di rate. Quali rate devono essere eliminate?",
+ "installmentScopeThis": "Solo questa",
+ "installmentScopeFuture": "Questa e future",
+ "installmentScopeAll": "Tutte le rate",
"recurringBadge": "Ricorrente",
"recurringLinkedTooltip": "Collegata a una spesa ricorrente",
"recurringLinkedInfo": "Questa transazione è collegata a una spesa ricorrente.",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 20470340..053eb272 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -330,6 +330,15 @@
"deleted": "Usunięto transakcję",
"confirmDelete": "Czy na pewno usunąć tę transakcję?",
"makeRecurring": "Ustaw jako cykliczną",
+ "makeInstallment": "Powtórz jako raty",
+ "installmentCount": "Liczba rat",
+ "installmentFrequency": "Częstotliwość",
+ "installmentScopeTitle": "Do których rat zastosować?",
+ "installmentScopeEditDesc": "Ta transakcja jest częścią serii rat. Jak daleko ma zostać zastosowana ta zmiana?",
+ "installmentScopeDeleteDesc": "Ta transakcja jest częścią serii rat. Które raty mają zostać usunięte?",
+ "installmentScopeThis": "Tylko ta",
+ "installmentScopeFuture": "Ta i przyszłe",
+ "installmentScopeAll": "Wszystkie raty",
"recurringBadge": "Cykliczna",
"recurringLinkedTooltip": "Powiązana z cyklicznym rachunkiem",
"recurringLinkedInfo": "Ta transakcja jest powiązana z cyklicznym rachunkiem.",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index c442da3d..4552b6ec 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -324,6 +324,15 @@
"deleted": "Transação excluída",
"confirmDelete": "Tem certeza que deseja excluir esta transação?",
"makeRecurring": "Tornar recorrente",
+ "makeInstallment": "Repetir em parcelas",
+ "installmentCount": "Número de parcelas",
+ "installmentFrequency": "Frequência",
+ "installmentScopeTitle": "Aplicar a quais parcelas?",
+ "installmentScopeEditDesc": "Esta transação faz parte de uma série de parcelas. Até onde esta alteração deve ser aplicada?",
+ "installmentScopeDeleteDesc": "Esta transação faz parte de uma série de parcelas. Quais parcelas devem ser excluídas?",
+ "installmentScopeThis": "Apenas esta",
+ "installmentScopeFuture": "Esta e as futuras",
+ "installmentScopeAll": "Todas as parcelas",
"recurringBadge": "Recorrente",
"recurringLinkedTooltip": "Vinculada a uma conta recorrente",
"recurringLinkedInfo": "Esta transação está vinculada a uma conta recorrente.",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index a74d2358..8505414c 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -324,6 +324,15 @@
"deleted": "Transação eliminada",
"confirmDelete": "Tens a certeza de que queres eliminar esta transação?",
"makeRecurring": "Tornar recorrente",
+ "makeInstallment": "Repetir em prestações",
+ "installmentCount": "Número de prestações",
+ "installmentFrequency": "Frequência",
+ "installmentScopeTitle": "Aplicar a quais prestações?",
+ "installmentScopeEditDesc": "Esta transação faz parte de uma série de prestações. Até onde esta alteração deve ser aplicada?",
+ "installmentScopeDeleteDesc": "Esta transação faz parte de uma série de prestações. Quais prestações devem ser excluídas?",
+ "installmentScopeThis": "Apenas esta",
+ "installmentScopeFuture": "Esta e as futuras",
+ "installmentScopeAll": "Todas as prestações",
"recurringBadge": "Recorrente",
"recurringLinkedTooltip": "Vinculada a uma conta recorrente",
"recurringLinkedInfo": "Esta transação está vinculada a uma conta recorrente.",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 3ed7a893..b1edd323 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -324,6 +324,15 @@
"deleted": "Транзакция удалена",
"confirmDelete": "Вы уверены, что хотите удалить эту транзакцию?",
"makeRecurring": "Сделать регулярной",
+ "makeInstallment": "Повторить платежами",
+ "installmentCount": "Количество платежей",
+ "installmentFrequency": "Периодичность",
+ "installmentScopeTitle": "К каким платежам применить?",
+ "installmentScopeEditDesc": "Эта операция является частью серии платежей. Насколько далеко применить это изменение?",
+ "installmentScopeDeleteDesc": "Эта операция является частью серии платежей. Какие платежи удалить?",
+ "installmentScopeThis": "Только этот",
+ "installmentScopeFuture": "Этот и будущие",
+ "installmentScopeAll": "Все платежи",
"recurringBadge": "Регулярная",
"recurringLinkedTooltip": "Связана с регулярным платежом",
"recurringLinkedInfo": "Эта транзакция связана с регулярным платежом.",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index fef07269..a05f05ad 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -324,6 +324,15 @@
"deleted": "Транзакцію видалено",
"confirmDelete": "Ви впевнені, що хочете видалити цю транзакцію?",
"makeRecurring": "Зробити регулярною",
+ "makeInstallment": "Повторити платежами",
+ "installmentCount": "Кількість платежів",
+ "installmentFrequency": "Періодичність",
+ "installmentScopeTitle": "До яких платежів застосувати?",
+ "installmentScopeEditDesc": "Ця операція є частиною серії платежів. Наскільки далеко застосувати цю зміну?",
+ "installmentScopeDeleteDesc": "Ця операція є частиною серії платежів. Які платежі видалити?",
+ "installmentScopeThis": "Тільки цей",
+ "installmentScopeFuture": "Цей і майбутні",
+ "installmentScopeAll": "Усі платежі",
"recurringBadge": "Регулярна",
"recurringLinkedTooltip": "Пов'язана з регулярним платежем",
"recurringLinkedInfo": "Ця транзакція пов'язана з регулярним платежем.",
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index 89a5db13..65556505 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -14,7 +14,7 @@ import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { ArrowLeft, ArrowLeftRight, CalendarClock, ChevronLeft, ChevronRight, Clock, EyeClosed, HelpCircle, Paperclip, Pencil, X } from 'lucide-react'
import { CategoryIcon } from '@/components/category-icon'
-import { TransactionDialog, extractApiError } from '@/components/transaction-dialog'
+import { TransactionDialog, extractApiError, type TransactionSavePayload } from '@/components/transaction-dialog'
import { TransferDialog } from '@/components/transfer-dialog'
import { DatePickerInput } from '@/components/ui/date-picker-input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
@@ -532,7 +532,7 @@ export default function AccountDetailPage() {
})
const updateMutation = useMutation({
- mutationFn: ({ id: txId, ...data }: Partial<Transaction> & { id: string }) =>
+ mutationFn: ({ id: txId, ...data }: TransactionSavePayload & { id: string }) =>
transactions.update(txId, data),
onSuccess: () => {
invalidateFinancialQueries(queryClient)
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index e02e4cd3..e924f8f0 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -36,14 +36,14 @@ import {
Tooltip,
ResponsiveContainer,
} from 'recharts'
-import { CheckCircle2, CalendarIcon, Paperclip, Target, ArrowUpDown, HelpCircle, EyeClosed } from 'lucide-react'
+import { CheckCircle2, CalendarIcon, Clock, Paperclip, Target, ArrowUpDown, HelpCircle, EyeClosed } from 'lucide-react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { ICON_MAP } from '@/lib/category-icons'
import { PageHeader } from '@/components/page-header'
import { CategoryIcon } from '@/components/category-icon'
import { AccountIcon } from '@/components/account-icon'
import { TransactionDrillDown, type DrillDownFilter } from '@/components/transaction-drill-down'
-import { TransactionDialog, extractApiError } from '@/components/transaction-dialog'
+import { TransactionDialog, extractApiError, type TransactionSavePayload } from '@/components/transaction-dialog'
import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useIsMobile } from '@/hooks/use-mobile'
@@ -52,6 +52,7 @@ import { useCollectionFilter } from '@/contexts/collection-filter-context'
import { resolveDateFnsLocale } from '@/lib/date-fns-locale'
import type { Rule, Transaction } from '@/types'
import { formatCurrency } from '@/lib/format'
+import { shouldShowPendingBadge } from '@/lib/transaction-status'
function formatDate(dateStr: string, locale = 'pt-BR') {
return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale)
@@ -243,7 +244,7 @@ export default function DashboardPage() {
})
const updateMutation = useMutation({
- mutationFn: ({ id, ...data }: Partial<Transaction> & { id: string }) =>
+ mutationFn: ({ id, ...data }: TransactionSavePayload & { id: string }) =>
transactions.update(id, data),
onSuccess: () => {
invalidateFinancialQueries(queryClient)
@@ -424,6 +425,9 @@ export default function DashboardPage() {
parentOwnerName: string | null
groupName: string | null
isIgnored: boolean
+ installmentNumber: number | null
+ totalInstallments: number | null
+ showPendingBadge: boolean
}
const [txPerPage, setTxPerPage] = useState<number>(() => {
@@ -470,7 +474,10 @@ export default function DashboardPage() {
groupId,
parentOwnerName: isShared ? tx.parent_owner_name ?? null : null,
groupName: groupId ? groupNameById.get(groupId) ?? null : null,
- isIgnored: tx.is_ignored
+ isIgnored: tx.is_ignored,
+ installmentNumber: tx.installment_number,
+ totalInstallments: tx.total_installments,
+ showPendingBadge: shouldShowPendingBadge(tx),
})
}
for (const pt of projectedTxs ?? []) {
@@ -494,7 +501,10 @@ export default function DashboardPage() {
groupId: null,
parentOwnerName: null,
groupName: null,
- isIgnored: false
+ isIgnored: false,
+ installmentNumber: null,
+ totalInstallments: null,
+ showPendingBadge: false,
})
}
rows.sort((a, b) => txSortDesc ? b.date.localeCompare(a.date) : a.date.localeCompare(b.date))
@@ -1090,6 +1100,19 @@ export default function DashboardPage() {
{t('transactions.recurringBadge')}
</span>
)}
+ {row.installmentNumber != null && row.totalInstallments != null && (
+ <span className="inline-flex items-center text-[9px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1 py-0.5 rounded-full shrink-0">
+ {row.installmentNumber}/{row.totalInstallments}
+ </span>
+ )}
+ {row.showPendingBadge && (
+ <span
+ title={t('transactions.pending')}
+ className="shrink-0 inline-flex items-center justify-center rounded-full border border-amber-200 bg-amber-50 p-0.5 dark:border-amber-500/30 dark:bg-amber-500/10"
+ >
+ <Clock size={12} className="text-amber-500" role="img" aria-label={t('transactions.pending')} />
+ </span>
+ )}
{row.isIgnored && (
<EyeClosed className="h-3 w-3 text-gray-500 shrink-0" />
)}
@@ -1194,6 +1217,19 @@ export default function DashboardPage() {
{t('transactions.recurringBadge')}
</span>
)}
+ {row.installmentNumber != null && row.totalInstallments != null && (
+ <span className="inline-flex items-center text-[10px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1.5 py-0.5 rounded-full shrink-0">
+ {row.installmentNumber}/{row.totalInstallments}
+ </span>
+ )}
+ {row.showPendingBadge && (
+ <span
+ title={t('transactions.pending')}
+ className="shrink-0 inline-flex items-center justify-center rounded-full border border-amber-200 bg-amber-50 p-0.5 dark:border-amber-500/30 dark:bg-amber-500/10"
+ >
+ <Clock size={12} className="text-amber-500" role="img" aria-label={t('transactions.pending')} />
+ </span>
+ )}
{row.isIgnored && (
<span className="ml-2 inline-flex items-center gap-1 text-xs text-gray-600 font-normal bg-gray-100 border border-gray-200 rounded px-1.5 py-0.5">
<EyeClosed className="h-3 w-3" />
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index 9c5647dc..af166ef3 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -36,13 +36,14 @@ import {
} from '@/components/ui/table'
import { Skeleton } from '@/components/ui/skeleton'
import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, HelpCircle, Info, Paperclip, Trash2, Users, X, EyeClosed, SlidersHorizontal } from 'lucide-react'
-import type { Transaction, Rule } from '@/types'
+import type { Transaction, Rule, InstallmentSeriesInput, TransactionApplyScope, TransactionEditPayload } from '@/types'
import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'
import { PageHeader } from '@/components/page-header'
import { calculateRangeSelection } from '@/lib/selection-utils'
+import { isManualInstallmentSeriesRow } from '@/lib/installment-series'
import { CategoryIcon } from '@/components/category-icon'
import { CategorySelect } from '@/components/category-select'
-import { TransactionDialog, extractApiError, type SaveAction } from '@/components/transaction-dialog'
+import { TransactionDialog, extractApiError, type SaveAction, type TransactionSavePayload } from '@/components/transaction-dialog'
import { TransactionsColumnPicker } from '@/components/transactions-column-picker'
import { TransactionsPageActions } from '@/components/transactions-page-actions'
import { MobileBulkSelectionActions } from '@/components/mobile-bulk-selection-actions'
@@ -60,8 +61,9 @@ import { useWorkspace } from '@/contexts/workspace-context'
import { useCollectionFilter } from '@/contexts/collection-filter-context'
import { formatCurrency } from '@/lib/format'
-type TransactionUpdatePayload = Partial<Transaction> & {
+type TransactionUpdatePayload = TransactionEditPayload & {
apply_to_transfer_pair?: boolean
+ apply_to?: TransactionApplyScope
}
type PendingTransferCategoryUpdate = {
@@ -134,8 +136,11 @@ export default function TransactionsPage() {
const [editingTx, setEditingTx] = useState<Transaction | null>(null)
const [pendingTransferCategoryUpdate, setPendingTransferCategoryUpdate] =
useState<PendingTransferCategoryUpdate | null>(null)
+ // Manual installment-series scoped delete. Scoped edits are handled by the
+ // shared TransactionDialog so account detail and dashboard behave the same.
+ const [pendingSeriesDeleteId, setPendingSeriesDeleteId] = useState<string | null>(null)
const [formResetKey, setFormResetKey] = useState(0)
- const [duplicateDraft, setDuplicateDraft] = useState<Partial<Transaction> | null>(null)
+ const [duplicateDraft, setDuplicateDraft] = useState<TransactionEditPayload | null>(null)
const [viewMode, setViewMode] = useState<'list' | 'calendar'>(() => (
searchParams.get('view') === 'calendar' ? 'calendar' : 'list'
))
@@ -465,8 +470,16 @@ export default function TransactionsPage() {
const invalidateAfterTxMutation = () => invalidateFinancialQueries(queryClient)
const createMutation = useMutation({
- mutationFn: async (payload: { tx: Partial<Transaction>; recurringData?: { frequency: string; end_date?: string }; pendingFiles?: File[]; action?: SaveAction }) => {
- const created = await transactions.create(payload.tx)
+ mutationFn: async (payload: { tx: TransactionEditPayload; recurringData?: { frequency: string; end_date?: string }; installmentData?: InstallmentSeriesInput; pendingFiles?: File[]; action?: SaveAction }) => {
+ let created: Transaction
+ if (payload.installmentData) {
+ // Manual installment series: the backend repeats the base row N
+ // times with the shared installment fingerprint.
+ const series = await transactions.createInstallments(payload.installmentData)
+ created = series[0]
+ } else {
+ created = await transactions.create(payload.tx)
+ }
if (payload.recurringData) {
await recurring.create({
description: payload.tx.description,
@@ -522,7 +535,8 @@ export default function TransactionsPage() {
})
const deleteMutation = useMutation({
- mutationFn: (id: string) => transactions.delete(id),
+ mutationFn: (payload: { id: string; applyTo?: TransactionApplyScope }) =>
+ transactions.delete(payload.id, payload.applyTo ?? 'this'),
onSuccess: () => {
invalidateAfterTxMutation()
setDialogOpen(false)
@@ -832,13 +846,14 @@ export default function TransactionsPage() {
}
const handleTransactionSave = (
- data: Partial<Transaction>,
+ data: TransactionSavePayload,
recurringData?: { frequency: string; end_date?: string },
+ installmentData?: InstallmentSeriesInput,
pendingFiles?: File[],
action?: SaveAction,
) => {
if (!editingTx) {
- createMutation.mutate({ tx: data, recurringData, pendingFiles, action })
+ createMutation.mutate({ tx: data, recurringData, installmentData, pendingFiles, action })
return
}
@@ -855,13 +870,19 @@ export default function TransactionsPage() {
updateMutation.mutate({ id: editingTx.id, ...data })
}
+ const submitPendingSeriesDelete = (scope: TransactionApplyScope) => {
+ if (!pendingSeriesDeleteId) return
+ deleteMutation.mutate({ id: pendingSeriesDeleteId, applyTo: scope })
+ setPendingSeriesDeleteId(null)
+ }
+
// Open the Add Transaction dialog seeded from an existing row's
// fields (issue #158). Identity-bearing fields (id, transfer_pair,
// installment series, splits) are dropped so the dialog treats the
// result as a brand-new transaction; the user can tweak the date or
// any other field before saving.
const handleDuplicateTransaction = (tx: Transaction) => {
- const draft: Partial<Transaction> = {
+ const draft: TransactionEditPayload = {
description: tx.description,
amount: tx.amount,
currency: tx.currency,
@@ -1929,7 +1950,15 @@ export default function TransactionsPage() {
: undefined
}
onSave={handleTransactionSave}
- onDelete={editingTx ? () => deleteMutation.mutate(editingTx.id) : undefined}
+ onDelete={editingTx ? () => {
+ if (isManualInstallmentSeriesRow(editingTx)) {
+ // Deleting one row of a manual series — ask the user
+ // whether to drop this, this+future, or all installments.
+ setPendingSeriesDeleteId(editingTx.id)
+ } else {
+ deleteMutation.mutate({ id: editingTx.id })
+ }
+ } : undefined}
onUnlinkTransfer={(pairId) => unlinkTransferMutation.mutate(pairId)}
onIgnoreChanged={invalidateAfterTxMutation}
onCreateRule={(tx) => {
@@ -1984,6 +2013,52 @@ export default function TransactionsPage() {
</DialogContent>
</Dialog>
+ {/* Installment-series delete scope. Edit scope is handled by the shared
+ TransactionDialog so every edit surface behaves consistently. */}
+ <Dialog
+ open={!!pendingSeriesDeleteId}
+ onOpenChange={(open) => {
+ if (!open) setPendingSeriesDeleteId(null)
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('transactions.installmentScopeTitle')}</DialogTitle>
+ </DialogHeader>
+ <p className="text-sm text-muted-foreground">
+ {t('transactions.installmentScopeDeleteDesc')}
+ </p>
+ <DialogFooter className="flex-col sm:flex-row sm:justify-end gap-2">
+ <Button
+ autoFocus
+ onClick={() => submitPendingSeriesDelete('this')}
+ disabled={updateMutation.isPending || deleteMutation.isPending}
+ className="justify-center"
+ >
+ {updateMutation.isPending || deleteMutation.isPending
+ ? t('common.loading')
+ : t('transactions.installmentScopeThis')}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => submitPendingSeriesDelete('future')}
+ disabled={updateMutation.isPending || deleteMutation.isPending}
+ className="justify-center"
+ >
+ {t('transactions.installmentScopeFuture')}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => submitPendingSeriesDelete('all')}
+ disabled={updateMutation.isPending || deleteMutation.isPending}
+ className="justify-center"
+ >
+ {t('transactions.installmentScopeAll')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
{/* Bulk Delete confirmation */}
<Dialog open={bulkDeleteConfirmOpen} onOpenChange={setBulkDeleteConfirmOpen}>
<DialogContent>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index e53926a8..d0af75e7 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -220,6 +220,7 @@ export interface Transaction {
total_installments: number | null
installment_total_amount: number | null
installment_purchase_date: string | null
+ installment_series_id: string | null
bill_id: string | null
// Manual override for which credit-card bill cycle this tx belongs to
// (issue #92). Empty / null = use auto bucketing (Pluggy bill_id when
@@ -243,6 +244,37 @@ export interface Transaction {
is_ignored: boolean
}
+// Scope for installment-series edits/deletes: "this" (default) only touches
+// the target row, "future" touches it plus later installments, "all" touches
+// the whole series. Ignored server-side for non-installment transactions.
+export type TransactionApplyScope = 'this' | 'future' | 'all'
+
+// Payload for POST /api/transactions/installments. `base` is
+// the amount repeated as-is; the backend fans it out into `installments`
+// equal parcels sharing the installment fingerprint and stores
+// installment_total_amount = base.amount * installments.
+export interface InstallmentSeriesInput {
+ base: {
+ account_id: string
+ category_id?: string | null
+ payee_id?: string | null
+ description: string
+ amount: number
+ date: string
+ type: 'debit' | 'credit'
+ currency?: string
+ notes?: string | null
+ status?: 'posted' | 'pending'
+ amount_primary?: number | null
+ fx_rate_used?: number | null
+ effective_bill_date?: string | null
+ splits?: TransactionSplitsInput | null
+ }
+ installments: number
+ first_installment_status?: 'posted' | 'pending'
+ frequency?: 'monthly' | 'quarterly' | 'weekly' | 'yearly'
+}
+
export type ShareType = 'equal' | 'exact' | 'percent'
export interface TransactionSplit {
@@ -268,6 +300,14 @@ export interface TransactionSplitsInput {
splits: TransactionSplitInput[]
}
+// Payload the transaction dialog sends on save. `splits` is the normalized
+// TransactionSplitsInput the split section produces, not the
+// TransactionSplit[] rows the API returns, so the edit payload type reflects
+// the form's actual shape.
+export type TransactionEditPayload = Omit<Partial<Transaction>, 'splits'> & {
+ splits?: TransactionSplitsInput | null
+}
+
export type GroupKind = 'social' | 'cost_center' | 'project' | 'client' | 'other'
export interface Group {