Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): stop a hand-picked date range from hiding billed transactions (#874)
Tássio Noronha5128db4899ef
diff --git a/frontend/src/lib/credit-card-cycle.test.ts b/frontend/src/lib/credit-card-cycle.test.tsnew file mode 100644index 00000000..0b269422--- /dev/null+++ b/frontend/src/lib/credit-card-cycle.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest'++import { closeDateForBill, isOpenCycleWindow } from './credit-card-cycle'++describe('closeDateForBill', () => {+ it('takes the close day of the due date month when it falls on or before the due date', () => {+ expect(closeDateForBill('2026-03-25', 16)).toBe('2026-03-16')+ })++ it('falls back to the previous month when the close day is after the due date', () => {+ expect(closeDateForBill('2026-03-05', 28)).toBe('2026-02-28')+ })++ it('clamps a close day that the month does not have', () => {+ expect(closeDateForBill('2026-03-05', 31)).toBe('2026-02-28')+ })++ it('crosses the year boundary', () => {+ expect(closeDateForBill('2026-01-05', 20)).toBe('2025-12-20')+ })++ it('returns the due date when no close day is configured', () => {+ expect(closeDateForBill('2026-03-25', null)).toBe('2026-03-25')+ })+})++describe('isOpenCycleWindow', () => {+ // Card closing on the 16th, bill due on the 25th. The newest bill is due+ // 2026-03-25, so the open cycle runs from 2026-03-16.+ const newestDue = '2026-03-25'+ const closeDay = 16++ it('accepts the cycle-math window the next-cycle arrow produces', () => {+ expect(isOpenCycleWindow('2026-03-16', newestDue, closeDay)).toBe(true)+ })++ it('accepts a window that starts inside the open cycle', () => {+ expect(isOpenCycleWindow('2026-03-20', newestDue, closeDay)).toBe(true)+ })++ it('rejects a hand-edited window that reaches back into billed history', () => {+ // Regression: picking 19/02 to 20/03 used to be read as the open cycle+ // because the end date matched no bill, and the resulting unbilled_only+ // hid every transaction the closed bills already carry.+ expect(isOpenCycleWindow('2026-02-19', newestDue, closeDay)).toBe(false)+ })++ it('rejects a window covering the whole history', () => {+ expect(isOpenCycleWindow('2025-01-01', newestDue, closeDay)).toBe(false)+ })++ it('rejects the day before the open cycle starts', () => {+ expect(isOpenCycleWindow('2026-03-15', newestDue, closeDay)).toBe(false)+ })++ it('handles a close day later in the month than the due day', () => {+ // Closes on the 28th, due on the 5th of the next month: the open cycle+ // starts 2026-02-28, before the newest bill's own due date.+ expect(isOpenCycleWindow('2026-02-28', '2026-03-05', 28)).toBe(true)+ expect(isOpenCycleWindow('2026-02-01', '2026-03-05', 28)).toBe(false)+ })++ it('falls back to the due date when the account has no close day', () => {+ expect(isOpenCycleWindow('2026-03-26', newestDue, null)).toBe(true)+ expect(isOpenCycleWindow('2026-03-20', newestDue, null)).toBe(false)+ })++ it('is false without a window start', () => {+ expect(isOpenCycleWindow('', newestDue, closeDay)).toBe(false)+ })+})diff --git a/frontend/src/lib/credit-card-cycle.ts b/frontend/src/lib/credit-card-cycle.tsnew file mode 100644index 00000000..e4fa7a5f--- /dev/null+++ b/frontend/src/lib/credit-card-cycle.ts@@ -0,0 +1,45 @@+import { format, parseISO } from 'date-fns'++/** 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. */+export 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')+}++/** True when `windowStart` falls inside the cycle that is still open, meaning+ * every transaction in the window is by definition unbilled.+ *+ * This is the question `unbilled_only` answers on the backend: it drops every+ * transaction already linked to a bill, which is right for the open cycle+ * (whose window overlaps the newest closed bill's range, so without it the+ * closed bill's charges would double-count) and wrong for anything else.+ *+ * The open cycle starts on the newest bill's close day, since the close day+ * itself opens the next cycle. A window starting before that covers billed+ * history, and the caller must not ask for unbilled transactions only, or the+ * history disappears.+ *+ * Both arguments are `yyyy-MM-dd`, which compares chronologically as a string.+ */+export function isOpenCycleWindow(+ windowStart: string,+ newestBillDueDate: string,+ closeDay: number | null | undefined,+): boolean {+ if (!windowStart) return false+ return windowStart >= closeDateForBill(newestBillDueDate, closeDay)+}diff --git a/frontend/src/pages/account-detail-cycle.test.tsx b/frontend/src/pages/account-detail-cycle.test.tsxnew file mode 100644index 00000000..ca3d2e5d--- /dev/null+++ b/frontend/src/pages/account-detail-cycle.test.tsx@@ -0,0 +1,174 @@+/**+ * The cycle window a credit card's date fields produce, and what it makes the+ * page ask the API for.+ *+ * `lib/credit-card-cycle.test.ts` covers the arithmetic. This covers the wiring,+ * which is where the bug actually lived: the page decided it was on the open+ * cycle whenever the window matched no bill, so touching a date field made it+ * request unbilled transactions only over a period that had already closed,+ * and the charges those bills carry disappeared from a window that had just+ * been made wider.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import AccountDetailPage from '@/pages/account-detail'+import { renderWithProviders } from '@/test/utils'++const api = vi.hoisted(() => ({+ accounts: {+ get: vi.fn(),+ bills: vi.fn(),+ summary: vi.fn(),+ list: vi.fn(),+ update: vi.fn(),+ },+ transactions: { list: vi.fn(), update: vi.fn(), delete: vi.fn(), create: vi.fn() },+ dashboard: { projectedTransactions: vi.fn() },+ categories: { list: vi.fn() },+ categoryGroups: { list: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ accounts: api.accounts,+ transactions: api.transactions,+ dashboard: api.dashboard,+ categories: api.categories,+ categoryGroups: api.categoryGroups,+}))++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value, privacyMode: false, MASK: '***' }),+}))++vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { preferences: { currency_display: 'BRL' } } }),+}))++vi.mock('@/contexts/workspace-context', () => ({+ useWorkspace: () => ({ canWrite: true }),+}))++// Closes on the 30th, bills due on the 10th. The newest bill is due+// 2026-05-10, so the cycle that is still open starts on 2026-04-30.+const account = {+ id: 'acc-1',+ name: 'Card',+ type: 'credit_card',+ currency: 'BRL',+ balance: -280,+ is_active: true,+ credit_limit: 5000,+ statement_close_day: 30,+ payment_due_day: 10,+}++const bills = [+ { id: 'bill-apr', account_id: 'acc-1', external_id: 'a', due_date: '2026-04-10', total_amount: 125, currency: 'BRL', minimum_payment: null },+ { id: 'bill-may', account_id: 'acc-1', external_id: 'b', due_date: '2026-05-10', total_amount: 280, currency: 'BRL', minimum_payment: null },+]++/** The cycle header. Matching on the month alone is ambiguous: the timeline+ * bar for the same cycle carries the same text. */+function cycleHeader() {+ return screen+ .getAllByRole('button')+ .find((b) => b.getAttribute('aria-haspopup') === 'dialog' && /\d{4}|-/.test(b.textContent ?? ''))!+}++/** Every `transactions.list` call the page has made, oldest first. */+function txCalls() {+ return api.transactions.list.mock.calls.map(([args]) => args as Record<string, unknown>)+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.setSystemTime(new Date('2026-09-08T12:00:00'))+ api.accounts.get.mockResolvedValue(account)+ api.accounts.bills.mockResolvedValue(bills)+ api.accounts.list.mockResolvedValue([account])+ api.accounts.summary.mockResolvedValue({+ monthly_income: 0, monthly_expenses: 0, projected_income: 0, projected_expenses: 0,+ })+ api.transactions.list.mockResolvedValue({ items: [], total: 0 })+ api.dashboard.projectedTransactions.mockResolvedValue([])+ api.categories.list.mockResolvedValue([])+ api.categoryGroups.list.mockResolvedValue([])+})++async function renderPage() {+ const rendered = renderWithProviders(<AccountDetailPage />, {+ route: '/accounts/acc-1',+ path: '/accounts/:id',+ })+ await waitFor(() => expect(api.transactions.list).toHaveBeenCalled())+ return rendered+}++describe('credit card cycle window', () => {+ it('asks for unbilled transactions only on the cycle that is still open', async () => {+ await renderPage()++ // No bill is due after today, so the page opens on the trailing cycle.+ // Excluding already-billed rows there is the whole point of the flag:+ // the window overlaps the newest closed bill's range.+ await waitFor(() => {+ const last = txCalls().at(-1)!+ expect(last.unbilled_only).toBe(true)+ expect(String(last.from) >= '2026-04-30').toBe(true)+ })+ })++ it('does not ask for unbilled transactions only on a bill cycle', async () => {+ const { user } = await renderPage()++ await user.click(await screen.findByTitle('Previous cycle'))++ await waitFor(() => {+ const last = txCalls().at(-1)!+ expect(last.bill_id).toBe('bill-may')+ expect(last.unbilled_only).toBeUndefined()+ })+ })++ it('does not ask for unbilled transactions only on a hand-picked range', async () => {+ const { user } = await renderPage()++ // Land on a real bill first, then move the end date off it. The window+ // still covers everything the bill cycle did, so nothing about the edit+ // may remove a transaction from the answer.+ await user.click(await screen.findByTitle('Previous cycle'))+ await waitFor(() => expect(txCalls().at(-1)!.bill_id).toBe('bill-may'))++ await user.click(cycleHeader())+ await user.click(await screen.findByRole('button', { name: '5/10/2026' }))+ await user.click(await screen.findByRole('button', { name: '15' }))++ await waitFor(() => {+ const last = txCalls().at(-1)!+ expect(last.to).toBe('2026-05-15')+ expect(last.bill_id).toBeUndefined()+ // The regression: this used to be `true`, and the R$280 bill's charges+ // vanished from a window five days wider than the one that showed them.+ expect(last.unbilled_only).toBeUndefined()+ })+ })++ it('names a hand-picked range by its own dates instead of a statement month', async () => {+ const { user } = await renderPage()++ await user.click(await screen.findByTitle('Previous cycle'))+ await user.click(cycleHeader())+ await user.click(await screen.findByRole('button', { name: '5/10/2026' }))+ await user.click(await screen.findByRole('button', { name: '15' }))++ // Before the fix this read "Jun 2026", naming the window after a bill it+ // has no claim to.+ await waitFor(() => expect(cycleHeader().textContent).toMatch(/11 Apr - 15 May/i))+ })+})diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex d802d771..f06a9c26 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -10,6 +10,7 @@ import { localDateString } from '@/lib/date-utils'import { applyTransactionToBalance, excludeMaterializedProjections, transactionAmountForBalance } from '@/lib/account-detail-utils'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { shouldShowPendingBadge } from '@/lib/transaction-status'+import { closeDateForBill, isOpenCycleWindow } from '@/lib/credit-card-cycle'import { toast } from 'sonner'import type { CreditCardBill, ProjectedTransaction, Transaction } from '@/types'import { Skeleton } from '@/components/ui/skeleton'@@ -157,31 +158,6 @@ function creditCardCycleLabel(return format(bill, 'MMM yyyy', { locale: dateFnsLocale })}-/** Return the [start, end] dates of the billing cycle that CONTAINS `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. */-/** 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,@@ -199,6 +175,10 @@ function rangeForBill(}+/** Return the [start, end] dates of the billing cycle that CONTAINS `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,reference: Date,@@ -260,6 +240,17 @@ function daysUntil(dateStr: string): number {return Math.round((target.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))}+/** Label a window that belongs to no bill and is not the open cycle, which is+ * what a hand-edited date range produces. Naming it after a bill month would+ * claim it is a statement it is not, so it says what it actually is. The year+ * only shows up when the range crosses one, to keep the header narrow. */+function cycleRangeLabel(from: string, to: string, i18nLanguage: string): string {+ const dfLocale = resolveDateFnsLocale(i18nLanguage)+ const pattern = from.slice(0, 4) === to.slice(0, 4) ? 'dd MMM' : "dd MMM ''yy"+ const at = (d: string) => format(parseISO(d + 'T00:00:00'), pattern, { locale: dfLocale })+ return `${at(from)} - ${at(to)}`+}+function utilizationColor(pct: number): string {if (pct >= 90) return 'bg-rose-500'if (pct >= 70) return 'bg-amber-400'@@ -316,11 +307,36 @@ export default function AccountDetailPage() {if (!billsAsc.length) return nullreturn 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-+ // True when the user is on the trailing in-progress cycle. 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+ //+ // Not matching a bill is necessary but nowhere near sufficient: any window+ // the user picks by hand misses the equality check above, and asking for+ // unbilled transactions over a period that already closed drops the charges+ // those bills carry. Widening a cycle by five days used to shrink its total,+ // which is the one thing a wider window must never do. So the window also+ // has to start inside the cycle that is still open, which is what the+ // next-cycle arrow produces and a hand-edited range over history does not.+ const isInProgressCycle = useMemo(() => {+ if (activeBill || !billsAsc.length) return false+ const newestBill = billsAsc[billsAsc.length - 1]+ return isOpenCycleWindow(filterFrom, newestBill.due_date, account?.statement_close_day)+ }, [activeBill, billsAsc, filterFrom, account?.statement_close_day])++ // A window this page computed, as opposed to one the user picked in the+ // date fields. Every cycle range here comes out of creditCardCycleBoundaries+ // (the arrows, the timeline bars and the initial default all route through+ // it), so asking it for the cycle containing this window's end hands the+ // window back when it is one of them. A card with no close day has no cycles+ // to compare against, so it keeps the label it has always had.+ const isCycleMathWindow = useMemo(() => {+ const closeDay = account?.statement_close_day+ if (!closeDay) return true+ if (!filterFrom || !filterTo) return false+ const cycle = creditCardCycleBoundaries(closeDay, parseISO(filterTo + 'T00:00:00'))+ return cycle.start === filterFrom && cycle.end === filterTo+ }, [account?.statement_close_day, filterFrom, filterTo])const [cycleSource, setCycleSource] = useState<{ account: typeof account; bills: typeof bills } | null>(null)if (!cycleSource || cycleSource.account !== account || cycleSource.bills !== bills) {@@ -930,7 +946,9 @@ export default function AccountDetailPage() {? format(parseISO(activeBill.due_date + 'T00:00:00'), 'MMM yyyy', {locale: resolveDateFnsLocale(i18n.resolvedLanguage ?? i18n.language),})- : creditCardCycleLabel(filterTo, account?.payment_due_day, i18n.language)}+ : isCycleMathWindow+ ? creditCardCycleLabel(filterTo, account?.payment_due_day, i18n.language)+ : cycleRangeLabel(filterFrom, filterTo, i18n.resolvedLanguage ?? i18n.language)}</button></PopoverTrigger><PopoverContent align="center" className="w-auto p-3 space-y-3">