Skip to content

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

adding bills notion for credit card and effective bill date (#92) (#139)

Tássio Noronha3746354806d7
diff --git a/backend/alembic/versions/040_credit_card_bills.py b/backend/alembic/versions/040_credit_card_bills.py
new file mode 100644
index 00000000..20273b6a
--- /dev/null
+++ b/backend/alembic/versions/040_credit_card_bills.py
@@ -0,0 +1,52 @@
+"""create credit_card_bills table
+
+Provider-agnostic credit-card bill (fatura) snapshot — see issue #92.
+Schema is a generic billing shape; provider-specific payloads live in
+`raw_data` so we don't tie the table to one integration.
+
+Phase 1: schema only. Sync wiring ships in a follow-up so this migration
+is safe to apply ahead of the provider changes.
+
+Revision ID: 040
+Revises: 039
+Create Date: 2026-04-27
+"""
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+
+revision = "040"
+down_revision = "039"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "credit_card_bills",
+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("account_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("external_id", sa.String(length=255), nullable=False),
+ sa.Column("due_date", sa.Date(), nullable=False),
+ sa.Column("total_amount", sa.Numeric(precision=15, scale=2), nullable=False),
+ sa.Column("currency", sa.String(length=3), nullable=False, server_default="BRL"),
+ sa.Column("minimum_payment", sa.Numeric(precision=15, scale=2), nullable=True),
+ sa.Column("raw_data", sa.JSON(), nullable=True),
+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
+ sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], ondelete="CASCADE"),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("account_id", "external_id", name="uq_cc_bills_account_external_id"),
+ )
+ op.create_index("ix_credit_card_bills_due_date", "credit_card_bills", ["due_date"])
+ op.create_index("ix_credit_card_bills_account_id", "credit_card_bills", ["account_id"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_credit_card_bills_account_id", table_name="credit_card_bills")
+ op.drop_index("ix_credit_card_bills_due_date", table_name="credit_card_bills")
+ op.drop_table("credit_card_bills")
diff --git a/backend/alembic/versions/041_transaction_bill_id.py b/backend/alembic/versions/041_transaction_bill_id.py
new file mode 100644
index 00000000..33ab3e95
--- /dev/null
+++ b/backend/alembic/versions/041_transaction_bill_id.py
@@ -0,0 +1,43 @@
+"""link transactions to credit_card_bills
+
+Adds a nullable FK so the sync layer can record which bill (fatura) a credit
+card transaction belongs to (issue #92). Null = fall back to locally-computed
+cycle math; ON DELETE SET NULL = unlink rather than cascade-delete the tx if
+the bill row goes away.
+
+Revision ID: 041
+Revises: 040
+Create Date: 2026-04-27
+"""
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+
+revision = "041"
+down_revision = "040"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "transactions",
+ sa.Column("bill_id", postgresql.UUID(as_uuid=True), nullable=True),
+ )
+ op.create_foreign_key(
+ "transactions_bill_id_fkey",
+ "transactions",
+ "credit_card_bills",
+ ["bill_id"],
+ ["id"],
+ ondelete="SET NULL",
+ )
+ op.create_index("ix_transactions_bill_id", "transactions", ["bill_id"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_transactions_bill_id", table_name="transactions")
+ op.drop_constraint("transactions_bill_id_fkey", "transactions", type_="foreignkey")
+ op.drop_column("transactions", "bill_id")
diff --git a/backend/alembic/versions/042_backfill_transaction_bill_id.py b/backend/alembic/versions/042_backfill_transaction_bill_id.py
new file mode 100644
index 00000000..949f3e09
--- /dev/null
+++ b/backend/alembic/versions/042_backfill_transaction_bill_id.py
@@ -0,0 +1,46 @@
+"""backfill transaction.bill_id from raw_data on existing CC transactions
+
+Phase 2 starts persisting credit_card_bills and linking new transactions to
+them, but the 14-day sync rewind doesn't refetch older transactions. For
+already-synced data, the bill linkage is recoverable directly: every
+Pluggy CC transaction stores the original payload in raw_data, including
+creditCardMetadata.billId. This migration matches those to the bills table
+and stamps bill_id + effective_date in one shot — no HTTP traffic needed.
+
+Idempotent (only touches rows where bill_id is NULL). Safe to re-run.
+Issue #92.
+
+Revision ID: 042
+Revises: 041
+Create Date: 2026-04-27
+"""
+
+from alembic import op
+
+
+revision = "042"
+down_revision = "041"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.execute(
+ """
+ UPDATE transactions AS t
+ SET bill_id = b.id,
+ effective_date = b.due_date
+ FROM credit_card_bills AS b
+ WHERE t.bill_id IS NULL
+ AND t.account_id = b.account_id
+ AND b.external_id = t.raw_data -> 'creditCardMetadata' ->> 'billId'
+ """
+ )
+
+
+def downgrade() -> None:
+ # No-op: clearing bill_id wholesale would also wipe links the sync layer
+ # legitimately set after this migration ran. Operators who really need to
+ # reverse should run the equivalent UPDATE manually with whatever filter
+ # makes sense for their case.
+ pass
diff --git a/backend/alembic/versions/043_transaction_effective_bill_date.py b/backend/alembic/versions/043_transaction_effective_bill_date.py
new file mode 100644
index 00000000..b87844f8
--- /dev/null
+++ b/backend/alembic/versions/043_transaction_effective_bill_date.py
@@ -0,0 +1,31 @@
+"""manual effective_bill_date override on transactions
+
+Lets users override the cycle assignment for a credit-card transaction by
+setting an explicit date. Useful when the provider didn't tag the tx with a
+billId, or when the user disagrees with how a tx was bucketed (LucasFidelis's
+suggestion in issue #92). Empty by default; only meaningful for CC accounts.
+
+Revision ID: 043
+Revises: 042
+Create Date: 2026-04-28
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+
+revision = "043"
+down_revision = "042"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "transactions",
+ sa.Column("effective_bill_date", sa.Date(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("transactions", "effective_bill_date")
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.py
index 217532b4..76d699c9 100644
--- a/backend/app/api/accounts.py
+++ b/backend/app/api/accounts.py
@@ -9,7 +9,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.auth import current_active_user
from app.core.database import get_async_session
from app.models.user import User
-from app.schemas.account import AccountCreate, AccountRead, AccountUpdate, AccountSummary
+from app.schemas.account import (
+ AccountCreate,
+ AccountRead,
+ AccountSummary,
+ AccountUpdate,
+ CreditCardBillRead,
+)
from app.services import account_service
from app.services.fx_rate_service import convert
@@ -38,6 +44,8 @@ async def get_account_summary(
account_id: uuid.UUID,
date_from: Optional[str] = Query(None, alias="from", description="YYYY-MM-DD"),
date_to: Optional[str] = Query(None, alias="to", description="YYYY-MM-DD"),
+ bill_id: Optional[uuid.UUID] = Query(None, description="Aggregate by bill_id (issue #92); takes precedence over from/to"),
+ unbilled_only: bool = Query(False, description="Cycle-math fallback only: exclude txs already linked to any bill"),
session: AsyncSession = Depends(get_async_session),
user: User = Depends(current_active_user),
):
@@ -45,6 +53,7 @@ async def get_account_summary(
to_date = date.fromisoformat(date_to) if date_to else None
summary = await account_service.get_account_summary(
session, account_id, user.id, date_from=from_date, date_to=to_date,
+ bill_id=bill_id, unbilled_only=unbilled_only,
)
if not summary:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")
@@ -91,6 +100,27 @@ async def get_account_balance_history(
return history
[email protected]("/{account_id}/bills", response_model=list[CreditCardBillRead])
+async def get_account_bills(
+ account_id: uuid.UUID,
+ limit: int = Query(24, ge=1, le=200, description="Max bills to return, newest due_date first"),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ """List credit-card bills for an account, newest due_date first.
+
+ Returns an empty list for non-CC accounts and for CC accounts that have
+ no synced bills (provider doesn't expose them, or first sync hasn't
+ happened). Issue #92.
+ """
+ bills = await account_service.get_credit_card_bills(
+ session, account_id, user.id, limit=limit,
+ )
+ if bills is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")
+ return bills
+
+
@router.get("/{account_id}", response_model=AccountRead)
async def get_account(
account_id: uuid.UUID,
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 757d121f..36735679 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -54,6 +54,8 @@ async def list_transactions(
payee_id: Optional[uuid.UUID] = Query(None),
from_date: Optional[date] = Query(None, alias="from"),
to_date: Optional[date] = Query(None, alias="to"),
+ bill_id: Optional[uuid.UUID] = Query(None, description="Filter by credit-card bill (issue #92); takes precedence over from/to"),
+ unbilled_only: bool = Query(False, description="Cycle-math fallback only: exclude txs already linked to any bill (used for in-progress CC cycles)"),
q: Optional[str] = Query(None),
uncategorized: bool = Query(False),
type: Optional[str] = Query(None),
@@ -75,6 +77,8 @@ async def list_transactions(
txn_type=type, exclude_transfers=exclude_transfers,
accounting_mode=accounting_mode,
tags=tags,
+ bill_id=bill_id,
+ unbilled_only=unbilled_only,
)
primary_currency = user.primary_currency
items = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index dfd097e2..57e50539 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -16,6 +16,7 @@ from app.models.transaction_attachment import TransactionAttachment
from app.models.payee import Payee, PayeeMapping
from app.models.app_settings import AppSetting
from app.models.goal import Goal
+from app.models.credit_card_bill import CreditCardBill
__all__ = [
"User",
@@ -37,4 +38,5 @@ __all__ = [
"PayeeMapping",
"AppSetting",
"Goal",
+ "CreditCardBill",
]
diff --git a/backend/app/models/credit_card_bill.py b/backend/app/models/credit_card_bill.py
new file mode 100644
index 00000000..9f0a4fc2
--- /dev/null
+++ b/backend/app/models/credit_card_bill.py
@@ -0,0 +1,51 @@
+import uuid
+from datetime import date as _date, datetime, timezone
+from decimal import Decimal
+from typing import Optional
+
+from sqlalchemy import Date, DateTime, ForeignKey, JSON, Numeric, String, UniqueConstraint
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.core.database import Base
+
+
+class CreditCardBill(Base):
+ """A credit-card bill (fatura) — issue #92.
+
+ Models the universal credit-card billing shape: a statement closes on a
+ cycle, has a due date and a total to be paid, and is the canonical "which
+ transactions belong in which statement" anchor. Surfaced from whichever
+ integration the account uses (Pluggy /bills today, others tomorrow); when
+ no integration provides bills, the read path falls back to locally-computed
+ cycle math (see app.services.credit_card_service).
+
+ Provider-specific extras live in `raw_data` so we can pull more out later
+ without forcing a schema-shaped opinion now.
+ """
+
+ __tablename__ = "credit_card_bills"
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
+ account_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False
+ )
+ external_id: Mapped[str] = mapped_column(String(255), nullable=False)
+ due_date: Mapped[_date] = mapped_column(Date, nullable=False, index=True)
+ total_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), nullable=False)
+ currency: Mapped[str] = mapped_column(String(3), default="BRL")
+ minimum_payment: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)
+ raw_data: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+
+ __table_args__ = (
+ UniqueConstraint("account_id", "external_id", name="uq_cc_bills_account_external_id"),
+ )
diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.py
index 641e3355..404d48d9 100644
--- a/backend/app/models/transaction.py
+++ b/backend/app/models/transaction.py
@@ -12,6 +12,7 @@ from app.core.database import Base
if TYPE_CHECKING:
from app.models.account import Account
from app.models.category import Category
+ from app.models.credit_card_bill import CreditCardBill
from app.models.import_log import ImportLog
from app.models.payee import Payee
from app.models.transaction_attachment import TransactionAttachment
@@ -55,10 +56,27 @@ class Transaction(Base):
Numeric(precision=15, scale=2), nullable=True
)
installment_purchase_date: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)
+ # User-set manual override for which bill cycle this tx belongs to. Null
+ # by default; only meaningful for credit-card accounts. When set, beats
+ # both Pluggy's billId and the cycle-math fallback (issue #92, the
+ # LucasFidelis cycle_override request).
+ effective_bill_date: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)
+ # FK to the bill this transaction belongs to (issue #92). Set during sync
+ # for providers that expose a bills feed; null otherwise — in which case
+ # the read path falls back to locally-computed cycle math via
+ # apply_effective_date. ON DELETE SET NULL: if a bill row is removed
+ # (re-sync, deletion), the transaction stays put and just unlinks.
+ bill_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True),
+ ForeignKey("credit_card_bills.id", ondelete="SET NULL"),
+ nullable=True,
+ index=True,
+ )
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
account: Mapped["Account"] = relationship(back_populates="transactions")
category: Mapped[Optional["Category"]] = relationship()
+ bill: Mapped[Optional["CreditCardBill"]] = relationship()
payee_entity: Mapped[Optional["Payee"]] = relationship(back_populates="transactions")
import_log: Mapped[Optional["ImportLog"]] = relationship(back_populates="transactions")
attachments: Mapped[list["TransactionAttachment"]] = relationship(
diff --git a/backend/app/providers/base.py b/backend/app/providers/base.py
index 0f3c8410..85effc80 100644
--- a/backend/app/providers/base.py
+++ b/backend/app/providers/base.py
@@ -38,6 +38,9 @@ class TransactionData:
total_installments: Optional[int] = None
installment_total_amount: Optional[Decimal] = None
installment_purchase_date: Optional[date] = None
+ # Provider-side identifier of the bill this transaction belongs to.
+ # Resolved to a credit_card_bills.id FK at sync time (issue #92).
+ bill_external_id: Optional[str] = None
@dataclass
@@ -53,6 +56,24 @@ class ConnectTokenData:
access_token: str
+@dataclass
+class BillData:
+ """A normalized credit-card bill (fatura), provider-agnostic.
+
+ Only the fields universal to a credit-card statement are promoted. Anything
+ a specific integration provides on top (finance charges, recorded payments,
+ installment options, etc.) is preserved verbatim in `raw_data` so we can
+ pull more out later without forcing a schema-shaped opinion now.
+ """
+
+ external_id: str
+ due_date: date
+ total_amount: Decimal
+ currency: str = "BRL"
+ minimum_payment: Optional[Decimal] = None
+ raw_data: Optional[dict] = None
+
+
@dataclass
class HoldingData:
"""A normalized investment holding, provider-agnostic.
@@ -158,3 +179,13 @@ class BankProvider(ABC):
default empty list.
"""
return []
+
+ async def get_bills(self, credentials: dict, account_external_id: str) -> list[BillData]:
+ """Fetch credit-card bills (faturas) for an account.
+
+ Providers without a bills endpoint, or non-regulated Pluggy
+ connections that don't expose /bills, return the default empty list.
+ The sync layer falls back to locally-computed cycle math in that case
+ (see app.services.credit_card_service).
+ """
+ return []
diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.py
index 7b8a2902..00d2ebd0 100644
--- a/backend/app/providers/pluggy.py
+++ b/backend/app/providers/pluggy.py
@@ -1,6 +1,6 @@
import time
from datetime import date
-from decimal import Decimal
+from decimal import Decimal, InvalidOperation
from typing import Optional
import httpx
@@ -9,6 +9,7 @@ from app.core.config import get_settings
from app.providers.base import (
AccountData,
BankProvider,
+ BillData,
ConnectionData,
ConnectTokenData,
HoldingData,
@@ -33,7 +34,7 @@ def _decimal_or_none(value) -> Optional[Decimal]:
return None
try:
return Decimal(str(value))
- except (ValueError, TypeError):
+ except (ValueError, TypeError, InvalidOperation):
return None
@@ -96,6 +97,35 @@ def _build_holding_data(inv: dict) -> HoldingData:
)
+def _build_bill_data(raw: dict) -> Optional[BillData]:
+ """Map a Pluggy bill payload to BillData.
+
+ Returns None when required anchors (id, dueDate, totalAmount) are missing
+ or unparseable — the caller drops those rows rather than failing the whole
+ sync. Negative `totalAmount` is preserved (not abs'd): a negative bill
+ means the bank owes the user money, and silently flipping the sign would
+ hide that fact in reports.
+
+ Provider-specific extras (financeCharges, payments, allowsInstallments,
+ etc.) survive in `raw_data` and can be promoted to first-class columns
+ later if/when the read path actually needs them.
+ """
+ bill_id = raw.get("id")
+ due_date = _date_or_none(raw.get("dueDate"))
+ total_amount = _decimal_or_none(raw.get("totalAmount"))
+ if not bill_id or due_date is None or total_amount is None:
+ return None
+
+ return BillData(
+ external_id=str(bill_id),
+ due_date=due_date,
+ total_amount=total_amount,
+ currency=raw.get("totalAmountCurrencyCode") or "BRL",
+ minimum_payment=_decimal_or_none(raw.get("minimumPaymentAmount")),
+ raw_data=raw,
+ )
+
+
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", ""))
@@ -346,6 +376,13 @@ class PluggyProvider(BankProvider):
if inst_total_amount is not None
else None
)
+ # Bill linkage: Pluggy stamps each charge with the id of
+ # the bill it lands in. The sync layer resolves this to a
+ # credit_card_bills FK; we just capture the string here.
+ bill_external_id_raw = cc_meta.get("billId")
+ bill_external_id = (
+ str(bill_external_id_raw) if bill_external_id_raw else None
+ )
all_transactions.append(
TransactionData(
@@ -364,6 +401,7 @@ class PluggyProvider(BankProvider):
total_installments=inst_total if isinstance(inst_total, int) else None,
installment_total_amount=inst_total_amount_dec,
installment_purchase_date=inst_purchase_date,
+ bill_external_id=bill_external_id,
)
)
@@ -413,6 +451,45 @@ class PluggyProvider(BankProvider):
return holdings
+ async def get_bills(self, credentials: dict, account_external_id: str) -> list[BillData]:
+ """Fetch credit-card bills from Pluggy /bills.
+
+ Pluggy only exposes /bills on Regulado (Open Finance) connections.
+ For non-regulated connectors the request returns 4xx — we let the
+ error propagate so the sync layer can decide whether to fall back
+ to locally-computed cycle math (compute_effective_date).
+ """
+ headers = await self._headers()
+ bills: list[BillData] = []
+ page = 1
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ while True:
+ resp = await client.get(
+ f"{PLUGGY_API_BASE}/bills",
+ headers=headers,
+ params={
+ "accountId": account_external_id,
+ "pageSize": 500,
+ "page": page,
+ },
+ )
+ resp.raise_for_status()
+ data = resp.json()
+
+ results = data.get("results", [])
+ for raw in results:
+ bill = _build_bill_data(raw)
+ if bill is not None:
+ bills.append(bill)
+
+ total_pages = data.get("totalPages", 1)
+ if page >= total_pages or not results:
+ break
+ page += 1
+
+ return bills
+
@staticmethod
def _extract_payee(txn: dict, txn_type: str, payee_source: str = "auto") -> Optional[str]:
"""Extract payee name based on configured source."""
diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.py
index 8346e801..1b72265b 100644
--- a/backend/app/schemas/account.py
+++ b/backend/app/schemas/account.py
@@ -65,6 +65,24 @@ class AccountRead(AccountBase):
model_config = ConfigDict(from_attributes=True)
+class CreditCardBillRead(BaseModel):
+ """Provider-agnostic credit-card bill (fatura) — issue #92.
+
+ Provider-specific extras live in `raw_data` on the model but are not
+ exposed here so that consumers don't form provider-shaped dependencies.
+ """
+
+ id: uuid.UUID
+ account_id: uuid.UUID
+ external_id: str
+ due_date: date
+ total_amount: float
+ currency: str
+ minimum_payment: Optional[float] = None
+
+ model_config = ConfigDict(from_attributes=True)
+
+
class AccountSummary(BaseModel):
account_id: uuid.UUID
current_balance: float
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index 853eb464..85d0a724 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -27,6 +27,7 @@ class TransactionCreate(TransactionBase):
notes: Optional[str] = None
amount_primary: Optional[Decimal] = None
fx_rate_used: Optional[Decimal] = None
+ effective_bill_date: Optional[_Date] = None
class TransactionUpdate(BaseModel):
@@ -41,6 +42,9 @@ class TransactionUpdate(BaseModel):
notes: Optional[str] = None
amount_primary: Optional[Decimal] = None
fx_rate_used: Optional[Decimal] = None
+ # CC bucketing override (issue #92). Empty string / explicit null clears
+ # it back to auto. Only meaningful for credit-card accounts.
+ effective_bill_date: Optional[_Date] = None
class TransactionRead(TransactionBase):
@@ -65,6 +69,8 @@ class TransactionRead(TransactionBase):
total_installments: Optional[int] = None
installment_total_amount: Optional[float] = None
installment_purchase_date: Optional[_Date] = None
+ bill_id: Optional[uuid.UUID] = None
+ effective_bill_date: Optional[_Date] = None
model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index 98c23cb3..5da0c7ef 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
from app.models.bank_connection import BankConnection
+from app.models.credit_card_bill import CreditCardBill
from app.models.transaction import Transaction
from app.schemas.account import AccountCreate, AccountUpdate
from app.services._query_filters import counts_as_pnl
@@ -132,6 +133,34 @@ def serialize_account(
return payload
+async def get_credit_card_bills(
+ session: AsyncSession,
+ account_id: uuid.UUID,
+ user_id: uuid.UUID,
+ *,
+ limit: int = 24,
+) -> Optional[list[CreditCardBill]]:
+ """Return bills for a CC account, newest due_date first.
+
+ Returns None when the account doesn't exist or isn't owned by the user
+ (the caller maps that to a 404). Returns [] for non-CC accounts and CC
+ accounts with no synced bills — the read path then keeps using the
+ cycle-math fallback.
+ """
+ account = await get_account(session, account_id, user_id)
+ if account is None:
+ return None
+ if account.type != "credit_card":
+ return []
+ result = await session.execute(
+ select(CreditCardBill)
+ .where(CreditCardBill.account_id == account_id)
+ .order_by(CreditCardBill.due_date.desc())
+ .limit(limit)
+ )
+ return list(result.scalars().all())
+
+
async def get_account(session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Account]:
result = await session.execute(
select(Account)
@@ -492,6 +521,8 @@ async def reopen_account(
async def get_account_summary(
session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID,
date_from: Optional[_Date] = None, date_to: Optional[_Date] = None,
+ bill_id: Optional[uuid.UUID] = None,
+ unbilled_only: bool = False,
) -> Optional[dict]:
account = await get_account(session, account_id, user_id)
if not account:
@@ -534,30 +565,92 @@ async def get_account_summary(
if account.type == "credit_card" and account.connection_id:
current_balance = -current_balance
- # Income = SUM of credit transactions in [date_from, date_to] (excluding
- # opening_balance, paired transfers, and transfer-like categories).
+ # Bucketing date: for credit-card txs the user can override which cycle
+ # a tx belongs to via `effective_bill_date`. We honor that first so the
+ # totals card and bar chart agree with the transactions list (issue #92).
+ bucket_date = func.coalesce(Transaction.effective_bill_date, Transaction.date)
+
+ # Bill-driven filter (issue #92): when the caller passes bill_id, include
+ # (a) txs linked to this bill via Pluggy's billId mapping, AND
+ # (b) txs with NO bill_id (manual entries, OFX/CSV imports, recurring
+ # fills) whose bucketing date is in the cycle window — without (b)
+ # we'd drop user-added compensations for missing provider txs.
+ # Without bill_id (cycle-math or non-CC), apply the date window straight.
+ from sqlalchemy import and_ as _and, not_ as _not # local: only for scope
+ # Resolve the active bill's due_date once so the pending-exclusion can
+ # trust our cycle-math pre-classification (see get_transactions).
+ active_due_subq = (
+ select(CreditCardBill.due_date)
+ .where(CreditCardBill.id == bill_id)
+ .scalar_subquery()
+ ) if bill_id is not None else None
+
+ def _scope(query):
+ if bill_id is not None:
+ unlinked_in_window = _and(
+ Transaction.bill_id.is_(None),
+ # Defer sync-pending txs only when their effective_date does
+ # NOT match this bill — i.e., cycle math placed them in a
+ # different bill. If effective_date matches, the tx is
+ # pre-classified to this bill and we include it (the
+ # in-progress case abdalanervoso reported empty).
+ _not(_and(
+ Transaction.source == "sync",
+ Transaction.status == "pending",
+ Transaction.effective_date != active_due_subq,
+ )),
+ bucket_date >= date_from,
+ bucket_date <= date_to,
+ )
+ return query.where(or_(Transaction.bill_id == bill_id, unlinked_in_window))
+ # Cycle-math fallback. Opt-in `unbilled_only` excludes already-billed
+ # txs so an in-progress cycle's bar/total doesn't double-count past-
+ # bill txs whose date falls in the window (see get_transactions).
+ if unbilled_only:
+ return query.where(
+ Transaction.bill_id.is_(None),
+ bucket_date >= date_from,
+ bucket_date <= date_to,
+ )
+ return query.where(bucket_date >= date_from, bucket_date <= date_to)
+
+ # Income = SUM of credit transactions in window (excluding opening_balance,
+ # paired transfers, and transfer-like categories).
income_result = await session.execute(
- select(func.coalesce(func.sum(effective_amount), 0)).where(
+ _scope(select(func.coalesce(func.sum(effective_amount), 0)).where(
Transaction.account_id == account_id,
Transaction.type == "credit",
Transaction.source != "opening_balance",
counts_as_pnl(),
- Transaction.date >= date_from,
- Transaction.date <= date_to,
- )
+ ))
)
monthly_income = float(income_result.scalar())
- # Expenses = SUM of debit transactions in [date_from, date_to] (same exclusions)
- expenses_result = await session.execute(
- select(func.coalesce(func.sum(func.abs(effective_amount)), 0)).where(
- Transaction.account_id == account_id,
- Transaction.type == "debit",
- counts_as_pnl(),
- Transaction.date >= date_from,
- Transaction.date <= date_to,
+ # Expenses = SUM of debit transactions in window (same exclusions).
+ # For credit-card accounts, NET refund credits against debits so the
+ # cycle's "Total da fatura" matches the bank's bill (refunds reduce the
+ # invoice amount). counts_as_pnl already excludes paired transfers and
+ # transfer-like categories, so bill payments are not double-counted.
+ if account.type == "credit_card":
+ signed_for_bill = case(
+ (Transaction.type == "credit", -func.abs(effective_amount)),
+ else_=func.abs(effective_amount),
+ )
+ expenses_result = await session.execute(
+ _scope(select(func.coalesce(func.sum(signed_for_bill), 0)).where(
+ Transaction.account_id == account_id,
+ Transaction.source != "opening_balance",
+ counts_as_pnl(),
+ ))
+ )
+ else:
+ expenses_result = await session.execute(
+ _scope(select(func.coalesce(func.sum(func.abs(effective_amount)), 0)).where(
+ Transaction.account_id == account_id,
+ Transaction.type == "debit",
+ counts_as_pnl(),
+ ))
)
- )
monthly_expenses = float(expenses_result.scalar())
return {
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index 73809d86..f2d53249 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -1,6 +1,7 @@
import logging
import uuid
from datetime import date, datetime, timedelta, timezone
+from decimal import Decimal, InvalidOperation
from typing import Optional
from sqlalchemy import or_, select, update
@@ -14,6 +15,7 @@ from app.models.asset_value import AssetValue
from app.models.bank_connection import BankConnection
from app.models.account import Account
from app.models.category import Category
+from app.models.credit_card_bill import CreditCardBill
from app.models.transaction import Transaction
from app.models.user import User
from app.providers import get_provider
@@ -422,6 +424,10 @@ async def handle_oauth_callback(
session.add(account)
await session.flush()
+ bills_by_external_id = await _sync_credit_card_bills(
+ session, user_id, account, provider, connection_data.credentials
+ )
+
# Fetch initial transactions (since=None fetches all available history)
transactions_data = await provider.get_transactions(
connection_data.credentials, acc_data.external_id, None
@@ -436,6 +442,11 @@ async def handle_oauth_callback(
payee_entity = await get_or_create_payee(session, user_id, txn_data.payee)
payee_id = payee_entity.id
+ bill = (
+ bills_by_external_id.get(txn_data.bill_external_id)
+ if txn_data.bill_external_id
+ else None
+ )
transaction = Transaction(
user_id=user_id,
account_id=account.id,
@@ -455,8 +466,11 @@ async def handle_oauth_callback(
total_installments=txn_data.total_installments,
installment_total_amount=txn_data.installment_total_amount,
installment_purchase_date=txn_data.installment_purchase_date,
+ bill_id=bill.id if bill else None,
+ )
+ apply_effective_date(
+ transaction, account, bill_due_date=bill.due_date if bill else None
)
- apply_effective_date(transaction, account)
session.add(transaction)
await session.flush()
new_tx_ids.append(transaction.id)
@@ -603,6 +617,238 @@ async def _cleanup_phantom_duplicates(
return deleted
+# Finance-charge `additionalInfo` strings that Pluggy emits but which would
+# double-count if materialized as transactions:
+# - "Saldo em atraso" — the prior bill's unpaid balance carried into this
+# bill. It's an informational line, not part of bill.totalAmount.
+# - "Juros de dívida encerrada" — an aggregate that equals the sum of the
+# detailed late-charge items (IOF + LATE_PAYMENT_*) Pluggy ALSO lists
+# separately on the same bill.
+# Matched case-insensitively after stripping whitespace. Issue #92.
+_FINANCE_CHARGE_SKIP_INFO = {
+ "saldo em atraso",
+ "juros de dívida encerrada",
+}
+
+
+def _compute_bill_close_date(due_date: date, close_day: Optional[int]) -> date:
+ """The cycle's close date — when the bank snapshots the bill and applies
+ finance charges. We don't get this from the provider directly; we derive
+ it as "the most recent statement_close_day on or before the bill's
+ due_date" (a few days before due, the typical close-to-due gap). When
+ the account has no close_day configured we fall back to due_date.
+
+ Why this date, not due_date: charges accrue at close, before the user
+ pays the bill. Stamping them at due_date makes them appear chronologically
+ after the payment in the tx list, which doesn't match real bank semantics.
+ """
+ import calendar # local — not used elsewhere in this file
+ if not close_day:
+ return due_date
+ last = calendar.monthrange(due_date.year, due_date.month)[1]
+ same_month = date(due_date.year, due_date.month, min(close_day, last))
+ if same_month <= due_date:
+ return same_month
+ if due_date.month == 1:
+ py, pm = due_date.year - 1, 12
+ else:
+ py, pm = due_date.year, due_date.month - 1
+ plast = calendar.monthrange(py, pm)[1]
+ return date(py, pm, min(close_day, plast))
+
+
+def _describe_finance_charge(type_str: str, additional_info: Optional[str]) -> str:
+ """User-facing description for a synthetic finance-charge transaction.
+
+ Pluggy connectors emit human-readable Portuguese strings in
+ `additionalInfo`; we prefer those because the bank's own wording is what
+ the user expects to see. Fall back to a localized label keyed off the
+ enumerated `type` when the info field is absent.
+ """
+ if additional_info:
+ return additional_info.strip()
+ return {
+ "IOF": "IOF",
+ "LATE_PAYMENT_FEE": "Multa por atraso",
+ "LATE_PAYMENT_INTEREST": "Juros por atraso",
+ "LATE_PAYMENT_REMUNERATIVE_INTEREST": "Juros remuneratórios",
+ }.get(type_str, "Encargo")
+
+
+async def _sync_bill_finance_charges(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ account: Account,
+ bill: CreditCardBill,
+ raw_charges: list,
+) -> None:
+ """Materialize a bill's finance charges (IOF, juros, multa, etc.) as
+ synthetic transactions linked to the bill.
+
+ Without this, the cycle's tx sum can't reconcile to bill.total_amount —
+ the bank charges these but the provider doesn't always emit them as
+ standalone transactions.
+
+ Each synthetic tx has a stable external_id of the form
+ `bill_charge:{bill.external_id}:{charge.id}` so re-sync is idempotent and
+ self-healing: removed charges are detected and deleted; updated charges
+ overwrite in place. Charges matching the double-count patterns above
+ (carry-over balance, aggregate of detailed lines) are skipped.
+ """
+ # date = close (when the bank applied the charge); effective_date stays
+ # at bill.due_date so accrual-mode aggregations bucket the same as
+ # regular CC purchases for this bill.
+ charge_date = _compute_bill_close_date(bill.due_date, account.statement_close_day)
+
+ desired_external_ids: set[str] = set()
+ for raw in raw_charges:
+ if not isinstance(raw, dict):
+ continue
+ info = (raw.get("additionalInfo") or "").strip().lower()
+ if info in _FINANCE_CHARGE_SKIP_INFO:
+ continue
+ amount_raw = raw.get("amount")
+ try:
+ amount = Decimal(str(amount_raw))
+ except (ValueError, TypeError, InvalidOperation):
+ continue
+ if amount == 0:
+ continue
+ charge_id = raw.get("id")
+ if not charge_id:
+ continue
+ external_id = f"bill_charge:{bill.external_id}:{charge_id}"
+ desired_external_ids.add(external_id)
+
+ existing = (await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.external_id == external_id,
+ )
+ )).scalar_one_or_none()
+
+ description = _describe_finance_charge(
+ str(raw.get("type") or ""), raw.get("additionalInfo")
+ )
+
+ if existing:
+ existing.amount = abs(amount)
+ existing.description = description
+ existing.date = charge_date
+ existing.effective_date = bill.due_date
+ existing.bill_id = bill.id
+ existing.raw_data = raw
+ else:
+ tx = Transaction(
+ user_id=user_id,
+ account_id=account.id,
+ external_id=external_id,
+ description=description,
+ amount=abs(amount),
+ currency=bill.currency,
+ date=charge_date,
+ effective_date=bill.due_date,
+ type="debit",
+ source="sync",
+ status="posted",
+ raw_data=raw,
+ bill_id=bill.id,
+ )
+ session.add(tx)
+
+ # Drop synthetic charges Pluggy no longer reports for this bill (e.g.
+ # the bank reversed an erroneous fee on a re-sync). Real transactions
+ # don't share the bill_charge: prefix so they're untouched.
+ orphans = (await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.bill_id == bill.id,
+ Transaction.external_id.like(f"bill_charge:{bill.external_id}:%"),
+ )
+ )).scalars().all()
+ for tx in orphans:
+ if tx.external_id not in desired_external_ids:
+ await session.delete(tx)
+
+
+async def _sync_credit_card_bills(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ account: Account,
+ provider,
+ credentials: dict,
+) -> dict[str, CreditCardBill]:
+ """Fetch and upsert bills for a credit-card account.
+
+ Returns a {external_id: bill} dict so the caller can resolve transaction
+ bill_id without N+1 queries. For non-CC accounts or providers that don't
+ expose bills, returns an empty dict — the read path then falls back to
+ locally-computed cycle math via apply_effective_date.
+
+ Failures are intentionally swallowed (logged at info): a non-regulado
+ Pluggy connection 4xx'es here, a temporary API hiccup shouldn't fail
+ the whole sync, and the cycle-math fallback already covers the gap.
+ """
+ if account.type != "credit_card":
+ return {}
+
+ try:
+ bills_data = await provider.get_bills(credentials, account.external_id)
+ except Exception as e: # noqa: BLE001 — provider failures must not fail sync
+ logger.info(
+ "Skipping credit-card bills sync for account %s: %s", account.id, e
+ )
+ return {}
+
+ if not bills_data:
+ return {}
+
+ existing = (
+ await session.execute(
+ select(CreditCardBill).where(CreditCardBill.account_id == account.id)
+ )
+ ).scalars().all()
+ by_external_id: dict[str, CreditCardBill] = {b.external_id: b for b in existing}
+
+ for bd in bills_data:
+ bill = by_external_id.get(bd.external_id)
+ if bill is None:
+ bill = CreditCardBill(
+ user_id=user_id,
+ account_id=account.id,
+ external_id=bd.external_id,
+ due_date=bd.due_date,
+ total_amount=bd.total_amount,
+ currency=bd.currency,
+ minimum_payment=bd.minimum_payment,
+ raw_data=bd.raw_data,
+ )
+ session.add(bill)
+ by_external_id[bd.external_id] = bill
+ else:
+ bill.due_date = bd.due_date
+ bill.total_amount = bd.total_amount
+ bill.currency = bd.currency
+ bill.minimum_payment = bd.minimum_payment
+ bill.raw_data = bd.raw_data
+
+ await session.flush()
+
+ # Materialize finance charges (IOF, juros, multa, etc.) as transactions
+ # linked to each bill so the cycle sum reconciles to bill.total_amount.
+ for bd in bills_data:
+ bill = by_external_id.get(bd.external_id)
+ if bill is None:
+ continue
+ raw_charges = (bd.raw_data or {}).get("financeCharges")
+ if isinstance(raw_charges, list) and raw_charges:
+ await _sync_bill_finance_charges(
+ session, user_id, account, bill, raw_charges,
+ )
+
+ return by_external_id
+
+
async def sync_connection(
session: AsyncSession, connection_id: uuid.UUID, user_id: uuid.UUID
) -> tuple[BankConnection, int]:
@@ -688,6 +934,13 @@ async def sync_connection(
session.add(account)
await session.flush()
+ # Fetch the bills feed before transactions so transaction → bill
+ # FK resolution happens in-memory (no N+1). Empty dict for non-CC
+ # accounts or providers without /bills.
+ bills_by_external_id = await _sync_credit_card_bills(
+ session, user_id, account, provider, credentials
+ )
+
# Fetch and sync transactions. The 14-day rewind is on Pluggy's
# `createdAt` (when their row was inserted), so it covers two
# cases: (1) PENDING transactions that POSTED since last sync,
@@ -716,6 +969,26 @@ async def sync_connection(
if existing_tx:
if existing_tx.status == "pending" and txn_data.status == "posted":
existing_tx.status = "posted"
+ # Self-heal bill linkage: a tx that pre-dates the bills
+ # feature (or whose bill we hadn't ingested last time)
+ # picks up bill_id + bank-truth effective_date on the
+ # first sync after the bill becomes available. Same
+ # branch covers re-bucketing if the bank moved a tx to
+ # a different bill (e.g. a chargeback).
+ #
+ # User's manual override wins: if effective_bill_date is
+ # set, we don't touch bill_id or effective_date — the
+ # user has explicitly overridden the auto bucketing.
+ if (
+ txn_data.bill_external_id
+ and existing_tx.effective_bill_date is None
+ ):
+ bill = bills_by_external_id.get(txn_data.bill_external_id)
+ if bill is not None and existing_tx.bill_id != bill.id:
+ existing_tx.bill_id = bill.id
+ apply_effective_date(
+ existing_tx, account, bill_due_date=bill.due_date
+ )
continue
# Pass 2: Fuzzy match against manual transactions
@@ -739,6 +1012,11 @@ async def sync_connection(
sync_payee_entity = await get_or_create_payee(session, user_id, txn_data.payee)
sync_payee_id = sync_payee_entity.id
+ bill = (
+ bills_by_external_id.get(txn_data.bill_external_id)
+ if txn_data.bill_external_id
+ else None
+ )
transaction = Transaction(
user_id=user_id,
account_id=account.id,
@@ -758,8 +1036,11 @@ async def sync_connection(
total_installments=txn_data.total_installments,
installment_total_amount=txn_data.installment_total_amount,
installment_purchase_date=txn_data.installment_purchase_date,
+ bill_id=bill.id if bill else None,
+ )
+ apply_effective_date(
+ transaction, account, bill_due_date=bill.due_date if bill else None
)
- apply_effective_date(transaction, account)
session.add(transaction)
await session.flush()
new_tx_ids.append(transaction.id)
diff --git a/backend/app/services/credit_card_service.py b/backend/app/services/credit_card_service.py
index d888f8c2..f965bbea 100644
--- a/backend/app/services/credit_card_service.py
+++ b/backend/app/services/credit_card_service.py
@@ -66,23 +66,36 @@ def compute_available_credit(
return credit_limit - utilized
-def apply_effective_date(transaction, account) -> None:
+def apply_effective_date(transaction, account, *, bill_due_date: Optional[date] = None) -> 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.
+ Resolution order (highest priority first):
+ 1. `transaction.effective_bill_date` — manual user override; whatever
+ the user set wins, since they're hand-correcting a bucketing they
+ disagree with (issue #92's LucasFidelis suggestion).
+ 2. `bill_due_date` — bank-truth from Pluggy /bills (passed in by the
+ sync layer when a bill is linked).
+ 3. Cycle math from `account.statement_close_day` / `payment_due_day`.
+
+ For non-CC accounts, effective_date is always equal to `date`.
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."""
+ override = getattr(transaction, "effective_bill_date", None)
+ if override is not None:
+ transaction.effective_date = override
+ return
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),
- )
+ if bill_due_date is not None:
+ transaction.effective_date = bill_due_date
+ else:
+ 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
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index e659c578..336f1da6 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -64,12 +64,32 @@ async def get_transactions(
category_ids: Optional[list[uuid.UUID]] = None,
accounting_mode: Optional[str] = None,
tags: Optional[list[str]] = None,
+ bill_id: Optional[uuid.UUID] = None,
+ unbilled_only: bool = False,
) -> tuple[list[Transaction], int]:
# In "accrual" mode, bucket/order by effective_date so list filters
# line up with the cash-flow view used by the dashboard and reports.
- date_col = (
- Transaction.effective_date if accounting_mode == "accrual" else Transaction.date
+ # When the user has set a manual cycle override (effective_bill_date)
+ # we honor it FIRST regardless of accounting mode — that's the whole
+ # point of the override (issue #92, LucasFidelis suggestion).
+ date_col = func.coalesce(
+ Transaction.effective_bill_date,
+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date,
)
+ # CC bill-view date column: when the caller asks "what's in this bill?"
+ # (bill_id passed, or in-progress cycle via unbilled_only), the answer
+ # is bank-truth — the charges that fell in the cycle by purchase date —
+ # independent of the user's cash/accrual reporting preference. Without
+ # this carve-out, accrual mode would hide a 4/30 charge whose
+ # effective_date points at the next bill's due date because the cycle
+ # window [prev_close, this_close-1] doesn't contain the future
+ # effective_date (issue #92, abdalanervoso's accrual case).
+ bill_view_date_col = func.coalesce(
+ Transaction.effective_bill_date,
+ Transaction.date,
+ )
+ in_bill_view = bill_id is not None or unbilled_only
+ filter_date_col = bill_view_date_col if in_bill_view else date_col
# Base query: user's own transactions (manual or via account)
base_query = (
select(Transaction)
@@ -110,10 +130,66 @@ async def get_transactions(
base_query = base_query.where(Transaction.transfer_pair_id.is_(None))
if txn_type:
base_query = base_query.where(Transaction.type == txn_type)
- if from_date:
- base_query = base_query.where(date_col >= from_date)
- if to_date:
- base_query = base_query.where(date_col <= to_date)
+ # Bill-driven filter: when the caller passes bill_id, include
+ # (a) txs linked to this bill via Pluggy's billId mapping (handles
+ # charges the bank rolled into a bill whose nominal range doesn't
+ # contain them — e.g. a 30/03 charge in the May statement), AND
+ # (b) txs with NO bill_id (manual / OFX / CSV / recurring fills) whose
+ # bucketing date falls in the cycle window. Without (b) we'd drop
+ # user-added entries that exist precisely to compensate for txs
+ # the provider failed to fetch (issue #92, abdalanervoso's Wellhub
+ # case on Bradesco).
+ # Without bill_id (cycle-math cycles or non-CC), apply the date window
+ # straight to all txs.
+ if bill_id is not None:
+ from app.models.credit_card_bill import CreditCardBill # local — avoid cycle
+ bill_predicates = [Transaction.bill_id == bill_id]
+ if from_date or to_date:
+ from sqlalchemy import and_ as _and, not_ as _not
+ # Resolve the active bill's due_date once so we can trust
+ # cycle-math classification when Pluggy hasn't tagged a tx yet.
+ active_due_subq = (
+ select(CreditCardBill.due_date)
+ .where(CreditCardBill.id == bill_id)
+ .scalar_subquery()
+ )
+ unlinked_clauses = [
+ Transaction.bill_id.is_(None),
+ # Sync-pending txs without a billId are normally deferred
+ # (provider hasn't classified them) — but if our cycle-math
+ # `apply_effective_date` already pre-classified them to THIS
+ # bill's due_date, trust it and include them. That's the
+ # in-progress case: pending charges the user can already see
+ # in their bank app, classified by close-date math we
+ # computed at sync time. Past closed bills aren't affected
+ # because pending txs there have effective_date pointing
+ # forward to a later bill (ingrid's case stays clean).
+ # Issue #92, abdalanervoso's empty-May.
+ _not(_and(
+ Transaction.source == "sync",
+ Transaction.status == "pending",
+ Transaction.effective_date != active_due_subq,
+ )),
+ ]
+ if from_date:
+ unlinked_clauses.append(filter_date_col >= from_date)
+ if to_date:
+ unlinked_clauses.append(filter_date_col <= to_date)
+ bill_predicates.append(_and(*unlinked_clauses))
+ base_query = base_query.where(or_(*bill_predicates))
+ else:
+ # Cycle-math fallback (no bill_id was passed). The opt-in
+ # `unbilled_only` flag is for callers that need the in-progress
+ # cycle on a CC account whose date window may overlap a closed
+ # bill's range — they ask us to exclude already-billed txs so the
+ # in-progress bar / list doesn't double-count them. The global
+ # /transactions list and other generic callers leave it False.
+ if unbilled_only:
+ base_query = base_query.where(Transaction.bill_id.is_(None))
+ if from_date:
+ base_query = base_query.where(filter_date_col >= from_date)
+ if to_date:
+ base_query = base_query.where(filter_date_col <= to_date)
if search:
term = f"%{search}%"
base_query = base_query.where(
@@ -145,8 +221,11 @@ async def get_transactions(
count_query = select(func.count()).select_from(base_query.subquery())
total = await session.scalar(count_query)
- # Apply ordering (and pagination unless skipped)
- query = base_query.order_by(date_col.desc(), Transaction.created_at.desc())
+ # Apply ordering (and pagination unless skipped). Bill-view callers
+ # order by purchase date so the in-cycle list matches the bank's own
+ # statement ordering regardless of accounting mode.
+ order_col = bill_view_date_col if in_bill_view else date_col
+ query = base_query.order_by(order_col.desc(), Transaction.created_at.desc())
if not skip_pagination:
query = query.offset((page - 1) * limit).limit(limit)
@@ -497,6 +576,51 @@ async def link_existing_as_transfer(
return debit_tx, credit_tx
+async def _resync_bill_link_from_override(
+ session: AsyncSession, transaction: Transaction, account: Optional[Account]
+) -> None:
+ """Re-link transaction.bill_id when the manual effective_bill_date changes.
+
+ - Override SET to a date matching an existing bill's due_date → link to it.
+ - Override SET to a date with no matching bill → keep bill_id null (the
+ override still sets effective_date directly).
+ - Override CLEARED → fall back to whatever Pluggy originally tagged via
+ `creditCardMetadata.billId` in raw_data, if recoverable; else null.
+ """
+ from app.models.credit_card_bill import CreditCardBill # local: avoid circular
+ if account is None or account.type != "credit_card":
+ return
+ override = transaction.effective_bill_date
+ if override is not None:
+ bill = (
+ await session.execute(
+ select(CreditCardBill).where(
+ CreditCardBill.account_id == account.id,
+ CreditCardBill.due_date == override,
+ )
+ )
+ ).scalar_one_or_none()
+ transaction.bill_id = bill.id if bill is not None else None
+ return
+ # Override cleared: try to recover the original Pluggy linkage.
+ raw_bill_id = None
+ if isinstance(transaction.raw_data, dict):
+ meta = transaction.raw_data.get("creditCardMetadata") or {}
+ raw_bill_id = meta.get("billId")
+ if raw_bill_id:
+ bill = (
+ await session.execute(
+ select(CreditCardBill).where(
+ CreditCardBill.account_id == account.id,
+ CreditCardBill.external_id == str(raw_bill_id),
+ )
+ )
+ ).scalar_one_or_none()
+ transaction.bill_id = bill.id if bill is not None else None
+ else:
+ transaction.bill_id = None
+
+
async def update_transaction(
session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID, data: TransactionUpdate
) -> Optional[Transaction]:
@@ -558,9 +682,13 @@ 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:
+ # Refresh effective_date when the purchase date, account, or the manual
+ # bill-cycle override changed. Also re-link bill_id when the override
+ # changed so the tx moves into the right cycle (issue #92 manual override).
+ if "date" in update_data or "account_id" in update_data or "effective_bill_date" in update_data:
account_for_tx = await session.get(Account, transaction.account_id)
+ if "effective_bill_date" in update_data:
+ await _resync_bill_link_from_override(session, transaction, account_for_tx)
apply_effective_date(transaction, account_for_tx)
# Cascade changes to paired transfer transaction
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 07bb6a9f..134e0a26 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -24,6 +24,7 @@ from app.models.transaction_attachment import TransactionAttachment # noqa: F40
from app.models.payee import Payee, PayeeMapping # noqa: F401
from app.models.app_settings import AppSetting # noqa: F401
from app.models.goal import Goal # noqa: F401
+from app.models.credit_card_bill import CreditCardBill # noqa: F401
# Use SQLite for tests — fast, no external dependency
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
diff --git a/backend/tests/test_accounts_api.py b/backend/tests/test_accounts_api.py
index a7e01bce..dcba6f9c 100644
--- a/backend/tests/test_accounts_api.py
+++ b/backend/tests/test_accounts_api.py
@@ -585,3 +585,138 @@ async def test_connected_account_name_still_rejected(
)
assert response.status_code == 400
assert "bank-connected" in response.json()["detail"].lower()
+
+
+# ---------------------------------------------------------------------------
+# GET /accounts/{id}/bills (issue #92)
+# ---------------------------------------------------------------------------
+
+
+import uuid as _uuid # noqa: E402
+from datetime import date as _date # noqa: E402
+from decimal import Decimal as _Decimal # noqa: E402
+
+from sqlalchemy.ext.asyncio import AsyncSession # noqa: E402
+
+from app.models.account import Account as _Account # noqa: E402
+from app.models.credit_card_bill import CreditCardBill as _CreditCardBill # noqa: E402
+
+
+async def _make_cc_account(session: AsyncSession, user_id: _uuid.UUID, name: str = "CC") -> _Account:
+ acc = _Account(
+ id=_uuid.uuid4(),
+ user_id=user_id,
+ name=name,
+ type="credit_card",
+ balance=_Decimal("0"),
+ currency="BRL",
+ )
+ session.add(acc)
+ await session.commit()
+ await session.refresh(acc)
+ return acc
+
+
+async def _make_bill(
+ session: AsyncSession, user_id: _uuid.UUID, account_id: _uuid.UUID,
+ *, external_id: str, due_date: _date, total: str = "100.00",
+ minimum: str | None = "10.00",
+) -> _CreditCardBill:
+ bill = _CreditCardBill(
+ user_id=user_id,
+ account_id=account_id,
+ external_id=external_id,
+ due_date=due_date,
+ total_amount=_Decimal(total),
+ currency="BRL",
+ minimum_payment=_Decimal(minimum) if minimum else None,
+ )
+ session.add(bill)
+ await session.commit()
+ await session.refresh(bill)
+ return bill
+
+
+async def test_get_account_bills_returns_newest_first(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,
+):
+ cc = await _make_cc_account(session, test_user.id, "Itaú")
+ await _make_bill(session, test_user.id, cc.id, external_id="b-old", due_date=_date(2026, 1, 5))
+ await _make_bill(session, test_user.id, cc.id, external_id="b-mid", due_date=_date(2026, 3, 5))
+ await _make_bill(session, test_user.id, cc.id, external_id="b-new", due_date=_date(2026, 5, 5))
+
+ resp = await client.get(f"/api/accounts/{cc.id}/bills", headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.json()
+ assert [b["external_id"] for b in data] == ["b-new", "b-mid", "b-old"]
+ assert data[0]["account_id"] == str(cc.id)
+ assert data[0]["due_date"] == "2026-05-05"
+ assert data[0]["total_amount"] == 100.0
+ assert data[0]["currency"] == "BRL"
+ assert data[0]["minimum_payment"] == 10.0
+
+
+async def test_get_account_bills_empty_for_non_cc_account(
+ client: AsyncClient, auth_headers, test_account: Account,
+):
+ """Checking accounts return [] — caller treats this same as "no bills"."""
+ resp = await client.get(f"/api/accounts/{test_account.id}/bills", headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.json() == []
+
+
+async def test_get_account_bills_empty_for_cc_with_no_bills(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,
+):
+ """A CC account that hasn't synced bills yet returns [] — the UI must
+ fall back to cycle math, not 404 / error."""
+ cc = await _make_cc_account(session, test_user.id, "Empty CC")
+ resp = await client.get(f"/api/accounts/{cc.id}/bills", headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.json() == []
+
+
+async def test_get_account_bills_404_for_nonexistent_account(
+ client: AsyncClient, auth_headers,
+):
+ resp = await client.get(
+ "/api/accounts/00000000-0000-0000-0000-000000000000/bills", headers=auth_headers,
+ )
+ assert resp.status_code == 404
+
+
+async def test_get_account_bills_respects_limit_param(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,
+):
+ cc = await _make_cc_account(session, test_user.id, "Many Bills")
+ for i in range(5):
+ await _make_bill(
+ session, test_user.id, cc.id,
+ external_id=f"b-{i}", due_date=_date(2026, i + 1, 5),
+ )
+
+ resp = await client.get(
+ f"/api/accounts/{cc.id}/bills", headers=auth_headers, params={"limit": 2},
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert len(data) == 2
+ # Newest first — May (i=4) and April (i=3)
+ assert data[0]["external_id"] == "b-4"
+ assert data[1]["external_id"] == "b-3"
+
+
+async def test_get_account_bills_rejects_invalid_limit(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,
+):
+ cc = await _make_cc_account(session, test_user.id, "X")
+ resp = await client.get(
+ f"/api/accounts/{cc.id}/bills", headers=auth_headers, params={"limit": 0},
+ )
+ assert resp.status_code == 422 # Query(ge=1) bound
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index f5c61329..0358be68 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.bank_connection import BankConnection
from app.models.category import Category
from app.models.transaction import Transaction
-from app.providers.base import AccountData, ConnectionData, ConnectTokenData, TransactionData
+from app.providers.base import AccountData, BillData, ConnectionData, ConnectTokenData, TransactionData
from app.services.connection_service import (
_description_similarity,
_match_pluggy_category,
@@ -700,3 +700,709 @@ async def test_sync_connection_does_not_recreate_closed_accounts(
assert len(rows) == 1, "sync must not create a duplicate active row"
assert rows[0].is_closed is True
assert rows[0].balance == Decimal("500"), "closed accounts must not be touched by sync"
+
+
+# ---------------------------------------------------------------------------
+# Credit-card bills wiring (issue #92)
+# ---------------------------------------------------------------------------
+
+
+def _cc_account(external_id: str = "cc-acc-1", name: str = "Credit Card") -> AccountData:
+ return AccountData(
+ external_id=external_id,
+ name=name,
+ type="credit_card",
+ balance=Decimal("0"),
+ currency="BRL",
+ )
+
+
+def _cc_provider_mock(
+ *,
+ bills: list[BillData],
+ transactions: list[TransactionData],
+ bills_side_effect=None,
+) -> AsyncMock:
+ """Build a provider mock for a single CC account that returns the given
+ bills and transactions. `bills_side_effect` overrides the return value
+ (e.g. to raise) when set."""
+ mock = AsyncMock()
+ mock.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock.get_accounts = AsyncMock(return_value=[_cc_account()])
+ mock.get_transactions = AsyncMock(return_value=transactions)
+ if bills_side_effect is not None:
+ mock.get_bills = AsyncMock(side_effect=bills_side_effect)
+ else:
+ mock.get_bills = AsyncMock(return_value=bills)
+ return mock
+
+
+def _patch_sync_helpers():
+ """Common context managers for sync tests — silences out-of-scope helpers."""
+ return (
+ 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),
+ )
+
+
+async def test_sync_persists_bills_for_credit_card_account(
+ session: AsyncSession, test_user,
+):
+ """First sync of a CC account upserts bills returned by /bills."""
+ from app.models.credit_card_bill import CreditCardBill
+
+ conn = await _make_connection(session, test_user.id, "Bills Bank")
+ bills = [
+ BillData(
+ external_id="bill-1",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("1500.00"),
+ currency="BRL",
+ minimum_payment=Decimal("150.00"),
+ raw_data={"id": "bill-1"},
+ ),
+ ]
+ mock_provider = _cc_provider_mock(bills=bills, transactions=[])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(CreditCardBill).where(CreditCardBill.user_id == test_user.id)
+ )).scalars().all()
+ assert len(rows) == 1
+ assert rows[0].external_id == "bill-1"
+ assert rows[0].due_date == date(2026, 4, 15)
+ assert rows[0].total_amount == Decimal("1500.00")
+ assert rows[0].minimum_payment == Decimal("150.00")
+ assert rows[0].raw_data == {"id": "bill-1"}
+
+
+async def test_sync_links_transaction_to_matching_bill(
+ session: AsyncSession, test_user,
+):
+ """Transactions whose bill_external_id matches a synced bill get bill_id
+ set and effective_date = bill.due_date (the bank-truth path, issue #92)."""
+ from app.models.credit_card_bill import CreditCardBill
+
+ conn = await _make_connection(session, test_user.id, "Linked Bank")
+ bill = BillData(
+ external_id="bill-99",
+ due_date=date(2026, 5, 10),
+ total_amount=Decimal("500.00"),
+ currency="BRL",
+ )
+ txn = TransactionData(
+ external_id="tx-linked",
+ description="AMAZON",
+ amount=Decimal("100"),
+ date=date(2026, 4, 20),
+ type="debit",
+ currency="BRL",
+ bill_external_id="bill-99",
+ )
+ mock_provider = _cc_provider_mock(bills=[bill], transactions=[txn])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ bill_row = (await session.execute(
+ select(CreditCardBill).where(CreditCardBill.external_id == "bill-99")
+ )).scalar_one()
+ tx_row = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-linked")
+ )).scalar_one()
+ assert tx_row.bill_id == bill_row.id
+ # Bank-truth date wins over local cycle math.
+ assert tx_row.effective_date == date(2026, 5, 10)
+
+
+async def test_sync_falls_back_to_cycle_math_when_bill_missing(
+ session: AsyncSession, test_user,
+):
+ """A tx with bill_external_id that isn't in the bills feed (older bill,
+ bills 4xx, etc.) leaves bill_id null and uses local cycle math —
+ nothing about the legacy path may regress."""
+ conn = await _make_connection(session, test_user.id, "Cycle Bank")
+
+ # CC account with explicit close/due so cycle math has something to compute
+ cc_acc = AccountData(
+ external_id="cc-acc-cyc", name="CC", type="credit_card",
+ balance=Decimal("0"), currency="BRL",
+ statement_close_day=20, payment_due_day=28,
+ )
+ txn = TransactionData(
+ external_id="tx-orphan",
+ description="ORPHAN",
+ amount=Decimal("30"),
+ date=date(2026, 4, 5),
+ type="debit",
+ currency="BRL",
+ bill_external_id="bill-not-in-feed",
+ )
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[cc_acc])
+ mock_provider.get_transactions = AsyncMock(return_value=[txn])
+ mock_provider.get_bills = AsyncMock(return_value=[]) # empty feed
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ tx_row = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-orphan")
+ )).scalar_one()
+ assert tx_row.bill_id is None
+ # close=20 (>tx_date=5) → cycle ends 2026-04-20, due=28 → effective=2026-04-28
+ assert tx_row.effective_date == date(2026, 4, 28)
+
+
+async def test_sync_swallows_get_bills_error(
+ session: AsyncSession, test_user,
+):
+ """Non-regulado Pluggy connections 4xx on /bills. Sync must keep going
+ and persist transactions via the cycle-math fallback."""
+ conn = await _make_connection(session, test_user.id, "Err Bank")
+ txn = TransactionData(
+ external_id="tx-after-bills-fail",
+ description="X",
+ amount=Decimal("10"),
+ date=date(2026, 4, 5),
+ type="debit",
+ currency="BRL",
+ )
+ mock_provider = _cc_provider_mock(
+ bills=[], transactions=[txn],
+ bills_side_effect=RuntimeError("403 Forbidden"),
+ )
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ result, _ = await sync_connection(session, conn.id, test_user.id)
+
+ assert result.status == "active"
+ tx_row = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-after-bills-fail")
+ )).scalar_one()
+ assert tx_row.bill_id is None
+
+
+async def test_sync_skips_get_bills_for_non_credit_card_account(
+ session: AsyncSession, test_user,
+):
+ """Checking accounts must not hit /bills — saves an HTTP roundtrip and
+ avoids 4xx noise on providers that scope bills to credit accounts."""
+ conn = await _make_connection(session, test_user.id, "Checking Bank")
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="chk-1", name="Checking",
+ type="checking", balance=Decimal("100"), currency="BRL",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+ mock_provider.get_bills = AsyncMock(return_value=[])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ mock_provider.get_bills.assert_not_called()
+
+
+async def test_sync_backfills_bill_link_on_existing_transaction(
+ session: AsyncSession, test_user,
+):
+ """A transaction synced before the /bills feature must self-heal: on the
+ next sync, when the matching bill is in the feed, bill_id and
+ effective_date pick up the bank-truth values without re-inserting."""
+ from app.models.credit_card_bill import CreditCardBill
+
+ conn = await _make_connection(session, test_user.id, "Backfill Bank")
+ txn_v0 = TransactionData(
+ external_id="tx-preexisting",
+ description="OLD CHARGE",
+ amount=Decimal("75"),
+ date=date(2026, 4, 6),
+ type="debit",
+ currency="BRL",
+ bill_external_id="bill-future-1",
+ )
+
+ # First sync — no bills returned yet (simulates pre-feature state)
+ mock_provider = _cc_provider_mock(bills=[], transactions=[txn_v0])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ pre = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-preexisting")
+ )).scalar_one()
+ assert pre.bill_id is None # not linked yet
+
+ # Second sync — same tx, but now /bills returns a matching bill
+ bill = BillData(
+ external_id="bill-future-1",
+ due_date=date(2026, 5, 10),
+ total_amount=Decimal("75"),
+ currency="BRL",
+ )
+ mock_provider.get_bills = AsyncMock(return_value=[bill])
+ mock_provider.get_transactions = AsyncMock(return_value=[txn_v0])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ bill_row = (await session.execute(
+ select(CreditCardBill).where(CreditCardBill.external_id == "bill-future-1")
+ )).scalar_one()
+ post = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-preexisting")
+ )).scalar_one()
+ # Same tx row, now linked + effective_date follows the bill due date.
+ assert post.id == pre.id
+ assert post.bill_id == bill_row.id
+ assert post.effective_date == date(2026, 5, 10)
+
+
+async def test_sync_relinks_transaction_when_bank_moves_it_to_another_bill(
+ session: AsyncSession, test_user,
+):
+ """If the bank later re-buckets a tx (chargeback, billing dispute), the
+ next sync must update bill_id and effective_date — same row, new link."""
+ from app.models.credit_card_bill import CreditCardBill
+
+ conn = await _make_connection(session, test_user.id, "Relink Bank")
+
+ bill_a = BillData(
+ external_id="bill-a", due_date=date(2026, 4, 10),
+ total_amount=Decimal("40"), currency="BRL",
+ )
+ bill_b = BillData(
+ external_id="bill-b", due_date=date(2026, 5, 10),
+ total_amount=Decimal("40"), currency="BRL",
+ )
+
+ txn_to_a = TransactionData(
+ external_id="tx-relink", description="X",
+ amount=Decimal("40"), date=date(2026, 3, 15), type="debit",
+ currency="BRL", bill_external_id="bill-a",
+ )
+ mock_provider = _cc_provider_mock(bills=[bill_a, bill_b], transactions=[txn_to_a])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ # Bank moves the tx to bill_b on the next sync
+ txn_to_b = TransactionData(
+ external_id="tx-relink", description="X",
+ amount=Decimal("40"), date=date(2026, 3, 15), type="debit",
+ currency="BRL", bill_external_id="bill-b",
+ )
+ mock_provider.get_transactions = AsyncMock(return_value=[txn_to_b])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ bill_b_row = (await session.execute(
+ select(CreditCardBill).where(CreditCardBill.external_id == "bill-b")
+ )).scalar_one()
+ tx = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-relink")
+ )).scalar_one()
+ assert tx.bill_id == bill_b_row.id
+ assert tx.effective_date == date(2026, 5, 10)
+
+
+async def test_sync_creates_synthetic_transactions_for_finance_charges(
+ session: AsyncSession, test_user,
+):
+ """A bill carrying IOF / multa / juros lines that don't exist as standalone
+ transactions must yield synthetic txs so the cycle sum reconciles to
+ bill.total_amount (issue #92)."""
+ conn = await _make_connection(session, test_user.id, "Charges Bank")
+ bill = BillData(
+ external_id="bill-fc-1",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("232.76"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-fc-1",
+ "financeCharges": [
+ {"id": "fc-iof", "type": "IOF", "amount": 0.91, "additionalInfo": "IOF de atraso"},
+ {"id": "fc-fee", "type": "LATE_PAYMENT_FEE", "amount": 4.5, "additionalInfo": "Multa de atraso"},
+ {"id": "fc-int", "type": "LATE_PAYMENT_REMUNERATIVE_INTEREST", "amount": 3.46, "additionalInfo": "Juros de atraso"},
+ ],
+ },
+ )
+ mock_provider = _cc_provider_mock(bills=[bill], transactions=[])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction)
+ .where(
+ Transaction.user_id == test_user.id,
+ Transaction.source != "opening_balance",
+ )
+ .order_by(Transaction.amount)
+ )).scalars().all()
+ assert len(rows) == 3
+ amounts = sorted(float(r.amount) for r in rows)
+ assert amounts == [0.91, 3.46, 4.5]
+ descriptions = {r.description for r in rows}
+ assert descriptions == {"IOF de atraso", "Multa de atraso", "Juros de atraso"}
+ # All linked to the bill, dated to its due_date, marked as debits.
+ for r in rows:
+ assert r.bill_id is not None
+ assert r.date == date(2026, 4, 15)
+ assert r.effective_date == date(2026, 4, 15)
+ assert r.type == "debit"
+ assert r.external_id.startswith("bill_charge:bill-fc-1:")
+
+
+async def test_sync_dates_charges_at_cycle_close_when_close_day_known(
+ session: AsyncSession, test_user,
+):
+ """Synthetic finance charges should be dated at the cycle close (the
+ bank's snapshot moment) rather than the bill's due date — otherwise
+ they'd appear chronologically AFTER the user's payment in the tx list,
+ which doesn't match real bank semantics. effective_date stays at
+ due_date for accrual aggregation."""
+ conn = await _make_connection(session, test_user.id, "CloseDateBank")
+ # CC account with explicit close=12, due=18 (Goldinho-style)
+ cc = AccountData(
+ external_id="cd-acc", name="CC", type="credit_card",
+ balance=Decimal("0"), currency="BRL",
+ statement_close_day=12, payment_due_day=18,
+ )
+ bill = BillData(
+ external_id="bill-cd",
+ due_date=date(2026, 2, 18),
+ total_amount=Decimal("100"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-cd",
+ "financeCharges": [
+ {"id": "fc-1", "type": "IOF", "amount": 0.91, "additionalInfo": "IOF"},
+ ],
+ },
+ )
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[cc])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+ mock_provider.get_bills = AsyncMock(return_value=[bill])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ tx = (await session.execute(
+ select(Transaction).where(
+ Transaction.user_id == test_user.id,
+ Transaction.source != "opening_balance",
+ )
+ )).scalar_one()
+ # Close = the most recent close_day on or before due — same month here.
+ assert tx.date == date(2026, 2, 12)
+ # Accrual bucketing still anchors on bill.due_date.
+ assert tx.effective_date == date(2026, 2, 18)
+
+
+async def test_sync_skips_carry_over_balance_finance_charge(
+ session: AsyncSession, test_user,
+):
+ """`Saldo em atraso` is the prior bill's unpaid balance carried into this
+ bill — informational only, NOT part of bill.total_amount, so we must not
+ materialize it as a tx (would double-count the user's debt)."""
+ conn = await _make_connection(session, test_user.id, "SaldoBank")
+ bill = BillData(
+ external_id="bill-saldo",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("229.26"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-saldo",
+ "financeCharges": [
+ {"id": "x1", "type": "OTHER", "amount": 223.9, "additionalInfo": "Saldo em atraso"},
+ {"id": "x2", "type": "IOF", "amount": 0.87, "additionalInfo": "IOF de atraso"},
+ ],
+ },
+ )
+ mock_provider = _cc_provider_mock(bills=[bill], transactions=[])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction).where(
+ Transaction.user_id == test_user.id,
+ Transaction.source != "opening_balance",
+ )
+ )).scalars().all()
+ assert len(rows) == 1
+ assert rows[0].description == "IOF de atraso"
+ assert float(rows[0].amount) == 0.87
+
+
+async def test_sync_skips_juros_aggregate_finance_charge(
+ session: AsyncSession, test_user,
+):
+ """`Juros de dívida encerrada` is an aggregate that equals the sum of the
+ detailed late-charge lines Pluggy ALSO emits — including it would
+ double-count by ~one charge worth."""
+ conn = await _make_connection(session, test_user.id, "AggBank")
+ bill = BillData(
+ external_id="bill-agg",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("100.00"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-agg",
+ "financeCharges": [
+ {"id": "a1", "type": "OTHER", "amount": 5.37, "additionalInfo": "Juros de dívida encerrada"},
+ {"id": "a2", "type": "IOF", "amount": 0.87, "additionalInfo": "IOF de atraso"},
+ {"id": "a3", "type": "LATE_PAYMENT_FEE", "amount": 4.5, "additionalInfo": "Multa de atraso"},
+ ],
+ },
+ )
+ mock_provider = _cc_provider_mock(bills=[bill], transactions=[])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction).where(
+ Transaction.user_id == test_user.id,
+ Transaction.source != "opening_balance",
+ )
+ )).scalars().all()
+ descriptions = {r.description for r in rows}
+ # Aggregate is dropped; the two detailed lines remain.
+ assert descriptions == {"IOF de atraso", "Multa de atraso"}
+
+
+async def test_sync_finance_charges_are_idempotent(
+ session: AsyncSession, test_user,
+):
+ """Re-syncing the same bill must not duplicate synthetic charges."""
+ conn = await _make_connection(session, test_user.id, "IdemFC")
+ bill = BillData(
+ external_id="bill-idem-fc",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("100"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-idem-fc",
+ "financeCharges": [
+ {"id": "fc-1", "type": "IOF", "amount": 1.23, "additionalInfo": "IOF de atraso"},
+ ],
+ },
+ )
+ mock_provider = _cc_provider_mock(bills=[bill], transactions=[])
+ p1, p2, p3 = _patch_sync_helpers()
+
+ for _ in range(2):
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction).where(
+ Transaction.user_id == test_user.id,
+ Transaction.source != "opening_balance",
+ )
+ )).scalars().all()
+ assert len(rows) == 1
+
+
+async def test_sync_removes_orphaned_finance_charges_on_resync(
+ session: AsyncSession, test_user,
+):
+ """If a charge disappears from the bill on the next sync (e.g. bank
+ reversed it), the synthetic tx must be removed."""
+ conn = await _make_connection(session, test_user.id, "OrphFC")
+ bill_v1 = BillData(
+ external_id="bill-orph",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("100"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-orph",
+ "financeCharges": [
+ {"id": "fc-keep", "type": "IOF", "amount": 1.0, "additionalInfo": "IOF"},
+ {"id": "fc-drop", "type": "LATE_PAYMENT_FEE", "amount": 4.5, "additionalInfo": "Multa"},
+ ],
+ },
+ )
+ mock_provider = _cc_provider_mock(bills=[bill_v1], transactions=[])
+ p1, p2, p3 = _patch_sync_helpers()
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ # Second sync — the LATE_PAYMENT_FEE charge is gone (bank reversed it)
+ bill_v2 = BillData(
+ external_id="bill-orph",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("100"),
+ currency="BRL",
+ raw_data={
+ "id": "bill-orph",
+ "financeCharges": [
+ {"id": "fc-keep", "type": "IOF", "amount": 1.0, "additionalInfo": "IOF"},
+ ],
+ },
+ )
+ mock_provider.get_bills = AsyncMock(return_value=[bill_v2])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction).where(
+ Transaction.user_id == test_user.id,
+ Transaction.source != "opening_balance",
+ )
+ )).scalars().all()
+ assert len(rows) == 1
+ assert "fc-keep" in rows[0].external_id
+
+
+async def test_sync_does_not_overwrite_manual_effective_bill_date(
+ session: AsyncSession, test_user,
+):
+ """When the user has manually set effective_bill_date on a tx, the next
+ sync must NOT relink bill_id or recompute effective_date — the user is
+ explicitly overriding the auto bucketing (issue #92, LucasFidelis idea)."""
+ from datetime import date as _date_
+
+ conn = await _make_connection(session, test_user.id, "OverrideBank")
+
+ bill_a = BillData(
+ external_id="bill-A", due_date=_date_(2026, 4, 5),
+ total_amount=Decimal("100"), currency="BRL",
+ )
+ txn = TransactionData(
+ external_id="tx-overridden",
+ description="X",
+ amount=Decimal("50"),
+ date=_date_(2026, 3, 20),
+ type="debit",
+ currency="BRL",
+ bill_external_id="bill-A", # Pluggy says: belongs to bill A
+ )
+ mock_provider = _cc_provider_mock(bills=[bill_a], transactions=[txn])
+ p1, p2, p3 = _patch_sync_helpers()
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ # User overrides: this tx belongs to a different bill (May 5, manually).
+ tx_row = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-overridden")
+ )).scalar_one()
+ bill_a_row_id = tx_row.bill_id # link from sync
+ tx_row.effective_bill_date = _date_(2026, 5, 5)
+ tx_row.bill_id = None # user manually unlinked
+ tx_row.effective_date = _date_(2026, 5, 5)
+ await session.commit()
+
+ # Re-sync — provider still says bill A. Override must be preserved.
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ tx_row = (await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-overridden")
+ )).scalar_one()
+ assert tx_row.effective_bill_date == _date_(2026, 5, 5)
+ assert tx_row.bill_id is None # not re-linked to A
+ assert tx_row.effective_date == _date_(2026, 5, 5)
+ assert bill_a_row_id is not None # sanity: A had been linked initially
+
+
+async def test_sync_updates_existing_bill_idempotently(
+ session: AsyncSession, test_user,
+):
+ """A second sync that returns the same bill id with updated totals must
+ update in place, not insert a duplicate (the unique(account_id,
+ external_id) constraint would fail otherwise)."""
+ from app.models.credit_card_bill import CreditCardBill
+
+ conn = await _make_connection(session, test_user.id, "Idem Bank")
+ bill_v1 = BillData(
+ external_id="bill-idem",
+ due_date=date(2026, 4, 15),
+ total_amount=Decimal("100.00"),
+ currency="BRL",
+ )
+ mock_provider = _cc_provider_mock(bills=[bill_v1], transactions=[])
+
+ p1, p2, p3 = _patch_sync_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ # Second sync: same id, new totals (e.g. mid-cycle adjustment)
+ bill_v2 = BillData(
+ external_id="bill-idem",
+ due_date=date(2026, 4, 16),
+ total_amount=Decimal("125.50"),
+ currency="BRL",
+ )
+ mock_provider.get_bills = AsyncMock(return_value=[bill_v2])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(CreditCardBill).where(CreditCardBill.user_id == test_user.id)
+ )).scalars().all()
+ assert len(rows) == 1, "second sync must not duplicate the row"
+ assert rows[0].due_date == date(2026, 4, 16)
+ assert rows[0].total_amount == Decimal("125.50")
diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.py
index 68afe23b..731c56e7 100644
--- a/backend/tests/test_credit_card_accounting_mode.py
+++ b/backend/tests/test_credit_card_accounting_mode.py
@@ -155,6 +155,56 @@ class TestApplyEffectiveDate:
apply_effective_date(tx, account)
assert tx.effective_date == date(2026, 4, 16)
+ def test_manual_effective_bill_date_override_wins(self):
+ """User-set effective_bill_date beats both Pluggy bill_due_date and
+ cycle math (issue #92, LucasFidelis manual override)."""
+ tx = Transaction(
+ user_id=uuid.uuid4(),
+ account_id=uuid.uuid4(),
+ description="x",
+ amount=Decimal("10"),
+ date=date(2026, 4, 3),
+ type="debit",
+ source="manual",
+ )
+ tx.effective_bill_date = date(2026, 6, 16) # user explicitly says June
+ 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,
+ )
+ # Even when sync passes a Pluggy bill_due_date, override still wins.
+ apply_effective_date(tx, account, bill_due_date=date(2026, 5, 16))
+ assert tx.effective_date == date(2026, 6, 16)
+
+ def test_manual_effective_bill_date_works_for_non_cc_too(self):
+ """The override is mainly for CC accounts but the helper applies it
+ regardless — useful if a future feature lets users override on other
+ accounts; today the schema only exposes it for CC."""
+ tx = Transaction(
+ user_id=uuid.uuid4(),
+ account_id=uuid.uuid4(),
+ description="x",
+ amount=Decimal("10"),
+ date=date(2026, 4, 3),
+ type="debit",
+ source="manual",
+ )
+ tx.effective_bill_date = date(2026, 5, 1)
+ 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, 5, 1)
+
def test_cc_account_without_cycle_metadata_falls_back_to_purchase_date(self):
tx = Transaction(
user_id=uuid.uuid4(),
@@ -658,3 +708,856 @@ class TestAccountCycleEditRecomputesEffectiveDates:
)
txs = result.scalars().all()
assert all(t.effective_date == date(2026, 4, 16) for t in txs)
+
+
+# ---------------------------------------------------------------------------
+# Manual cycle override (effective_bill_date) — tx list filter must respect
+# the override regardless of accounting mode (issue #92, LucasFidelis).
+# ---------------------------------------------------------------------------
+
+
+class TestEffectiveBillDateFiltersList:
+ @pytest.mark.asyncio
+ async def test_override_moves_tx_between_cycles_in_cash_mode(
+ self, session, test_user, cc_account
+ ):
+ """A tx whose natural date falls in May, but with an effective_bill_date
+ in March, must be returned for a March-window query AND excluded from
+ a May-window query — even in cash mode (where the default filter is
+ Transaction.date)."""
+ from app.services.transaction_service import get_transactions
+ await _set_mode(session, "cash")
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 18), Decimal("55.90"),
+ effective_date=date(2026, 5, 22),
+ )
+ tx.effective_bill_date = date(2026, 3, 1)
+ await session.commit()
+
+ # March window: should include the override'd tx.
+ march_txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 2, 16), to_date=date(2026, 3, 15),
+ accounting_mode="cash",
+ )
+ assert any(t.id == tx.id for t in march_txs)
+
+ # May window: should NOT include it anymore.
+ may_txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 16), to_date=date(2026, 5, 15),
+ accounting_mode="cash",
+ )
+ assert not any(t.id == tx.id for t in may_txs)
+
+ @pytest.mark.asyncio
+ async def test_override_moves_tx_between_cycles_in_accrual_mode(
+ self, session, test_user, cc_account
+ ):
+ """Same behavior in accrual mode — override must beat both modes'
+ default columns."""
+ from app.services.transaction_service import get_transactions
+ await _set_mode(session, "accrual")
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 18), Decimal("55.90"),
+ effective_date=date(2026, 5, 22), # accrual would put this in May
+ )
+ tx.effective_bill_date = date(2026, 3, 1)
+ await session.commit()
+
+ march_txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 2, 16), to_date=date(2026, 3, 15),
+ accounting_mode="accrual",
+ )
+ assert any(t.id == tx.id for t in march_txs)
+
+ @pytest.mark.asyncio
+ async def test_bill_id_filter_includes_unlinked_txs_in_cycle_window(
+ self, session, test_user, cc_account
+ ):
+ """When a tx is NOT linked to the bill via bill_id (e.g. a manual
+ recurring entry the user added to compensate for a tx Pluggy failed
+ to fetch — abdalanervoso's Wellhub on Bradesco case), it should
+ still count toward the bill's cycle if its date falls in the
+ cycle window."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ # Pluggy bill due Apr 16
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-x", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ # Linked tx (the real one Pluggy returned)
+ linked = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 5), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ )
+ linked.bill_id = bill.id
+
+ # Unlinked manual recurring (the workaround tx)
+ unlinked = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 6), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ )
+ await session.commit()
+
+ # Cycle window for this bill = [Mar 17, Apr 16]
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=bill.id,
+ from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),
+ accounting_mode="cash",
+ )
+ ids = {t.id for t in txs}
+ assert linked.id in ids
+ assert unlinked.id in ids, (
+ "manual unlinked tx in cycle window must still count when filtering "
+ "by bill_id (issue #92, abdalanervoso's recurring-payment workaround)"
+ )
+
+ @pytest.mark.asyncio
+ async def test_pending_sync_included_when_effective_date_matches_active_bill(
+ self, session, test_user, cc_account
+ ):
+ """Pending sync tx with bill_id NULL but effective_date == active
+ bill's due_date IS included — cycle math pre-classified it to this
+ bill, even though the provider hasn't tagged a billId yet. This is
+ abdalanervoso's empty-May case: late-April pending charges with
+ effective_date=2026-05-10 must show up in May."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ may_bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="may", due_date=date(2026, 5, 10),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(may_bill)
+ await session.flush()
+
+ # Pending sync tx, no billId, effective_date matches May's due_date
+ pending = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 17), Decimal("44.90"),
+ effective_date=date(2026, 5, 10), # cycle-math pre-classified to May
+ source="sync",
+ )
+ pending.status = "pending"
+ await session.commit()
+
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=may_bill.id,
+ from_date=date(2026, 4, 11), to_date=date(2026, 5, 10),
+ accounting_mode="cash",
+ )
+ assert pending.id in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_inprogress_cycle_includes_prev_close_day_tx_per_brazilian_convention(
+ self, session, test_user, cc_account
+ ):
+ """Brazilian convention: a tx ON the previous close day belongs to the
+ NEXT cycle. Cycle math sets effective_date accordingly, but the
+ in-progress cycle window must also START at prev_close (not
+ prev_close+1) so the date filter picks it up. abdalanervoso's
+ SUPERMERCADO MERCOCENTR dated 2026-04-30 with effective_date
+ 2026-06-10 must show in the in-progress June cycle."""
+ from app.services.transaction_service import get_transactions
+
+ # Pending sync, no billId, dated on the close day (April 30 with close=30)
+ pending = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 30), Decimal("91.51"),
+ effective_date=date(2026, 6, 10), # cycle-math classified to June
+ source="sync",
+ )
+ pending.status = "pending"
+ await session.commit()
+
+ # In-progress June cycle (cycle-math fallback, no bill_id passed)
+ # range = [April 30, May 29] — the start INCLUDES the prev close day.
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),
+ accounting_mode="cash",
+ )
+ assert pending.id in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_inprogress_cycle_excludes_already_billed_txs(
+ self, session, test_user, cc_account
+ ):
+ """When the user views the in-progress cycle (no bill_id passed) but
+ the date window overlaps a closed bill's range, txs already linked
+ to that closed bill must NOT appear — otherwise they'd double-count
+ in the bar/total against their bill's view."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ prior_bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="may", due_date=date(2026, 5, 10),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(prior_bill)
+ await session.flush()
+
+ # Tx already linked to the May bill, dated within the in-progress
+ # June cycle window
+ billed = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 5, 5), Decimal("50"),
+ effective_date=date(2026, 5, 10),
+ )
+ billed.bill_id = prior_bill.id
+ await session.commit()
+
+ # In-progress cycle window happens to include May 5. With the
+ # `unbilled_only` flag set (which account-detail uses for the
+ # in-progress cycle), the prior-bill tx must NOT appear.
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),
+ accounting_mode="cash",
+ unbilled_only=True,
+ )
+ assert billed.id not in {t.id for t in txs}
+
+ # Without unbilled_only (e.g., the global /transactions list page),
+ # the same tx IS visible — the flag is opt-in.
+ txs_unfiltered, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),
+ accounting_mode="cash",
+ )
+ assert billed.id in {t.id for t in txs_unfiltered}
+
+ @pytest.mark.asyncio
+ async def test_bill_view_filter_is_mode_independent(
+ self, session, test_user, cc_account
+ ):
+ """Bill view = bank-truth: a 4/30 charge with effective_date 6/10
+ must show in the in-progress June cycle in BOTH cash and accrual
+ modes. The cycle is the bank's bill, not the user's report; the
+ accounting mode only affects balance/reports, not what's in a bill.
+
+ Without this carve-out, accrual mode filtered the in-progress
+ cycle by effective_date against a close-day window, hiding the
+ tx (issue #92, abdalanervoso's accrual report).
+ """
+ from app.services.transaction_service import get_transactions
+
+ pending = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 30), Decimal("91.51"),
+ effective_date=date(2026, 6, 10),
+ source="sync",
+ )
+ pending.status = "pending"
+ await session.commit()
+
+ for mode in ("cash", "accrual"):
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),
+ accounting_mode=mode,
+ unbilled_only=True,
+ )
+ assert pending.id in {t.id for t in txs}, (
+ f"in-progress bill view must include the tx in {mode} mode"
+ )
+
+ @pytest.mark.asyncio
+ async def test_global_list_still_mode_aware_outside_bill_view(
+ self, session, test_user, cc_account
+ ):
+ """Regression guard: outside the bill view (no bill_id, no
+ unbilled_only), the global list MUST still respect accounting
+ mode. Accrual users on /transactions filter by effective_date so
+ a 4/30 charge effective 6/10 appears in the JUNE date window
+ (when cash hits), not the April one.
+ """
+ from app.services.transaction_service import get_transactions
+
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 30), Decimal("91.51"),
+ effective_date=date(2026, 6, 10),
+ source="sync",
+ )
+ await session.commit()
+
+ # Cash mode: filtered by purchase date → in April window
+ txs_cash_apr, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 1), to_date=date(2026, 4, 30),
+ accounting_mode="cash",
+ )
+ assert tx.id in {t.id for t in txs_cash_apr}
+
+ # Accrual mode: filtered by effective_date → NOT in April window,
+ # but IS in June window. This is the existing mode-aware semantic
+ # callers outside the bill view rely on.
+ txs_accrual_apr, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 1), to_date=date(2026, 4, 30),
+ accounting_mode="accrual",
+ )
+ assert tx.id not in {t.id for t in txs_accrual_apr}
+
+ txs_accrual_jun, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 6, 1), to_date=date(2026, 6, 30),
+ accounting_mode="accrual",
+ )
+ assert tx.id in {t.id for t in txs_accrual_jun}
+
+ @pytest.mark.asyncio
+ async def test_pending_sync_excluded_from_past_bill_when_effective_date_points_elsewhere(
+ self, session, test_user, cc_account
+ ):
+ """Reverse case: pending sync tx whose effective_date points to a
+ FUTURE bill must NOT show in a past closed bill. Keeps ingrid's
+ fix intact — pending charges don't pollute closed statements."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ april_bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="apr", due_date=date(2026, 4, 10),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(april_bill)
+ await session.flush()
+
+ # Pending tx whose cycle math classified it to a DIFFERENT bill (May)
+ pending = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("99"),
+ effective_date=date(2026, 5, 10), # NOT April's due_date
+ source="sync",
+ )
+ pending.status = "pending"
+ await session.commit()
+
+ # Viewing April bill — must NOT include this pending tx
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=april_bill.id,
+ from_date=date(2026, 3, 11), to_date=date(2026, 4, 10),
+ accounting_mode="cash",
+ )
+ assert pending.id not in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_bill_id_filter_excludes_pending_sync_pointing_to_other_bill(
+ self, session, test_user, cc_account
+ ):
+ """Pending sync txs whose effective_date points to a DIFFERENT bill
+ (cycle math classified them elsewhere) must NOT auto-bucket into
+ this bill by date. Posted sync / manual entries with date in window
+ still count regardless of effective_date (they're definitive)."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ # Active bill (April), plus an existing future bill (May) the
+ # pending tx will be cycle-math-classified to.
+ april = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-z", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(april)
+ await session.flush()
+
+ # Pending sync tx with effective_date pointing to a DIFFERENT bill
+ # (May) — cycle math classified it elsewhere, must NOT show in April
+ pending = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("99"),
+ effective_date=date(2026, 5, 16), # ≠ April's due_date
+ source="sync",
+ )
+ pending.status = "pending"
+
+ # Posted sync tx in window without billId — SHOULD count (provider
+ # returned but didn't tag, reasonable to fill in by date)
+ posted_synced = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 9), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ source="sync",
+ )
+ posted_synced.status = "posted"
+
+ # Manual user entry in window — SHOULD count (explicit intent)
+ manual = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 10), Decimal("75"),
+ effective_date=date(2026, 4, 16),
+ source="manual",
+ )
+ await session.commit()
+
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=april.id,
+ from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),
+ accounting_mode="cash",
+ )
+ ids = {t.id for t in txs}
+ assert pending.id not in ids, (
+ "pending sync pointing to a different bill must NOT be counted "
+ "in this bill"
+ )
+ assert posted_synced.id in ids
+ assert manual.id in ids
+
+ @pytest.mark.asyncio
+ async def test_bill_id_filter_excludes_unlinked_txs_outside_window(
+ self, session, test_user, cc_account
+ ):
+ """An unlinked tx with a date outside the cycle window must NOT be
+ counted — otherwise we'd pick up unrelated manual entries."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-y", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ # Unlinked tx in a totally different month — should NOT be in cycle
+ outside = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 1, 5), Decimal("99"),
+ effective_date=date(2026, 1, 16),
+ )
+ await session.commit()
+
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=bill.id,
+ from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),
+ accounting_mode="cash",
+ )
+ assert outside.id not in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_bill_id_filter_includes_pending_tx_with_bill_id_set(
+ self, session, test_user, cc_account
+ ):
+ """The pending-sync exclusion only applies when bill_id IS NULL.
+ A pending tx that Pluggy already tagged with a billId is still
+ bank-truth and must count — otherwise we'd lose pending charges
+ that the bank has already classified."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-pending-tagged", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ # Pluggy tagged a pending tx — bill_id is set even though status is pending
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ source="sync",
+ )
+ tx.bill_id = bill.id
+ tx.status = "pending"
+ await session.commit()
+
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=bill.id,
+ from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),
+ accounting_mode="cash",
+ )
+ assert tx.id in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_bill_id_filter_includes_posted_sync_unlinked_in_window(
+ self, session, test_user, cc_account
+ ):
+ """Posted sync tx without billId is the rare case where the provider
+ returned the tx but didn't tag a bill. Date-window inclusion is
+ reasonable — the user wants to see their charges, and the tx is
+ definitively settled. Only pending sync without billId is excluded."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-posted-untagged", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ source="sync",
+ )
+ tx.status = "posted"
+ # bill_id stays None
+ await session.commit()
+
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=bill.id,
+ from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),
+ accounting_mode="cash",
+ )
+ assert tx.id in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_bill_id_filter_includes_ofx_imported_in_window(
+ self, session, test_user, cc_account
+ ):
+ """An OFX import is a definitive user intent — must count toward the
+ bill cycle whose window contains its date. Confirms the pending-sync
+ exclusion is narrow (sync+pending only), not blanket source-based."""
+ from app.services.transaction_service import get_transactions
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-ofx", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ source="ofx",
+ )
+ await session.commit()
+
+ txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ bill_id=bill.id,
+ from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),
+ accounting_mode="cash",
+ )
+ assert tx.id in {t.id for t in txs}
+
+ @pytest.mark.asyncio
+ async def test_override_to_date_with_no_matching_bill_keeps_bill_id_null(
+ self, session, test_user, cc_account
+ ):
+ """The user can pick any date as effective_bill_date — including one
+ that doesn't correspond to a known bill (e.g. a far-future statement
+ that hasn't been issued yet). bill_id stays null, effective_date
+ follows the override, and the tx is bucketed by override only."""
+ from app.services.transaction_service import update_transaction
+ from app.schemas.transaction import TransactionUpdate
+
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 18), Decimal("55.90"),
+ effective_date=date(2026, 5, 16),
+ source="manual",
+ )
+ await session.commit()
+
+ # No bill exists for 2099-01-01 — override still takes effect
+ await update_transaction(
+ session, tx.id, test_user.id,
+ TransactionUpdate(effective_bill_date=date(2099, 1, 1)),
+ )
+ await session.commit()
+ await session.refresh(tx)
+
+ assert tx.effective_bill_date == date(2099, 1, 1)
+ assert tx.effective_date == date(2099, 1, 1)
+ assert tx.bill_id is None
+
+ @pytest.mark.asyncio
+ async def test_credit_tx_with_bill_id_counts_as_income(
+ self, session, test_user, cc_account
+ ):
+ """Refund/return txs are type=credit. Per-bill summary must include
+ them in monthly_income when their bill_id matches — otherwise CC
+ refunds show up as 0 for the cycle."""
+ from app.services.account_service import get_account_summary
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-refund", due_date=date(2026, 4, 16),
+ total_amount=Decimal("0"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ refund = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("80"),
+ effective_date=date(2026, 4, 16),
+ tx_type="credit",
+ )
+ refund.bill_id = bill.id
+ await session.commit()
+
+ summary = await get_account_summary(
+ session, cc_account.id, test_user.id,
+ date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),
+ bill_id=bill.id,
+ )
+ assert summary["monthly_income"] == 80.0
+
+ @pytest.mark.asyncio
+ async def test_cc_refund_credit_nets_against_debits_in_bill_total(
+ self, session, test_user, cc_account
+ ):
+ """For CC accounts, refund credits must subtract from the cycle's
+ monthly_expenses so 'Total da fatura' matches the bank's bill (which
+ is net of refunds, e.g. R$50 charge + R$50 refund = R$0 owed).
+ abdalanervoso reported this on Bradesco — refunds on the same day
+ as the original charge should zero out the cycle."""
+ from app.services.account_service import get_account_summary
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-net", due_date=date(2026, 4, 16),
+ total_amount=Decimal("0"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ # Original charge (debit)
+ charge = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 17), Decimal("44.90"),
+ effective_date=date(2026, 4, 16),
+ )
+ charge.bill_id = bill.id
+
+ # Same-day refund (credit) — fully reverses the charge
+ refund = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 17), Decimal("44.90"),
+ effective_date=date(2026, 4, 16),
+ tx_type="credit",
+ )
+ refund.bill_id = bill.id
+
+ # An unrelated charge that should still appear in the bill
+ other = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 18), Decimal("32.50"),
+ effective_date=date(2026, 4, 16),
+ )
+ other.bill_id = bill.id
+ await session.commit()
+
+ summary = await get_account_summary(
+ session, cc_account.id, test_user.id,
+ date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),
+ bill_id=bill.id,
+ )
+ # 44.90 (charge) - 44.90 (refund) + 32.50 (other) = 32.50
+ assert summary["monthly_expenses"] == 32.50
+
+ @pytest.mark.asyncio
+ async def test_non_cc_account_keeps_debit_only_expenses(
+ self, session, test_user, test_connection
+ ):
+ """For non-CC accounts (checking, etc.), monthly_expenses must STAY
+ as sum-of-debits — credits there are income, not refunds. Confirms
+ the CC netting fix doesn't leak into other account types."""
+ from app.services.account_service import get_account_summary
+
+ checking = Account(
+ id=uuid.uuid4(), user_id=test_user.id,
+ connection_id=test_connection.id,
+ name="Checking", type="checking",
+ balance=Decimal("100"), currency="BRL",
+ )
+ session.add(checking)
+ await session.flush()
+
+ await _make_tx(
+ session, test_user.id, checking.id,
+ date(2026, 4, 5), Decimal("50"),
+ effective_date=date(2026, 4, 5),
+ )
+ # Salary credit — must NOT subtract from expenses
+ await _make_tx(
+ session, test_user.id, checking.id,
+ date(2026, 4, 10), Decimal("3000"),
+ effective_date=date(2026, 4, 10),
+ tx_type="credit",
+ )
+ await session.commit()
+
+ summary = await get_account_summary(
+ session, checking.id, test_user.id,
+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),
+ )
+ assert summary["monthly_expenses"] == 50.0
+ assert summary["monthly_income"] == 3000.0
+
+ @pytest.mark.asyncio
+ async def test_year_boundary_cycle_buckets_correctly(
+ self, session, test_user, cc_account
+ ):
+ """December → January cycle: a tx dated 27/12 with override 5/1 must
+ bucket into the January cycle, not December. Catches off-by-month
+ bugs in the COALESCE/OR logic at year boundaries."""
+ from app.services.transaction_service import get_transactions
+
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2025, 12, 27), Decimal("100"),
+ effective_date=date(2025, 12, 27),
+ source="manual",
+ )
+ tx.effective_bill_date = date(2026, 1, 5)
+ await session.commit()
+
+ # December window: tx must NOT appear (override moved it to Jan)
+ dec_txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2025, 12, 1), to_date=date(2025, 12, 31),
+ accounting_mode="cash",
+ )
+ assert tx.id not in {t.id for t in dec_txs}
+
+ # January window: tx must appear
+ jan_txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 1, 1), to_date=date(2026, 1, 31),
+ accounting_mode="cash",
+ )
+ assert tx.id in {t.id for t in jan_txs}
+
+ @pytest.mark.asyncio
+ async def test_summary_excludes_pending_sync_pointing_to_other_bill(
+ self, session, test_user, cc_account
+ ):
+ """get_account_summary applies the same effective_date-aware pending
+ rule as get_transactions — pending sync pointing to a DIFFERENT bill
+ must NOT pollute this bill's total. Otherwise the totals card and
+ bar chart would sum a tx the transactions list omits."""
+ from app.services.account_service import get_account_summary
+ from app.models.credit_card_bill import CreditCardBill
+ from datetime import datetime, timezone
+
+ bill = CreditCardBill(
+ user_id=test_user.id, account_id=cc_account.id,
+ external_id="bill-summary", due_date=date(2026, 4, 16),
+ total_amount=Decimal("100"), currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+ session.add(bill)
+ await session.flush()
+
+ # Pending sync, no billId, effective_date points to a different bill
+ pending = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 8), Decimal("99"),
+ effective_date=date(2026, 5, 16), # NOT this bill's due_date
+ source="sync",
+ )
+ pending.status = "pending"
+
+ # Manual entry in the same window — must be included
+ await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 9), Decimal("50"),
+ effective_date=date(2026, 4, 16),
+ source="manual",
+ )
+ await session.commit()
+
+ summary = await get_account_summary(
+ session, cc_account.id, test_user.id,
+ date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),
+ bill_id=bill.id,
+ )
+ # Manual 50 counted, pending 99 excluded
+ assert summary["monthly_expenses"] == 50.0
+
+ @pytest.mark.asyncio
+ async def test_override_unset_falls_back_to_mode_column(
+ self, session, test_user, cc_account
+ ):
+ """Without an override, the configured accounting mode's column
+ (date for cash, effective_date for accrual) drives bucketing."""
+ from app.services.transaction_service import get_transactions
+ await _set_mode(session, "cash")
+ tx = await _make_tx(
+ session, test_user.id, cc_account.id,
+ date(2026, 4, 18), Decimal("55.90"),
+ effective_date=date(2026, 5, 22),
+ )
+ await session.commit()
+
+ # April window: cash mode uses date (Apr 18), should include
+ apr_txs, _ = await get_transactions(
+ session, test_user.id, account_id=cc_account.id,
+ from_date=date(2026, 4, 1), to_date=date(2026, 4, 30),
+ accounting_mode="cash",
+ )
+ assert any(t.id == tx.id for t in apr_txs)
diff --git a/backend/tests/test_providers_pluggy.py b/backend/tests/test_providers_pluggy.py
index 0a904756..ca60e0ff 100644
--- a/backend/tests/test_providers_pluggy.py
+++ b/backend/tests/test_providers_pluggy.py
@@ -214,6 +214,54 @@ async def test_parser_negative_total_amount_is_stored_as_absolute():
assert tx.installment_total_amount == Decimal("600.00")
+async def test_parser_captures_bill_external_id():
+ """`creditCardMetadata.billId` flows into TransactionData.bill_external_id —
+ the sync layer resolves it to a credit_card_bills FK (issue #92)."""
+ result = await _fetch([
+ {
+ "id": "tx-bill-1",
+ "description": "RESTAURANT",
+ "amount": -50.00,
+ "date": "2026-04-10",
+ "type": "DEBIT",
+ "creditCardMetadata": {"billId": "bill-abc-123"},
+ }
+ ])
+ assert result[0].bill_external_id == "bill-abc-123"
+
+
+async def test_parser_no_bill_id_leaves_field_none():
+ result = await _fetch([
+ {
+ "id": "tx-no-bill",
+ "description": "X",
+ "amount": -10,
+ "date": "2026-04-10",
+ "type": "DEBIT",
+ "creditCardMetadata": {"installmentNumber": 1, "totalInstallments": 1},
+ }
+ ])
+ assert result[0].bill_external_id is None
+
+
+async def test_parser_bill_id_coerced_to_string():
+ """Defensive: providers may emit numeric bill ids; column is String(255)."""
+ result = await _fetch([
+ {
+ "id": "tx-num-bill",
+ "description": "X",
+ "amount": -10,
+ "date": "2026-04-10",
+ "type": "DEBIT",
+ "creditCardMetadata": {"billId": 999},
+ }
+ ])
+ assert result[0].bill_external_id == "999"
+
+
@pytest.mark.asyncio
async def test_parser_missing_purchase_date_only():
"""Some connectors omit purchaseDate even when counts are present."""
diff --git a/backend/tests/test_providers_pluggy_bills.py b/backend/tests/test_providers_pluggy_bills.py
new file mode 100644
index 00000000..c7f697e6
--- /dev/null
+++ b/backend/tests/test_providers_pluggy_bills.py
@@ -0,0 +1,356 @@
+"""Parser tests for the Pluggy /bills endpoint introduced for issue #92.
+
+Mirrors the test_providers_pluggy.py pattern: httpx is stubbed out so no
+network traffic happens; we exercise PluggyProvider.get_bills end-to-end
+against the JSON shapes Pluggy may emit. The goal is to pin down every
+"what does the parser do when X is malformed/missing" decision so we can
+fearlessly turn /bills sync on for real users.
+"""
+
+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:
+ """Single-page client mock — same shape as test_providers_pluggy.py."""
+ 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
+
+
+def _mock_httpx_client_paged(pages: list[list[dict]]) -> MagicMock:
+ """Multi-page client mock — each .get() returns the next page."""
+ total = len(pages)
+ responses = []
+ for page_results in pages:
+ resp = MagicMock()
+ resp.raise_for_status = MagicMock()
+ resp.json = MagicMock(return_value={"results": page_results, "totalPages": total})
+ responses.append(resp)
+
+ client = MagicMock()
+ client.get = AsyncMock(side_effect=responses)
+ client.__aenter__ = AsyncMock(return_value=client)
+ client.__aexit__ = AsyncMock(return_value=None)
+ return client
+
+
+async def _fetch(bills: list[dict]):
+ provider = PluggyProvider()
+ fake_client = _mock_httpx_client(bills)
+ 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_bills({"item_id": "i"}, "acc-ext-1")
+
+
+async def _fetch_paged(pages: list[list[dict]]):
+ provider = PluggyProvider()
+ fake_client = _mock_httpx_client_paged(pages)
+ 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_bills({"item_id": "i"}, "acc-ext-1")
+
+
+# ---- Happy path ------------------------------------------------------------
+
+
+async def test_bills_parser_full_payload():
+ """Universal credit-card billing fields flow through into BillData."""
+ raw = {
+ "id": "bill-1",
+ "dueDate": "2026-04-15",
+ "totalAmount": 2431.99,
+ "totalAmountCurrencyCode": "BRL",
+ "minimumPaymentAmount": 250.00,
+ }
+ result = await _fetch([raw])
+ assert len(result) == 1
+ bill = result[0]
+ assert bill.external_id == "bill-1"
+ assert bill.due_date == date(2026, 4, 15)
+ assert bill.total_amount == Decimal("2431.99")
+ assert bill.currency == "BRL"
+ assert bill.minimum_payment == Decimal("250.00")
+ assert bill.raw_data == raw
+
+
+async def test_bills_parser_minimal_payload_uses_defaults():
+ """Optional fields default to None; currency falls back to BRL."""
+ result = await _fetch([
+ {"id": "bill-2", "dueDate": "2026-03-15", "totalAmount": 100}
+ ])
+ bill = result[0]
+ assert bill.currency == "BRL"
+ assert bill.minimum_payment is None
+ assert bill.total_amount == Decimal("100")
+
+
+async def test_bills_parser_preserves_provider_extras_in_raw_data():
+ """Provider-specific fields we don't promote to columns survive verbatim
+ in raw_data — the contract for "we don't lose data when adding a new
+ integration." Today these are Pluggy fields; tomorrow it could be Belvo
+ or a custom script, and downstream code can opt into them via raw_data."""
+ raw = {
+ "id": "bill-extras",
+ "dueDate": "2026-04-15",
+ "totalAmount": 100,
+ "financeCharges": [{"type": "IOF", "amount": 12.34}],
+ "payments": [{"id": "p-1", "amount": 100, "paymentDate": "2026-04-15"}],
+ "allowsInstallments": True,
+ "someFutureField": {"nested": "value"},
+ }
+ bill = (await _fetch([raw]))[0]
+ assert bill.raw_data == raw
+ # And we explicitly do NOT promote them to BillData fields.
+ assert not hasattr(bill, "finance_charges")
+ assert not hasattr(bill, "payments")
+ assert not hasattr(bill, "allows_installments")
+
+
+# ---- Required-field handling: skip rather than crash ----------------------
+
+
+async def test_bills_parser_skips_missing_id():
+ result = await _fetch([
+ {"dueDate": "2026-03-15", "totalAmount": 50},
+ {"id": "bill-ok", "dueDate": "2026-04-15", "totalAmount": 50},
+ ])
+ assert [b.external_id for b in result] == ["bill-ok"]
+
+
+async def test_bills_parser_skips_empty_string_id():
+ """Falsy id must be skipped, not coerced to "" — that would collide on the
+ unique(account_id, external_id) constraint downstream."""
+ result = await _fetch([
+ {"id": "", "dueDate": "2026-04-15", "totalAmount": 10},
+ {"id": "bill-ok", "dueDate": "2026-04-15", "totalAmount": 50},
+ ])
+ assert [b.external_id for b in result] == ["bill-ok"]
+
+
+async def test_bills_parser_skips_missing_due_date():
+ result = await _fetch([
+ {"id": "bill-x", "totalAmount": 10},
+ {"id": "bill-ok", "dueDate": "2026-04-15", "totalAmount": 50},
+ ])
+ assert [b.external_id for b in result] == ["bill-ok"]
+
+
+async def test_bills_parser_skips_malformed_due_date():
+ result = await _fetch([
+ {"id": "bill-x", "dueDate": "not-a-date", "totalAmount": 10},
+ {"id": "bill-ok", "dueDate": "2026-04-15", "totalAmount": 50},
+ ])
+ assert [b.external_id for b in result] == ["bill-ok"]
+
+
+async def test_bills_parser_skips_missing_total_amount():
+ result = await _fetch([
+ {"id": "bill-x", "dueDate": "2026-04-15"},
+ {"id": "bill-ok", "dueDate": "2026-04-15", "totalAmount": 50},
+ ])
+ assert [b.external_id for b in result] == ["bill-ok"]
+
+
+async def test_bills_parser_skips_malformed_total_amount():
+ result = await _fetch([
+ {"id": "bill-x", "dueDate": "2026-04-15", "totalAmount": "not-a-number"},
+ {"id": "bill-ok", "dueDate": "2026-04-15", "totalAmount": 50},
+ ])
+ assert [b.external_id for b in result] == ["bill-ok"]
+
+
+# ---- Edge formats Pluggy may send -----------------------------------------
+
+
+async def test_bills_parser_due_date_with_time_suffix():
+ """ISO datetime strings get truncated to date cleanly."""
+ result = await _fetch([
+ {"id": "bill-3", "dueDate": "2026-05-10T03:00:00.000Z", "totalAmount": 200}
+ ])
+ assert result[0].due_date == date(2026, 5, 10)
+
+
+async def test_bills_parser_total_amount_as_string():
+ result = await _fetch([
+ {"id": "b", "dueDate": "2026-04-15", "totalAmount": "1234.56"}
+ ])
+ assert result[0].total_amount == Decimal("1234.56")
+
+
+async def test_bills_parser_total_amount_as_int():
+ result = await _fetch([
+ {"id": "b", "dueDate": "2026-04-15", "totalAmount": 100}
+ ])
+ assert result[0].total_amount == Decimal("100")
+
+
+async def test_bills_parser_negative_total_preserves_sign():
+ """Pluggy reports credit-balance bills as negative — keep as-is, not abs'd.
+ A negative bill means the bank owes the user money; flipping the sign
+ would silently turn a credit into a debt in any aggregation."""
+ result = await _fetch([
+ {"id": "b", "dueDate": "2026-04-15", "totalAmount": -12.50}
+ ])
+ assert result[0].total_amount == Decimal("-12.50")
+
+
+async def test_bills_parser_zero_total_is_kept():
+ """A R$0,00 fatura is still a valid statement (e.g. a closed cycle with
+ no spend) — must not be confused with "missing totalAmount"."""
+ result = await _fetch([
+ {"id": "b", "dueDate": "2026-04-15", "totalAmount": 0}
+ ])
+ assert len(result) == 1
+ assert result[0].total_amount == Decimal("0")
+
+
+async def test_bills_parser_currency_defaults_to_brl():
+ result = await _fetch([
+ {"id": "b", "dueDate": "2026-04-15", "totalAmount": 10}
+ ])
+ assert result[0].currency == "BRL"
+
+
+async def test_bills_parser_currency_explicit_overrides_default():
+ result = await _fetch([
+ {
+ "id": "b",
+ "dueDate": "2026-04-15",
+ "totalAmount": 10,
+ "totalAmountCurrencyCode": "USD",
+ }
+ ])
+ assert result[0].currency == "USD"
+
+
+async def test_bills_parser_id_coerced_to_string():
+ """Pluggy normally returns string IDs but we coerce defensively — the
+ column is String(255) and a numeric id would otherwise blow up the
+ upsert with a type error."""
+ result = await _fetch([
+ {"id": 12345, "dueDate": "2026-04-15", "totalAmount": 10}
+ ])
+ assert result[0].external_id == "12345"
+ assert isinstance(result[0].external_id, str)
+
+
+async def test_bills_parser_minimum_payment_string():
+ result = await _fetch([
+ {
+ "id": "b",
+ "dueDate": "2026-04-15",
+ "totalAmount": 10,
+ "minimumPaymentAmount": "12.50",
+ }
+ ])
+ assert result[0].minimum_payment == Decimal("12.50")
+
+
+async def test_bills_parser_minimum_payment_garbage_drops_to_none():
+ result = await _fetch([
+ {
+ "id": "b",
+ "dueDate": "2026-04-15",
+ "totalAmount": 10,
+ "minimumPaymentAmount": "n/a",
+ }
+ ])
+ assert result[0].minimum_payment is None
+
+
+# ---- Pagination & empty results -------------------------------------------
+
+
+async def test_bills_parser_empty_results():
+ result = await _fetch([])
+ assert result == []
+
+
+async def test_bills_parser_paginates_across_multiple_pages():
+ page1 = [
+ {"id": "b-1", "dueDate": "2026-01-15", "totalAmount": 100},
+ {"id": "b-2", "dueDate": "2026-02-15", "totalAmount": 200},
+ ]
+ page2 = [
+ {"id": "b-3", "dueDate": "2026-03-15", "totalAmount": 300},
+ ]
+ result = await _fetch_paged([page1, page2])
+ assert [b.external_id for b in result] == ["b-1", "b-2", "b-3"]
+
+
+async def test_bills_parser_mixed_valid_and_invalid_in_same_page():
+ """Bad rows in the middle of a page don't poison the good ones."""
+ result = await _fetch([
+ {"id": "ok-1", "dueDate": "2026-01-15", "totalAmount": 100},
+ {"id": "bad", "dueDate": "garbage", "totalAmount": 50},
+ {"id": "ok-2", "dueDate": "2026-02-15", "totalAmount": 200},
+ ])
+ assert [b.external_id for b in result] == ["ok-1", "ok-2"]
+
+
+# ---- Default abstract method on BankProvider ------------------------------
+
+
+async def test_default_get_bills_returns_empty_list():
+ """Providers that don't override get_bills get an empty list — the sync
+ layer reads "no bills" as "fall back to local cycle math"."""
+ from app.providers.base import BankProvider
+
+ class StubProvider(BankProvider):
+ @property
+ def name(self) -> str:
+ return "stub"
+
+ def get_oauth_url(self, redirect_uri, state):
+ return ""
+
+ async def handle_oauth_callback(self, code):
+ raise NotImplementedError
+
+ async def get_accounts(self, credentials):
+ return []
+
+ async def get_transactions(self, credentials, account_external_id, since=None, payee_source="auto"):
+ return []
+
+ async def refresh_credentials(self, credentials):
+ return credentials
+
+ assert await StubProvider().get_bills({}, "acc") == []
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 55304ca8..68dec54e 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -78,7 +78,7 @@ export function TransactionDialog({
onClose: () => void
transaction: Transaction | null
categories: { id: string; name: string; icon: string }[]
- accounts: { id: string; name: string }[]
+ accounts: { id: string; name: string; type?: string }[]
recurringMatch?: RecurringTransaction
onSave: (data: Partial<Transaction>, recurringData?: { frequency: string; end_date?: string }, pendingFiles?: File[], action?: SaveAction) => void
onDelete?: () => void
@@ -278,7 +278,7 @@ function TransactionForm({
transaction: Transaction | null
duplicateDraft: Partial<Transaction> | null
categories: { id: string; name: string; icon: string }[]
- accounts: { id: string; name: string }[]
+ accounts: { id: string; name: string; type?: string }[]
recurringMatch?: RecurringTransaction
onSave: (data: Partial<Transaction>, recurringData?: { frequency: string; end_date?: string }, pendingFiles?: File[], action?: SaveAction) => void
onDelete?: () => void
@@ -314,6 +314,9 @@ function TransactionForm({
const [payeeId, setPayeeId] = useState(seed?.payee_id ?? '')
const [accountId, setAccountId] = useState(seed?.account_id ?? accounts[0]?.id ?? '')
const [notes, setNotes] = useState(seed?.notes ?? '')
+ // Manual CC bucketing override (issue #92). Empty = auto. Visible only
+ // when the selected account is a credit card.
+ const [effectiveBillDate, setEffectiveBillDate] = useState(seed?.effective_bill_date ?? '')
const [convertedAmount, setConvertedAmount] = useState(
seed?.amount_primary != null ? seed.amount_primary.toString() : ''
)
@@ -430,11 +433,21 @@ function TransactionForm({
if (showConversion && fxRate) {
fxFields.fx_rate_used = parseFloat(fxRate)
}
+ // Active CC account ⇒ surface effective_bill_date in the payload
+ // (sent both for synced and manual edits since the user can hand-
+ // correct the bucketing on either; null clears the override back to
+ // auto bucketing).
+ const selectedAcc = accounts.find(a => a.id === accountId)
+ const isCcSelected = selectedAcc?.type === 'credit_card'
+ const overridePayload: Partial<Transaction> = isCcSelected
+ ? { effective_bill_date: effectiveBillDate || null }
+ : {}
const txData = isSynced
? {
category_id: categoryId || null,
payee_id: payeeId || null,
notes: notes.trim() || null,
+ ...overridePayload,
} as Partial<Transaction>
: {
description,
@@ -447,6 +460,7 @@ function TransactionForm({
account_id: accountId || undefined,
notes: notes.trim() || null,
...fxFields,
+ ...overridePayload,
} as Partial<Transaction>
const recurringData = isCreating && isRecurring
? { frequency, end_date: endDate || undefined }
@@ -660,6 +674,42 @@ function TransactionForm({
/>
</div>
+ {/* Manual bill-cycle override (issue #92). CC accounts only. Empty
+ input = use auto bucketing (Pluggy bill_id when available, cycle
+ math otherwise). Setting the date forces this tx into the bill
+ whose due_date matches. */}
+ {(() => {
+ const selectedAcc = accounts.find(a => a.id === accountId)
+ if (selectedAcc?.type !== 'credit_card') return null
+ return (
+ <div className="space-y-2">
+ <Label>
+ {t('transactions.effectiveBillDate', 'Data efetiva da fatura')}{' '}
+ <span className="text-muted-foreground font-normal text-xs">
+ ({t('transactions.effectiveBillDateHint', 'manual, sobrescreve o ciclo automático')})
+ </span>
+ </Label>
+ <div className="inline-flex items-center gap-1">
+ <DatePickerInput
+ value={effectiveBillDate}
+ onChange={setEffectiveBillDate}
+ placeholder={t('transactions.effectiveBillDatePlaceholder', 'Vencimento da fatura (opcional)')}
+ />
+ {effectiveBillDate && (
+ <button
+ type="button"
+ className="h-9 w-9 inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors shrink-0"
+ onClick={() => setEffectiveBillDate('')}
+ title={t('transactions.clearOverride', 'Remover sobrescrição')}
+ >
+ <X className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+ </div>
+ )
+ })()}
+
{!isCreating && transaction ? (
<TransactionAttachments
transactionId={transaction.id}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 83d77d8c..ad2a2efd 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -10,6 +10,7 @@ import type {
ConnectionSettings,
Account,
AccountSummary,
+ CreditCardBill,
Transaction,
Payee,
PayeeSummary,
@@ -222,14 +223,18 @@ export const accounts = {
delete: async (id: string): Promise<void> => {
await api.delete(`/accounts/${id}`)
},
- summary: async (id: string, from?: string, to?: string): Promise<AccountSummary> => {
- const { data } = await api.get(`/accounts/${id}/summary`, { params: { from, to } })
+ summary: async (id: string, from?: string, to?: string, billId?: string, unbilledOnly?: boolean): Promise<AccountSummary> => {
+ const { data } = await api.get(`/accounts/${id}/summary`, { params: { from, to, bill_id: billId, unbilled_only: unbilledOnly || undefined } })
return data
},
balanceHistory: async (id: string, from?: string, to?: string): Promise<{ date: string; balance: number; balance_primary?: number }[]> => {
const { data } = await api.get(`/accounts/${id}/balance-history`, { params: { from, to } })
return data
},
+ bills: async (id: string, limit = 24): Promise<CreditCardBill[]> => {
+ const { data } = await api.get(`/accounts/${id}/bills`, { params: { limit } })
+ return data
+ },
close: async (id: string): Promise<Account> => {
const { data } = await api.post(`/accounts/${id}/close`)
return data
@@ -252,6 +257,8 @@ export const transactions = {
type?: string
from?: string
to?: string
+ bill_id?: string
+ unbilled_only?: boolean
q?: string
page?: number
limit?: number
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index 10d6d3e2..db76b785 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -8,7 +8,7 @@ import { ptBR, enUS } from 'date-fns/locale'
import { accounts, transactions, categories as categoriesApi } from '@/lib/api'
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
import { toast } from 'sonner'
-import type { Transaction } from '@/types'
+import type { CreditCardBill, Transaction } from '@/types'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { ArrowLeft, ArrowLeftRight, ChevronLeft, ChevronRight, Clock, HelpCircle, Paperclip, Pencil, X } from 'lucide-react'
@@ -149,6 +149,44 @@ function creditCardCycleLabel(
* Brazilian convention: a transaction ON the close day belongs to the NEXT
* cycle, so the cycle boundaries are [previous close day, next close day − 1].
* Falls back to "previous month → today" when no closeDay is configured. */
+/** Derive a bill's cycle close date from the account's statement_close_day.
+ * Pluggy doesn't expose the close date directly, but it's recoverable: the
+ * close is the most recent occurrence of close_day on or before the bill's
+ * due_date. Falls back to due_date when close_day is not configured. */
+function closeDateForBill(billDueDate: string, closeDay: number | null | undefined): string {
+ if (!closeDay) return billDueDate
+ const due = parseISO(billDueDate + 'T00:00:00')
+ const y = due.getFullYear()
+ const m = due.getMonth()
+ const lastThis = new Date(y, m + 1, 0).getDate()
+ const sameMonth = new Date(y, m, Math.min(closeDay, lastThis))
+ if (sameMonth.getTime() <= due.getTime()) {
+ return format(sameMonth, 'yyyy-MM-dd')
+ }
+ const py = m === 0 ? y - 1 : y
+ const pm = m === 0 ? 11 : m - 1
+ const lastPrev = new Date(py, pm + 1, 0).getDate()
+ return format(new Date(py, pm, Math.min(closeDay, lastPrev)), 'yyyy-MM-dd')
+}
+
+
+/** Build the [start, end] range a credit-card transaction would belong to
+ * when the cycle is anchored on a real bill (issue #92). The bill's due_date
+ * is the period end; the start is the day after the previous bill's due_date,
+ * which is when the post-close cycle begins. For the oldest known bill we
+ * fall back to a wide window so any older purchases still show up. */
+function rangeForBill(
+ bill: CreditCardBill,
+ prevBill: CreditCardBill | null,
+): { start: string; end: string } {
+ const end = bill.due_date
+ const start = prevBill
+ ? format(addDays(parseISO(prevBill.due_date + 'T00:00:00'), 1), 'yyyy-MM-dd')
+ : format(addDays(parseISO(bill.due_date + 'T00:00:00'), -45), 'yyyy-MM-dd')
+ return { start, end }
+}
+
+
function creditCardCycleBoundaries(
closeDay: number | null | undefined,
reference: Date,
@@ -241,6 +279,33 @@ export default function AccountDetailPage() {
const handleFilterToChange = (v: string) => { filterTouched.current = true; setFilterTo(v) }
const shiftCycleBy = (direction: -1 | 1) => {
filterTouched.current = true
+ // Bill-aware nav: step through the bills list when we have it, so prev/next
+ // mirrors the bank's actual statements (handles dynamic close days).
+ if (billsAsc.length > 0) {
+ const currentIdx = activeBill
+ ? billsAsc.indexOf(activeBill)
+ : billsAsc.length // viewing in-progress cycle past the newest bill
+ const newIdx = currentIdx + direction
+ if (newIdx >= 0 && newIdx < billsAsc.length) {
+ const next = billsAsc[newIdx]
+ const prev = newIdx > 0 ? billsAsc[newIdx - 1] : null
+ const { start, end } = rangeForBill(next, prev)
+ setFilterFrom(start)
+ setFilterTo(end)
+ return
+ }
+ // Stepping forward past the newest bill = the in-progress cycle.
+ // Use the full cycle-math range [prev_close, next_close-1] so a tx
+ // dated on the previous close (Brazilian convention: belongs to the
+ // NEXT cycle) shows up. The backend filters bill_id IS NULL in this
+ // path so already-billed txs don't double-count against the bar.
+ if (newIdx === billsAsc.length && account?.statement_close_day) {
+ const cm = creditCardCycleBoundaries(account.statement_close_day, new Date())
+ setFilterFrom(cm.start)
+ setFilterTo(cm.end)
+ return
+ }
+ }
if (account?.type === 'credit_card' && account?.statement_close_day) {
const ref = direction === -1
? new Date(parseISO(filterFrom + 'T00:00:00').getTime() - 86400000)
@@ -260,9 +325,64 @@ export default function AccountDetailPage() {
enabled: !!id,
})
+ // Bills (faturas) from the provider's bills feed — issue #92. Only fetched
+ // for CC accounts; non-CC and CC-without-bills both return [] so the UI
+ // falls back to local cycle math wherever bills aren't available.
+ // Declared early so the cycle-init useEffect and shiftCycleBy can read it.
+ const { data: bills } = useQuery({
+ queryKey: ['accounts', id, 'bills'],
+ queryFn: () => accounts.bills(id!, 24),
+ enabled: !!id && account?.type === 'credit_card',
+ })
+ // Bills sorted oldest → newest, for indexing helpers below.
+ const billsAsc = useMemo(() => {
+ if (!bills) return []
+ return [...bills].sort((a, b) => a.due_date.localeCompare(b.due_date))
+ }, [bills])
+ // The bill, if any, the active filter currently corresponds to. We always
+ // set filterTo = bill.due_date when navigating to a bill, so the lookup is
+ // a simple equality check.
+ const activeBill = useMemo(() => {
+ if (!billsAsc.length) return null
+ return billsAsc.find(b => b.due_date === filterTo) ?? null
+ }, [billsAsc, filterTo])
+ // True when the user is on the trailing in-progress cycle (CC has bills,
+ // but the current view doesn't match any of them). Backend uses this to
+ // exclude already-billed txs from the cycle window so they don't double-
+ // count against the in-progress bar/total.
+ const isInProgressCycle = !activeBill && billsAsc.length > 0
+
useEffect(() => {
if (!account || filterTouched.current) return
if (account.type === 'credit_card') {
+ // Default landing matches the existing UX: the bill the user is
+ // about to pay (next due). With a bills feed we can prefer an
+ // upcoming bank-reported bill; if today is past the newest bill,
+ // fall through to local cycle math for the in-progress cycle so
+ // the user sees what's accumulating on the next (not-yet-issued)
+ // statement.
+ if (billsAsc.length > 0) {
+ const today = format(new Date(), 'yyyy-MM-dd')
+ const upcoming = billsAsc.find(b => b.due_date >= today)
+ if (upcoming) {
+ const idx = billsAsc.indexOf(upcoming)
+ const prev = idx > 0 ? billsAsc[idx - 1] : null
+ const { start, end } = rangeForBill(upcoming, prev)
+ setFilterFrom(start)
+ setFilterTo(end)
+ return
+ }
+ // Today is past the newest bill — use cycle-math range
+ // [prev_close, next_close-1] so the prev-close-day tx (Brazilian:
+ // belongs to next cycle) is in window. Backend's bill_id IS NULL
+ // filter in the cycle-math fallback keeps already-billed txs out.
+ if (account.statement_close_day) {
+ const { start, end } = creditCardCycleBoundaries(account.statement_close_day, new Date())
+ setFilterFrom(start)
+ setFilterTo(end)
+ return
+ }
+ }
const { start, end } = defaultCycleForCreditCard(
account.statement_close_day,
account.payment_due_day,
@@ -271,7 +391,7 @@ export default function AccountDetailPage() {
setFilterFrom(start)
setFilterTo(end)
}
- }, [account])
+ }, [account, billsAsc])
const { data: accountsList } = useQuery({
queryKey: ['accounts'],
@@ -279,8 +399,21 @@ export default function AccountDetailPage() {
})
const { data: summary, isLoading: summaryLoading } = useQuery({
- queryKey: ['accounts', id, 'summary', filterFrom, filterTo],
- queryFn: () => accounts.summary(id!, filterFrom || undefined, filterTo || undefined),
+ // When a real bill anchors the active cycle, send bill_id AND the cycle
+ // window. Backend ORs them so both bill_id-linked txs (bank truth) and
+ // unlinked txs in the window (manual recurring, CSV imports) count.
+ // For the in-progress cycle (no bill match), unbilled_only excludes
+ // txs already linked to a closed bill (anti-double-count).
+ queryKey: activeBill
+ ? ['accounts', id, 'summary', { bill_id: activeBill.id, from: filterFrom, to: filterTo }]
+ : ['accounts', id, 'summary', filterFrom, filterTo, { unbilled_only: isInProgressCycle }],
+ queryFn: () => accounts.summary(
+ id!,
+ filterFrom || undefined,
+ filterTo || undefined,
+ activeBill?.id,
+ isInProgressCycle || undefined,
+ ),
enabled: !!id,
})
@@ -299,8 +432,37 @@ export default function AccountDetailPage() {
})
// Last 6 cycles (oldest → newest) for the bill timeline strip.
- const timelineCycles = useMemo(() => {
- if (!account || account.type !== 'credit_card' || !account.statement_close_day) return []
+ // When we have a bills feed (Pluggy Regulado, etc.) the strip is driven
+ // directly by bills — total comes from bill.total_amount, label from the
+ // bill's actual due_date — so the bars match the bank statement-for-statement
+ // even when the close day shifts month to month (issue #92). Otherwise we
+ // fall back to local cycle math.
+ const timelineCycles: { start: string; end: string; bill?: CreditCardBill }[] = useMemo(() => {
+ if (!account || account.type !== 'credit_card') return []
+
+ if (billsAsc.length > 0) {
+ const cycles: { start: string; end: string; bill?: CreditCardBill }[] = []
+ for (let i = 0; i < billsAsc.length; i++) {
+ const b = billsAsc[i]
+ const prev = i > 0 ? billsAsc[i - 1] : null
+ cycles.push({ ...rangeForBill(b, prev), bill: b })
+ }
+ // The current in-progress cycle (no bill yet) is ALWAYS a trailing
+ // bar when the account has any bills — charges accrue to the next
+ // bill the moment the previous one closes, regardless of whether
+ // its due date has passed. Skipping it hides the user's currently-
+ // accumulating spend from the strip until ~10 days into the cycle.
+ // Use the cycle-math range [prev_close, next_close-1] so a tx dated
+ // on the previous close (which belongs to the NEXT cycle per
+ // Brazilian convention) shows up. The backend's `bill_id IS NULL`
+ // filter prevents already-billed txs from leaking in.
+ if (account.statement_close_day) {
+ cycles.push(creditCardCycleBoundaries(account.statement_close_day, new Date()))
+ }
+ return cycles.slice(-6)
+ }
+
+ if (!account.statement_close_day) return []
const cycles: { start: string; end: string }[] = []
let ref = new Date()
for (let i = 0; i < 6; i++) {
@@ -309,12 +471,22 @@ export default function AccountDetailPage() {
ref = new Date(parseISO(c.start + 'T00:00:00').getTime() - 86400000)
}
return cycles
- }, [account])
+ }, [account, billsAsc])
const timelineQueries = useQueries({
queries: timelineCycles.map(c => ({
- queryKey: ['accounts', id, 'summary', c.start, c.end],
- queryFn: () => accounts.summary(id!, c.start, c.end),
+ // Bill-anchored cycles send bill_id AND the cycle window so the
+ // backend includes both Pluggy-linked txs and any unlinked txs
+ // (manual / recurring) the user placed in this cycle. The trailing
+ // in-progress cycle (no bill) sets unbilled_only so prior-bill txs
+ // that fall in the window aren't double-counted in the bar.
+ queryKey: c.bill
+ ? ['accounts', id, 'summary', { bill_id: c.bill.id, from: c.start, to: c.end }]
+ : ['accounts', id, 'summary', c.start, c.end, { unbilled_only: billsAsc.length > 0 }],
+ queryFn: () => accounts.summary(
+ id!, c.start, c.end, c.bill?.id,
+ c.bill ? undefined : (billsAsc.length > 0 || undefined),
+ ),
enabled: !!id,
})),
})
@@ -326,9 +498,18 @@ export default function AccountDetailPage() {
})
const { data: txData, isLoading: txLoading } = useQuery({
- queryKey: ['transactions', { account_id: id, from: filterFrom, to: filterTo, limit: 500, include_opening_balance: true }],
+ queryKey: ['transactions', { account_id: id, bill_id: activeBill?.id, from: filterFrom, to: filterTo, limit: 500, include_opening_balance: true, unbilled_only: isInProgressCycle }],
queryFn: () => transactions.list({
account_id: id,
+ // When the active cycle is a real bill, prefer bill_id (Pluggy's
+ // truth — picks up charges the bank rolled outside the nominal date
+ // range) AND keep from/to so manual / non-bill-linked txs (recurring
+ // fills, CSV imports) bucketed into this cycle still show up.
+ bill_id: activeBill?.id,
+ // For the in-progress cycle (CC has bills, but no bill matches the
+ // current view), exclude already-billed txs so the bar/list only
+ // shows what's accumulating toward the next bill.
+ unbilled_only: isInProgressCycle || undefined,
from: filterFrom || undefined,
to: filterTo || undefined,
limit: 500,
@@ -435,7 +616,7 @@ export default function AccountDetailPage() {
// (answers "how much have I spent this cycle", ignores bill payments/transfers)
const chartData = useMemo(() => {
if (isCreditCard) {
- if (!txData?.items || !filterFrom || !filterTo) return []
+ if (!txData?.items) return []
const byDay = new Map<string, number>()
for (const tx of txData.items) {
if (tx.type !== 'debit') continue
@@ -444,15 +625,31 @@ export default function AccountDetailPage() {
const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)
byDay.set(tx.date, (byDay.get(tx.date) ?? 0) + amt)
}
+ // Chart span: when a real bill is active, derive the range from the
+ // actual debit dates so charges Pluggy bucketed outside our nominal
+ // [prev_due+1, this_due] window (e.g. a 03/02 charge rolled into the
+ // March bill) still show up. Otherwise use the cycle-math range.
+ let rangeStart: string | null = null
+ let rangeEnd: string | null = null
+ if (activeBill) {
+ const dates = Array.from(byDay.keys()).sort()
+ if (dates.length === 0) return []
+ rangeStart = dates[0]
+ rangeEnd = activeBill.due_date < dates[dates.length - 1] ? dates[dates.length - 1] : activeBill.due_date
+ } else if (filterFrom && filterTo) {
+ rangeStart = filterFrom
+ rangeEnd = filterTo
+ }
+ if (!rangeStart || !rangeEnd) return []
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 startDate = parseISO(rangeStart + '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')
+ const end = new Date(rangeEnd + 'T00:00:00')
let running = 0
while (cur <= end) {
const key = format(cur, 'yyyy-MM-dd')
@@ -468,28 +665,31 @@ export default function AccountDetailPage() {
date: p.date,
balance: usePrimary ? (p.balance_primary ?? p.balance) : p.balance,
}))
- }, [isCreditCard, txData, filterFrom, filterTo, balanceHistory, locale, usePrimary])
+ }, [isCreditCard, txData, filterFrom, filterTo, balanceHistory, locale, usePrimary, activeBill])
// Running balance computation for transaction table
const txWithRunningBalance = useMemo((): TxWithBalance[] => {
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.
+ // Cycle running total: debits add, refund credits subtract (net
+ // matches the bank's bill total). Excludes opening_balance and any
+ // transfer-paired tx (bill payments — those zero out separately).
+ // Computed oldest → newest, then reversed (not re-sorted) so
+ // same-day rows read monotonically top-down.
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) {
+ if (tx.source !== 'opening_balance' && !tx.transfer_pair_id) {
const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)
- running += amt
+ if (tx.type === 'debit') running += amt
+ else if (tx.type === 'credit') running -= amt
}
return { ...tx, runningBalance: running }
})
- return withBalance.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
+ return withBalance.reverse()
}
if (summary === undefined) return []
@@ -620,7 +820,11 @@ export default function AccountDetailPage() {
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)}
+ {activeBill
+ ? format(parseISO(activeBill.due_date + 'T00:00:00'), 'MMM yyyy', {
+ locale: i18n.language === 'pt-BR' ? ptBR : enUS,
+ })
+ : creditCardCycleLabel(filterTo, account?.payment_due_day, i18n.language)}
</button>
</PopoverTrigger>
<PopoverContent align="center" className="w-auto p-3 space-y-3">
@@ -731,11 +935,20 @@ export default function AccountDetailPage() {
{/* 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 dfLocale = i18n.language === 'pt-BR' ? ptBR : enUS
+ const totals = timelineQueries.map((q, i) => {
+ const c = timelineCycles[i]
+ // Single source of truth: live debit sum from the summary endpoint,
+ // filtered by bill_id when the cycle has a bill (handles dynamic
+ // close days) or by [start, end] otherwise. Same number whether
+ // the bar is active or not — clicking doesn't shift the value.
+ const total = Number(q.data?.monthly_expenses ?? 0)
+ return {
+ ...c,
+ total,
+ 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">
@@ -743,7 +956,12 @@ export default function AccountDetailPage() {
{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)
+ // When a bill anchors this cycle, label by the bill's actual
+ // month (handles dynamic close days). Otherwise fall back to
+ // the cycle-math label that maps close → due → month.
+ const label = c.bill
+ ? format(parseISO(c.bill.due_date + 'T00:00:00'), 'MMM yyyy', { locale: dfLocale })
+ : creditCardCycleLabel(c.end, account.payment_due_day, i18n.language)
return (
<button
key={i}
@@ -781,13 +999,21 @@ export default function AccountDetailPage() {
{/* Compact stat bar */}
{isCreditCard ? (() => {
+ // Total da fatura. When a real bill is active, sum debits from the
+ // bill_id-filtered tx list (matches the bank app — bills' total_amount
+ // can lag any charges added since the last sync). Otherwise use the
+ // summary endpoint's monthly_expenses now nets refund credits against
+ // debits for CC accounts (matches the bank's bill total).
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)
+ // Compute the due date for THIS cycle. activeBill.due_date is the
+ // bank-truth date and varies month-to-month with weekends/holidays.
+ const cycleDueDate = activeBill
+ ? activeBill.due_date
+ : 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
@@ -807,10 +1033,33 @@ export default function AccountDetailPage() {
// 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
+ // Cycle-over-cycle comparison. When we have a previous bill, use ITS
+ // total_amount as the prev (stable bank snapshot — the date-range
+ // summary endpoint can't bucket linked txs by bill_id and ends up
+ // mismatched). Falls back to summary for the cycle-math case.
+ let prevLabelBill: CreditCardBill | null = null
+ if (activeBill) {
+ const idx = billsAsc.indexOf(activeBill)
+ prevLabelBill = idx > 0 ? billsAsc[idx - 1] : null
+ } else if (billsAsc.length > 0) {
+ const newest = billsAsc[billsAsc.length - 1]
+ const today = format(new Date(), 'yyyy-MM-dd')
+ if (newest.due_date < today) {
+ prevLabelBill = newest
+ }
+ }
+ const prevTotal = prevLabelBill
+ ? Number(prevLabelBill.total_amount)
+ : previousCycleSummary?.monthly_expenses ?? 0
+ const showComparison = (prevLabelBill || previousCycle) && prevTotal > 0
const deltaPct = showComparison ? ((billTotal - prevTotal) / prevTotal) * 100 : null
- const prevCycleLabel = previousCycle ? creditCardCycleLabel(previousCycle.end, account.payment_due_day, i18n.language) : null
+ const prevCycleLabel = prevLabelBill
+ ? format(parseISO(prevLabelBill.due_date + 'T00:00:00'), 'MMM yyyy', {
+ locale: i18n.language === 'pt-BR' ? ptBR : enUS,
+ })
+ : 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">
@@ -962,13 +1211,19 @@ export default function AccountDetailPage() {
</p>
</div>
<div>
+ {/* Closing date. For bill-driven cycles we derive it from the
+ bill's due_date + account.statement_close_day (handles
+ dynamic close days). For cycle-math cycles, filterTo is
+ the day before the close, so close = filterTo + 1. */}
<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(format(addDays(parseISO(filterTo), 1), 'yyyy-MM-dd'), locale)
- : '—'}
+ {activeBill
+ ? formatDateStr(closeDateForBill(activeBill.due_date, account.statement_close_day), locale)
+ : (account.statement_close_day && filterTo
+ ? formatDateStr(format(addDays(parseISO(filterTo), 1), 'yyyy-MM-dd'), locale)
+ : '—')}
</p>
</div>
</div>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index f7b105dd..ebc4cfff 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -101,6 +101,16 @@ export interface Account {
closed_at: string | null
}
+export interface CreditCardBill {
+ id: string
+ account_id: string
+ external_id: string
+ due_date: string // YYYY-MM-DD
+ total_amount: number
+ currency: string
+ minimum_payment: number | null
+}
+
export interface AccountSummary {
account_id: string
current_balance: number
@@ -138,6 +148,12 @@ export interface Transaction {
total_installments: number | null
installment_total_amount: number | null
installment_purchase_date: string | null
+ bill_id: string | null
+ // Manual override for which credit-card bill cycle this tx belongs to
+ // (issue #92). Empty / null = use auto bucketing (Pluggy bill_id when
+ // available, cycle math otherwise). Setting it forces the tx into the
+ // bill whose due_date matches.
+ effective_bill_date: string | null
}
export interface Payee {