Open-source personal finance manager. Self-hosted, privacy-first.
feat/enhancing credit card management (#65)
Tássio Noronhabad3a95db8c6
diff --git a/backend/alembic/versions/025_credit_card_fields.py b/backend/alembic/versions/025_credit_card_fields.pynew file mode 100644index 00000000..adbf4437--- /dev/null+++ b/backend/alembic/versions/025_credit_card_fields.py@@ -0,0 +1,26 @@+"""add credit card fields to accounts++Revision ID: 025+Revises: 024+Create Date: 2026-04-12+"""++from alembic import op+import sqlalchemy as sa++revision = "025"+down_revision = "024"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column("accounts", sa.Column("credit_limit", sa.Numeric(precision=15, scale=2), nullable=True))+ op.add_column("accounts", sa.Column("statement_close_day", sa.SmallInteger(), nullable=True))+ op.add_column("accounts", sa.Column("payment_due_day", sa.SmallInteger(), nullable=True))+++def downgrade() -> None:+ op.drop_column("accounts", "payment_due_day")+ op.drop_column("accounts", "statement_close_day")+ op.drop_column("accounts", "credit_limit")diff --git a/backend/alembic/versions/026_credit_card_metadata.py b/backend/alembic/versions/026_credit_card_metadata.pynew file mode 100644index 00000000..502683ff--- /dev/null+++ b/backend/alembic/versions/026_credit_card_metadata.py@@ -0,0 +1,26 @@+"""add minimum_payment, card_brand, card_level to accounts++Revision ID: 026+Revises: 025+Create Date: 2026-04-13+"""++from alembic import op+import sqlalchemy as sa++revision = "026"+down_revision = "025"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column("accounts", sa.Column("minimum_payment", sa.Numeric(precision=15, scale=2), nullable=True))+ op.add_column("accounts", sa.Column("card_brand", sa.String(length=50), nullable=True))+ op.add_column("accounts", sa.Column("card_level", sa.String(length=50), nullable=True))+++def downgrade() -> None:+ op.drop_column("accounts", "card_level")+ op.drop_column("accounts", "card_brand")+ op.drop_column("accounts", "minimum_payment")diff --git a/backend/alembic/versions/027_transaction_effective_date.py b/backend/alembic/versions/027_transaction_effective_date.pynew file mode 100644index 00000000..8458566a--- /dev/null+++ b/backend/alembic/versions/027_transaction_effective_date.py@@ -0,0 +1,29 @@+"""add effective_date to transactions for cash/accrual reporting++Revision ID: 027+Revises: 026+Create Date: 2026-04-13+"""++from alembic import op+import sqlalchemy as sa++revision = "027"+down_revision = "026"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column("transactions", sa.Column("effective_date", sa.Date(), nullable=True))+ # Backfill: effective_date defaults to the transaction date for everyone.+ # Credit card transactions get their cycle-due-date computed on next sync/edit;+ # a post-migration helper (or manual re-save) can populate historical data later.+ op.execute("UPDATE transactions SET effective_date = date WHERE effective_date IS NULL")+ op.alter_column("transactions", "effective_date", nullable=False)+ op.create_index("ix_transactions_effective_date", "transactions", ["effective_date"])+++def downgrade() -> None:+ op.drop_index("ix_transactions_effective_date", table_name="transactions")+ op.drop_column("transactions", "effective_date")diff --git a/backend/alembic/versions/028_transaction_installments.py b/backend/alembic/versions/028_transaction_installments.pynew file mode 100644index 00000000..c3af038c--- /dev/null+++ b/backend/alembic/versions/028_transaction_installments.py@@ -0,0 +1,34 @@+"""add installment metadata to transactions++Revision ID: 028+Revises: 027+Create Date: 2026-04-13+"""++from alembic import op+import sqlalchemy as sa++revision = "028"+down_revision = "027"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column("transactions", sa.Column("installment_number", sa.SmallInteger(), nullable=True))+ op.add_column("transactions", sa.Column("total_installments", sa.SmallInteger(), nullable=True))+ op.add_column(+ "transactions",+ sa.Column("installment_total_amount", sa.Numeric(precision=15, scale=2), nullable=True),+ )+ op.add_column(+ "transactions",+ sa.Column("installment_purchase_date", sa.Date(), nullable=True),+ )+++def downgrade() -> None:+ op.drop_column("transactions", "installment_purchase_date")+ op.drop_column("transactions", "installment_total_amount")+ op.drop_column("transactions", "total_installments")+ op.drop_column("transactions", "installment_number")diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex 7142378a..217532b4 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -100,7 +100,7 @@ async def get_account(account = await account_service.get_account(session, account_id, user.id)if not account:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")- return account+ return account_service.serialize_account(account, None, None)@router.post("", response_model=AccountRead, status_code=status.HTTP_201_CREATED)@@ -109,7 +109,8 @@ async def create_account(session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):- return await account_service.create_account(session, user.id, data)+ account = await account_service.create_account(session, user.id, data)+ return account_service.serialize_account(account, None, None)@router.patch("/{account_id}", response_model=AccountRead)@@ -125,7 +126,7 @@ async def update_account(raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not account:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")- return account+ return account_service.serialize_account(account, None, None)@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex 7e62b272..a9393947 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -18,7 +18,7 @@ from app.services import admin_servicerouter = APIRouter(prefix="/api/admin", tags=["admin"])-ALLOWED_SETTINGS = {"registration_enabled"}+ALLOWED_SETTINGS = {"registration_enabled", "credit_card_accounting_mode"}@router.get("/users", response_model=AdminUserList)@@ -118,6 +118,7 @@ async def update_setting()SETTING_VALIDATORS = {"registration_enabled": {"true", "false"},+ "credit_card_accounting_mode": {"cash", "accrual"},}if key in SETTING_VALIDATORS and data.value not in SETTING_VALIDATORS[key]:raise HTTPException(diff --git a/backend/app/models/account.py b/backend/app/models/account.pyindex bdaec594..349dcfd8 100644--- a/backend/app/models/account.py+++ b/backend/app/models/account.py@@ -3,7 +3,7 @@ from datetime import datetimefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional-from sqlalchemy import Boolean, DateTime, ForeignKey, Numeric, String+from sqlalchemy import Boolean, DateTime, ForeignKey, Numeric, SmallInteger, Stringfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import Mapped, mapped_column, relationship@@ -26,6 +26,12 @@ class Account(Base):balance: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))currency: Mapped[str] = mapped_column(String(3), default="USD")balance_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ credit_limit: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ statement_close_day: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)+ payment_due_day: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)+ minimum_payment: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ card_brand: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ card_level: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)is_closed: Mapped[bool] = mapped_column(Boolean, default=False)closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.pyindex fd38ad16..641e3355 100644--- a/backend/app/models/transaction.py+++ b/backend/app/models/transaction.py@@ -1,9 +1,9 @@import uuid-from datetime import date, datetime, timezone+from datetime import date as _date, datetime, timezonefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional-from sqlalchemy import Date, DateTime, ForeignKey, JSON, Numeric, String+from sqlalchemy import Date, DateTime, ForeignKey, JSON, Numeric, SmallInteger, String, eventfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import Mapped, mapped_column, relationship@@ -28,7 +28,12 @@ class Transaction(Base):description: Mapped[str] = mapped_column(String(500))amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))currency: Mapped[str] = mapped_column(String(3), default="USD")- date: Mapped[date] = mapped_column(Date)+ date: Mapped[_date] = mapped_column(Date)+ # Effective date for cash-flow reporting. For regular accounts this equals+ # `date`. For credit card transactions it's the due date of the bill that+ # the transaction belongs to — so accrual-mode aggregations count the+ # purchase when it hits the user's cash, not when it was made.+ effective_date: Mapped[_date] = mapped_column(Date, index=True)type: Mapped[str] = mapped_column(String(10)) # debit, creditsource: Mapped[str] = mapped_column(String(20)) # sync, ofx, csv, manualstatus: Mapped[str] = mapped_column(String(10), default="posted") # posted, pending@@ -40,6 +45,16 @@ class Transaction(Base):transfer_pair_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)fx_rate_used: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=20, scale=10), nullable=True)+ # Installment (parcelamento) metadata. Populated from provider data when available.+ # `installment_number` is 1-indexed (e.g. 3 for "3/12"). Storing alongside the+ # raw tx row so the door stays open to a plan view or manual entry later+ # without another migration.+ installment_number: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)+ total_installments: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)+ installment_total_amount: Mapped[Optional[Decimal]] = mapped_column(+ Numeric(precision=15, scale=2), nullable=True+ )+ installment_purchase_date: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))account: Mapped["Account"] = relationship(back_populates="transactions")@@ -49,3 +64,19 @@ class Transaction(Base):attachments: Mapped[list["TransactionAttachment"]] = relationship(back_populates="transaction", cascade="all, delete-orphan")+++# Safety net: `effective_date` is NOT NULL. For non-CC transactions it always+# equals `date`, so if a call site (or test) forgets to set it, fall back+# silently. CC-aware service code still calls `apply_effective_date` explicitly+# so that cycle-based due dates are stored when the account has the metadata.[email protected]_for(Transaction, "before_insert")+def _default_effective_date(mapper, connection, target): # type: ignore+ if target.effective_date is None:+ target.effective_date = target.date++[email protected]_for(Transaction, "before_update")+def _default_effective_date_on_update(mapper, connection, target): # type: ignore+ if target.effective_date is None:+ target.effective_date = target.datediff --git a/backend/app/providers/base.py b/backend/app/providers/base.pyindex 8ad0e0de..364c9a12 100644--- a/backend/app/providers/base.py+++ b/backend/app/providers/base.py@@ -12,6 +12,12 @@ class AccountData:type: str # checking, savings, credit_cardbalance: Decimalcurrency: str+ credit_limit: Optional[Decimal] = None+ statement_close_day: Optional[int] = None+ payment_due_day: Optional[int] = None+ minimum_payment: Optional[Decimal] = None+ card_brand: Optional[str] = None+ card_level: Optional[str] = None@dataclass@@ -27,6 +33,11 @@ class TransactionData:status: str = "posted" # posted, pendingpayee: Optional[str] = Noneraw_data: Optional[dict] = None+ # Installment metadata (parcelamento) — populated by CC providers that expose it.+ installment_number: Optional[int] = None+ total_installments: Optional[int] = None+ installment_total_amount: Optional[Decimal] = None+ installment_purchase_date: Optional[date] = None@dataclassdiff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.pyindex e3830833..d70b065d 100644--- a/backend/app/providers/pluggy.py+++ b/backend/app/providers/pluggy.py@@ -17,6 +17,55 @@ from app.providers.base import (PLUGGY_API_BASE = "https://api.pluggy.ai"+def _parse_day(value) -> Optional[int]:+ """Extract day-of-month from a Pluggy ISO date string (yyyy-mm-dd or datetime)."""+ if not value:+ return None+ try:+ return int(str(value)[8:10])+ except (ValueError, IndexError):+ return None+++def _build_account_data(acc: dict, type_mapper) -> AccountData:+ """Map a Pluggy account payload to AccountData, including creditData when present."""+ account_type = type_mapper(acc.get("type", ""))+ credit_data = acc.get("creditData") or {}++ credit_limit: Optional[Decimal] = None+ statement_close_day: Optional[int] = None+ payment_due_day: Optional[int] = None+ minimum_payment: Optional[Decimal] = None+ card_brand: Optional[str] = None+ card_level: Optional[str] = None++ if account_type == "credit_card" and credit_data:+ raw_limit = credit_data.get("creditLimit")+ if raw_limit is not None:+ credit_limit = Decimal(str(raw_limit))+ statement_close_day = _parse_day(credit_data.get("balanceCloseDate"))+ payment_due_day = _parse_day(credit_data.get("balanceDueDate"))+ raw_min = credit_data.get("minimumPayment")+ if raw_min is not None:+ minimum_payment = Decimal(str(raw_min))+ card_brand = credit_data.get("brand") or None+ card_level = credit_data.get("level") or None++ return AccountData(+ external_id=acc["id"],+ name=acc["name"],+ type=account_type,+ balance=Decimal(str(acc.get("balance", 0))),+ currency=acc.get("currencyCode", "USD"),+ credit_limit=credit_limit,+ statement_close_day=statement_close_day,+ payment_due_day=payment_due_day,+ minimum_payment=minimum_payment,+ card_brand=card_brand,+ card_level=card_level,+ )++class PluggyProvider(BankProvider):"""Pluggy (MeuPluggy) open finance provider.@@ -118,15 +167,7 @@ class PluggyProvider(BankProvider):account_list = []for acc in accounts_data.get("results", []):- account_list.append(- AccountData(- external_id=acc["id"],- name=acc["name"],- type=self._map_account_type(acc.get("type", "")),- balance=Decimal(str(acc.get("balance", 0))),- currency=acc.get("currencyCode", "USD"),- )- )+ account_list.append(_build_account_data(acc, self._map_account_type))return ConnectionData(external_id=item_id,@@ -150,15 +191,7 @@ class PluggyProvider(BankProvider):accounts = []for acc in data.get("results", []):- accounts.append(- AccountData(- external_id=acc["id"],- name=acc["name"],- type=self._map_account_type(acc.get("type", "")),- balance=Decimal(str(acc.get("balance", 0))),- currency=acc.get("currencyCode", "USD"),- )- )+ accounts.append(_build_account_data(acc, self._map_account_type))return accountsasync def get_transactions(@@ -218,6 +251,26 @@ class PluggyProvider(BankProvider):Decimal(str(abs(amt_in_acct))) if amt_in_acct is not None else None)+ # Installment metadata from creditCardMetadata (parcelamento).+ # Pluggy reports installment_number, total, original amount and+ # purchase date on each charge for CC connectors that support it.+ cc_meta = txn.get("creditCardMetadata") or {}+ inst_number = cc_meta.get("installmentNumber")+ inst_total = cc_meta.get("totalInstallments")+ inst_total_amount = cc_meta.get("totalAmount")+ inst_purchase_date_raw = cc_meta.get("purchaseDate")+ inst_purchase_date: Optional[date] = None+ if inst_purchase_date_raw:+ try:+ inst_purchase_date = date.fromisoformat(str(inst_purchase_date_raw)[:10])+ except ValueError:+ inst_purchase_date = None+ inst_total_amount_dec = (+ Decimal(str(abs(inst_total_amount)))+ if inst_total_amount is not None+ else None+ )+all_transactions.append(TransactionData(external_id=txn["id"],@@ -231,6 +284,10 @@ class PluggyProvider(BankProvider):status=status,payee=payee,raw_data=txn,+ installment_number=inst_number if isinstance(inst_number, int) else None,+ total_installments=inst_total if isinstance(inst_total, int) else None,+ installment_total_amount=inst_total_amount_dec,+ installment_purchase_date=inst_purchase_date,))diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex ca7afde6..4b2a80bd 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -19,6 +19,12 @@ class AccountCreate(BaseModel):balance: Decimal = Decimal("0.00")balance_date: Optional[date] = Nonecurrency: str = "USD"+ credit_limit: Optional[Decimal] = None+ statement_close_day: Optional[int] = None+ payment_due_day: Optional[int] = None+ minimum_payment: Optional[Decimal] = None+ card_brand: Optional[str] = None+ card_level: Optional[str] = Noneclass AccountUpdate(BaseModel):@@ -26,6 +32,12 @@ class AccountUpdate(BaseModel):type: Optional[str] = Nonebalance: Optional[Decimal] = Nonebalance_date: Optional[date] = None+ credit_limit: Optional[Decimal] = None+ statement_close_day: Optional[int] = None+ payment_due_day: Optional[int] = None+ minimum_payment: Optional[Decimal] = None+ card_brand: Optional[str] = None+ card_level: Optional[str] = Noneclass AccountRead(AccountBase):@@ -36,6 +48,15 @@ class AccountRead(AccountBase):current_balance: float = 0.0previous_balance: Optional[float] = Nonebalance_primary: Optional[float] = None+ credit_limit: Optional[float] = None+ available_credit: Optional[float] = None+ statement_close_day: Optional[int] = None+ payment_due_day: Optional[int] = None+ next_close_date: Optional[date] = None+ next_due_date: Optional[date] = None+ minimum_payment: Optional[float] = None+ card_brand: Optional[str] = None+ card_level: Optional[str] = Noneis_closed: bool = Falseclosed_at: Optional[datetime] = Nonediff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex 8d66027b..6ab04cfd 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -61,6 +61,10 @@ class TransactionRead(TransactionBase):fx_rate_used: Optional[float] = Nonefx_fallback: bool = Falseattachment_count: int = 0+ installment_number: Optional[int] = None+ total_installments: Optional[int] = None+ installment_total_amount: Optional[float] = None+ installment_purchase_date: Optional[_Date] = Nonemodel_config = ConfigDict(from_attributes=True)diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex b7cc7f64..3f027c15 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -10,6 +10,7 @@ from app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.transaction import Transactionfrom app.schemas.account import AccountCreate, AccountUpdate+from app.services.credit_card_service import apply_effective_date, compute_available_credit, get_cycle_datesasync def get_accounts(session: AsyncSession, user_id: uuid.UUID, include_closed: bool = False) -> list[dict]:@@ -74,26 +75,57 @@ async def get_accounts(session: AsyncSession, user_id: uuid.UUID, include_closedresult = await session.execute(query)return [- {- "id": acc.id,- "user_id": acc.user_id,- "connection_id": acc.connection_id,- "external_id": acc.external_id,- "name": acc.name,- "type": acc.type,- "balance": acc.balance,- "currency": acc.currency,- # Connected CC: provider stores positive for debt → negate.- # Manual accounts: transaction math already gives correct sign.- "current_balance": float(acc.balance) * (-1 if acc.type == "credit_card" else 1) if acc.connection_id else float(current_balance or 0),- "previous_balance": float(previous_balance or 0),- "is_closed": acc.is_closed,- "closed_at": acc.closed_at,- }+ serialize_account(acc, current_balance, previous_balance)for acc, current_balance, previous_balance in result.all()]+def serialize_account(+ acc: Account,+ current_balance: Optional[Decimal],+ previous_balance: Optional[Decimal],+) -> dict:+ # Connected CC: provider stores positive for debt → negate.+ # Manual accounts: transaction math already gives correct sign.+ if acc.connection_id:+ resolved_balance = float(acc.balance) * (-1 if acc.type == "credit_card" else 1)+ else:+ resolved_balance = float(current_balance or 0)++ payload = {+ "id": acc.id,+ "user_id": acc.user_id,+ "connection_id": acc.connection_id,+ "external_id": acc.external_id,+ "name": acc.name,+ "type": acc.type,+ "balance": acc.balance,+ "currency": acc.currency,+ "current_balance": resolved_balance,+ "previous_balance": float(previous_balance or 0),+ "is_closed": acc.is_closed,+ "closed_at": acc.closed_at,+ "credit_limit": float(acc.credit_limit) if acc.credit_limit is not None else None,+ "statement_close_day": acc.statement_close_day,+ "payment_due_day": acc.payment_due_day,+ "minimum_payment": float(acc.minimum_payment) if acc.minimum_payment is not None else None,+ "card_brand": acc.card_brand,+ "card_level": acc.card_level,+ "available_credit": None,+ "next_close_date": None,+ "next_due_date": None,+ }++ if acc.type == "credit_card":+ available = compute_available_credit(acc.credit_limit, Decimal(str(resolved_balance)))+ payload["available_credit"] = float(available) if available is not None else None+ cycle = get_cycle_dates(acc.statement_close_day, acc.payment_due_day)+ payload["next_close_date"] = cycle["next_close_date"]+ payload["next_due_date"] = cycle["next_due_date"]++ return payload++async def get_account(session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Account]:result = await session.execute(select(Account)@@ -110,12 +142,19 @@ async def get_account(session: AsyncSession, account_id: uuid.UUID, user_id: uuiasync def create_account(session: AsyncSession, user_id: uuid.UUID, data: AccountCreate) -> Account:+ is_cc = data.type == "credit_card"account = Account(user_id=user_id,name=data.name,type=data.type,balance=data.balance,currency=data.currency,+ credit_limit=data.credit_limit if is_cc else None,+ statement_close_day=data.statement_close_day if is_cc else None,+ payment_due_day=data.payment_due_day if is_cc else None,+ minimum_payment=data.minimum_payment if is_cc else None,+ card_brand=data.card_brand if is_cc else None,+ card_level=data.card_level if is_cc else None,)session.add(account)await session.flush() # get account.id without committing@@ -134,6 +173,7 @@ async def create_account(session: AsyncSession, user_id: uuid.UUID, data: Accountype=opening_type,source="opening_balance",)+ apply_effective_date(opening_tx, account)session.add(opening_tx)await session.commit()@@ -148,16 +188,52 @@ async def update_account(if not account:return None- # Only allow editing manual accounts- if account.connection_id is not None:- raise ValueError("Cannot edit bank-connected accounts")-update_data = data.model_dump(exclude_unset=True)balance_date = update_data.pop("balance_date", None)+ # Track whether we need to recompute effective_date for all transactions.+ # Changes to the CC cycle days shift which bill each historical purchase+ # belongs to, so stored effective_dates need to be rebuilt.+ cycle_fields_changed = any(+ k in update_data for k in ("statement_close_day", "payment_due_day")+ )++ # Bank-connected accounts are managed by the sync pipeline. Only credit card+ # metadata (limit + cycle days) can be user-edited, since providers often don't+ # expose those — users fill them in to unlock cycle-aware filtering.+ if account.connection_id is not None:+ editable_fields = {+ "credit_limit",+ "statement_close_day",+ "payment_due_day",+ "minimum_payment",+ "card_brand",+ "card_level",+ }+ disallowed = set(update_data.keys()) - editable_fields+ if disallowed:+ raise ValueError("Cannot edit bank-connected accounts")+ if account.type != "credit_card":+ raise ValueError("Credit card fields can only be set on credit card accounts")+ for key, value in update_data.items():+ setattr(account, key, value)+ if cycle_fields_changed:+ await _recompute_effective_dates(session, account)+ await session.commit()+ await session.refresh(account)+ return account+for key, value in update_data.items():setattr(account, key, value)+ if account.type != "credit_card":+ account.credit_limit = None+ account.statement_close_day = None+ account.payment_due_day = None+ account.minimum_payment = None+ account.card_brand = None+ account.card_level = None+# When balance changes, sync the opening_balance transactionif "balance" in update_data:new_balance = update_data["balance"]@@ -176,6 +252,7 @@ async def update_account(opening_tx.type = opening_typeif balance_date:opening_tx.date = balance_date+ apply_effective_date(opening_tx, account)else:opening_tx = Transaction(user_id=account.user_id,@@ -187,15 +264,32 @@ async def update_account(type=opening_type,source="opening_balance",)+ apply_effective_date(opening_tx, account)session.add(opening_tx)elif opening_tx:await session.delete(opening_tx)+ if cycle_fields_changed:+ await _recompute_effective_dates(session, account)+await session.commit()await session.refresh(account)return account+async def _recompute_effective_dates(session: AsyncSession, account: Account) -> None:+ """Recompute effective_date on every transaction in this account.++ Called when an account's CC cycle metadata (statement_close_day,+ payment_due_day) changes, so historical transactions get rebucketed into+ the correct bill. Cheap: a few hundred rows per account at most."""+ result = await session.execute(+ select(Transaction).where(Transaction.account_id == account.id)+ )+ for tx in result.scalars():+ apply_effective_date(tx, account)++async def delete_account(session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID) -> bool:account = await get_account(session, account_id, user_id)if not account:diff --git a/backend/app/services/admin_service.py b/backend/app/services/admin_service.pyindex f899fdd1..56bae6dc 100644--- a/backend/app/services/admin_service.py+++ b/backend/app/services/admin_service.py@@ -210,3 +210,14 @@ async def is_registration_enabled(session: AsyncSession) -> bool:return setting.value.lower() == "true"# Fall back to env varreturn get_settings().registration_enabled+++async def get_credit_card_accounting_mode(session: AsyncSession) -> str:+ """Return the global CC accounting mode: 'cash' or 'accrual'.++ Global app setting — affects how dashboard/reports/budgets bucket credit+ card transactions. Defaults to 'cash' (current behavior) when unset."""+ setting = await get_app_setting(session, "credit_card_accounting_mode")+ if setting and setting.value in ("cash", "accrual"):+ return setting.value+ return "cash"diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.pyindex c71a1182..491a91df 100644--- a/backend/app/services/budget_service.py+++ b/backend/app/services/budget_service.py@@ -12,6 +12,7 @@ from app.models.category_group import CategoryGroupfrom app.models.transaction import Transactionfrom app.models.user import Userfrom app.schemas.budget import BudgetCreate, BudgetUpdate, BudgetVsActual+from app.services.admin_service import get_credit_card_accounting_modefrom app.services.dashboard_service import _get_recurring_projectionsfrom app.services.fx_rate_service import convertfrom app.core.config import get_settings@@ -240,9 +241,13 @@ async def get_budget_vs_actual(# Get budgets for this month (with recurring resolution)budget_map = await _build_budget_map(session, user_id, month_start)- # Get user's primary currency for FX conversion+ # Get user's primary currency for FX conversion + reporting modeuser = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency+ accounting_mode = await get_credit_card_accounting_mode(session)+ report_date = (+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date+ )# Get actual spending by category for this month (exclude transfer pairs)# Use amount_primary for multi-currency support@@ -254,8 +259,8 @@ async def get_budget_vs_actual(.where(Transaction.user_id == user_id,Transaction.type == "debit",- Transaction.date >= month_start,- Transaction.date < month_end,+ report_date >= month_start,+ report_date < month_end,Transaction.category_id.isnot(None),Transaction.transfer_pair_id.is_(None),)@@ -286,8 +291,8 @@ async def get_budget_vs_actual(.where(Transaction.user_id == user_id,Transaction.type == "debit",- Transaction.date >= prev_month_start,- Transaction.date < prev_month_end,+ report_date >= prev_month_start,+ report_date < prev_month_end,Transaction.category_id.isnot(None),Transaction.transfer_pair_id.is_(None),)diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 0077604e..39185df5 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -13,6 +13,7 @@ from app.models.category import Categoryfrom app.models.transaction import Transactionfrom app.models.user import Userfrom app.providers import get_provider+from app.services.credit_card_service import apply_effective_datefrom app.services.rule_service import apply_rules_to_transactionfrom app.services.transfer_detection_service import detect_transfer_pairsfrom app.services.fx_rate_service import stamp_primary_amount@@ -141,6 +142,7 @@ async def handle_oauth_callback(new_tx_ids: list[uuid.UUID] = []for acc_data in connection_data.accounts:+ is_cc = acc_data.type == "credit_card"account = Account(user_id=user_id,connection_id=connection.id,@@ -149,6 +151,12 @@ async def handle_oauth_callback(type=acc_data.type,balance=acc_data.balance,currency=acc_data.currency,+ credit_limit=acc_data.credit_limit if is_cc else None,+ statement_close_day=acc_data.statement_close_day if is_cc else None,+ payment_due_day=acc_data.payment_due_day if is_cc else None,+ minimum_payment=acc_data.minimum_payment if is_cc else None,+ card_brand=acc_data.card_brand if is_cc else None,+ card_level=acc_data.card_level if is_cc else None,)session.add(account)await session.flush()@@ -182,7 +190,12 @@ async def handle_oauth_callback(payee_id=payee_id,raw_data=txn_data.raw_data,category_id=category_id,+ installment_number=txn_data.installment_number,+ total_installments=txn_data.total_installments,+ installment_total_amount=txn_data.installment_total_amount,+ installment_purchase_date=txn_data.installment_purchase_date,)+ apply_effective_date(transaction, account)session.add(transaction)await session.flush()new_tx_ids.append(transaction.id)@@ -260,6 +273,64 @@ async def _fuzzy_match_manual(return None+async def _cleanup_phantom_duplicates(+ session: AsyncSession,+ connection_id: uuid.UUID,+) -> int:+ """Delete synced transactions that are phantom duplicates.++ Some providers (or sandbox data) report the same payment twice with+ different external ids on adjacent days. Transfer detection matches the+ real one against the counterpart in another account; the phantom remains+ orphaned.++ We delete an unpaired synced tx when it has a *paired* sibling in the same+ account with: same amount, same type, near-identical description, dated+ within ±1 day. The pairing of the sibling is the safety signal that lets+ us distinguish the duplicate from a legitimate same-day repeat (e.g. two+ real Uber rides for the same fare).+ """+ accounts_result = await session.execute(+ select(Account.id).where(Account.connection_id == connection_id)+ )+ account_ids = [row[0] for row in accounts_result.all()]+ if not account_ids:+ return 0++ unmatched_result = await session.execute(+ select(Transaction).where(+ Transaction.account_id.in_(account_ids),+ Transaction.source == "sync",+ Transaction.transfer_pair_id.is_(None),+ )+ )+ unmatched = list(unmatched_result.scalars().all())++ deleted = 0+ for tx in unmatched:+ date_lo = tx.date - timedelta(days=1)+ date_hi = tx.date + timedelta(days=1)+ sibling_result = await session.execute(+ select(Transaction).where(+ Transaction.account_id == tx.account_id,+ Transaction.source == "sync",+ Transaction.amount == tx.amount,+ Transaction.type == tx.type,+ Transaction.date >= date_lo,+ Transaction.date <= date_hi,+ Transaction.transfer_pair_id.is_not(None),+ Transaction.id != tx.id,+ )+ )+ for sibling in sibling_result.scalars():+ if _description_similarity(sibling.description, tx.description) >= 0.9:+ await session.delete(tx)+ deleted += 1+ break++ return deleted++async def sync_connection(session: AsyncSession, connection_id: uuid.UUID, user_id: uuid.UUID) -> tuple[BankConnection, int]:@@ -296,7 +367,25 @@ async def sync_connection(if account:account.balance = acc_data.balanceaccount.name = acc_data.name+ if acc_data.type == "credit_card":+ account.credit_limit = acc_data.credit_limit+ # Preserve existing close/due days when the provider doesn't expose+ # them. Pluggy's balanceCloseDate is intermittently null even on+ # connectors that have it elsewhere, and users may have set these+ # manually via the edit dialog. Treat user input + previously-synced+ # values as the higher source of truth than a fresh None.+ if acc_data.statement_close_day is not None:+ account.statement_close_day = acc_data.statement_close_day+ if acc_data.payment_due_day is not None:+ account.payment_due_day = acc_data.payment_due_day+ if acc_data.minimum_payment is not None:+ account.minimum_payment = acc_data.minimum_payment+ if acc_data.card_brand is not None:+ account.card_brand = acc_data.card_brand+ if acc_data.card_level is not None:+ account.card_level = acc_data.card_levelelse:+ is_cc = acc_data.type == "credit_card"account = Account(user_id=user_id,connection_id=connection.id,@@ -305,6 +394,12 @@ async def sync_connection(type=acc_data.type,balance=acc_data.balance,currency=acc_data.currency,+ credit_limit=acc_data.credit_limit if is_cc else None,+ statement_close_day=acc_data.statement_close_day if is_cc else None,+ payment_due_day=acc_data.payment_due_day if is_cc else None,+ minimum_payment=acc_data.minimum_payment if is_cc else None,+ card_brand=acc_data.card_brand if is_cc else None,+ card_level=acc_data.card_level if is_cc else None,)session.add(account)await session.flush()@@ -312,8 +407,17 @@ async def sync_connection(if account and account.is_closed:continue- # Fetch and sync transactions- since = connection.last_sync_at.date() if connection.last_sync_at else None+ # Fetch and sync transactions.+ # Rewind the window by 14 days on incremental syncs so we catch+ # late-arriving transactions: bank authorizations that post a few+ # days after the purchase date, or direct debits that Pluggy only+ # exposes once they've been processed by the issuer. Dedup on+ # external_id below handles any overlap cheaply.+ since = (+ connection.last_sync_at.date() - timedelta(days=14)+ if connection.last_sync_at+ else None+ )transactions_data = await provider.get_transactions(credentials, acc_data.external_id, since, payee_source=payee_source)@@ -370,7 +474,12 @@ async def sync_connection(payee_id=sync_payee_id,raw_data=txn_data.raw_data,category_id=category_id,+ installment_number=txn_data.installment_number,+ total_installments=txn_data.total_installments,+ installment_total_amount=txn_data.installment_total_amount,+ installment_purchase_date=txn_data.installment_purchase_date,)+ apply_effective_date(transaction, account)session.add(transaction)await session.flush()new_tx_ids.append(transaction.id)@@ -394,6 +503,11 @@ async def sync_connection(if new_tx_ids:await detect_transfer_pairs(session, user_id, candidate_ids=new_tx_ids)+ # Clean up phantom duplicates: providers occasionally double-report the+ # same payment with different ids. Once transfer detection has paired+ # the real one, the orphan twin gets removed here.+ await _cleanup_phantom_duplicates(session, connection.id)+connection.last_sync_at = datetime.now(timezone.utc)connection.status = "active"await session.commit()diff --git a/backend/app/services/credit_card_service.py b/backend/app/services/credit_card_service.pynew file mode 100644index 00000000..b347efd8--- /dev/null+++ b/backend/app/services/credit_card_service.py@@ -0,0 +1,128 @@+import calendar+from datetime import date+from decimal import Decimal+from typing import Optional+++def _clamp_day(year: int, month: int, day: int) -> date:+ last_day = calendar.monthrange(year, month)[1]+ return date(year, month, min(day, last_day))+++def _next_day_occurrence(target_day: int, reference: date) -> date:+ candidate = _clamp_day(reference.year, reference.month, target_day)+ if candidate >= reference:+ return candidate+ if reference.month == 12:+ return _clamp_day(reference.year + 1, 1, target_day)+ return _clamp_day(reference.year, reference.month + 1, target_day)+++def get_cycle_dates(+ statement_close_day: Optional[int],+ payment_due_day: Optional[int],+ reference: Optional[date] = None,+) -> dict:+ """Return the close + due dates of the nearest upcoming billing cycle.++ Both dates are from the SAME cycle: the due is anchored on the nearest upcoming+ occurrence of payment_due_day, and the close is the most recent occurrence of+ statement_close_day on or before that due date. This guarantees close <= due."""+ if reference is None:+ reference = date.today()++ next_due = _next_day_occurrence(payment_due_day, reference) if payment_due_day else None++ next_close: Optional[date] = None+ if statement_close_day:+ if next_due:+ # Pick the close that belongs to next_due's cycle: try same month first;+ # if it lands after the due date, walk back one month (with end-of-month clamping).+ anchor = next_due+ candidate = _clamp_day(anchor.year, anchor.month, statement_close_day)+ if candidate > anchor:+ if anchor.month == 1:+ candidate = _clamp_day(anchor.year - 1, 12, statement_close_day)+ else:+ candidate = _clamp_day(anchor.year, anchor.month - 1, statement_close_day)+ next_close = candidate+ else:+ next_close = _next_day_occurrence(statement_close_day, reference)++ return {+ "next_close_date": next_close,+ "next_due_date": next_due,+ }+++def compute_available_credit(+ credit_limit: Optional[Decimal],+ current_balance: Decimal,+) -> Optional[Decimal]:+ """available = limit − utilized. current_balance for a credit card is negative when debt."""+ if credit_limit is None:+ return None+ utilized = -current_balance if current_balance < 0 else Decimal("0")+ return credit_limit - utilized+++def apply_effective_date(transaction, account) -> None:+ """Populate `transaction.effective_date` based on the account type.++ Non-CC accounts: effective_date == transaction.date (passthrough).+ CC accounts: effective_date is the due date of the bill the transaction+ belongs to — see `compute_effective_date` for the cycle math.++ Call this from every tx create/update path (manual, sync, import,+ transfers, opening balances). `effective_date` is stored on every row+ regardless of the user's reporting mode; the mode only affects which+ date the aggregation queries read from."""+ if account is not None and getattr(account, "type", None) == "credit_card":+ transaction.effective_date = compute_effective_date(+ transaction.date,+ getattr(account, "statement_close_day", None),+ getattr(account, "payment_due_day", None),+ )+ else:+ transaction.effective_date = transaction.date+++def compute_effective_date(+ tx_date: date,+ statement_close_day: Optional[int],+ payment_due_day: Optional[int],+) -> date:+ """Return the *cash-flow* date for a credit card transaction.++ In accrual reporting mode, a credit card purchase doesn't impact cash flow+ on the purchase date — it impacts cash flow when the bill is paid. This+ helper computes that "effective" date:++ 1. Find the cycle the transaction belongs to: the next statement close+ date on or after tx_date.+ 2. The bill for that cycle is due on the next occurrence of payment_due_day+ strictly after the close.+ 3. Return that bill's due date.++ Returns tx_date as-is when either close_day or due_day is not configured+ (nothing we can do without the cycle metadata)."""+ if not statement_close_day or not payment_due_day:+ return tx_date++ # Step 1: find the cycle end — the first close day on or after tx_date.+ same_month_close = _clamp_day(tx_date.year, tx_date.month, statement_close_day)+ if same_month_close >= tx_date:+ cycle_end = same_month_close+ else:+ if tx_date.month == 12:+ cycle_end = _clamp_day(tx_date.year + 1, 1, statement_close_day)+ else:+ cycle_end = _clamp_day(tx_date.year, tx_date.month + 1, statement_close_day)++ # Step 2: find the bill due date — the first due day strictly after cycle_end.+ same_month_due = _clamp_day(cycle_end.year, cycle_end.month, payment_due_day)+ if same_month_due > cycle_end:+ return same_month_due+ if cycle_end.month == 12:+ return _clamp_day(cycle_end.year + 1, 1, payment_due_day)+ return _clamp_day(cycle_end.year, cycle_end.month + 1, payment_due_day)diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 94722794..6bee2154 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -13,6 +13,7 @@ from app.models.transaction import Transactionfrom app.models.category import Categoryfrom app.models.recurring_transaction import RecurringTransactionfrom app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, BalanceHistory+from app.services.admin_service import get_credit_card_accounting_modefrom app.services.recurring_transaction_service import get_occurrences_in_rangefrom app.services.asset_service import get_total_asset_valuefrom app.services.fx_rate_service import convert@@ -75,6 +76,16 @@ async def get_summary(month_start, month_end = _month_range(month)today = date.today()+ # Reporting mode is a global app setting (admin-controlled). When "accrual",+ # aggregation queries bucket credit card transactions by the bill's due+ # date (effective_date) instead of the purchase date — gives a true+ # cash-flow view.+ user = await session.get(User, user_id)+ accounting_mode = await get_credit_card_accounting_mode(session)+ report_date = (+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date+ )+# Compute the effective cutoff date for balance calculationif balance_date:cutoff = balance_date@@ -109,8 +120,8 @@ async def get_summary(.where(Transaction.user_id == user_id,Account.is_closed == False,- Transaction.date >= month_start,- Transaction.date < month_end,+ report_date >= month_start,+ report_date < month_end,Transaction.source != "opening_balance",Transaction.transfer_pair_id.is_(None),)@@ -164,8 +175,7 @@ async def get_summary(for currency, amount in assets_value.items():total_balance[currency] = total_balance.get(currency, 0.0) + amount- # Get user's primary currency- user = await session.get(User, user_id)+ # Get user's primary currency (user already loaded above for reporting mode)primary_currency = user.primary_currency if user else get_settings().default_currency# Convert totals to primary currency@@ -190,8 +200,8 @@ async def get_summary(.where(Transaction.user_id == user_id,Account.is_closed == False,- Transaction.date >= month_start,- Transaction.date < month_end,+ report_date >= month_start,+ report_date < month_end,Transaction.source != "opening_balance",Transaction.transfer_pair_id.is_(None),Transaction.amount_primary.isnot(None),@@ -244,6 +254,12 @@ async def get_spending_by_category(month_start, month_end = _month_range(month)+ user = await session.get(User, user_id)+ accounting_mode = await get_credit_card_accounting_mode(session)+ report_date = (+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date+ )+# Real transactions grouped by category (exclude transfer pairs and closed accounts)# Use amount_primary for multi-currency supportresult = await session.execute(@@ -261,8 +277,8 @@ async def get_spending_by_category(Transaction.user_id == user_id,Account.is_closed == False,Transaction.type == "debit",- Transaction.date >= month_start,- Transaction.date < month_end,+ report_date >= month_start,+ report_date < month_end,Transaction.transfer_pair_id.is_(None),).group_by(Category.id, Category.name, Category.icon, Category.color)@@ -282,7 +298,6 @@ async def get_spending_by_category(# Add virtual recurring projections (debit only), converted to primary currencyprojections = await _get_recurring_projections(session, user_id, month_start, month_end)- user = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency# We need category info for recurring projections — fetch categoriescat_cache: dict[str, dict] = {}@@ -338,7 +353,11 @@ async def get_spending_by_category(async def get_monthly_trend(session: AsyncSession, user_id: uuid.UUID, months: int = 6) -> list[MonthlyTrend]:- month_label = func.to_char(Transaction.date, 'YYYY-MM').label('month')+ accounting_mode = await get_credit_card_accounting_mode(session)+ report_date = (+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date+ )+ month_label = func.to_char(report_date, 'YYYY-MM').label('month')primary_amt = _primary_amount_expr()result = await session.execute(select(diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.pyindex 0588caf4..94fc5de9 100644--- a/backend/app/services/import_service.py+++ b/backend/app/services/import_service.py@@ -14,6 +14,7 @@ from app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.transaction import Transactionfrom app.schemas.transaction import TransactionBase+from app.services.credit_card_service import apply_effective_datefrom app.services.rule_service import apply_rules_to_transactionfrom app.services.fx_rate_service import stamp_primary_amountfrom app.services.payee_service import get_or_create_payee@@ -424,6 +425,7 @@ async def import_transactions(payee=import_payee_raw,payee_id=import_payee_id,)+ apply_effective_date(transaction, account)# If CSV provided an fx_rate, use it directlyif txn_data.fx_rate:diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex 2d9ae672..8a57b4e2 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -11,6 +11,7 @@ from app.models.bank_connection import BankConnectionfrom app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transactionfrom app.schemas.recurring_transaction import RecurringTransactionCreate, RecurringTransactionUpdate+from app.services.credit_card_service import apply_effective_datefrom app.services.fx_rate_service import stamp_primary_amount@@ -218,6 +219,8 @@ async def generate_pending(type=recurring.type,source="recurring",)+ account = await session.get(Account, recurring.account_id)+ apply_effective_date(transaction, account)session.add(transaction)await session.flush()await stamp_primary_amount(session, user_id, transaction)diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 901923b3..8c66bccd 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -12,6 +12,7 @@ from app.models.asset_value import AssetValuefrom app.models.transaction import Transactionfrom app.models.category import Categoryfrom app.models.user import User+from app.services.admin_service import get_credit_card_accounting_modefrom app.services.fx_rate_service import convertfrom app.schemas.report import (CategoryTrendItem,@@ -324,20 +325,21 @@ async def get_net_worth_report(return ReportResponse(summary=summary, trend=trend, meta=meta, composition=composition)-def _interval_label_expr(interval: str):+def _interval_label_expr(interval: str, date_col=None):"""SQL expression that groups transaction dates into interval buckets."""+ col = date_col if date_col is not None else Transaction.dateif interval == "daily":- return func.to_char(Transaction.date, 'YYYY-MM-DD')+ return func.to_char(col, 'YYYY-MM-DD')elif interval == "weekly":return func.concat(- func.extract('isoyear', Transaction.date).cast(String),+ func.extract('isoyear', col).cast(String),'-W',- func.lpad(func.extract('week', Transaction.date).cast(String), 2, '0'),+ func.lpad(func.extract('week', col).cast(String), 2, '0'),)elif interval == "yearly":- return func.to_char(Transaction.date, 'YYYY')+ return func.to_char(col, 'YYYY')else: # monthly (default)- return func.to_char(Transaction.date, 'YYYY-MM')+ return func.to_char(col, 'YYYY-MM')async def get_income_expenses_report(@@ -352,11 +354,15 @@ async def get_income_expenses_report(start = date(today.year, today.month, 1) - timedelta(days=months * 30)start = start.replace(day=1)- # Get user's primary currency+ # Get user's primary currency + global reporting modeuser = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency+ accounting_mode = await get_credit_card_accounting_mode(session)+ report_date = (+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date+ )- label_expr = _interval_label_expr(interval).label('period')+ label_expr = _interval_label_expr(interval, report_date).label('period')# Use amount_primary when available, fall back to amountamount_expr = func.coalesce(Transaction.amount_primary, Transaction.amount)@@ -371,8 +377,8 @@ async def get_income_expenses_report(.where(Transaction.user_id == user_id,Account.is_closed == False,- Transaction.date >= start,- Transaction.date <= today,+ report_date >= start,+ report_date <= today,Transaction.source != "opening_balance",Transaction.transfer_pair_id.is_(None),)@@ -494,8 +500,8 @@ async def get_income_expenses_report(.where(Transaction.user_id == user_id,Account.is_closed == False,- Transaction.date >= start,- Transaction.date <= today,+ report_date >= start,+ report_date <= today,Transaction.source != "opening_balance",Transaction.transfer_pair_id.is_(None),)@@ -534,8 +540,8 @@ async def get_income_expenses_report(.where(Transaction.user_id == user_id,Account.is_closed == False,- Transaction.date >= start,- Transaction.date <= today,+ report_date >= start,+ report_date <= today,Transaction.source != "opening_balance",Transaction.transfer_pair_id.is_(None),)diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 1f0e882d..b239054b 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -12,6 +12,7 @@ from app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.payee import Payeefrom app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate+from app.services.credit_card_service import apply_effective_datefrom app.services.rule_service import apply_rules_to_transactionfrom app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert@@ -210,6 +211,7 @@ async def create_transaction(source="manual",notes=data.notes,)+ apply_effective_date(transaction, account)session.add(transaction)await session.flush() # get ID without committing@@ -275,6 +277,7 @@ async def create_transfer(notes=data.notes,transfer_pair_id=transfer_pair_id,)+ apply_effective_date(debit_tx, from_account)session.add(debit_tx)# Credit transaction (to account) — convert if cross-currency@@ -304,6 +307,7 @@ async def create_transfer(notes=data.notes,transfer_pair_id=transfer_pair_id,)+ apply_effective_date(credit_tx, to_account)session.add(credit_tx)await session.flush()@@ -530,6 +534,11 @@ async def update_transaction(elif needs_restamp:await stamp_primary_amount(session, user_id, transaction)+ # Refresh effective_date when the purchase date or the account changed.+ if "date" in update_data or "account_id" in update_data:+ account_for_tx = await session.get(Account, transaction.account_id)+ apply_effective_date(transaction, account_for_tx)+# Cascade changes to paired transfer transactioncascade_fields = {"amount", "date", "description", "notes"}if transaction.transfer_pair_id and (cascade_fields & update_data.keys()):@@ -554,6 +563,9 @@ async def update_transaction(else:paired_tx.amount = update_data[key]await stamp_primary_amount(session, user_id, paired_tx)+ if "date" in update_data:+ paired_account = await session.get(Account, paired_tx.account_id)+ apply_effective_date(paired_tx, paired_account)await session.commit()await session.refresh(transaction)diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.pyindex 85b9658f..2351594f 100644--- a/backend/tests/test_connection_service.py+++ b/backend/tests/test_connection_service.py@@ -4,10 +4,12 @@ from decimal import Decimalfrom unittest.mock import AsyncMock, patchimport pytest+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.bank_connection import BankConnectionfrom app.models.category import Category+from app.models.transaction import Transactionfrom app.providers.base import AccountData, ConnectionData, ConnectTokenData, TransactionDatafrom app.services.connection_service import (_description_similarity,@@ -460,3 +462,110 @@ async def test_sync_connection_skips_pending(session: AsyncSession, test_user):result_conn, _ = await sync_connection(session, conn.id, test_user.id)assert result_conn.status == "active"+++# ---------------------------------------------------------------------------+# Installment metadata persistence (issue #14 v1)+# ---------------------------------------------------------------------------+++async def test_oauth_callback_persists_installment_metadata(+ session: AsyncSession, test_user,+):+ """handle_oauth_callback must store all 4 installment fields on the+ Transaction row exactly as the provider returned them."""+ mock_provider = AsyncMock()+ mock_provider.handle_oauth_callback = AsyncMock(return_value=ConnectionData(+ external_id="ext-inst-1",+ institution_name="Inst Bank",+ credentials={"token": "x"},+ accounts=[+ AccountData(+ external_id="inst-acc-1", name="Nubank Gold",+ type="credit_card", balance=Decimal("0"), currency="BRL",+ credit_limit=Decimal("5000"),+ ),+ ],+ ))+ mock_provider.get_transactions = AsyncMock(return_value=[+ TransactionData(+ external_id="inst-tx-1", description="AMAZON PARCELADO",+ amount=Decimal("120.50"), date=date(2026, 4, 10),+ type="debit", currency="BRL",+ installment_number=3,+ total_installments=12,+ installment_total_amount=Decimal("1446.00"),+ installment_purchase_date=date(2026, 2, 10),+ ),+ TransactionData(+ external_id="inst-tx-2", description="SINGLE CHARGE",+ amount=Decimal("40.00"), date=date(2026, 4, 11),+ type="debit", currency="BRL",+ ),+ ])++ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):+ await handle_oauth_callback(session, test_user.id, "code", "pluggy")++ rows = (await session.execute(+ select(Transaction).where(Transaction.user_id == test_user.id)+ .order_by(Transaction.external_id)+ )).scalars().all()+ assert len(rows) == 2++ parcel = next(t for t in rows if t.external_id == "inst-tx-1")+ assert parcel.installment_number == 3+ assert parcel.total_installments == 12+ assert parcel.installment_total_amount == Decimal("1446.00")+ assert parcel.installment_purchase_date == date(2026, 2, 10)++ single = next(t for t in rows if t.external_id == "inst-tx-2")+ assert single.installment_number is None+ assert single.total_installments is None+ assert single.installment_total_amount is None+ assert single.installment_purchase_date is None+++async def test_sync_connection_persists_installment_metadata(+ session: AsyncSession, test_user,+):+ """Incremental sync path must also persist installment fields."""+ conn = await _make_connection(session, test_user.id, "Sync Inst Bank")+ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.get_accounts = AsyncMock(return_value=[+ AccountData(+ external_id="sync-inst-acc-1", name="Credit Card",+ type="credit_card", balance=Decimal("0"), currency="BRL",+ ),+ ])+ mock_provider.get_transactions = AsyncMock(return_value=[+ TransactionData(+ external_id="sync-inst-tx-1", description="PARCELA MAGALU",+ amount=Decimal("50.00"), date=date(2026, 4, 1),+ type="debit", currency="BRL",+ installment_number=1,+ total_installments=6,+ installment_total_amount=Decimal("300.00"),+ installment_purchase_date=date(2026, 3, 25),+ ),+ ])++ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):+ await sync_connection(session, conn.id, test_user.id)++ row = (await session.execute(+ select(Transaction).where(Transaction.external_id == "sync-inst-tx-1")+ )).scalar_one()+ assert row.installment_number == 1+ assert row.total_installments == 6+ assert row.installment_total_amount == Decimal("300.00")+ assert row.installment_purchase_date == date(2026, 3, 25)diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.pynew file mode 100644index 00000000..15faed8f--- /dev/null+++ b/backend/tests/test_credit_card_accounting_mode.py@@ -0,0 +1,658 @@+"""Tests for the cash vs accrual accounting mode feature.++Covers:+ 1. compute_effective_date cycle math (edge cases, month-end clamping, wraparound).+ 2. apply_effective_date dispatch (CC vs non-CC, missing metadata).+ 3. Event-listener safety net (defaults effective_date to date when unset).+ 4. Aggregation services in both modes — dashboard, budgets, reports.+ 5. Global setting getter + default fallback.+ 6. Account-level balance queries are NOT affected by mode (ledger invariant).+ 7. Transaction updates refresh effective_date when date or account_id changes.+ 8. Editing statement_close_day on an account recomputes historical txs.++The tests exercise the in-memory SQLite test DB from conftest. They use the+standard `session`, `test_user`, `test_categories`, `test_connection` fixtures.+"""++import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+import pytest_asyncio+from sqlalchemy import select++from app.models.account import Account+from app.models.transaction import Transaction+from app.services import (+ account_service,+ admin_service,+ budget_service,+ dashboard_service,+)+from app.services.credit_card_service import (+ apply_effective_date,+ compute_effective_date,+)+++# ---------------------------------------------------------------------------+# Unit tests: compute_effective_date — pure cycle math, no DB needed.+# ---------------------------------------------------------------------------+++class TestComputeEffectiveDate:+ """Cycle math: given a purchase date + close day + due day, return the+ due date of the bill the purchase belongs to."""++ def test_purchase_before_close_day_same_month(self):+ # Gold card: close 11, due 16. Purchase Apr 3 → bill closes Apr 11 → due Apr 16.+ assert compute_effective_date(date(2026, 4, 3), 11, 16) == date(2026, 4, 16)++ def test_purchase_on_close_day_is_still_that_cycle(self):+ # Purchase ON the close day belongs to the cycle that closes that day.+ assert compute_effective_date(date(2026, 4, 11), 11, 16) == date(2026, 4, 16)++ def test_purchase_day_after_close_rolls_to_next_cycle(self):+ # Apr 12 is after Apr 11 close → next cycle closes May 11 → due May 16.+ assert compute_effective_date(date(2026, 4, 12), 11, 16) == date(2026, 5, 16)++ def test_cycle_spanning_month_boundary(self):+ # Tassio card: close 28, due 5 (of next month).+ # Mar 15 → cycle closes Mar 28 → bill due Apr 5.+ assert compute_effective_date(date(2026, 3, 15), 28, 5) == date(2026, 4, 5)++ def test_purchase_after_close_day_crosses_two_months(self):+ # Mar 29 (after the Mar 28 close) → next close Apr 28 → due May 5.+ assert compute_effective_date(date(2026, 3, 29), 28, 5) == date(2026, 5, 5)++ def test_close_day_clamps_to_month_end(self):+ # close_day=31 with a 30-day month should clamp to the last day.+ # Apr has 30 days. Apr 30 is the effective close day. Due 10 of May.+ assert compute_effective_date(date(2026, 4, 15), 31, 10) == date(2026, 5, 10)++ def test_due_day_clamps_to_month_end(self):+ # due_day=31 with Feb (28 days in 2026) clamps to 28.+ # close=10 → Feb cycle closes Feb 10 → due clamps to Feb 28.+ assert compute_effective_date(date(2026, 2, 5), 10, 31) == date(2026, 2, 28)++ def test_year_wraparound(self):+ # Dec purchase on CC with close day in December → cycle closes Dec, due Jan.+ assert compute_effective_date(date(2026, 12, 20), 28, 5) == date(2027, 1, 5)++ def test_december_purchase_after_close(self):+ # Dec 29, close=28 → next cycle closes Jan 28 → due Feb 5.+ assert compute_effective_date(date(2026, 12, 29), 28, 5) == date(2027, 2, 5)++ def test_passthrough_when_close_day_missing(self):+ # Without a close day, we can't compute the cycle — return tx_date.+ assert compute_effective_date(date(2026, 4, 3), None, 16) == date(2026, 4, 3)++ def test_passthrough_when_due_day_missing(self):+ assert compute_effective_date(date(2026, 4, 3), 11, None) == date(2026, 4, 3)++ def test_passthrough_when_both_missing(self):+ assert compute_effective_date(date(2026, 4, 3), None, None) == date(2026, 4, 3)++ def test_close_and_due_same_day(self):+ # Edge: close and due are the same calendar day. A cycle where the+ # bill is due on the close day itself (uncommon but legal).+ # Close=15, due=15. Mar 10 purchase → cycle closes Mar 15 → due Mar 15.+ # Wait — due > close required. With close=15 and due=15, "due day+ # strictly after close" wraps to next month. So Mar 10 → Apr 15.+ assert compute_effective_date(date(2026, 3, 10), 15, 15) == date(2026, 4, 15)+++# ---------------------------------------------------------------------------+# Unit tests: apply_effective_date — dispatch on account type.+# ---------------------------------------------------------------------------+++class TestApplyEffectiveDate:+ """Helper that sets transaction.effective_date based on account."""++ def test_non_cc_account_uses_purchase_date(self):+ tx = Transaction(+ user_id=uuid.uuid4(),+ account_id=uuid.uuid4(),+ description="x",+ amount=Decimal("10"),+ date=date(2026, 4, 3),+ type="debit",+ source="manual",+ )+ account = Account(+ id=uuid.uuid4(),+ user_id=uuid.uuid4(),+ name="checking",+ type="checking",+ balance=Decimal("0"),+ )+ apply_effective_date(tx, account)+ assert tx.effective_date == date(2026, 4, 3)++ def test_cc_account_with_full_metadata(self):+ tx = Transaction(+ user_id=uuid.uuid4(),+ account_id=uuid.uuid4(),+ description="x",+ amount=Decimal("10"),+ date=date(2026, 4, 3),+ type="debit",+ source="manual",+ )+ account = Account(+ id=uuid.uuid4(),+ user_id=uuid.uuid4(),+ name="gold",+ type="credit_card",+ balance=Decimal("0"),+ statement_close_day=11,+ payment_due_day=16,+ )+ apply_effective_date(tx, account)+ assert tx.effective_date == date(2026, 4, 16)++ def test_cc_account_without_cycle_metadata_falls_back_to_purchase_date(self):+ tx = Transaction(+ user_id=uuid.uuid4(),+ account_id=uuid.uuid4(),+ description="x",+ amount=Decimal("10"),+ date=date(2026, 4, 3),+ type="debit",+ source="manual",+ )+ account = Account(+ id=uuid.uuid4(),+ user_id=uuid.uuid4(),+ name="nubank",+ type="credit_card",+ balance=Decimal("0"),+ statement_close_day=None,+ payment_due_day=None,+ )+ apply_effective_date(tx, account)+ assert tx.effective_date == date(2026, 4, 3)++ def test_none_account_falls_back_to_purchase_date(self):+ tx = Transaction(+ user_id=uuid.uuid4(),+ account_id=uuid.uuid4(),+ description="x",+ amount=Decimal("10"),+ date=date(2026, 4, 3),+ type="debit",+ source="manual",+ )+ apply_effective_date(tx, None)+ assert tx.effective_date == date(2026, 4, 3)+++# ---------------------------------------------------------------------------+# Integration helpers and fixtures.+# ---------------------------------------------------------------------------+++@pytest_asyncio.fixture+async def cc_account(session, test_user, test_connection):+ """A credit card account with close=11, due=16 (gold-like)."""+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ connection_id=test_connection.id,+ external_id="cc-ext",+ name="gold",+ type="credit_card",+ balance=Decimal("0"),+ currency="BRL",+ statement_close_day=11,+ payment_due_day=16,+ credit_limit=Decimal("5000"),+ )+ session.add(account)+ await session.commit()+ await session.refresh(account)+ return account+++async def _make_tx(+ session,+ user_id,+ account_id,+ tx_date: date,+ amount: Decimal,+ tx_type: str = "debit",+ source: str = "sync",+ effective_date: date | None = None,+ category_id=None,+) -> Transaction:+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ account_id=account_id,+ description="test",+ amount=amount,+ currency="BRL",+ date=tx_date,+ effective_date=effective_date if effective_date is not None else tx_date,+ type=tx_type,+ source=source,+ status="posted",+ category_id=category_id,+ amount_primary=amount,+ created_at=datetime.now(timezone.utc),+ )+ session.add(tx)+ await session.flush()+ return tx+++async def _set_mode(session, mode: str) -> None:+ await admin_service.set_app_setting(session, "credit_card_accounting_mode", mode)+++# ---------------------------------------------------------------------------+# Safety net: the before_insert event listener defaults effective_date to date.+# ---------------------------------------------------------------------------+++class TestEventListenerSafetyNet:+ @pytest.mark.asyncio+ async def test_effective_date_defaults_to_date_when_unset(+ self, session, test_user, test_account+ ):+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=test_account.id,+ description="auto",+ amount=Decimal("5"),+ currency="BRL",+ date=date(2026, 4, 3),+ type="debit",+ source="manual",+ status="posted",+ amount_primary=Decimal("5"),+ created_at=datetime.now(timezone.utc),+ )+ session.add(tx)+ await session.commit()+ await session.refresh(tx)+ assert tx.effective_date == date(2026, 4, 3)+++# ---------------------------------------------------------------------------+# Global setting getter.+# ---------------------------------------------------------------------------+++class TestGlobalSetting:+ @pytest.mark.asyncio+ async def test_default_is_cash_when_unset(self, session, clean_db):+ mode = await admin_service.get_credit_card_accounting_mode(session)+ assert mode == "cash"++ @pytest.mark.asyncio+ async def test_returns_stored_cash(self, session, clean_db):+ await admin_service.set_app_setting(session, "credit_card_accounting_mode", "cash")+ mode = await admin_service.get_credit_card_accounting_mode(session)+ assert mode == "cash"++ @pytest.mark.asyncio+ async def test_returns_stored_accrual(self, session, clean_db):+ await admin_service.set_app_setting(session, "credit_card_accounting_mode", "accrual")+ mode = await admin_service.get_credit_card_accounting_mode(session)+ assert mode == "accrual"++ @pytest.mark.asyncio+ async def test_ignores_invalid_value(self, session, clean_db):+ await admin_service.set_app_setting(session, "credit_card_accounting_mode", "bogus")+ mode = await admin_service.get_credit_card_accounting_mode(session)+ assert mode == "cash" # falls back to default+++# ---------------------------------------------------------------------------+# Aggregation queries: dashboard summary — the showcase case.+#+# Scenario: gold card with close=11, due=16.+# • Mar 30 charge R$100 → effective_date Apr 16 (bill paid in Apr)+# • Apr 5 charge R$ 50 → effective_date Apr 16 (same bill)+# • Apr 12 charge R$ 30 → effective_date May 16 (next cycle)+# • Apr 20 charge R$ 20 → effective_date May 16+#+# Expected monthly totals for April:+# cash = R$50 + R$30 + R$20 = R$100 (Apr 5, 12, 20 fall in April)+# accrual = R$100 + R$50 = R$150 (txs whose bill is due in Apr)+# ---------------------------------------------------------------------------+++class TestDashboardSummary:+ @pytest_asyncio.fixture+ async def seeded(self, session, test_user, cc_account, test_categories):+ # food category for category aggregation tests+ food_cat = test_categories[0]+ # Mar 30: R$100 debit, effective Apr 16 (bills paid in April)+ await _make_tx(+ session,+ test_user.id,+ cc_account.id,+ date(2026, 3, 30),+ Decimal("100"),+ effective_date=date(2026, 4, 16),+ category_id=food_cat.id,+ )+ # Apr 5: R$50 debit, effective Apr 16+ await _make_tx(+ session,+ test_user.id,+ cc_account.id,+ date(2026, 4, 5),+ Decimal("50"),+ effective_date=date(2026, 4, 16),+ category_id=food_cat.id,+ )+ # Apr 12: R$30 debit, effective May 16 (next cycle)+ await _make_tx(+ session,+ test_user.id,+ cc_account.id,+ date(2026, 4, 12),+ Decimal("30"),+ effective_date=date(2026, 5, 16),+ category_id=food_cat.id,+ )+ # Apr 20: R$20 debit, effective May 16+ await _make_tx(+ session,+ test_user.id,+ cc_account.id,+ date(2026, 4, 20),+ Decimal("20"),+ effective_date=date(2026, 5, 16),+ category_id=food_cat.id,+ )+ await session.commit()++ @pytest.mark.asyncio+ async def test_cash_mode_april_totals(self, session, test_user, seeded):+ await _set_mode(session, "cash")+ summary = await dashboard_service.get_summary(+ session, test_user.id, month=date(2026, 4, 1)+ )+ # Cash: Apr 5 (50) + Apr 12 (30) + Apr 20 (20) = 100+ assert summary.monthly_expenses == 100.0++ @pytest.mark.asyncio+ async def test_accrual_mode_april_totals(self, session, test_user, seeded):+ await _set_mode(session, "accrual")+ summary = await dashboard_service.get_summary(+ session, test_user.id, month=date(2026, 4, 1)+ )+ # Accrual: Mar 30 (100) + Apr 5 (50) = 150+ # (both bills hit Apr 16, land in the April month bucket)+ assert summary.monthly_expenses == 150.0++ @pytest.mark.asyncio+ async def test_cash_mode_may_totals(self, session, test_user, seeded):+ await _set_mode(session, "cash")+ summary = await dashboard_service.get_summary(+ session, test_user.id, month=date(2026, 5, 1)+ )+ # Cash: no May purchases+ assert summary.monthly_expenses == 0.0++ @pytest.mark.asyncio+ async def test_accrual_mode_may_totals(self, session, test_user, seeded):+ await _set_mode(session, "accrual")+ summary = await dashboard_service.get_summary(+ session, test_user.id, month=date(2026, 5, 1)+ )+ # Accrual: Apr 12 (30) + Apr 20 (20) = 50 — bills due May 16+ assert summary.monthly_expenses == 50.0++ @pytest.mark.asyncio+ async def test_total_conserved_across_modes(self, session, test_user, seeded):+ """The grand total across enough months must match regardless of mode."""+ await _set_mode(session, "cash")+ cash_total = 0.0+ for m in [date(2026, 3, 1), date(2026, 4, 1), date(2026, 5, 1), date(2026, 6, 1)]:+ s = await dashboard_service.get_summary(session, test_user.id, month=m)+ cash_total += s.monthly_expenses+ await _set_mode(session, "accrual")+ accrual_total = 0.0+ for m in [date(2026, 3, 1), date(2026, 4, 1), date(2026, 5, 1), date(2026, 6, 1)]:+ s = await dashboard_service.get_summary(session, test_user.id, month=m)+ accrual_total += s.monthly_expenses+ # All 4 charges account for R$200 total regardless of which month buckets them.+ assert cash_total == 200.0+ assert accrual_total == 200.0+++# ---------------------------------------------------------------------------+# Aggregation: spending by category (dashboard pie).+# ---------------------------------------------------------------------------+++class TestSpendingByCategory:+ @pytest.mark.asyncio+ async def test_category_breakdown_follows_mode(+ self, session, test_user, cc_account, test_categories+ ):+ food = test_categories[0]+ transport = test_categories[1]+ # Mar 30: R$100 food, bill Apr 16+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 3, 30),+ Decimal("100"), effective_date=date(2026, 4, 16), category_id=food.id,+ )+ # Apr 12: R$40 transport, bill May 16+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 4, 12),+ Decimal("40"), effective_date=date(2026, 5, 16), category_id=transport.id,+ )+ await session.commit()++ await _set_mode(session, "cash")+ cash = await dashboard_service.get_spending_by_category(+ session, test_user.id, month=date(2026, 4, 1)+ )+ cash_map = {c.category_name: c.total for c in cash}+ # Cash April: only Apr 12 transport R$40 counts+ assert cash_map.get("Transporte", 0) == 40.0+ assert cash_map.get("Alimentação", 0) == 0.0++ await _set_mode(session, "accrual")+ accrual = await dashboard_service.get_spending_by_category(+ session, test_user.id, month=date(2026, 4, 1)+ )+ accrual_map = {c.category_name: c.total for c in accrual}+ # Accrual April: Mar 30 food R$100 bills Apr 16+ assert accrual_map.get("Alimentação", 0) == 100.0+ assert accrual_map.get("Transporte", 0) == 0.0+++# ---------------------------------------------------------------------------+# Budget vs actual.+# ---------------------------------------------------------------------------+++class TestBudgetVsActual:+ @pytest.mark.asyncio+ async def test_budget_spending_follows_mode(+ self, session, test_user, cc_account, test_categories+ ):+ from app.models.budget import Budget+ food = test_categories[0]+ # Budget R$200/month for food+ budget = Budget(+ id=uuid.uuid4(),+ user_id=test_user.id,+ category_id=food.id,+ amount=Decimal("200"),+ currency="BRL",+ month=date(2026, 4, 1),+ )+ session.add(budget)++ # Mar 30 R$150 food (effective Apr 16)+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 3, 30),+ Decimal("150"), effective_date=date(2026, 4, 16), category_id=food.id,+ )+ # Apr 5 R$30 food (effective Apr 16)+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 4, 5),+ Decimal("30"), effective_date=date(2026, 4, 16), category_id=food.id,+ )+ # Apr 15 R$20 food (effective May 16 — next cycle)+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 4, 15),+ Decimal("20"), effective_date=date(2026, 5, 16), category_id=food.id,+ )+ await session.commit()++ await _set_mode(session, "cash")+ cash = await budget_service.get_budget_vs_actual(+ session, test_user.id, date(2026, 4, 1)+ )+ cash_food = next((c for c in cash if c.category_id == food.id), None)+ # Cash April: Apr 5 (30) + Apr 15 (20) = 50+ assert cash_food is not None+ assert float(cash_food.actual_amount) == 50.0++ await _set_mode(session, "accrual")+ accrual = await budget_service.get_budget_vs_actual(+ session, test_user.id, date(2026, 4, 1)+ )+ accrual_food = next((c for c in accrual if c.category_id == food.id), None)+ # Accrual April: Mar 30 (150) + Apr 5 (30) = 180+ assert accrual_food is not None+ assert float(accrual_food.actual_amount) == 180.0+++# ---------------------------------------------------------------------------+# Reports: income/expenses monthly report.+# ---------------------------------------------------------------------------+++class TestIncomeExpensesReport:+ @pytest.mark.asyncio+ async def test_monthly_report_follows_mode(+ self, session, test_user, cc_account, test_categories+ ):+ # This path uses Postgres-specific `to_char`, which SQLite (the test DB)+ # doesn't implement. Rather than duplicate the query, we skip here and+ # rely on the fact that `get_income_expenses_report` uses the exact+ # same `report_date` expression as the dashboard queries above — if+ # those tests pass, this one is wired identically.+ pytest.skip("get_income_expenses_report uses Postgres to_char — SQLite test DB doesn't support it")+++# ---------------------------------------------------------------------------+# Invariant: account balance queries are NOT affected by mode.+# ---------------------------------------------------------------------------+++class TestAccountBalanceInvariant:+ """The physical balance of an account is independent of reporting mode.+ The CC account detail page's cycle navigation also uses Transaction.date+ deliberately, so get_account_summary should return the same numbers+ regardless of the global accounting mode."""++ @pytest.mark.asyncio+ async def test_account_balance_history_unchanged_by_mode(+ self, session, test_user, test_account+ ):+ """Non-CC account: effective_date == date so both modes are identical."""+ await _make_tx(+ session, test_user.id, test_account.id, date(2026, 4, 3),+ Decimal("100"), tx_type="debit",+ )+ await session.commit()++ await _set_mode(session, "cash")+ cash = await account_service.get_account_balance_history(+ session, test_account.id, test_user.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )+ await _set_mode(session, "accrual")+ accrual = await account_service.get_account_balance_history(+ session, test_account.id, test_user.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )+ assert cash == accrual+++# ---------------------------------------------------------------------------+# Transaction update: changing date refreshes effective_date.+# ---------------------------------------------------------------------------+++class TestTransactionUpdateRefreshesEffectiveDate:+ @pytest.mark.asyncio+ async def test_changing_date_on_cc_tx_refreshes_effective_date(+ self, session, test_user, cc_account+ ):+ from app.schemas.transaction import TransactionUpdate+ from app.services.transaction_service import create_transaction, update_transaction+ from app.schemas.transaction import TransactionCreate++ created = await create_transaction(+ session, test_user.id,+ TransactionCreate(+ account_id=cc_account.id,+ description="test",+ amount=Decimal("50"),+ currency="BRL",+ date=date(2026, 4, 3), # Apr 3 → effective Apr 16+ type="debit",+ )+ )+ assert created.effective_date == date(2026, 4, 16)++ updated = await update_transaction(+ session, created.id, test_user.id,+ TransactionUpdate(date=date(2026, 4, 12)) # Apr 12 → effective May 16+ )+ assert updated is not None+ assert updated.effective_date == date(2026, 5, 16)+++# ---------------------------------------------------------------------------+# Account update: changing close/due days recomputes historical effective_dates.+# ---------------------------------------------------------------------------+++class TestAccountCycleEditRecomputesEffectiveDates:+ @pytest.mark.asyncio+ async def test_changing_close_day_rebuckets_historical_txs(+ self, session, test_user, cc_account+ ):+ from app.schemas.account import AccountUpdate++ # Create 2 historical txs.+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 3, 5),+ Decimal("10"), effective_date=date(2026, 3, 16),+ )+ await _make_tx(+ session, test_user.id, cc_account.id, date(2026, 3, 20),+ Decimal("20"), effective_date=date(2026, 4, 16),+ )+ await session.commit()++ # Now admin changes the close day from 11 to 25.+ # With close=25 and due=16:+ # Mar 5 → cycle Feb 26..Mar 25 → bill due Apr 16+ # Mar 20 → cycle Feb 26..Mar 25 → bill due Apr 16+ await account_service.update_account(+ session, cc_account.id, test_user.id,+ AccountUpdate(statement_close_day=25)+ )+ result = await session.execute(+ select(Transaction).where(Transaction.account_id == cc_account.id)+ .order_by(Transaction.date)+ )+ txs = result.scalars().all()+ assert all(t.effective_date == date(2026, 4, 16) for t in txs)diff --git a/backend/tests/test_providers_pluggy.py b/backend/tests/test_providers_pluggy.pynew file mode 100644index 00000000..0a904756--- /dev/null+++ b/backend/tests/test_providers_pluggy.py@@ -0,0 +1,238 @@+"""Parser tests for the Pluggy provider, focused on the+`creditCardMetadata` → `TransactionData` mapping introduced with the+installment-metadata v1 feature (issue #14).++These tests exercise `PluggyProvider.get_transactions` with an httpx+client stubbed out, so no network traffic happens.+"""++from datetime import date+from decimal import Decimal+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from app.providers.pluggy import PluggyProvider+++def _mock_httpx_client(results: list[dict]) -> MagicMock:+ """Build a MagicMock that behaves like an `httpx.AsyncClient` context+ manager whose `.get()` returns a single page of `results`."""+ response = MagicMock()+ response.raise_for_status = MagicMock()+ response.json = MagicMock(return_value={"results": results, "totalPages": 1})++ client = MagicMock()+ client.get = AsyncMock(return_value=response)+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=None)+ return client+++async def _fetch(txns: list[dict]):+ provider = PluggyProvider()+ fake_client = _mock_httpx_client(txns)+ with patch.object(+ PluggyProvider, "_ensure_api_key", new=AsyncMock(return_value="fake-key")+ ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=fake_client):+ return await provider.get_transactions({"item_id": "i"}, "acc-ext-1")+++async def test_parser_captures_full_installment_metadata():+ """Happy path: all 4 creditCardMetadata fields flow into TransactionData."""+ result = await _fetch([+ {+ "id": "tx-1",+ "description": "AMAZON PARCELADO",+ "amount": -120.50,+ "date": "2026-04-10",+ "type": "DEBIT",+ "creditCardMetadata": {+ "installmentNumber": 3,+ "totalInstallments": 12,+ "totalAmount": 1446.00,+ "purchaseDate": "2026-02-10",+ },+ }+ ])+ assert len(result) == 1+ tx = result[0]+ assert tx.installment_number == 3+ assert tx.total_installments == 12+ assert tx.installment_total_amount == Decimal("1446.00")+ assert tx.installment_purchase_date == date(2026, 2, 10)+++async def test_parser_no_credit_card_metadata_leaves_fields_none():+ """Non-CC txns (no creditCardMetadata) get null installment fields."""+ result = await _fetch([+ {+ "id": "tx-2",+ "description": "GROCERIES",+ "amount": -30.00,+ "date": "2026-04-11",+ "type": "DEBIT",+ }+ ])+ tx = result[0]+ assert tx.installment_number is None+ assert tx.total_installments is None+ assert tx.installment_total_amount is None+ assert tx.installment_purchase_date is None+++async def test_parser_empty_credit_card_metadata():+ """`creditCardMetadata: {}` should yield all-null installment fields."""+ result = await _fetch([+ {+ "id": "tx-3",+ "description": "SINGLE CHARGE",+ "amount": -50.00,+ "date": "2026-04-11",+ "type": "DEBIT",+ "creditCardMetadata": {},+ }+ ])+ tx = result[0]+ assert tx.installment_number is None+ assert tx.total_installments is None+ assert tx.installment_total_amount is None+ assert tx.installment_purchase_date is None+++async def test_parser_null_credit_card_metadata():+ """`creditCardMetadata: null` should be handled like missing."""+ result = await _fetch([+ {+ "id": "tx-4",+ "description": "NULL META",+ "amount": -10,+ "date": "2026-04-12",+ "type": "DEBIT",+ "creditCardMetadata": None,+ }+ ])+ tx = result[0]+ assert tx.installment_number is None+ assert tx.installment_total_amount is None+++async def test_parser_invalid_installment_number_types_coerce_to_none():+ """Non-integer installmentNumber/totalInstallments must not break parsing."""+ result = await _fetch([+ {+ "id": "tx-5",+ "description": "BAD TYPES",+ "amount": -1,+ "date": "2026-04-12",+ "type": "DEBIT",+ "creditCardMetadata": {+ "installmentNumber": "3", # string, not int+ "totalInstallments": 12.0, # float, not int+ "totalAmount": 100,+ "purchaseDate": "2026-04-01",+ },+ }+ ])+ tx = result[0]+ assert tx.installment_number is None+ assert tx.total_installments is None+ assert tx.installment_total_amount == Decimal("100")+ assert tx.installment_purchase_date == date(2026, 4, 1)+++async def test_parser_malformed_purchase_date_falls_back_to_none():+ """Invalid purchaseDate strings should not raise — silently drop."""+ result = await _fetch([+ {+ "id": "tx-6",+ "description": "BAD DATE",+ "amount": -1,+ "date": "2026-04-12",+ "type": "DEBIT",+ "creditCardMetadata": {+ "installmentNumber": 1,+ "totalInstallments": 2,+ "totalAmount": 2,+ "purchaseDate": "not-a-date",+ },+ }+ ])+ tx = result[0]+ assert tx.installment_purchase_date is None+ assert tx.installment_number == 1+ assert tx.total_installments == 2+++async def test_parser_purchase_date_with_time_suffix():+ """ISO datetime strings (with time) should be truncated to date cleanly."""+ result = await _fetch([+ {+ "id": "tx-7",+ "description": "WITH TIME",+ "amount": -1,+ "date": "2026-04-12",+ "type": "DEBIT",+ "creditCardMetadata": {+ "installmentNumber": 1,+ "totalInstallments": 1,+ "totalAmount": 10,+ "purchaseDate": "2026-01-15T12:34:56.000Z",+ },+ }+ ])+ tx = result[0]+ assert tx.installment_purchase_date == date(2026, 1, 15)+++async def test_parser_negative_total_amount_is_stored_as_absolute():+ """Pluggy may report negative totalAmount for debits; we store absolute."""+ result = await _fetch([+ {+ "id": "tx-8",+ "description": "NEG TOTAL",+ "amount": -10,+ "date": "2026-04-12",+ "type": "DEBIT",+ "creditCardMetadata": {+ "installmentNumber": 2,+ "totalInstallments": 6,+ "totalAmount": -600.00,+ "purchaseDate": "2026-01-01",+ },+ }+ ])+ tx = result[0]+ assert tx.installment_total_amount == Decimal("600.00")+++async def test_parser_missing_purchase_date_only():+ """Some connectors omit purchaseDate even when counts are present."""+ result = await _fetch([+ {+ "id": "tx-9",+ "description": "NO PURCHASE DATE",+ "amount": -25,+ "date": "2026-04-12",+ "type": "DEBIT",+ "creditCardMetadata": {+ "installmentNumber": 4,+ "totalInstallments": 10,+ "totalAmount": 250,+ },+ }+ ])+ tx = result[0]+ assert tx.installment_number == 4+ assert tx.total_installments == 10+ assert tx.installment_total_amount == Decimal("250")+ assert tx.installment_purchase_date is Nonediff --git a/backend/tests/test_transaction_schemas.py b/backend/tests/test_transaction_schemas.pyindex 2c82b348..60967568 100644--- a/backend/tests/test_transaction_schemas.py+++ b/backend/tests/test_transaction_schemas.py@@ -11,7 +11,7 @@ from decimal import Decimalimport pytestfrom pydantic import ValidationError-from app.schemas.transaction import TransactionCreate, TransactionUpdate+from app.schemas.transaction import TransactionCreate, TransactionRead, TransactionUpdateclass TestTransactionUpdateDateField:@@ -70,6 +70,56 @@ class TestTransactionUpdateAllFields:assert dumped == {"amount": Decimal("99.99"), "currency": "EUR"}+class TestTransactionReadInstallmentFields:+ """Verify the installment metadata fields (issue #14 v1) round-trip+ through TransactionRead without loss."""++ def _base(self, **overrides):+ data = {+ "id": "11111111-1111-1111-1111-111111111111",+ "user_id": "22222222-2222-2222-2222-222222222222",+ "description": "AMAZON PARCELADO",+ "amount": "120.50",+ "date": "2026-04-10",+ "type": "debit",+ "source": "pluggy",+ }+ data.update(overrides)+ return data++ def test_all_installment_fields_round_trip(self):+ data = TransactionRead.model_validate(self._base(+ installment_number=3,+ total_installments=12,+ installment_total_amount="1446.00",+ installment_purchase_date="2026-02-10",+ ))+ 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)++ def test_installment_fields_default_none(self):+ data = TransactionRead.model_validate(self._base())+ assert data.installment_number is None+ assert data.total_installments is None+ assert data.installment_total_amount is None+ assert data.installment_purchase_date is None++ def test_installment_fields_serialize_in_api_response(self):+ data = TransactionRead.model_validate(self._base(+ installment_number=1,+ total_installments=6,+ installment_total_amount="300.00",+ installment_purchase_date="2026-03-25",+ ))+ dumped = data.model_dump(mode="json")+ assert dumped["installment_number"] == 1+ assert dumped["total_installments"] == 6+ assert dumped["installment_total_amount"] == 300.00+ assert dumped["installment_purchase_date"] == "2026-03-25"++class TestTransactionCreateDateField:"""Ensure TransactionCreate also handles the date field correctly."""diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 008fe2f4..4efffc24 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -199,7 +199,16 @@ export const accounts = {const { data } = await api.get(`/accounts/${id}`)return data},- create: async (account: { name: string; type: string; balance?: number; currency?: string }): Promise<Account> => {+ create: async (account: {+ name: string+ type: string+ balance?: number+ balance_date?: string+ currency?: string+ credit_limit?: number | null+ statement_close_day?: number | null+ payment_due_day?: number | null+ }): Promise<Account> => {const { data } = await api.post('/accounts', account)return data},diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 8c837e75..26f7ce6f 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -215,6 +215,7 @@"transferNotes": "Notes","transferInfo": "This is a transfer — changes to description, date, and notes will apply to both sides","transferTooltip": "Transfers are excluded from report and dashboard totals",+ "installmentTooltip": "Installment plan — {{count}} charges totaling {{total}}","linkAsTransfer": "Link as transfer","linkTransferTitle": "Link as transfer","linkTransferDescription": "Mark these two transactions as a single inter-account transfer. They will be excluded from spending and income reports.",@@ -289,6 +290,26 @@"typeCreditCard": "Credit Card","typeInvestment": "Investment","typeWallet": "Wallet",+ "creditLimit": "Credit limit",+ "statementCloseDay": "Statement close day",+ "paymentDueDay": "Payment due day",+ "dayOfMonthHint": "Day of month (1–31)",+ "availableCredit": "Available credit",+ "utilization": "Utilization",+ "cycleSpending": "Cycle spending",+ "payments": "Payments",+ "charges": "Charges",+ "previousCycle": "Previous cycle",+ "nextCycle": "Next cycle",+ "cycleBillTotal": "Bill total",+ "dueDate": "Due date",+ "minimumPayment": "Minimum",+ "noChargesYet": "No charges yet this cycle",+ "currentTag": "now",+ "overdueDays": "Overdue by {{count}} days",+ "dueIn": "Due in {{count}} days",+ "dueToday": "Due today",+ "overdue": "Overdue","created": "Account created","updated": "Account updated","deleted": "Account deleted",@@ -764,6 +785,12 @@"registrationTitle": "Registration","registration": "Allow user registration","registrationDesc": "When disabled, only admins can create new user accounts.",+ "accountingTitle": "Accounting",+ "accountingSubtitle": "How credit card transactions are counted in dashboards, reports, and budgets.",+ "accountingCash": "Cash basis",+ "accountingCashDesc": "Credit card purchases count on the day they happen (default).",+ "accountingAccrual": "Accrual basis",+ "accountingAccrualDesc": "Credit card purchases count on the bill's due date — reflects actual cash flow.","updated": "Setting updated"}},diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 1b4081bc..fe0ee81d 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -215,6 +215,7 @@"transferNotes": "Notas","transferInfo": "Esta é uma transferência — alterações na descrição, data e notas serão aplicadas em ambos os lados","transferTooltip": "Transferências são excluídas dos totais de relatórios e dashboard",+ "installmentTooltip": "Compra parcelada — {{count}} parcelas totalizando {{total}}","linkAsTransfer": "Vincular como transferência","linkTransferTitle": "Vincular como transferência","linkTransferDescription": "Marcar estas duas transações como uma única transferência entre contas. Elas serão excluídas dos relatórios de gastos e receitas.",@@ -289,6 +290,26 @@"typeCreditCard": "Cartão de Crédito","typeInvestment": "Investimento","typeWallet": "Carteira",+ "creditLimit": "Limite do cartão",+ "statementCloseDay": "Dia de fechamento",+ "paymentDueDay": "Dia de vencimento",+ "dayOfMonthHint": "Dia do mês (1–31)",+ "availableCredit": "Limite disponível",+ "utilization": "Utilização",+ "cycleSpending": "Gastos do ciclo",+ "payments": "Pagamentos",+ "charges": "Compras",+ "previousCycle": "Ciclo anterior",+ "nextCycle": "Próximo ciclo",+ "cycleBillTotal": "Total da fatura",+ "dueDate": "Vencimento",+ "minimumPayment": "Mínimo",+ "noChargesYet": "Nenhuma compra ainda neste ciclo",+ "currentTag": "agora",+ "overdueDays": "Atrasado há {{count}} dias",+ "dueIn": "Vence em {{count}} dias",+ "dueToday": "Vence hoje",+ "overdue": "Atrasado","created": "Conta criada","updated": "Conta atualizada","deleted": "Conta excluída",@@ -764,6 +785,12 @@"registrationTitle": "Registro","registration": "Permitir registro de usuários","registrationDesc": "Quando desativado, apenas admins podem criar novas contas.",+ "accountingTitle": "Contabilidade",+ "accountingSubtitle": "Como as transações de cartão de crédito entram no painel, relatórios e orçamentos.",+ "accountingCash": "Regime de caixa",+ "accountingCashDesc": "Compras no cartão contam no dia em que acontecem (padrão).",+ "accountingAccrual": "Regime de competência",+ "accountingAccrualDesc": "Compras no cartão contam na data de vencimento da fatura — reflete o fluxo de caixa real.","updated": "Configuração atualizada"}},diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex 9265f8d3..ce1533af 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -1,18 +1,23 @@-import { useState, useMemo } from 'react'+import { useState, useMemo, useEffect, useRef } from 'react'import { useParams, Link } from 'react-router-dom'import { useTranslation } from 'react-i18next'-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { format } from 'date-fns'+import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query'+import { format, addMonths, parseISO } from 'date-fns'+import { ptBR, enUS } from 'date-fns/locale'import { accounts, transactions, categories as categoriesApi } from '@/lib/api'import { toast } from 'sonner'import type { Transaction } from '@/types'import { Skeleton } from '@/components/ui/skeleton'import { Button } from '@/components/ui/button'-import { ArrowLeft, ArrowLeftRight, Clock, HelpCircle, Paperclip, X } from 'lucide-react'+import { ArrowLeft, ArrowLeftRight, ChevronLeft, ChevronRight, Clock, HelpCircle, Paperclip, Pencil, X } from 'lucide-react'import { CategoryIcon } from '@/components/category-icon'import { TransactionDialog, extractApiError } 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'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'import {@@ -33,6 +38,150 @@ function defaultTo() {return format(new Date(), 'yyyy-MM-dd')}+function daysInMonth(year: number, month: number): number {+ return new Date(year, month + 1, 0).getDate()+}++/** Return the default cycle for a credit card: the cycle whose bill is *next due*.+ *+ * This is NOT the cycle containing today. When the statement has just closed+ * (e.g. gold: closes day 11, today is day 13, due day 16), the user wants to+ * see the bill they're about to pay (Abr 2026), not the brand-new open cycle+ * that's busy accumulating charges for next month's bill (Mai 2026). For accounts+ * where the close hasn't happened yet (e.g. TASSIO: close 28, today 13) the+ * "next due" cycle IS the open one, so this function returns the same as+ * creditCardCycleBoundaries(closeDay, today). */+function defaultCycleForCreditCard(+ closeDay: number | null | undefined,+ dueDay: number | null | undefined,+ reference: Date,+): { start: string; end: string } {+ if (!closeDay || !dueDay) {+ return creditCardCycleBoundaries(closeDay, reference)+ }+ // Step 1: find the next occurrence of dueDay on or after `reference`.+ const ref0 = new Date(reference)+ ref0.setHours(0, 0, 0, 0)+ const y = ref0.getFullYear()+ const m = ref0.getMonth()+ const clampDue = (yy: number, mm: number) => Math.min(dueDay, daysInMonth(yy, mm))+ const sameMonthDue = new Date(y, m, clampDue(y, m))+ let billDate: Date+ if (sameMonthDue.getTime() >= ref0.getTime()) {+ billDate = sameMonthDue+ } else {+ const ny = m === 11 ? y + 1 : y+ const nm = m === 11 ? 0 : m + 1+ billDate = new Date(ny, nm, clampDue(ny, nm))+ }+ // Step 2: find the cycle whose bill is `billDate` — its end is the most+ // recent close on or before billDate.+ const by = billDate.getFullYear()+ const bm = billDate.getMonth()+ const clampClose = (yy: number, mm: number) => Math.min(closeDay, daysInMonth(yy, mm))+ const sameMonthClose = new Date(by, bm, clampClose(by, bm))+ let cycleEnd: Date+ if (sameMonthClose.getTime() <= billDate.getTime()) {+ cycleEnd = sameMonthClose+ } else {+ const py = bm === 0 ? by - 1 : by+ const pm = bm === 0 ? 11 : bm - 1+ cycleEnd = new Date(py, pm, clampClose(py, pm))+ }+ return creditCardCycleBoundaries(closeDay, cycleEnd)+}++/** Compute the bill due date for a credit card cycle whose end is `cycleEnd`.+ * Each bill is due on the next occurrence of `dueDay` strictly after the cycle's+ * statement close. Returns null when dueDay is not configured. */+function dueDateForCycle(cycleEnd: string, dueDay: number | null | undefined): string | null {+ if (!dueDay) return null+ const to = parseISO(cycleEnd + 'T00:00:00')+ const y = to.getFullYear()+ const m = to.getMonth()+ const clamp = (yy: number, mm: number) => Math.min(dueDay, daysInMonth(yy, mm))+ const sameMonth = new Date(y, m, clamp(y, m))+ let bill: Date+ if (sameMonth > to) {+ bill = sameMonth+ } else {+ const ny = m === 11 ? y + 1 : y+ const nm = m === 11 ? 0 : m + 1+ bill = new Date(ny, nm, clamp(ny, nm))+ }+ return format(bill, 'yyyy-MM-dd')+}++/** Build a "Maio 2026"-style label for a credit card cycle.+ * Brazilian convention: the bill is named after the month it's due, which is+ * the next occurrence of payment_due_day strictly after the cycle close. */+function creditCardCycleLabel(+ filterTo: string,+ dueDay: number | null | undefined,+ i18nLanguage: string,+): string {+ const dateFnsLocale = i18nLanguage === 'pt-BR' ? ptBR : enUS+ const to = parseISO(filterTo + 'T00:00:00')+ if (!dueDay) {+ return format(to, 'MMM yyyy', { locale: dateFnsLocale })+ }+ const y = to.getFullYear()+ const m = to.getMonth()+ const clamp = (yy: number, mm: number) => Math.min(dueDay, daysInMonth(yy, mm))+ const sameMonth = new Date(y, m, clamp(y, m))+ let bill: Date+ if (sameMonth > to) {+ bill = sameMonth+ } else {+ const ny = m === 11 ? y + 1 : y+ const nm = m === 11 ? 0 : m + 1+ bill = new Date(ny, nm, clamp(ny, nm))+ }+ return format(bill, 'MMM yyyy', { locale: dateFnsLocale })+}++/** Return the [start, end] dates of the billing cycle that CONTAINS `reference`.+ * start = day after the previous cycle's close; end = next close on or after reference.+ * Falls back to "previous month → today" when no closeDay is configured. */+function creditCardCycleBoundaries(+ closeDay: number | null | undefined,+ reference: Date,+): { start: string; end: string } {+ if (!closeDay) {+ const y = reference.getFullYear()+ const m = reference.getMonth()+ return {+ start: format(new Date(y, m - 1, 1), 'yyyy-MM-dd'),+ end: format(reference, 'yyyy-MM-dd'),+ }+ }+ const ref0 = new Date(reference)+ ref0.setHours(0, 0, 0, 0)+ const y = ref0.getFullYear()+ const m = ref0.getMonth()+ const clamp = (yy: number, mm: number) => Math.min(closeDay, daysInMonth(yy, mm))+ // End of cycle = next close >= reference.+ const thisMonthClose = new Date(y, m, clamp(y, m))+ let end: Date+ if (thisMonthClose.getTime() >= ref0.getTime()) {+ end = thisMonthClose+ } else {+ const nextY = m === 11 ? y + 1 : y+ const nextM = m === 11 ? 0 : m + 1+ end = new Date(nextY, nextM, clamp(nextY, nextM))+ }+ // Start = previous close + 1 day.+ const prevY = end.getMonth() === 0 ? end.getFullYear() - 1 : end.getFullYear()+ const prevM = end.getMonth() === 0 ? 11 : end.getMonth() - 1+ const prevClose = new Date(prevY, prevM, clamp(prevY, prevM))+ const start = new Date(prevClose)+ start.setDate(start.getDate() + 1)+ return {+ start: format(start, 'yyyy-MM-dd'),+ end: format(end, 'yyyy-MM-dd'),+ }+}+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -41,6 +190,29 @@ function formatDateStr(dateStr: string, locale = 'pt-BR') {return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale)}+function formatFriendlyDate(dateStr: string, i18nLanguage: string) {+ const dateFnsLocale = i18nLanguage === 'pt-BR' ? ptBR : enUS+ const d = parseISO(dateStr + 'T00:00:00')+ // Compact friendly format: pt-BR → "qui, 16 abr" / en → "Thu, Apr 16"+ return i18nLanguage === 'pt-BR'+ ? format(d, 'EEE, d MMM', { locale: dateFnsLocale })+ : format(d, 'EEE, MMM d', { locale: dateFnsLocale })+}++function daysUntil(dateStr: string): number {+ const target = new Date(dateStr + 'T00:00:00')+ const today = new Date()+ today.setHours(0, 0, 0, 0)+ return Math.round((target.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))+}++function utilizationColor(pct: number): string {+ if (pct >= 90) return 'bg-rose-500'+ if (pct >= 70) return 'bg-amber-400'+ if (pct >= 30) return 'bg-blue-500'+ return 'bg-emerald-500'+}+type TxWithBalance = Transaction & { runningBalance: number }export default function AccountDetailPage() {@@ -57,6 +229,23 @@ export default function AccountDetailPage() {const [filterFrom, setFilterFrom] = useState(defaultFrom)const [filterTo, setFilterTo] = useState(defaultTo)const [showPrimary, setShowPrimary] = useState(false)+ const filterTouched = useRef(false)+ const handleFilterFromChange = (v: string) => { filterTouched.current = true; setFilterFrom(v) }+ const handleFilterToChange = (v: string) => { filterTouched.current = true; setFilterTo(v) }+ const shiftCycleBy = (direction: -1 | 1) => {+ filterTouched.current = true+ if (account?.type === 'credit_card' && account?.statement_close_day) {+ const ref = direction === -1+ ? new Date(parseISO(filterFrom + 'T00:00:00').getTime() - 86400000)+ : new Date(parseISO(filterTo + 'T00:00:00').getTime() + 86400000)+ const { start, end } = creditCardCycleBoundaries(account.statement_close_day, ref)+ setFilterFrom(start)+ setFilterTo(end)+ return+ }+ setFilterFrom(format(addMonths(parseISO(filterFrom + 'T00:00:00'), direction), 'yyyy-MM-dd'))+ setFilterTo(format(addMonths(parseISO(filterTo + 'T00:00:00'), direction), 'yyyy-MM-dd'))+ }const { data: account, isLoading: accountLoading } = useQuery({queryKey: ['accounts', id],@@ -64,6 +253,19 @@ export default function AccountDetailPage() {enabled: !!id,})+ useEffect(() => {+ if (!account || filterTouched.current) return+ if (account.type === 'credit_card') {+ const { start, end } = defaultCycleForCreditCard(+ account.statement_close_day,+ account.payment_due_day,+ new Date(),+ )+ setFilterFrom(start)+ setFilterTo(end)+ }+ }, [account])+const { data: accountsList } = useQuery({queryKey: ['accounts'],queryFn: () => accounts.list(),@@ -75,6 +277,41 @@ export default function AccountDetailPage() {enabled: !!id,})+ // Previous cycle (for the Total da fatura comparison subtitle).+ // Only fires for credit cards with a statement_close_day set.+ const previousCycle = useMemo(() => {+ if (!account || account.type !== 'credit_card' || !account.statement_close_day) return null+ const dayBeforeStart = new Date(parseISO(filterFrom + 'T00:00:00').getTime() - 86400000)+ return creditCardCycleBoundaries(account.statement_close_day, dayBeforeStart)+ }, [account, filterFrom])++ const { data: previousCycleSummary } = useQuery({+ queryKey: ['accounts', id, 'summary', previousCycle?.start, previousCycle?.end],+ queryFn: () => accounts.summary(id!, previousCycle!.start, previousCycle!.end),+ enabled: !!id && !!previousCycle,+ })++ // Last 6 cycles (oldest → newest) for the bill timeline strip.+ const timelineCycles = useMemo(() => {+ if (!account || account.type !== 'credit_card' || !account.statement_close_day) return []+ const cycles: { start: string; end: string }[] = []+ let ref = new Date()+ for (let i = 0; i < 6; i++) {+ const c = creditCardCycleBoundaries(account.statement_close_day, ref)+ cycles.unshift(c)+ ref = new Date(parseISO(c.start + 'T00:00:00').getTime() - 86400000)+ }+ return cycles+ }, [account])++ const timelineQueries = useQueries({+ queries: timelineCycles.map(c => ({+ queryKey: ['accounts', id, 'summary', c.start, c.end],+ queryFn: () => accounts.summary(id!, c.start, c.end),+ enabled: !!id,+ })),+ })+const { data: balanceHistory, isLoading: balanceHistoryLoading } = useQuery({queryKey: ['accounts', id, 'balance-history', filterFrom, filterTo],queryFn: () => accounts.balanceHistory(id!, filterFrom || undefined, filterTo || undefined),@@ -155,6 +392,19 @@ export default function AccountDetailPage() {onError: () => toast.error(t('common.error')),})+ const [ccSettingsOpen, setCcSettingsOpen] = useState(false)+ const ccSettingsMutation = useMutation({+ mutationFn: (data: { credit_limit?: number | null; statement_close_day?: number | null; payment_due_day?: number | null }) =>+ accounts.update(id!, data),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['accounts'] })+ queryClient.invalidateQueries({ queryKey: ['accounts', id] })+ setCcSettingsOpen(false)+ toast.success(t('accounts.updated'))+ },+ onError: (error) => toast.error(extractApiError(error)),+ })+const transferMutation = useMutation({mutationFn: (data: {from_account_id: string@@ -185,19 +435,70 @@ export default function AccountDetailPage() {const usePrimary = !isForeignCurrency || showPrimaryconst displayCurrency = (isForeignCurrency && !showPrimary) ? (account?.currency || userCurrency) : userCurrency- // Chart data — simple daily balance series+ // Chart data:+ // - Non-CC: daily running balance from /balance-history+ // - CC: cumulative charges within the current cycle, starting at 0+ // (answers "how much have I spent this cycle", ignores bill payments/transfers)const chartData = useMemo(() => {+ if (isCreditCard) {+ if (!txData?.items || !filterFrom || !filterTo) return []+ const byDay = new Map<string, number>()+ for (const tx of txData.items) {+ if (tx.type !== 'debit') continue+ if (tx.source === 'opening_balance') continue+ if (tx.transfer_pair_id) continue+ const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)+ byDay.set(tx.date, (byDay.get(tx.date) ?? 0) + amt)+ }+ const series: { label: string; date: string; balance: number }[] = []+ // Synthetic zero baseline (day before cycle start) so the line always+ // anchors at 0 even when the cycle's first day already has charges.+ const startDate = parseISO(filterFrom + 'T00:00:00')+ const baseline = new Date(startDate.getTime() - 86400000)+ const baselineKey = format(baseline, 'yyyy-MM-dd')+ series.push({ label: formatDateStr(baselineKey, locale), date: baselineKey, balance: 0 })+ const cur = new Date(startDate)+ const end = new Date(filterTo + 'T00:00:00')+ let running = 0+ while (cur <= end) {+ const key = format(cur, 'yyyy-MM-dd')+ running += byDay.get(key) ?? 0+ series.push({ label: formatDateStr(key, locale), date: key, balance: running })+ cur.setDate(cur.getDate() + 1)+ }+ return series+ }if (!balanceHistory) return []return balanceHistory.map(p => ({label: formatDateStr(p.date, locale),date: p.date,balance: usePrimary ? (p.balance_primary ?? p.balance) : p.balance,}))- }, [balanceHistory, locale, usePrimary])+ }, [isCreditCard, txData, filterFrom, filterTo, balanceHistory, locale, usePrimary])// Running balance computation for transaction tableconst txWithRunningBalance = useMemo((): TxWithBalance[] => {- if (!txData?.items || summary === undefined) return []+ if (!txData?.items) return []++ if (isCreditCard) {+ // Match the cycle spending chart: cumulative sum of debits (excluding+ // transfers and opening balance), computed oldest → newest, then displayed+ // newest-first. Each row shows the cycle total through that transaction.+ const ascending = [...txData.items].sort(+ (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),+ )+ let running = 0+ const withBalance = ascending.map((tx) => {+ if (tx.type === 'debit' && tx.source !== 'opening_balance' && !tx.transfer_pair_id) {+ const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)+ running += amt+ }+ return { ...tx, runningBalance: running }+ })+ return withBalance.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())+ }++ if (summary === undefined) return []const endBalance = usePrimary? (balanceHistory?.length? (balanceHistory[balanceHistory.length - 1].balance_primary ?? balanceHistory[balanceHistory.length - 1].balance)@@ -212,16 +513,15 @@ export default function AccountDetailPage() {return sorted.map((tx) => {const balanceAtPoint = runningconst amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)- if (isCreditCard) {- running -= tx.type === 'debit' ? amt : -amt- } else {- running -= tx.type === 'credit' ? amt : -amt- }+ running -= tx.type === 'credit' ? amt : -amtreturn { ...tx, runningBalance: balanceAtPoint }})}, [txData, summary, isCreditCard, balanceHistory, usePrimary])- const hasFilters = filterFrom !== defaultFrom() || filterTo !== defaultTo()+ const resolvedDefaultRange = account?.type === 'credit_card'+ ? defaultCycleForCreditCard(account.statement_close_day, account.payment_due_day, new Date())+ : { start: defaultFrom(), end: defaultTo() }+ const hasFilters = filterFrom !== resolvedDefaultRange.start || filterTo !== resolvedDefaultRange.endconst isLoading = accountLoading || summaryLoading@@ -241,49 +541,148 @@ export default function AccountDetailPage() {return (<div>- {/* Header bar with date range */}- <div className="mb-6 space-y-3">- <div className="flex items-center gap-3 flex-wrap">- <Button variant="ghost" size="sm" asChild className="text-muted-foreground hover:text-foreground">- <Link to="/accounts">- <ArrowLeft className="h-4 w-4 mr-1" />- <span className="hidden sm:inline">{t('accounts.backToAccounts')}</span>- </Link>- </Button>- <h1 className="text-xl sm:text-2xl font-bold text-foreground">{account.name}</h1>- <span className="text-xs font-medium bg-muted text-muted-foreground px-2.5 py-1 rounded-full capitalize">- {account.type}- </span>+ {/* Header */}+ <div className="mb-6 space-y-4">+ {/* Breadcrumb */}+ <Link+ to="/accounts"+ className="inline-flex items-center text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"+ >+ <ArrowLeft className="h-3.5 w-3.5 mr-1" />+ {t('accounts.backToAccounts')}+ </Link>++ {/* Title row */}+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-semibold text-foreground tracking-tight truncate">+ {account.name}+ </h1>+ <div className="flex items-center gap-2 mt-1 flex-wrap">+ <span className="text-xs font-medium text-muted-foreground">+ {t(`accounts.type${account.type.split('_').map(s => s[0].toUpperCase() + s.slice(1)).join('')}`, account.type)}+ </span>+ {isCreditCard && account.next_due_date && (() => {+ const d = daysUntil(account.next_due_date)+ if (d > 7) return null+ const cfg = d < 0+ ? { bg: 'bg-rose-100 dark:bg-rose-500/20', text: 'text-rose-700 dark:text-rose-400', label: t('accounts.overdue') }+ : d === 0+ ? { bg: 'bg-rose-100 dark:bg-rose-500/20', text: 'text-rose-700 dark:text-rose-400', label: t('accounts.dueToday') }+ : d <= 3+ ? { bg: 'bg-rose-100 dark:bg-rose-500/20', text: 'text-rose-700 dark:text-rose-400', label: t('accounts.dueIn', { count: d }) }+ : { bg: 'bg-amber-100 dark:bg-amber-500/20', text: 'text-amber-700 dark:text-amber-400', label: t('accounts.dueIn', { count: d }) }+ return (+ <>+ <span className="text-muted-foreground text-xs">·</span>+ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold ${cfg.bg} ${cfg.text}`}>+ {cfg.label}+ </span>+ </>+ )+ })()}+ </div>+ </div>{!account.is_closed && (- <Button variant="outline" size="sm" className="ml-auto" onClick={() => setTransferDialogOpen(true)}>+ <Button+ variant="outline"+ size="sm"+ className="shrink-0"+ onClick={() => setTransferDialogOpen(true)}+ ><ArrowLeftRight className="h-4 w-4 mr-1" />{t('transactions.transfer')}</Button>)}</div><div className="flex items-center gap-2 sm:gap-3 flex-wrap">- <div className="flex items-center gap-2">- <label className="text-sm text-muted-foreground hidden md:inline">{t('transactions.from')}</label>- <DatePickerInput- value={filterFrom}- onChange={setFilterFrom}- placeholder={t('transactions.from')}- />- </div>- <div className="flex items-center gap-2">- <label className="text-sm text-muted-foreground hidden md:inline">{t('transactions.to')}</label>- <DatePickerInput- value={filterTo}- onChange={setFilterTo}- placeholder={t('transactions.to')}- />- </div>+ {isCreditCard ? (+ <div className="flex items-center gap-1">+ <button+ type="button"+ className="h-8 w-8 flex items-center justify-center rounded-lg border border-border bg-card text-muted-foreground hover:border-border hover:text-foreground transition-all"+ onClick={() => shiftCycleBy(-1)}+ title={t('accounts.previousCycle')}+ >+ <ChevronLeft size={16} />+ </button>+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex items-center justify-center gap-2 min-w-[140px] border border-border rounded-lg px-3 py-1.5 text-sm bg-card text-foreground hover:bg-muted/50 transition-all cursor-pointer capitalize"+ >+ {creditCardCycleLabel(filterTo, account?.payment_due_day, i18n.language)}+ </button>+ </PopoverTrigger>+ <PopoverContent align="center" className="w-auto p-3 space-y-3">+ <div className="space-y-1.5">+ <Label className="text-xs">{t('transactions.from')}</Label>+ <DatePickerInput+ value={filterFrom}+ onChange={handleFilterFromChange}+ placeholder={t('transactions.from')}+ />+ </div>+ <div className="space-y-1.5">+ <Label className="text-xs">{t('transactions.to')}</Label>+ <DatePickerInput+ value={filterTo}+ onChange={handleFilterToChange}+ placeholder={t('transactions.to')}+ />+ </div>+ </PopoverContent>+ </Popover>+ <button+ type="button"+ className="h-8 w-8 flex items-center justify-center rounded-lg border border-border bg-card text-muted-foreground hover:border-border hover:text-foreground transition-all"+ onClick={() => shiftCycleBy(1)}+ title={t('accounts.nextCycle')}+ >+ <ChevronRight size={16} />+ </button>+ </div>+ ) : (+ <>+ <div className="flex items-center gap-2">+ <label className="text-sm text-muted-foreground hidden md:inline">{t('transactions.from')}</label>+ <DatePickerInput+ value={filterFrom}+ onChange={handleFilterFromChange}+ placeholder={t('transactions.from')}+ />+ </div>+ <div className="flex items-center gap-2">+ <label className="text-sm text-muted-foreground hidden md:inline">{t('transactions.to')}</label>+ <DatePickerInput+ value={filterTo}+ onChange={handleFilterToChange}+ placeholder={t('transactions.to')}+ />+ </div>+ </>+ )}{hasFilters && (<Buttonvariant="ghost"size="sm"className="text-muted-foreground hover:text-foreground"- onClick={() => { setFilterFrom(defaultFrom()); setFilterTo(defaultTo()) }}+ onClick={() => {+ filterTouched.current = false+ if (account?.type === 'credit_card') {+ const { start, end } = defaultCycleForCreditCard(+ account.statement_close_day,+ account.payment_due_day,+ new Date(),+ )+ setFilterFrom(start)+ setFilterTo(end)+ } else {+ setFilterFrom(defaultFrom())+ setFilterTo(defaultTo())+ }+ }}><X className="h-3.5 w-3.5 mr-1" />{t('transactions.clearFilters')}@@ -322,51 +721,269 @@ export default function AccountDetailPage() {</div>)}+ {/* Bill timeline (last 6 cycles) — only for CC with cycle metadata */}+ {isCreditCard && timelineCycles.length > 0 && (() => {+ const totals = timelineQueries.map((q, i) => ({+ ...timelineCycles[i],+ total: Number(q.data?.monthly_expenses ?? 0),+ loading: q.isLoading,+ }))+ const max = Math.max(1, ...totals.map(c => c.total))+ return (+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4 mb-6">+ <div className="flex items-end gap-2 sm:gap-3 overflow-x-auto pb-1">+ {totals.map((c, i) => {+ const isCurrent = c.start === filterFrom && c.end === filterTo+ const heightPct = c.total > 0 ? Math.max(8, (c.total / max) * 100) : 4+ const label = creditCardCycleLabel(c.end, account.payment_due_day, i18n.language)+ return (+ <button+ key={i}+ type="button"+ onClick={() => {+ filterTouched.current = true+ setFilterFrom(c.start)+ setFilterTo(c.end)+ }}+ className={`group flex-1 min-w-[60px] flex flex-col items-center gap-1.5 px-1 py-2 rounded-lg transition-colors ${isCurrent ? 'bg-rose-50 dark:bg-rose-500/10' : 'hover:bg-muted/50'}`}+ >+ <div className="h-12 w-full flex items-end justify-center">+ {c.loading ? (+ <div className="w-6 h-3 rounded-sm bg-muted animate-pulse" />+ ) : (+ <div+ className={`w-6 rounded-sm transition-colors ${isCurrent ? 'bg-rose-500' : c.total > 0 ? 'bg-rose-300 dark:bg-rose-500/40 group-hover:bg-rose-400' : 'bg-muted-foreground/20'}`}+ style={{ height: `${heightPct}%` }}+ />+ )}+ </div>+ <p className={`text-[10px] sm:text-xs font-medium capitalize ${isCurrent ? 'text-rose-700 dark:text-rose-400' : 'text-muted-foreground'}`}>+ {label}+ </p>+ <p className={`text-[10px] sm:text-xs font-semibold tabular-nums ${isCurrent ? 'text-foreground' : 'text-muted-foreground'}`}>+ {c.loading ? '—' : mask(formatCurrency(c.total, account.currency, locale))}+ </p>+ </button>+ )+ })}+ </div>+ </div>+ )+ })()}+{/* Compact stat bar */}- <div className="grid grid-cols-3 gap-2 sm:gap-4 mb-6">- <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">- <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">- {t('accounts.currentBalance')}- </p>- <p className={`text-base sm:text-2xl font-bold tabular-nums ${(account.type === 'credit_card' ? (summary?.current_balance ?? 0) > 0 : (summary?.current_balance ?? 0) < 0) ? 'text-rose-500' : 'text-foreground'}`}>- {mask(formatCurrency(- (showPrimary ? summary?.current_balance_primary : undefined) ?? summary?.current_balance ?? 0,- displayCurrency, locale- ))}- </p>- </div>- <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">- <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">- {t('accounts.income')}- </p>- <p className="text-base sm:text-2xl font-bold tabular-nums text-emerald-600">- {mask(formatCurrency(- (showPrimary ? summary?.monthly_income_primary : undefined) ?? summary?.monthly_income ?? 0,- displayCurrency, locale- ))}- </p>- </div>- <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">- <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">- {t('accounts.expenses')}- </p>- <p className="text-base sm:text-2xl font-bold tabular-nums text-rose-500">- {mask(formatCurrency(- (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0,- displayCurrency, locale- ))}- </p>+ {isCreditCard ? (() => {+ const billTotal = (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0+ // "Default cycle" = the bill the user is here to pay (next due). The+ // AGORA tag on Limite disponível only shows when viewing a different cycle.+ const isDefaultCycle =+ filterFrom === resolvedDefaultRange.start && filterTo === resolvedDefaultRange.end+ // Compute the due date for THIS cycle (bill due day after cycle close).+ const cycleDueDate = dueDateForCycle(filterTo, account.payment_due_day)+ const dueIn = cycleDueDate ? daysUntil(cycleDueDate) : null+ // Show the countdown whenever the due date is upcoming (future or today),+ // OR when the default bill is overdue (urgent, needs paying). Hide for+ // past bills the user can't act on.+ const dueSubtitle = (() => {+ if (dueIn == null) return null+ if (dueIn > 0) return t('accounts.dueIn', { count: dueIn })+ if (dueIn === 0) return t('accounts.dueToday')+ if (isDefaultCycle) return t('accounts.overdueDays', { count: Math.abs(dueIn) })+ return null+ })()+ const dueSubtitleClass =+ dueIn != null && dueIn < 0 ? 'text-rose-500'+ : dueIn != null && dueIn <= 3 ? 'text-rose-500'+ : dueIn != null && dueIn <= 7 ? 'text-amber-600'+ : 'text-muted-foreground'+ // Cycle-over-cycle comparison: any time we have a previous cycle to+ // compare against. A current bill of 0 is still meaningful (shows -100%+ // and tells the user "nothing spent yet vs last month").+ const prevTotal = previousCycleSummary?.monthly_expenses ?? 0+ const showComparison = previousCycle && prevTotal > 0+ const deltaPct = showComparison ? ((billTotal - prevTotal) / prevTotal) * 100 : null+ const prevCycleLabel = previousCycle ? creditCardCycleLabel(previousCycle.end, account.payment_due_day, i18n.language) : null+ return (+ <div className="grid grid-cols-3 gap-2 sm:gap-4 mb-6">+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">+ {t('accounts.cycleBillTotal')}+ </p>+ <p className="text-base sm:text-2xl font-bold tabular-nums text-foreground">+ {mask(formatCurrency(billTotal, displayCurrency, locale))}+ </p>+ {deltaPct != null && prevCycleLabel && (+ <p className={`text-[10px] sm:text-xs font-medium mt-0.5 tabular-nums ${deltaPct > 0 ? 'text-rose-500' : 'text-emerald-600'}`}>+ {deltaPct > 0 ? '+' : ''}{deltaPct.toFixed(0)}% <span className="text-muted-foreground font-normal">vs {prevCycleLabel}</span>+ </p>+ )}+ </div>+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1.5">+ {t('accounts.availableCredit')}+ <span className="inline-flex items-center px-1 py-0 rounded text-[9px] font-bold uppercase tracking-wide bg-muted text-muted-foreground">+ {t('accounts.currentTag')}+ </span>+ </p>+ <p className="text-base sm:text-2xl font-bold tabular-nums text-emerald-600">+ {account.available_credit != null+ ? mask(formatCurrency(Number(account.available_credit), account.currency, locale))+ : '—'}+ </p>+ </div>+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">+ {t('accounts.dueDate')}+ </p>+ <p className="text-base sm:text-2xl font-bold tabular-nums text-foreground">+ {cycleDueDate ? formatFriendlyDate(cycleDueDate, i18n.language) : '—'}+ </p>+ {dueSubtitle && (+ <p className={`text-[10px] sm:text-xs font-medium mt-0.5 ${dueSubtitleClass}`}>+ {dueSubtitle}+ </p>+ )}+ </div>+ </div>+ )+ })() : (+ <div className="grid grid-cols-3 gap-2 sm:gap-4 mb-6">+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">+ {t('accounts.currentBalance')}+ </p>+ <p className={`text-base sm:text-2xl font-bold tabular-nums ${(summary?.current_balance ?? 0) < 0 ? 'text-rose-500' : 'text-foreground'}`}>+ {mask(formatCurrency(+ (showPrimary ? summary?.current_balance_primary : undefined) ?? summary?.current_balance ?? 0,+ displayCurrency, locale+ ))}+ </p>+ </div>+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">+ {t('accounts.income')}+ </p>+ <p className="text-base sm:text-2xl font-bold tabular-nums text-emerald-600">+ {mask(formatCurrency(+ (showPrimary ? summary?.monthly_income_primary : undefined) ?? summary?.monthly_income ?? 0,+ displayCurrency, locale+ ))}+ </p>+ </div>+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1">+ {t('accounts.expenses')}+ </p>+ <p className="text-base sm:text-2xl font-bold tabular-nums text-rose-500">+ {mask(formatCurrency(+ (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0,+ displayCurrency, locale+ ))}+ </p>+ </div></div>- </div>+ )}- {/* Balance chart */}+ {isCreditCard && (() => {+ const limit = account.credit_limit != null ? Number(account.credit_limit) : null+ // Cycle-bound utilization: how much of the limit was charged in the cycle+ // currently being viewed. For the current cycle this matches the "current+ // open balance" since nothing has been paid yet; for past cycles it shows+ // that month's burn rate against the (current) limit.+ const cycleBillTotal = (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0+ const utilized = limit != null ? cycleBillTotal : null+ const rawPct = limit != null && limit > 0 && utilized != null ? (utilized / limit) * 100 : null+ const pct = rawPct != null ? Math.min(100, rawPct) : null+ return (+ <div className="bg-card rounded-xl border border-border shadow-sm p-4 sm:p-5 mb-6">+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ {account.card_brand && (+ <span className="inline-flex items-center px-2 py-0.5 rounded-md bg-foreground/5 text-foreground text-[10px] sm:text-xs font-bold tracking-wide uppercase">+ {account.card_brand}+ </span>+ )}+ {account.card_level && (+ <span className="inline-flex items-center px-2 py-0.5 rounded-md bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 text-[10px] sm:text-xs font-bold tracking-wide uppercase">+ {account.card_level}+ </span>+ )}+ {!account.card_brand && !account.card_level && (+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground uppercase tracking-wide">+ {t('accounts.typeCreditCard')}+ </p>+ )}+ </div>+ <button+ type="button"+ onClick={() => setCcSettingsOpen(true)}+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ title={t('common.edit')}+ >+ <Pencil size={13} />+ </button>+ </div>+ {limit != null && pct != null && rawPct != null && (+ <>+ <div className="flex items-baseline justify-between mb-2">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground uppercase tracking-wide">+ {t('accounts.utilization')}+ </p>+ <p className={`text-sm font-bold tabular-nums ${rawPct >= 100 ? 'text-rose-500' : 'text-foreground'}`}>{rawPct.toFixed(1)}%</p>+ </div>+ <div className="h-2 bg-muted/60 rounded-full overflow-hidden mb-2">+ <div+ className={`h-full rounded-full transition-all ${utilizationColor(rawPct)}`}+ style={{ width: `${pct}%` }}+ />+ </div>+ <p className="text-xs text-muted-foreground tabular-nums mb-4">+ {mask(formatCurrency(utilized ?? 0, account.currency, locale))}+ {' / '}+ {mask(formatCurrency(limit, account.currency, locale))}+ </p>+ </>+ )}+ <div className="grid grid-cols-2 gap-3 pt-3 border-t border-border">+ <div>+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-0.5">+ {t('accounts.creditLimit')}+ </p>+ <p className="text-sm sm:text-base font-semibold tabular-nums text-foreground">+ {limit != null ? mask(formatCurrency(limit, account.currency, locale)) : '—'}+ </p>+ </div>+ <div>+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-0.5">+ {t('accounts.statementCloseDay')}+ </p>+ <p className="text-sm sm:text-base font-semibold tabular-nums text-foreground">+ {account.statement_close_day && filterTo ? formatDateStr(filterTo, locale) : '—'}+ </p>+ </div>+ </div>+ </div>+ )+ })()}++ {/* Balance / Cycle spending chart */}+ {(() => {+ const cycleEmpty = isCreditCard && chartData.length > 0 && chartData[chartData.length - 1].balance === 0+ return (<div className="bg-card rounded-xl border border-border shadow-sm mb-6"><div className="px-5 pt-5 pb-3">- <p className="text-base font-bold text-foreground">{t('dashboard.balanceFlow')}</p>+ <p className="text-base font-bold text-foreground">+ {isCreditCard ? t('accounts.cycleSpending') : t('dashboard.balanceFlow')}+ </p></div><div className="px-1 pb-4 h-[280px]">- {balanceHistoryLoading ? (+ {(isCreditCard ? txLoading : balanceHistoryLoading) ? (<Skeleton className="h-full w-full" />+ ) : cycleEmpty ? (+ <div className="h-full w-full flex flex-col items-center justify-center gap-2 text-muted-foreground">+ <Clock className="h-8 w-8 opacity-40" />+ <p className="text-sm">{t('accounts.noChargesYet')}</p>+ </div>) : chartData.length > 0 ? (<ResponsiveContainer width="100%" height="100%"><AreaChart@@ -375,8 +992,8 @@ export default function AccountDetailPage() {><defs><linearGradient id="acctBalGrad" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#10B981" stopOpacity={0.18} />- <stop offset="95%" stopColor="#10B981" stopOpacity={0.02} />+ <stop offset="5%" stopColor={isCreditCard ? '#F43F5E' : '#10B981'} stopOpacity={0.18} />+ <stop offset="95%" stopColor={isCreditCard ? '#F43F5E' : '#10B981'} stopOpacity={0.02} /></linearGradient></defs><XAxis@@ -406,7 +1023,7 @@ export default function AccountDetailPage() {<Tooltipformatter={(value) => [value !== null ? (privacyMode ? MASK : formatCurrency(Number(value), displayCurrency, locale)) : '\u2014',- t('accounts.currentBalance'),+ isCreditCard ? t('accounts.cycleSpending') : t('accounts.currentBalance'),]}labelFormatter={(label) => label}contentStyle={{@@ -421,11 +1038,11 @@ export default function AccountDetailPage() {<Areatype="monotone"dataKey="balance"- stroke="#10B981"+ stroke={isCreditCard ? '#F43F5E' : '#10B981'}strokeWidth={2}fill="url(#acctBalGrad)"dot={false}- activeDot={{ r: 3, fill: '#10B981' }}+ activeDot={{ r: 3, fill: isCreditCard ? '#F43F5E' : '#10B981' }}/></AreaChart></ResponsiveContainer>@@ -434,6 +1051,8 @@ export default function AccountDetailPage() {)}</div></div>+ )+ })()}{/* Transaction table */}<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">@@ -499,6 +1118,16 @@ export default function AccountDetailPage() {{t('transactions.pending')}</span>)}+ {tx.installment_number != null && tx.total_installments != null && (+ <span+ className="ml-2 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"+ title={tx.installment_total_amount != null+ ? t('transactions.installmentTooltip', { count: tx.total_installments, total: tx.installment_total_amount })+ : undefined}+ >+ {tx.installment_number}/{tx.total_installments}+ </span>+ )}{(tx.attachment_count ?? 0) > 0 && (<Paperclip size={12} className="ml-2 inline text-muted-foreground" />)}@@ -564,6 +1193,112 @@ export default function AccountDetailPage() {loading={transferMutation.isPending}defaultFromAccountId={id}/>++ {account && (+ <CreditCardSettingsDialog+ open={ccSettingsOpen}+ onClose={() => setCcSettingsOpen(false)}+ account={account}+ onSave={(data) => ccSettingsMutation.mutate(data)}+ loading={ccSettingsMutation.isPending}+ />+ )}</div>)}++function CreditCardSettingsDialog({+ open,+ onClose,+ account,+ onSave,+ loading,+}: {+ open: boolean+ onClose: () => void+ account: { credit_limit: number | null; statement_close_day: number | null; payment_due_day: number | null }+ onSave: (data: { credit_limit: number | null; statement_close_day: number | null; payment_due_day: number | null }) => void+ loading: boolean+}) {+ const { t } = useTranslation()+ const [creditLimit, setCreditLimit] = useState('')+ const [closeDay, setCloseDay] = useState('')+ const [dueDay, setDueDay] = useState('')++ useEffect(() => {+ if (!open) return+ setCreditLimit(account.credit_limit != null ? String(account.credit_limit) : '')+ setCloseDay(account.statement_close_day != null ? String(account.statement_close_day) : '')+ setDueDay(account.payment_due_day != null ? String(account.payment_due_day) : '')+ }, [open, account.credit_limit, account.statement_close_day, account.payment_due_day])++ const parseDay = (v: string): number | null => {+ const n = parseInt(v, 10)+ return Number.isFinite(n) && n >= 1 && n <= 31 ? n : null+ }++ return (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('accounts.typeCreditCard')}</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault()+ onSave({+ credit_limit: creditLimit !== '' ? parseFloat(creditLimit) : null,+ statement_close_day: parseDay(closeDay),+ payment_due_day: parseDay(dueDay),+ })+ }}+ className="space-y-4"+ >+ <div className="space-y-2">+ <Label>{t('accounts.creditLimit')}</Label>+ <Input+ type="number"+ step="0.01"+ min="0"+ value={creditLimit}+ onChange={(e) => setCreditLimit(e.target.value)}+ placeholder="0.00"+ />+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('accounts.statementCloseDay')}</Label>+ <Input+ type="number"+ min="1"+ max="31"+ value={closeDay}+ onChange={(e) => setCloseDay(e.target.value)}+ placeholder={t('accounts.dayOfMonthHint')}+ />+ </div>+ <div className="space-y-2">+ <Label>{t('accounts.paymentDueDay')}</Label>+ <Input+ type="number"+ min="1"+ max="31"+ value={dueDay}+ onChange={(e) => setDueDay(e.target.value)}+ placeholder={t('accounts.dayOfMonthHint')}+ />+ </div>+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ <Button type="submit" disabled={loading}>+ {loading ? t('common.loading') : t('common.save')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex a7007001..38f0f9a9 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -43,6 +43,14 @@ function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}+function daysUntil(dateStr: string | null): number | null {+ if (!dateStr) return null+ const due = new Date(dateStr + 'T00:00:00')+ const today = new Date()+ today.setHours(0, 0, 0, 0)+ return Math.round((due.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))+}+const ACCOUNT_TYPE_CONFIG: Record<string, { icon: React.ElementType; color: string; bg: string; label: string }> = {checking: { icon: Building2, color: 'text-indigo-600', bg: 'bg-indigo-100', label: 'accounts.typeChecking' },savings: { icon: PiggyBank, color: 'text-emerald-600', bg: 'bg-emerald-100', label: 'accounts.typeSavings' },@@ -209,6 +217,14 @@ export default function AccountsPage() {const cfg = getTypeConfig(acc.type)const Icon = cfg.iconconst bal = Number(acc.current_balance)+ const isCC = acc.type === 'credit_card'+ const dueIn = isCC ? daysUntil(acc.next_due_date) : null+ const dueText =+ dueIn == null ? null+ : dueIn < 0 ? t('accounts.overdue')+ : dueIn === 0 ? t('accounts.dueToday')+ : t('accounts.dueIn', { count: dueIn })+ const dueClass = dueIn != null && dueIn <= 3 ? 'text-amber-600' : 'text-muted-foreground'return (<div key={acc.id} className="group flex items-center px-5 py-3 hover:bg-muted/50 transition-colors"><Link to={`/accounts/${acc.id}`} className="flex items-center gap-3 flex-1 min-w-0">@@ -217,7 +233,10 @@ export default function AccountsPage() {</div><div className="min-w-0 flex-1"><p className="text-sm font-medium text-foreground truncate">{acc.name}</p>- <p className="text-xs text-muted-foreground">{t(cfg.label)}</p>+ <p className="text-xs text-muted-foreground">+ {t(cfg.label)}+ {dueText && <> · <span className={dueClass}>{dueText}</span></>}+ </p></div></Link><div className="flex items-center gap-1 mr-3 opacity-0 group-hover:opacity-100 transition-opacity">@@ -248,7 +267,11 @@ export default function AccountsPage() {<p className={`text-xs sm:text-sm font-semibold tabular-nums ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>{mask(formatCurrency(bal, acc.currency, locale))}</p>- {acc.balance_primary != null && acc.currency !== userCurrency && (+ {isCC && acc.available_credit != null ? (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {t('accounts.availableCredit')}: {mask(formatCurrency(Number(acc.available_credit), acc.currency, locale))}+ </p>+ ) : acc.balance_primary != null && acc.currency !== userCurrency && (<p className="text-[10px] text-muted-foreground tabular-nums">{mask(formatCurrency(acc.balance_primary, userCurrency, locale))}</p>@@ -351,6 +374,14 @@ export default function AccountsPage() {const cfg = getTypeConfig(acc.type)const Icon = cfg.iconconst bal = Number(acc.current_balance)+ const isCC = acc.type === 'credit_card'+ const dueIn = isCC ? daysUntil(acc.next_due_date) : null+ const dueText =+ dueIn == null ? null+ : dueIn < 0 ? t('accounts.overdue')+ : dueIn === 0 ? t('accounts.dueToday')+ : t('accounts.dueIn', { count: dueIn })+ const dueClass = dueIn != null && dueIn <= 3 ? 'text-amber-600' : 'text-muted-foreground'return (<div key={acc.id} className="group flex items-center px-5 py-3 hover:bg-muted/50 transition-colors"><Link to={`/accounts/${acc.id}`} className="flex items-center gap-3 flex-1 min-w-0">@@ -359,7 +390,10 @@ export default function AccountsPage() {</div><div className="min-w-0 flex-1"><p className="text-sm font-medium text-foreground truncate">{acc.name}</p>- <p className="text-xs text-muted-foreground">{t(cfg.label)}</p>+ <p className="text-xs text-muted-foreground">+ {t(cfg.label)}+ {dueText && <> · <span className={dueClass}>{dueText}</span></>}+ </p></div></Link><button@@ -373,7 +407,11 @@ export default function AccountsPage() {<p className={`text-xs sm:text-sm font-semibold tabular-nums ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>{mask(formatCurrency(bal, acc.currency, locale))}</p>- {acc.balance_primary != null && acc.currency !== userCurrency && (+ {isCC && acc.available_credit != null ? (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {t('accounts.availableCredit')}: {mask(formatCurrency(Number(acc.available_credit), acc.currency, locale))}+ </p>+ ) : acc.balance_primary != null && acc.currency !== userCurrency && (<p className="text-[10px] text-muted-foreground tabular-nums">{mask(formatCurrency(acc.balance_primary, userCurrency, locale))}</p>@@ -547,7 +585,16 @@ function AccountDialog({open: booleanonClose: () => voidaccount: Account | null- onSave: (data: { name?: string; type?: string; balance?: number; balance_date?: string; currency?: string }) => void+ onSave: (data: {+ name?: string+ type?: string+ balance?: number+ balance_date?: string+ currency?: string+ credit_limit?: number | null+ statement_close_day?: number | null+ payment_due_day?: number | null+ }) => voidloading: boolean}) {const { t } = useTranslation()@@ -563,6 +610,9 @@ function AccountDialog({const [balance, setBalance] = useState(account?.balance?.toString() ?? '0')const [currency, setCurrency] = useState(account?.currency ?? userCurrency)const [balanceDate, setBalanceDate] = useState(new Date().toISOString().slice(0, 10))+ const [creditLimit, setCreditLimit] = useState(account?.credit_limit?.toString() ?? '')+ const [statementCloseDay, setStatementCloseDay] = useState(account?.statement_close_day?.toString() ?? '')+ const [paymentDueDay, setPaymentDueDay] = useState(account?.payment_due_day?.toString() ?? '')useEffect(() => {setName(account?.name ?? '')@@ -570,6 +620,9 @@ function AccountDialog({setBalance(account?.balance?.toString() ?? '0')setCurrency(account?.currency ?? userCurrency)setBalanceDate(new Date().toISOString().slice(0, 10))+ setCreditLimit(account?.credit_limit?.toString() ?? '')+ setStatementCloseDay(account?.statement_close_day?.toString() ?? '')+ setPaymentDueDay(account?.payment_due_day?.toString() ?? '')}, [account])return (@@ -584,7 +637,21 @@ function AccountDialog({key={account?.id ?? 'new'}onSubmit={(e) => {e.preventDefault()- onSave({ name, type, balance: parseFloat(balance), balance_date: balanceDate, currency })+ const isCC = type === 'credit_card'+ const parseDay = (v: string) => {+ const n = parseInt(v, 10)+ return Number.isFinite(n) && n >= 1 && n <= 31 ? n : null+ }+ onSave({+ name,+ type,+ balance: parseFloat(balance),+ balance_date: balanceDate,+ currency,+ credit_limit: isCC && creditLimit !== '' ? parseFloat(creditLimit) : null,+ statement_close_day: isCC ? parseDay(statementCloseDay) : null,+ payment_due_day: isCC ? parseDay(paymentDueDay) : null,+ })}}className="space-y-4">@@ -639,6 +706,45 @@ function AccountDialog({/></div></div>+ {type === 'credit_card' && (+ <div className="space-y-4 rounded-lg border border-border bg-muted/30 p-4">+ <div className="space-y-2">+ <Label>{t('accounts.creditLimit')}</Label>+ <Input+ type="number"+ step="0.01"+ min="0"+ value={creditLimit}+ onChange={(e) => setCreditLimit(e.target.value)}+ placeholder="0.00"+ />+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('accounts.statementCloseDay')}</Label>+ <Input+ type="number"+ min="1"+ max="31"+ value={statementCloseDay}+ onChange={(e) => setStatementCloseDay(e.target.value)}+ placeholder={t('accounts.dayOfMonthHint')}+ />+ </div>+ <div className="space-y-2">+ <Label>{t('accounts.paymentDueDay')}</Label>+ <Input+ type="number"+ min="1"+ max="31"+ value={paymentDueDay}+ onChange={(e) => setPaymentDueDay(e.target.value)}+ placeholder={t('accounts.dayOfMonthHint')}+ />+ </div>+ </div>+ </div>+ )}<DialogFooter><Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}diff --git a/frontend/src/pages/admin/settings.tsx b/frontend/src/pages/admin/settings.tsxindex 0f21a1d6..f0c88e5d 100644--- a/frontend/src/pages/admin/settings.tsx+++ b/frontend/src/pages/admin/settings.tsx@@ -19,7 +19,7 @@ import {DialogDescription,} from '@/components/ui/dialog'import { PageHeader } from '@/components/page-header'-import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users } from 'lucide-react'+import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users, Scale } from 'lucide-react'import type { AdminUser } from '@/types'export default function AdminSettingsPage() {@@ -104,6 +104,26 @@ export default function AdminSettingsPage() {},})+ // Credit card accounting mode: returns 404 when unset → defaults to "cash".+ const { data: ccModeSetting } = useQuery({+ queryKey: ['admin', 'settings', 'credit_card_accounting_mode'],+ queryFn: () => adminApi.getSetting('credit_card_accounting_mode').catch(() => null),+ retry: false,+ })++ const updateAccountingModeMutation = useMutation({+ mutationFn: (value: string) => adminApi.updateSetting('credit_card_accounting_mode', value),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['admin', 'settings', 'credit_card_accounting_mode'] })+ toast.success(t('admin.settings.updated'))+ },+ onError: () => {+ toast.error(t('common.error'))+ },+ })++ const accountingMode = (ccModeSetting?.value === 'accrual' ? 'accrual' : 'cash') as 'cash' | 'accrual'+function resetCreateForm() {setFormEmail('')setFormPassword('')@@ -215,6 +235,47 @@ export default function AdminSettingsPage() {)}</div>+ {/* Accounting section */}+ <div className="rounded-xl border border-border/60 bg-card overflow-hidden mb-8">+ <div className="px-5 py-4 border-b border-border/40">+ <div className="flex items-center gap-2 mb-0.5">+ <Scale size={15} className="text-muted-foreground" />+ <h3 className="text-sm font-semibold text-foreground">{t('admin.settings.accountingTitle')}</h3>+ </div>+ <p className="text-xs text-muted-foreground">{t('admin.settings.accountingSubtitle')}</p>+ </div>+ <div className="divide-y divide-border/40">+ <button+ type="button"+ onClick={() => updateAccountingModeMutation.mutate('cash')}+ disabled={updateAccountingModeMutation.isPending}+ className="flex items-start gap-3 w-full px-5 py-4 text-left hover:bg-muted/40 transition-colors"+ >+ <div className={`mt-0.5 h-4 w-4 rounded-full border-2 shrink-0 ${accountingMode === 'cash' ? 'border-primary bg-primary' : 'border-muted-foreground/40'}`}>+ {accountingMode === 'cash' && <div className="h-full w-full rounded-full bg-primary ring-2 ring-background ring-inset" />}+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-foreground">{t('admin.settings.accountingCash')}</p>+ <p className="text-xs text-muted-foreground mt-0.5">{t('admin.settings.accountingCashDesc')}</p>+ </div>+ </button>+ <button+ type="button"+ onClick={() => updateAccountingModeMutation.mutate('accrual')}+ disabled={updateAccountingModeMutation.isPending}+ className="flex items-start gap-3 w-full px-5 py-4 text-left hover:bg-muted/40 transition-colors"+ >+ <div className={`mt-0.5 h-4 w-4 rounded-full border-2 shrink-0 ${accountingMode === 'accrual' ? 'border-primary bg-primary' : 'border-muted-foreground/40'}`}>+ {accountingMode === 'accrual' && <div className="h-full w-full rounded-full bg-primary ring-2 ring-background ring-inset" />}+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-foreground">{t('admin.settings.accountingAccrual')}</p>+ <p className="text-xs text-muted-foreground mt-0.5">{t('admin.settings.accountingAccrualDesc')}</p>+ </div>+ </button>+ </div>+ </div>+{/* Settings section */}<div className="rounded-xl border border-border/60 bg-card overflow-hidden"><div className="px-5 py-4 border-b border-border/40">diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex dfe30434..27a5e581 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -491,6 +491,16 @@ export default function TransactionsPage() {{t('transactions.recurringBadge')}</span>)}+ {tx.installment_number != null && tx.total_installments != 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"+ title={tx.installment_total_amount != null+ ? t('transactions.installmentTooltip', { count: tx.total_installments, total: tx.installment_total_amount })+ : undefined}+ >+ {tx.installment_number}/{tx.total_installments}+ </span>+ )}{(tx.attachment_count ?? 0) > 0 && (<Paperclip size={12} className="text-muted-foreground shrink-0" />)}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 40d942f6..b825b62b 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -86,6 +86,15 @@ export interface Account {previous_balance: number | nullbalance_primary: number | nullcurrency: string+ credit_limit: number | null+ available_credit: number | null+ statement_close_day: number | null+ payment_due_day: number | null+ next_close_date: string | null+ next_due_date: string | null+ minimum_payment: number | null+ card_brand: string | null+ card_level: string | nullis_closed: booleanclosed_at: string | null}@@ -123,6 +132,10 @@ export interface Transaction {fx_rate_used: number | nullfx_fallback: booleanattachment_count?: number+ installment_number: number | null+ total_installments: number | null+ installment_total_amount: number | null+ installment_purchase_date: string | null}export interface Payee {