Skip to content

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

fix close-day transactions bucketing into wrong statement (#69)

Tássio Noronhafc2ebf1455c1
diff --git a/backend/alembic/versions/030_rebucket_cc_effective_dates_brazilian_convention.py b/backend/alembic/versions/030_rebucket_cc_effective_dates_brazilian_convention.py
new file mode 100644
index 00000000..f1bd3bf8
--- /dev/null
+++ b/backend/alembic/versions/030_rebucket_cc_effective_dates_brazilian_convention.py
@@ -0,0 +1,92 @@
+"""rebucket credit card effective_dates to Brazilian close-day convention
+
+Revision ID: 030
+Revises: 029
+Create Date: 2026-04-17
+
+Per Brazilian banking convention (Nubank, Itaú, Bradesco, Santander, etc.),
+a transaction dated ON the statement close day belongs to the NEXT invoice,
+not the invoice closing that day. Securo's original formula bucketed these
+transactions into the same-day close. This migration recomputes effective_date
+for every transaction on every credit card that has both statement_close_day
+and payment_due_day configured, using the corrected formula.
+
+Accounts without both cycle days stay untouched (effective_date already
+equals the transaction date for them — there's nothing to rebucket).
+"""
+
+import calendar
+from datetime import date
+
+from alembic import op
+from sqlalchemy import text
+
+revision = "030"
+down_revision = "029"
+branch_labels = None
+depends_on = None
+
+
+def _clamp_day(year: int, month: int, day: int) -> date:
+ last_day = calendar.monthrange(year, month)[1]
+ return date(year, month, min(day, last_day))
+
+
+def _compute_effective_date(tx_date: date, close_day: int, due_day: int) -> date:
+ # Mirror of app.services.credit_card_service.compute_effective_date
+ # (post-fix). Inlined so the migration doesn't depend on app code that
+ # may drift over time.
+ same_month_close = _clamp_day(tx_date.year, tx_date.month, close_day)
+ if same_month_close > tx_date:
+ cycle_end = same_month_close
+ elif tx_date.month == 12:
+ cycle_end = _clamp_day(tx_date.year + 1, 1, close_day)
+ else:
+ cycle_end = _clamp_day(tx_date.year, tx_date.month + 1, close_day)
+
+ same_month_due = _clamp_day(cycle_end.year, cycle_end.month, due_day)
+ if same_month_due > cycle_end:
+ return same_month_due
+ if cycle_end.month == 12:
+ return _clamp_day(cycle_end.year + 1, 1, due_day)
+ return _clamp_day(cycle_end.year, cycle_end.month + 1, due_day)
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+
+ accounts = conn.execute(
+ text(
+ """
+ SELECT id, statement_close_day, payment_due_day
+ FROM accounts
+ WHERE type = 'credit_card'
+ AND statement_close_day IS NOT NULL
+ AND payment_due_day IS NOT NULL
+ """
+ )
+ ).fetchall()
+
+ for acc_id, close_day, due_day in accounts:
+ rows = conn.execute(
+ text("SELECT id, date FROM transactions WHERE account_id = :acc_id"),
+ {"acc_id": str(acc_id)},
+ ).fetchall()
+
+ for tx_id, tx_date in rows:
+ new_effective = _compute_effective_date(tx_date, close_day, due_day)
+ conn.execute(
+ text(
+ "UPDATE transactions SET effective_date = :eff WHERE id = :tx_id"
+ ),
+ {"eff": new_effective, "tx_id": str(tx_id)},
+ )
+
+
+def downgrade() -> None:
+ # The old formula used `>=` instead of `>`. Restoring it precisely would
+ # require re-running that variant on every row. We skip the back-migration
+ # since effective_date is a derived/cached column — any future recompute
+ # (account edit or resync) will regenerate it from whichever formula is
+ # current. No schema changes to reverse.
+ pass
diff --git a/backend/app/services/credit_card_service.py b/backend/app/services/credit_card_service.py
index b347efd8..d888f8c2 100644
--- a/backend/app/services/credit_card_service.py
+++ b/backend/app/services/credit_card_service.py
@@ -99,7 +99,9 @@ def compute_effective_date(
helper computes that "effective" date:
1. Find the cycle the transaction belongs to: the next statement close
- date on or after tx_date.
+ date *strictly after* tx_date. Per Brazilian banking convention
+ (Nubank, Itaú, etc.), a transaction ON the close day belongs to the
+ next invoice, not the one closing that day.
2. The bill for that cycle is due on the next occurrence of payment_due_day
strictly after the close.
3. Return that bill's due date.
@@ -109,9 +111,9 @@ def compute_effective_date(
if not statement_close_day or not payment_due_day:
return tx_date
- # Step 1: find the cycle end — the first close day on or after tx_date.
+ # Step 1: find the cycle end — the first close day strictly after tx_date.
same_month_close = _clamp_day(tx_date.year, tx_date.month, statement_close_day)
- if same_month_close >= tx_date:
+ if same_month_close > tx_date:
cycle_end = same_month_close
else:
if tx_date.month == 12:
diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.py
index 15faed8f..68afe23b 100644
--- a/backend/tests/test_credit_card_accounting_mode.py
+++ b/backend/tests/test_credit_card_accounting_mode.py
@@ -49,9 +49,11 @@ class TestComputeEffectiveDate:
# Gold card: close 11, due 16. Purchase Apr 3 → bill closes Apr 11 → due Apr 16.
assert compute_effective_date(date(2026, 4, 3), 11, 16) == date(2026, 4, 16)
- def test_purchase_on_close_day_is_still_that_cycle(self):
- # Purchase ON the close day belongs to the cycle that closes that day.
- assert compute_effective_date(date(2026, 4, 11), 11, 16) == date(2026, 4, 16)
+ def test_purchase_on_close_day_rolls_to_next_cycle(self):
+ # Brazilian convention (Nubank, Itaú, etc.): a purchase ON the close
+ # day belongs to the NEXT invoice. Apr 11 close → next cycle closes
+ # May 11 → due May 16.
+ assert compute_effective_date(date(2026, 4, 11), 11, 16) == date(2026, 5, 16)
def test_purchase_day_after_close_rolls_to_next_cycle(self):
# Apr 12 is after Apr 11 close → next cycle closes May 11 → due May 16.
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index 2ca57786..8f01e76f 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -2,7 +2,7 @@ import { useState, useMemo, useEffect, useRef } from 'react'
import { useParams, Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query'
-import { format, addMonths, parseISO } from 'date-fns'
+import { format, addDays, addMonths, parseISO } from 'date-fns'
import { ptBR, enUS } from 'date-fns/locale'
import { accounts, transactions, categories as categoriesApi } from '@/lib/api'
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
@@ -75,21 +75,24 @@ function defaultCycleForCreditCard(
const nm = m === 11 ? 0 : m + 1
billDate = new Date(ny, nm, clampDue(ny, nm))
}
- // Step 2: find the cycle whose bill is `billDate` — its end is the most
- // recent close on or before billDate.
+ // Step 2: find the cycle whose bill is `billDate` — its close date is the
+ // most recent closeDay on or before billDate. The cycle's inclusive last
+ // day is one day before that close (per Brazilian convention).
const by = billDate.getFullYear()
const bm = billDate.getMonth()
const clampClose = (yy: number, mm: number) => Math.min(closeDay, daysInMonth(yy, mm))
const sameMonthClose = new Date(by, bm, clampClose(by, bm))
- let cycleEnd: Date
+ let cycleClose: Date
if (sameMonthClose.getTime() <= billDate.getTime()) {
- cycleEnd = sameMonthClose
+ cycleClose = sameMonthClose
} else {
const py = bm === 0 ? by - 1 : by
const pm = bm === 0 ? 11 : bm - 1
- cycleEnd = new Date(py, pm, clampClose(py, pm))
+ cycleClose = new Date(py, pm, clampClose(py, pm))
}
- return creditCardCycleBoundaries(closeDay, cycleEnd)
+ const refInsideCycle = new Date(cycleClose)
+ refInsideCycle.setDate(refInsideCycle.getDate() - 1)
+ return creditCardCycleBoundaries(closeDay, refInsideCycle)
}
/** Compute the bill due date for a credit card cycle whose end is `cycleEnd`.
@@ -142,7 +145,8 @@ function creditCardCycleLabel(
}
/** Return the [start, end] dates of the billing cycle that CONTAINS `reference`.
- * start = day after the previous cycle's close; end = next close on or after reference.
+ * 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. */
function creditCardCycleBoundaries(
closeDay: number | null | undefined,
@@ -161,22 +165,23 @@ function creditCardCycleBoundaries(
const y = ref0.getFullYear()
const m = ref0.getMonth()
const clamp = (yy: number, mm: number) => Math.min(closeDay, daysInMonth(yy, mm))
- // End of cycle = next close >= reference.
+ // The cycle containing `reference` ends the day before the next close date
+ // strictly after `reference`.
const thisMonthClose = new Date(y, m, clamp(y, m))
- let end: Date
- if (thisMonthClose.getTime() >= ref0.getTime()) {
- end = thisMonthClose
+ let nextClose: Date
+ if (thisMonthClose.getTime() > ref0.getTime()) {
+ nextClose = thisMonthClose
} else {
const nextY = m === 11 ? y + 1 : y
const nextM = m === 11 ? 0 : m + 1
- end = new Date(nextY, nextM, clamp(nextY, nextM))
+ nextClose = new Date(nextY, nextM, clamp(nextY, nextM))
}
- // Start = previous close + 1 day.
- const prevY = end.getMonth() === 0 ? end.getFullYear() - 1 : end.getFullYear()
- const prevM = end.getMonth() === 0 ? 11 : end.getMonth() - 1
- const prevClose = new Date(prevY, prevM, clamp(prevY, prevM))
- const start = new Date(prevClose)
- start.setDate(start.getDate() + 1)
+ const end = new Date(nextClose)
+ end.setDate(end.getDate() - 1)
+ // Start = the previous close day (the close day itself opens a new cycle).
+ const prevY = nextClose.getMonth() === 0 ? nextClose.getFullYear() - 1 : nextClose.getFullYear()
+ const prevM = nextClose.getMonth() === 0 ? 11 : nextClose.getMonth() - 1
+ const start = new Date(prevY, prevM, clamp(prevY, prevM))
return {
start: format(start, 'yyyy-MM-dd'),
end: format(end, 'yyyy-MM-dd'),
@@ -960,7 +965,9 @@ export default function AccountDetailPage() {
{t('accounts.statementCloseDay')}
</p>
<p className="text-sm sm:text-base font-semibold tabular-nums text-foreground">
- {account.statement_close_day && filterTo ? formatDateStr(filterTo, locale) : '—'}
+ {account.statement_close_day && filterTo
+ ? formatDateStr(format(addDays(parseISO(filterTo), 1), 'yyyy-MM-dd'), locale)
+ : '—'}
</p>
</div>
</div>