Open-source personal finance manager. Self-hosted, privacy-first.
feat: add month stepper to transactions page (closes #241) (#243)
Matheus Serpa8fadad5159c3
diff --git a/frontend/src/components/month-stepper.tsx b/frontend/src/components/month-stepper.tsxnew file mode 100644index 00000000..21d93aac--- /dev/null+++ b/frontend/src/components/month-stepper.tsx@@ -0,0 +1,49 @@+import { shiftMonth, monthLabel } from '@/lib/month-utils'++interface MonthStepperProps {+ /** Selected month as `"YYYY-MM"`. */+ value: string+ /** Called with the new `"YYYY-MM"` when the user steps to another month. */+ onChange: (yearMonth: string) => void+ /** BCP-47 locale for the month label (e.g. "pt-BR", "en-US"). */+ locale?: string+ /** Accessible labels for the prev/next buttons. */+ prevLabel?: string+ nextLabel?: string+}++/**+ * Compact month stepper: `‹ Month Year ›`. Stateless — it only renders the+ * given month and emits onChange. Wiring (URL/date-range/query) lives in the+ * parent so the stepper stays a single source of truth on top of existing filters.+ */+export function MonthStepper({ value, onChange, locale = 'pt-BR', prevLabel, nextLabel }: MonthStepperProps) {+ const label = monthLabel(value, locale).replace(/^\w/, (c) => c.toUpperCase())+ return (+ <div className="flex items-center gap-1">+ <button+ type="button"+ aria-label={prevLabel}+ className="h-8 w-8 flex items-center justify-center rounded-lg border border-border bg-card text-muted-foreground hover:text-foreground transition-all text-base"+ onClick={() => onChange(shiftMonth(value, -1))}+ >+ ‹+ </button>+ <span+ aria-live="polite"+ aria-atomic="true"+ className="inline-flex items-center justify-center border border-border rounded-lg px-3 py-1.5 text-sm bg-card text-foreground min-w-[160px]"+ >+ {label}+ </span>+ <button+ type="button"+ aria-label={nextLabel}+ className="h-8 w-8 flex items-center justify-center rounded-lg border border-border bg-card text-muted-foreground hover:text-foreground transition-all text-base"+ onClick={() => onChange(shiftMonth(value, 1))}+ >+ ›+ </button>+ </div>+ )+}diff --git a/frontend/src/lib/month-utils.ts b/frontend/src/lib/month-utils.tsnew file mode 100644index 00000000..8b4d9fe7--- /dev/null+++ b/frontend/src/lib/month-utils.ts@@ -0,0 +1,52 @@+/**+ * Month navigation helpers shared by the dashboard and the transactions page.+ *+ * Months are represented as `"YYYY-MM"` strings. Day ranges are emitted as+ * `"YYYY-MM-DD"` strings WITHOUT a time component, matching the date-range+ * filter and the `?from`/`?to` URL params (which are timezone-naive).+ */++/** Current month as `"YYYY-MM"` (browser local time). */+export function currentMonth(): string {+ const now = new Date()+ return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`+}++/** Shift a `"YYYY-MM"` month by `delta` months (handles year overflow). */+export function shiftMonth(yearMonth: string, delta: number): string {+ const [y, m] = yearMonth.split('-').map(Number)+ const d = new Date(y, m - 1 + delta, 1)+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`+}++/** Last day-of-month number for a `"YYYY-MM"` month (28–31, leap-year aware). */+export function monthLastDay(yearMonth: string): number {+ const [y, m] = yearMonth.split('-').map(Number)+ return new Date(y, m, 0).getDate()+}++/** First/last day of a `"YYYY-MM"` month as `"YYYY-MM-DD"` strings. */+export function monthRange(yearMonth: string): { from: string; to: string } {+ return {+ from: `${yearMonth}-01`,+ to: `${yearMonth}-${String(monthLastDay(yearMonth)).padStart(2, '0')}`,+ }+}++/** Localized label for a `"YYYY-MM"` month, e.g. "Maio de 2026" / "May 2026". */+export function monthLabel(yearMonth: string, locale = 'pt-BR'): string {+ const [y, m] = yearMonth.split('-').map(Number)+ return new Date(y, m - 1, 2).toLocaleDateString(locale, { month: 'long', year: 'numeric' })+}++/**+ * If a `from`/`to` pair exactly spans one full calendar month, return that+ * month as `"YYYY-MM"`. Otherwise return null (custom range / no filter).+ * Lets the stepper reflect the active date-range filter as a single month.+ */+export function monthFromRange(from: string | null | undefined, to: string | null | undefined): string | null {+ if (!from || !to) return null+ const ym = from.slice(0, 7)+ const expected = monthRange(ym)+ return from === expected.from && to === expected.to ? ym : null+}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex f738c3b2..7e50e7fc 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -222,6 +222,8 @@"transactions": {"title": "Transactions","section": "Financial",+ "monthPrevious": "Previous month",+ "monthNext": "Next month","description": "Description","amount": "Amount","status": "Status",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex a4c9cd15..61a39388 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -222,6 +222,8 @@"transactions": {"title": "Transações","section": "Financeiro",+ "monthPrevious": "Mês anterior",+ "monthNext": "Próximo mês","description": "Descrição","amount": "Valor","status": "Status",diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex 515a0982..363b7335 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -1,5 +1,6 @@import { useState, useEffect, useMemo } from 'react'import { getAccountName } from '@/lib/account-utils'+import { currentMonth, shiftMonth, monthLastDay, monthLabel, monthRange } from '@/lib/month-utils'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { format } from 'date-fns'@@ -42,26 +43,6 @@ function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}-function currentMonth() {- const now = new Date()- return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`-}--function shiftMonth(yearMonth: string, delta: number) {- const [y, m] = yearMonth.split('-').map(Number)- const d = new Date(y, m - 1 + delta, 1)- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`-}--function monthLastDay(yearMonth: string) {- const [y, m] = yearMonth.split('-').map(Number)- return new Date(y, m, 0).getDate()-}--function monthLabel(yearMonth: string, locale = 'pt-BR') {- const [y, m] = yearMonth.split('-').map(Number)- return new Date(y, m - 1, 2).toLocaleDateString(locale, { month: 'long', year: 'numeric' })-}function formatDate(dateStr: string, locale = 'pt-BR') {return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale)@@ -91,9 +72,8 @@ export default function DashboardPage() {const [headerCalOpen, setHeaderCalOpen] = useState(false)const [hoveredDay, setHoveredDay] = useState<number | null>(null)const dateFnsLocale = i18n.language === 'pt-BR' ? ptBR : enUS- const monthParam = `${selectedMonth}-01`- const monthStart = `${selectedMonth}-01`- const monthEnd = `${selectedMonth}-${String(monthLastDay(selectedMonth)).padStart(2, '0')}`+ const { from: monthStart, to: monthEnd } = monthRange(selectedMonth)+ const monthParam = monthStartconst monthLabelStr = monthLabel(selectedMonth, locale)const handleMonthChange = (newMonth: string) => {@@ -120,8 +100,8 @@ export default function DashboardPage() {const { data: currentMonthTxs, isLoading: currentTxLoading } = useQuery({queryKey: ['transactions', 'cumulative', selectedMonth],queryFn: () => transactions.list({- from: `${selectedMonth}-01`,- to: `${selectedMonth}-${String(monthLastDay(selectedMonth)).padStart(2, '0')}`,+ from: monthStart,+ to: monthEnd,limit: 500,exclude_transfers: true,}),diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 31297dbb..15ea6d62 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -1,6 +1,8 @@import { useState, useMemo, useEffect, useRef } from 'react'import { useRegisterPageChatContext } from '@/lib/page-chat-context'import { getAccountName } from '@/lib/account-utils'+import { currentMonth, monthRange, monthFromRange } from '@/lib/month-utils'+import { MonthStepper } from '@/components/month-stepper'import { useNavigate, useSearchParams } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'@@ -76,8 +78,28 @@ export default function TransactionsPage() {return initial ? [initial] : []})const [filterUncategorized, setFilterUncategorized] = useState<boolean>(false)- const [filterFrom, setFilterFrom] = useState<string>('')- const [filterTo, setFilterTo] = useState<string>('')+ // Seed the date range from the URL, or default to the current month on first+ // open (no ?from/?to). Done in the initializer so it survives effect re-runs+ // (e.g. React StrictMode's double-invoke in development).+ const [filterFrom, setFilterFrom] = useState<string>(() => {+ const f = searchParams.get('from')+ const t = searchParams.get('to')+ return f || t ? (f ?? '') : monthRange(currentMonth()).from+ })+ const [filterTo, setFilterTo] = useState<string>(() => {+ const f = searchParams.get('from')+ const t = searchParams.get('to')+ return f || t ? (t ?? '') : monthRange(currentMonth()).to+ })+ // Month reflected by the stepper: the active range when it spans exactly one+ // full month, otherwise the current month (custom ranges still navigable).+ const steppedMonth = monthFromRange(filterFrom, filterTo) ?? currentMonth()+ const handleMonthChange = (ym: string) => {+ const { from, to } = monthRange(ym)+ setFilterFrom(from)+ setFilterTo(to)+ setPage(1)+ }const [searchInput, setSearchInput] = useState(() => searchParams.get('q') ?? '')const [searchQuery, setSearchQuery] = useState(() => searchParams.get('q') ?? '')const [dialogOpen, setDialogOpen] = useState(false)@@ -137,11 +159,22 @@ export default function TransactionsPage() {const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)const highlightId = searchParams.get('highlight')const highlightedRowRef = useRef<HTMLTableRowElement | null>(null)+ // Last URL query we synced from, to tell a genuine navigation apart from the+ // initial mount (and from StrictMode's double-invoke, which repeats the same+ // value). Starts null so the first run is recognized as the initial mount.+ const prevSearchRef = useRef<string | null>(null)// Sync state from URL when navigating (e.g. from the command palette) while// the page is already mounted. Typing in the search box does not touch the// URL, so this effect only fires on genuine navigation events.useEffect(() => {+ const search = searchParams.toString()+ // Skip re-runs with an unchanged query (e.g. StrictMode's second mount),+ // so they can't override the initial current-month default.+ if (prevSearchRef.current === search) return+ const isInitial = prevSearchRef.current === null+ prevSearchRef.current = search+const nextQ = searchParams.get('q') ?? ''setSearchInput(nextQ)setSearchQuery(nextQ)@@ -155,8 +188,18 @@ export default function TransactionsPage() {setFilterUncategorized(searchParams.get('uncategorized') === '1');const accounts = searchParams.get('account_id');setFilterAccountIds(accounts ? accounts.split(',') : []);- setFilterFrom(searchParams.get('from') ?? '');- setFilterTo(searchParams.get('to') ?? '');+ const urlFrom = searchParams.get('from')+ const urlTo = searchParams.get('to')+ if (urlFrom || urlTo) {+ // Explicit range in the URL (shared/bookmarked link) wins.+ setFilterFrom(urlFrom ?? '')+ setFilterTo(urlTo ?? '')+ } else if (!isInitial) {+ // A genuine navigation cleared the range (e.g. Clear filters): show all.+ // On the initial mount we keep the current-month default seeded above.+ setFilterFrom('')+ setFilterTo('')+ }setFilterMinAmount(searchParams.get('min_amount') ?? '');setFilterMaxAmount(searchParams.get('max_amount') ?? '');setPage(1)@@ -955,6 +998,13 @@ export default function TransactionsPage() {title={t('transactions.title')}action={<div className="flex items-center gap-2">+ <MonthStepper+ value={steppedMonth}+ onChange={handleMonthChange}+ locale={i18n.language === 'en' ? 'en-US' : i18n.language}+ prevLabel={t('transactions.monthPrevious')}+ nextLabel={t('transactions.monthNext')}+ /><TransactionsColumnPicker state={grid} /><Buttonvariant="outline"