Open-source personal finance manager. Self-hosted, privacy-first.
feat: add activity mode to the cash-flow transaction calendar (#485)
Danny Feliz768d1dee5fac
diff --git a/backend/app/schemas/transaction_calendar.py b/backend/app/schemas/transaction_calendar.pyindex 97510e48..784081e3 100644--- a/backend/app/schemas/transaction_calendar.py+++ b/backend/app/schemas/transaction_calendar.py@@ -32,9 +32,16 @@ class TransactionCalendarDay(BaseModel):date: datein_month: boolending_balance: float+ # Combined totals kept for backwards compatibility with existing consumers.income: float = 0.0expense: float = 0.0transfer_net: float = 0.0+ actual_income: float = 0.0+ actual_expense: float = 0.0+ actual_transfer_net: float = 0.0+ projected_income: float = 0.0+ projected_expense: float = 0.0+ projected_transfer_net: float = 0.0actual_count: int = 0projected_count: int = 0has_income: bool = Falsediff --git a/backend/app/services/transaction_calendar_service.py b/backend/app/services/transaction_calendar_service.pyindex 239b5e47..8d1fd237 100644--- a/backend/app/services/transaction_calendar_service.py+++ b/backend/app/services/transaction_calendar_service.py@@ -98,14 +98,18 @@ async def get_transaction_calendar(ignored = bool(tx.is_ignored or (tx.category and tx.category.is_ignored))if not ignored:if is_transfer or tx.source == "transfer":- day.transfer_net += await _signed_balance_delta_primary(session, tx, primary_currency)+ transfer_delta = await _signed_balance_delta_primary(session, tx, primary_currency)+ day.transfer_net += transfer_delta+ day.actual_transfer_net += transfer_deltaday.has_transfer = Trueelif tx.source != "opening_balance":if tx.type == "credit":day.income += amount_primary+ day.actual_income += amount_primaryday.has_income = Trueelse:day.expense += amount_primary+ day.actual_expense += amount_primaryday.has_expense = Trueday.actual_count += 1@@ -122,15 +126,23 @@ async def get_transaction_calendar(for item, signed_delta in projected_items:day = days[item.date]amount_primary = abs(signed_delta)- if item.is_transfer:- day.transfer_net += signed_delta- day.has_transfer = True- elif item.type == "credit":- day.income += amount_primary- day.has_income = True- else:- day.expense += amount_primary- day.has_expense = True+ # Ignored projections stay out of every aggregate, exactly like ignored+ # actuals: out of the activity buckets here, and out of the balance deltas+ # built in _project_recurring_items. A recurring the user chose to ignore+ # must not move a projected balance that will not move once it posts.+ if not item.is_ignored:+ if item.is_transfer:+ day.transfer_net += signed_delta+ day.projected_transfer_net += signed_delta+ day.has_transfer = True+ elif item.type == "credit":+ day.income += amount_primary+ day.projected_income += amount_primary+ day.has_income = True+ else:+ day.expense += amount_primary+ day.projected_expense += amount_primary+ day.has_expense = Trueday.projected_count += 1day.items.append(item)@@ -146,6 +158,12 @@ async def get_transaction_calendar(day.income = round(day.income, 2)day.expense = round(day.expense, 2)day.transfer_net = round(day.transfer_net, 2)+ day.actual_income = round(day.actual_income, 2)+ day.actual_expense = round(day.actual_expense, 2)+ day.actual_transfer_net = round(day.actual_transfer_net, 2)+ day.projected_income = round(day.projected_income, 2)+ day.projected_expense = round(day.projected_expense, 2)+ day.projected_transfer_net = round(day.projected_transfer_net, 2)day.items.sort(key=lambda item: (item.kind != "actual", item.type, item.description.lower()))response_days.append(day)@@ -325,6 +343,7 @@ async def _project_recurring_items()signed_delta = amount_primary if rec.type == "credit" else -amount_primaryis_transfer = bool(category and category.treat_as_transfer)+ is_ignored = bool(category and category.is_ignored)for occ_date in occurrences:item = TransactionCalendarItem(kind="projected",@@ -343,7 +362,13 @@ async def _project_recurring_items(category_color=category.color if category else None,source="recurring",is_transfer=is_transfer,+ is_ignored=is_ignored,)items.append((item, signed_delta))- deltas[occ_date] = deltas.get(occ_date, 0.0) + signed_delta+ # The row is still listed, but an ignored occurrence never moves the+ # projected balance: _daily_balance_deltas_by_date already leaves the+ # posted version out, so counting the projection here would promise a+ # balance that reverts the day the recurring actually posts.+ if not is_ignored:+ deltas[occ_date] = deltas.get(occ_date, 0.0) + signed_deltareturn items, deltasdiff --git a/backend/tests/test_transaction_calendar_service.py b/backend/tests/test_transaction_calendar_service.pyindex 57cd4f43..671190cc 100644--- a/backend/tests/test_transaction_calendar_service.py+++ b/backend/tests/test_transaction_calendar_service.py@@ -91,17 +91,23 @@ async def test_transaction_calendar_combines_actual_projected_and_balances(july_2 = next(day for day in calendar.days if day.date == date(2026, 7, 2))assert july_2.income == 1000.0+ assert july_2.actual_income == 1000.0+ assert july_2.projected_income == 0.0assert july_2.ending_balance == 1000.0assert july_2.actual_count == 1assert july_2.items[0].kind == "actual"july_5 = next(day for day in calendar.days if day.date == date(2026, 7, 5))assert july_5.expense == 200.0+ assert july_5.actual_expense == 200.0+ assert july_5.projected_expense == 0.0assert july_5.ending_balance == 800.0july_10 = next(day for day in calendar.days if day.date == date(2026, 7, 10))assert july_10.projected_count == 1assert july_10.expense == 300.0+ assert july_10.actual_expense == 0.0+ assert july_10.projected_expense == 300.0assert july_10.ending_balance == 500.0assert july_10.items[0].kind == "projected"assert july_10.items[0].recurring_id == rent.id@@ -145,6 +151,7 @@ async def test_transaction_calendar_respects_account_filter(july_3 = next(day for day in calendar.days if day.date == date(2026, 7, 3))assert july_3.income == 100.0+ assert july_3.actual_income == 100.0assert july_3.ending_balance == 100.0assert [item.description for item in july_3.items] == ["Kept income"]@@ -200,6 +207,8 @@ async def test_transaction_calendar_single_foreign_account_uses_primary_currencyassert july_1.ending_balance == 500.0july_2 = next(day for day in calendar.days if day.date == date(2026, 7, 2))assert july_2.expense == 50.0+ assert july_2.actual_expense == 50.0+ assert july_2.projected_expense == 0.0assert july_2.ending_balance == 450.0@@ -244,3 +253,244 @@ async def test_transaction_calendar_skips_closed_account_recurring_projections(assert july_10.projected_count == 0assert july_10.items == []assert july_10.ending_balance == 0.0+++async def test_transaction_calendar_splits_mixed_day_and_keeps_combined_totals(+ session: AsyncSession, test_user, test_workspace+):+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Person", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(account)+ await session.flush()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Freelance", amount=Decimal("400"),+ currency="BRL", date=date(2026, 7, 15), type="credit", source="manual",+ ),+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Market", amount=Decimal("120"),+ currency="BRL", date=date(2026, 7, 15), type="debit", source="manual",+ ),+ RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Streaming", amount=Decimal("50"),+ currency="BRL", type="debit", frequency="monthly",+ start_date=date(2026, 7, 15), next_occurrence=date(2026, 7, 15),+ ),+ RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Dividends", amount=Decimal("80"),+ currency="BRL", type="credit", frequency="monthly",+ start_date=date(2026, 7, 15), next_occurrence=date(2026, 7, 15),+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )++ july_15 = next(day for day in calendar.days if day.date == date(2026, 7, 15))+ assert july_15.actual_income == 400.0+ assert july_15.actual_expense == 120.0+ assert july_15.projected_income == 80.0+ assert july_15.projected_expense == 50.0+ # Combined totals stay the sum of both buckets for backwards compatibility.+ assert july_15.income == 480.0+ assert july_15.expense == 170.0+ assert july_15.ending_balance == 310.0+++async def test_transaction_calendar_transfer_buckets_stay_out_of_activity(+ session: AsyncSession, test_user, test_workspace+):+ checking = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Checking", type="checking", balance=Decimal("0"), currency="BRL",+ )+ savings = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Savings", type="savings", balance=Decimal("0"), currency="BRL",+ )+ transfer_category = Category(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Transfers", icon="repeat", color="#0ea5e9", treat_as_transfer=True,+ )+ session.add_all([checking, savings, transfer_category])+ await session.flush()++ pair_id = uuid.uuid4()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=checking.id, description="To savings", amount=Decimal("250"),+ currency="BRL", date=date(2026, 7, 8), type="debit", source="manual",+ transfer_pair_id=pair_id,+ ),+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=savings.id, description="From checking", amount=Decimal("250"),+ currency="BRL", date=date(2026, 7, 8), type="credit", source="manual",+ transfer_pair_id=pair_id,+ ),+ RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=checking.id, category_id=transfer_category.id,+ description="Auto savings", amount=Decimal("100"), currency="BRL",+ type="debit", frequency="monthly",+ start_date=date(2026, 7, 20), next_occurrence=date(2026, 7, 20),+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )++ july_8 = next(day for day in calendar.days if day.date == date(2026, 7, 8))+ assert july_8.actual_income == 0.0+ assert july_8.actual_expense == 0.0+ assert july_8.income == 0.0+ assert july_8.expense == 0.0+ assert july_8.actual_transfer_net == 0.0+ assert july_8.has_transfer is True+ # Both legs stay listed even though they never count as income/expense.+ assert len(july_8.items) == 2++ july_20 = next(day for day in calendar.days if day.date == date(2026, 7, 20))+ assert july_20.projected_expense == 0.0+ assert july_20.projected_transfer_net == -100.0+ assert july_20.transfer_net == -100.0+ assert july_20.has_transfer is True+ # Projected transfers keep moving the future balance.+ assert july_20.ending_balance == -100.0+++async def test_transaction_calendar_opening_balance_and_ignored_category(+ session: AsyncSession, test_user, test_workspace+):+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Person", type="checking", balance=Decimal("0"), currency="BRL",+ )+ ignored_category = Category(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Reimbursed", icon="undo", color="#64748b", is_ignored=True,+ )+ session.add_all([account, ignored_category])+ await session.flush()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Opening", amount=Decimal("900"),+ currency="BRL", date=date(2026, 7, 1), type="credit", source="opening_balance",+ ),+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, category_id=ignored_category.id,+ description="Work lunch", amount=Decimal("60"), currency="BRL",+ date=date(2026, 7, 4), type="debit", source="manual",+ ),+ RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, category_id=ignored_category.id,+ description="Reimbursed sub", amount=Decimal("30"), currency="BRL",+ type="debit", frequency="monthly",+ start_date=date(2026, 7, 12), next_occurrence=date(2026, 7, 12),+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )++ july_1 = next(day for day in calendar.days if day.date == date(2026, 7, 1))+ assert july_1.income == 0.0+ assert july_1.actual_income == 0.0+ assert july_1.ending_balance == 900.0++ july_4 = next(day for day in calendar.days if day.date == date(2026, 7, 4))+ assert july_4.expense == 0.0+ assert july_4.actual_expense == 0.0+ assert july_4.actual_count == 1+ # Ignored actuals are excluded from the balance deltas too (existing behavior).+ assert july_4.ending_balance == 900.0++ july_12 = next(day for day in calendar.days if day.date == date(2026, 7, 12))+ assert july_12.expense == 0.0+ assert july_12.projected_expense == 0.0+ assert july_12.projected_count == 1+ assert july_12.items[0].is_ignored is True+ # Still listed, but ignored means ignored: the projection is kept out of the+ # balance too, matching how the posted version is treated on July 4.+ assert july_12.ending_balance == 900.0+++async def test_transaction_calendar_ignored_projection_matches_posted_balance(+ session: AsyncSession, test_user, test_workspace+):+ """A projected ignored occurrence must land on the same balance its posted+ sibling produces. Otherwise the calendar promises a future balance the app+ reverts the moment the recurring becomes a real transaction."""+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Checking", type="checking", balance=Decimal("0"), currency="BRL",+ )+ ignored_category = Category(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Reimbursed", icon="undo", color="#64748b", is_ignored=True,+ )+ session.add_all([account, ignored_category])+ await session.flush()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Seed", amount=Decimal("1000"),+ currency="BRL", date=date(2026, 7, 1), type="credit", source="manual",+ ),+ # The July 6 occurrence already posted as a real transaction.+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, category_id=ignored_category.id,+ description="Reimbursed sub", amount=Decimal("30"), currency="BRL",+ date=date(2026, 7, 6), type="debit", source="manual",+ ),+ # The later ones have not, so they are still projected in the same grid.+ RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, category_id=ignored_category.id,+ description="Reimbursed sub", amount=Decimal("30"), currency="BRL",+ type="debit", frequency="weekly",+ start_date=date(2026, 7, 6), next_occurrence=date(2026, 7, 13),+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )+ by_date = {day.date: day for day in calendar.days}++ posted = by_date[date(2026, 7, 6)]+ assert posted.items[0].kind == "actual"+ assert posted.actual_count == 1++ # Every row stays visible on its day, whether posted or projected.+ for occurrence in (date(2026, 7, 13), date(2026, 7, 20), date(2026, 7, 27)):+ assert by_date[occurrence].projected_count == 1+ assert by_date[occurrence].items[0].is_ignored is True++ # None of them moves the balance, so each projection is one the app can+ # honour. Before this, the balance drifted down 30 per projected occurrence+ # and snapped back as each one posted.+ for day in (date(2026, 7, 6), date(2026, 7, 13), date(2026, 7, 20), date(2026, 7, 27)):+ assert by_date[day].ending_balance == 1000.0diff --git a/frontend/src/components/transaction-calendar-view.tsx b/frontend/src/components/transaction-calendar-view.tsxindex 07d7ea96..19959118 100644--- a/frontend/src/components/transaction-calendar-view.tsx+++ b/frontend/src/components/transaction-calendar-view.tsx@@ -1,10 +1,11 @@import { useEffect, useMemo, useState } from 'react'import type { ReactNode } from 'react'import { useTranslation } from 'react-i18next'-import { ArrowLeftRight, CalendarDays, CircleDot } from 'lucide-react'+import { ArrowLeftRight, CalendarDays, CircleDot, Minus } from 'lucide-react'import type { TransactionCalendarDay, TransactionCalendarItem, TransactionCalendarResponse } from '@/types'import { Skeleton } from '@/components/ui/skeleton'import { CategoryIcon } from '@/components/category-icon'+import { activityChartData, dayActivity } from '@/lib/calendar-activity'import { cn } from '@/lib/utils'function parseLocalDate(value: string) {@@ -48,13 +49,20 @@ function topItemsBySize(items: TransactionCalendarItem[], limit: number) {type CalendarMarkerTone = 'income' | 'expense' | 'transfer' | 'projected'type CalendarDensity = 'compact' | 'detailed'+type CalendarMetric = 'balance' | 'activity'const CALENDAR_DENSITY_STORAGE_KEY = 'securo.transactionCalendar.density'+const CALENDAR_METRIC_STORAGE_KEY = 'securo.transactionCalendar.metric'function readCalendarDensity(): CalendarDensity {if (typeof window === 'undefined') return 'compact'return window.localStorage.getItem(CALENDAR_DENSITY_STORAGE_KEY) === 'detailed' ? 'detailed' : 'compact'}+function readCalendarMetric(): CalendarMetric {+ if (typeof window === 'undefined') return 'balance'+ return window.localStorage.getItem(CALENDAR_METRIC_STORAGE_KEY) === 'activity' ? 'activity' : 'balance'+}+export function TransactionCalendarView({calendar,isLoading,@@ -75,11 +83,16 @@ export function TransactionCalendarView({onOpenTransaction: (id: string) => void}) {const [density, setDensity] = useState<CalendarDensity>(readCalendarDensity)+ const [metric, setMetric] = useState<CalendarMetric>(readCalendarMetric)useEffect(() => {window.localStorage.setItem(CALENDAR_DENSITY_STORAGE_KEY, density)}, [density])+ useEffect(() => {+ window.localStorage.setItem(CALENDAR_METRIC_STORAGE_KEY, metric)+ }, [metric])+useEffect(() => {if (!calendar?.days.length) returnif (selectedDate && calendar.days.some((day) => day.date === selectedDate)) return@@ -124,17 +137,31 @@ export function TransactionCalendarView({<section className="min-w-0 flex-1 bg-card rounded-xl border border-border shadow-sm overflow-hidden"><div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 border-b border-border sm:px-5"><CalendarLegend />- <CalendarDensityToggle value={density} onChange={setDensity} />+ <div className="flex flex-wrap items-center gap-2">+ <CalendarMetricToggle value={metric} onChange={setMetric} />+ <CalendarDensityToggle value={density} onChange={setDensity} />+ </div></div>- <BalanceTrend- days={calendar.days.filter((day) => day.in_month)}- currency={calendar.currency}- locale={locale}- mask={mask}- selectedDate={selectedDate}- onSelectDate={onSelectedDateChange}- />+ {metric === 'balance' ? (+ <BalanceTrend+ days={calendar.days.filter((day) => day.in_month)}+ currency={calendar.currency}+ locale={locale}+ mask={mask}+ selectedDate={selectedDate}+ onSelectDate={onSelectedDateChange}+ />+ ) : (+ <ActivityBars+ days={calendar.days.filter((day) => day.in_month)}+ currency={calendar.currency}+ locale={locale}+ mask={mask}+ selectedDate={selectedDate}+ onSelectDate={onSelectedDateChange}+ />+ )}<div className="hidden md:grid grid-cols-7 border-b border-border bg-muted/30">{weekDays.map((day) => (@@ -145,7 +172,7 @@ export function TransactionCalendarView({</div><div className="hidden md:grid grid-cols-7">- {calendar.days.map((day) => (+ {calendar.days.map((day, index) => (<DayCellkey={day.date}day={day}@@ -155,7 +182,15 @@ export function TransactionCalendarView({locale={locale}mask={mask}density={density}+ metric={metric}onSelect={() => onSelectedDateChange(day.date)}+ // The container clips the grid with rounded-xl + overflow-hidden, so the+ // two bottom corner cells carry a matching radius (12px outer − 1px+ // border) — otherwise their selection/focus ring loses its corner.+ className={cn(+ index === calendar.days.length - 7 && 'rounded-bl-[11px]',+ index === calendar.days.length - 1 && 'rounded-br-[11px]',+ )}/>))}</div>@@ -171,6 +206,7 @@ export function TransactionCalendarView({dateLocale={dateLocale}mask={mask}density={density}+ metric={metric}onSelect={() => onSelectedDateChange(day.date)}/>))}@@ -183,6 +219,7 @@ export function TransactionCalendarView({locale={locale}dateLocale={dateLocale}mask={mask}+ metric={metric}onOpenTransaction={onOpenTransaction}/></div>@@ -329,6 +366,188 @@ function BalanceTrend({)}+// The activity strip answers the other monthly question: how much came in and went+// out each day. Actual amounts are solid bars around a zero axis; projected amounts+// stack on top as dashed violet outlines so a forecasted bill never reads as settled.+function ActivityBars({+ days,+ currency,+ locale,+ mask,+ selectedDate,+ onSelectDate,+}: {+ days: TransactionCalendarDay[]+ currency: string+ locale: string+ mask: (value: string) => string+ selectedDate: string+ onSelectDate: (date: string) => void+}) {+ const { t } = useTranslation()+ const W = 1000+ const H = 120+ const data = useMemo(() => activityChartData(days), [days])++ if (days.length === 0) return null++ if (!data.hasActivity) {+ return (+ <div className="hidden border-b border-border px-4 pb-3 pt-2 sm:px-5 md:block">+ <p className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ {t('transactions.calendarActivityTrend')}+ </p>+ <p className="flex h-16 items-center justify-center text-sm text-muted-foreground">+ {t('transactions.calendarNoActivity')}+ </p>+ </div>+ )+ }++ const totalSpan = data.maxUp + data.maxDown || 1+ // Leave breathing room so the tallest bar never touches the strip edges.+ const scale = (H * 0.92) / totalSpan+ const axisY = data.maxUp * scale + H * 0.04+ const slot = W / data.days.length+ const barW = slot * 0.55++ const barHeight = (value: number) => (value > 0 ? Math.max(value * scale, 1.5) : 0)++ const tooltipFor = (activity: (typeof data.days)[number]) => {+ const amount = (value: number) => mask(compactCurrency(value, currency, locale))+ const actualParts: string[] = []+ if (activity.actualIncome > 0) actualParts.push(`${t('transactions.summaryIncome')} +${amount(activity.actualIncome)}`)+ if (activity.actualExpense > 0) actualParts.push(`${t('transactions.summaryExpenses')} −${amount(activity.actualExpense)}`)+ const projectedParts: string[] = []+ if (activity.projectedIncome > 0) projectedParts.push(`+${amount(activity.projectedIncome)}`)+ if (activity.projectedExpense > 0) projectedParts.push(`−${amount(activity.projectedExpense)}`)+ const segments = [+ String(displayDayNumber(activity.date)),+ actualParts.length > 0 ? actualParts.join(' · ') : t('transactions.calendarNoMovements'),+ ]+ if (projectedParts.length > 0) {+ segments.push(`${t('transactions.calendarProjected')} ${projectedParts.join(' · ')}`)+ }+ return segments.join(' · ')+ }++ return (+ <div className="hidden border-b border-border px-4 pb-3 pt-2 sm:px-5 md:block">+ <p className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ {t('transactions.calendarActivityTrend')}+ </p>+ <svg+ viewBox={`0 0 ${W} ${H}`}+ preserveAspectRatio="none"+ className="h-16 w-full overflow-visible"+ role="img"+ aria-label={t('transactions.calendarActivityTrend')}+ >+ <line+ x1="0"+ x2={W}+ y1={axisY}+ y2={axisY}+ stroke="currentColor"+ strokeWidth="1"+ vectorEffect="non-scaling-stroke"+ className="text-border"+ />++ {data.days.map((activity, i) => {+ const x = slot * i + (slot - barW) / 2+ const selected = activity.date === selectedDate+ const actualIncomeH = barHeight(activity.actualIncome)+ const actualExpenseH = barHeight(activity.actualExpense)+ const projectedIncomeH = barHeight(activity.projectedIncome)+ const projectedExpenseH = barHeight(activity.projectedExpense)+ return (+ <g key={activity.date}>+ {selected && (+ <line+ x1={slot * i + slot / 2}+ x2={slot * i + slot / 2}+ y1="0"+ y2={H}+ stroke="currentColor"+ strokeWidth="1"+ vectorEffect="non-scaling-stroke"+ className="text-primary/40"+ />+ )}+ {actualIncomeH > 0 && (+ <rect+ x={x}+ y={axisY - actualIncomeH}+ width={barW}+ height={actualIncomeH}+ className="fill-emerald-500/80 dark:fill-emerald-400/80"+ />+ )}+ {projectedIncomeH > 0 && (+ <rect+ x={x}+ y={axisY - actualIncomeH - projectedIncomeH}+ width={barW}+ height={projectedIncomeH}+ strokeWidth="1"+ strokeDasharray="3 2"+ vectorEffect="non-scaling-stroke"+ className="fill-violet-500/10 stroke-violet-500 dark:stroke-violet-400"+ />+ )}+ {actualExpenseH > 0 && (+ <rect+ x={x}+ y={axisY}+ width={barW}+ height={actualExpenseH}+ className="fill-rose-500/80 dark:fill-rose-400/80"+ />+ )}+ {projectedExpenseH > 0 && (+ <rect+ x={x}+ y={axisY + actualExpenseH}+ width={barW}+ height={projectedExpenseH}+ strokeWidth="1"+ strokeDasharray="3 2"+ vectorEffect="non-scaling-stroke"+ className="fill-violet-500/10 stroke-violet-500 dark:stroke-violet-400"+ />+ )}+ {/* Full-height hit target: bars can be a couple of pixels tall, so the+ clickable/focusable area is the whole day column, keyboard included. */}+ <rect+ x={slot * i}+ y="0"+ width={slot}+ height={H}+ fill="transparent"+ role="button"+ tabIndex={0}+ aria-label={tooltipFor(activity)}+ aria-pressed={selected}+ className="cursor-pointer focus:outline-none focus-visible:fill-primary/10"+ onClick={() => onSelectDate(activity.date)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ onSelectDate(activity.date)+ }+ }}+ >+ <title>{tooltipFor(activity)}</title>+ </rect>+ </g>+ )+ })}+ </svg>+ </div>+ )+}+function CalendarLegend() {const { t } = useTranslation()return (@@ -346,14 +565,19 @@ function CalendarLegend() {)}-function CalendarDensityToggle({ value, onChange }: { value: CalendarDensity; onChange: (value: CalendarDensity) => void }) {- const { t } = useTranslation()- const options: Array<{ value: CalendarDensity; label: string }> = [- { value: 'compact', label: t('transactions.calendarCompact') },- { value: 'detailed', label: t('transactions.calendarDetailed') },- ]+function SegmentedToggle<T extends string>({+ value,+ onChange,+ options,+ label,+}: {+ value: T+ onChange: (value: T) => void+ options: Array<{ value: T; label: string }>+ label: string+}) {return (- <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-muted/30 p-0.5 text-xs" aria-label={t('transactions.calendarDensity')}>+ <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-muted/30 p-0.5 text-xs" role="group" aria-label={label}>{options.map((option) => (<buttonkey={option.value}@@ -372,6 +596,36 @@ function CalendarDensityToggle({ value, onChange }: { value: CalendarDensity; on)}+function CalendarDensityToggle({ value, onChange }: { value: CalendarDensity; onChange: (value: CalendarDensity) => void }) {+ const { t } = useTranslation()+ return (+ <SegmentedToggle+ value={value}+ onChange={onChange}+ label={t('transactions.calendarDensity')}+ options={[+ { value: 'compact', label: t('transactions.calendarCompact') },+ { value: 'detailed', label: t('transactions.calendarDetailed') },+ ]}+ />+ )+}++function CalendarMetricToggle({ value, onChange }: { value: CalendarMetric; onChange: (value: CalendarMetric) => void }) {+ const { t } = useTranslation()+ return (+ <SegmentedToggle+ value={value}+ onChange={onChange}+ label={t('transactions.calendarMetric')}+ options={[+ { value: 'balance', label: t('transactions.calendarBalanceMode') },+ { value: 'activity', label: t('transactions.calendarActivityMode') },+ ]}+ />+ )+}+function LegendItem({ tone, label, children }: { tone: CalendarMarkerTone; label: string; children?: ReactNode }) {return (<span className="inline-flex items-center gap-1 whitespace-nowrap">@@ -389,7 +643,9 @@ function DayCell({locale,mask,density,+ metric,onSelect,+ className,}: {day: TransactionCalendarDayselected: boolean@@ -398,10 +654,14 @@ function DayCell({locale: stringmask: (value: string) => stringdensity: CalendarDensity+ metric: CalendarMetriconSelect: () => void+ className?: string}) {const { t } = useTranslation()- const isLowBalance = day.ending_balance < 0+ // The negative-balance warning belongs to the balance metric; activity mode has+ // no running balance to warn about.+ const isLowBalance = metric === 'balance' && day.ending_balance < 0const detailed = density === 'detailed'const previewItems = detailed ? topItemsBySize(day.items, 3) : []const moreCount = detailed ? Math.max(0, day.items.length - previewItems.length) : 0@@ -417,14 +677,18 @@ function DayCell({}}}className={cn(- 'border-r border-b border-border p-3 text-left transition-colors hover:bg-muted/30 focus:outline-none focus:ring-2 focus:ring-primary/40',+ // Column flex so a quiet day's marker can claim the leftover height and+ // sit in the middle of the cell instead of hanging under the date.+ 'flex flex-col border-r border-b border-border p-3 text-left transition-colors hover:bg-muted/30 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary/40',detailed ? 'min-h-44' : 'min-h-24',!day.in_month && 'bg-muted/20 text-muted-foreground',day.in_month && isLowBalance && 'bg-rose-50/60 dark:bg-rose-950/20',// Selection is a ring, not a fill, on low-balance days: tinting the cell// would hide the negative-balance warning exactly when the user opens it.- selected && 'z-10 ring-2 ring-primary/70',+ // Inset so the container's overflow-hidden never clips it on edge rows.+ selected && 'z-10 ring-2 ring-inset ring-primary/70',selected && !isLowBalance && 'bg-primary/5 dark:bg-primary/10',+ className,)}><div className="flex items-center justify-between gap-1">@@ -442,23 +706,27 @@ function DayCell({<CalendarBadges day={day} /></div>- {/* The balance is plain text on an ordinary day. Almost every day repeats- yesterday's number, so making all of them loud buries the days that matter.- Negative days keep the pill; the day it first turns negative is called out- in words above the grid rather than with an icon nobody can decode. */}- <div className="mt-3 flex items-center gap-1">- <p- title={mask(formatCurrency(day.ending_balance, currency, locale))}- className={cn(- 'whitespace-nowrap text-sm tabular-nums',- isLowBalance- ? 'rounded-full border border-rose-300 bg-rose-100 px-1.5 py-0.5 font-bold text-rose-700 dark:border-rose-500/50 dark:bg-rose-500/15 dark:text-rose-300'- : 'font-semibold text-muted-foreground',- )}- >- {mask(compactCurrency(day.ending_balance, currency, locale))}- </p>- </div>+ {metric === 'balance' ? (+ /* The balance is plain text on an ordinary day. Almost every day repeats+ yesterday's number, so making all of them loud buries the days that matter.+ Negative days keep the pill; the day it first turns negative is called out+ in words above the grid rather than with an icon nobody can decode. */+ <div className="mt-3 flex items-center gap-1">+ <p+ title={mask(formatCurrency(day.ending_balance, currency, locale))}+ className={cn(+ 'whitespace-nowrap text-sm tabular-nums',+ isLowBalance+ ? 'rounded-full border border-rose-300 bg-rose-100 px-1.5 py-0.5 font-bold text-rose-700 dark:border-rose-500/50 dark:bg-rose-500/15 dark:text-rose-300'+ : 'font-semibold text-muted-foreground',+ )}+ >+ {mask(compactCurrency(day.ending_balance, currency, locale))}+ </p>+ </div>+ ) : (+ <DayCellActivity day={day} currency={currency} locale={locale} mask={mask} />+ )}{detailed && previewItems.length > 0 && (<div className="mt-3 space-y-1.5 pr-1">@@ -506,9 +774,80 @@ function DayPreviewRow({ item, locale, mask }: { item: TransactionCalendarItem;)}+// Activity cells report what actually moved: green income and red expense, real+// amounts only. Projected amounts get a secondary violet line so a forecast never+// blends into settled money. A day with nothing at all gets a centred dash rather+// than a sentence: in a quiet month the same string repeated 30 times is noise,+// and the eye should land on the days that moved. A day whose only entry is a+// projection is not empty, so it shows the violet figure and no dash.+function DayCellActivity({+ day,+ currency,+ locale,+ mask,+ align = 'left',+}: {+ day: TransactionCalendarDay+ currency: string+ locale: string+ mask: (value: string) => string+ align?: 'left' | 'right'+}) {+ const { t } = useTranslation()+ const activity = dayActivity(day)+ const projectedParts = [+ activity.projectedIncome > 0 ? mask(`+${compactCurrency(activity.projectedIncome, currency, locale)}`) : null,+ activity.projectedExpense > 0 ? mask(`−${compactCurrency(activity.projectedExpense, currency, locale)}`) : null,+ ].filter(Boolean)++ if (!activity.hasActual && !activity.hasProjected) {+ return (+ <div+ className={cn(+ 'flex items-center text-muted-foreground/40',+ align === 'right' ? 'mt-0 justify-end' : 'flex-1 justify-center',+ )}+ >+ <Minus size={16} aria-hidden="true" />+ {/* The dash carries no meaning on its own, so the sentence stays for+ screen readers and keeps the string translated in every locale. */}+ <span className="sr-only">{t('transactions.calendarNoMovements')}</span>+ </div>+ )+ }++ return (+ <div className={cn('mt-3 space-y-0.5', align === 'right' && 'mt-0 text-right')}>+ {activity.hasActual && (+ <p className={cn('flex flex-wrap items-center gap-x-1.5 text-sm font-semibold tabular-nums', align === 'right' && 'justify-end')}>+ {activity.actualIncome > 0 && (+ <span className="text-emerald-600 dark:text-emerald-400">+ {mask(`+${compactCurrency(activity.actualIncome, currency, locale)}`)}+ </span>+ )}+ {activity.actualExpense > 0 && (+ <span className="text-rose-600 dark:text-rose-400">+ {mask(`−${compactCurrency(activity.actualExpense, currency, locale)}`)}+ </span>+ )}+ </p>+ )}+ {projectedParts.length > 0 && (+ <p+ title={t('transactions.calendarProjected')}+ className="text-[11px] font-semibold tabular-nums text-violet-600 dark:text-violet-300"+ >+ {projectedParts.join(' · ')}+ </p>+ )}+ </div>+ )+}+// Markers stay on one line beside the day number. A cell header is ~100px wide and the// date takes 28px, so the four badges are sized to fit the remainder rather than wrap-// onto a second row, which used to push the balance chip down.+// onto a second row, which used to push the balance chip down. They render the same+// in both metrics so a day always reads the same way regardless of the toggle.function CalendarBadges({ day }: { day: TransactionCalendarDay }) {const { t } = useTranslation()return (@@ -563,6 +902,7 @@ function MobileDayRow({dateLocale,mask,density,+ metric,onSelect,}: {day: TransactionCalendarDay@@ -572,10 +912,11 @@ function MobileDayRow({dateLocale: stringmask: (value: string) => stringdensity: CalendarDensity+ metric: CalendarMetriconSelect: () => void}) {const { t } = useTranslation()- const isLowBalance = day.ending_balance < 0+ const isLowBalance = metric === 'balance' && day.ending_balance < 0const previewItems = density === 'detailed' ? day.items.slice(0, 3) : []const moreCount = density === 'detailed' ? Math.max(0, day.items.length - previewItems.length) : 0return (@@ -597,10 +938,14 @@ function MobileDayRow({{t('transactions.calendarItemCount', { count: day.actual_count + day.projected_count })}</p></div>- <div className="text-right">- <p className={cn('text-sm font-bold tabular-nums', day.ending_balance < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400')}>- {mask(formatCurrency(day.ending_balance, currency, locale))}- </p>+ <div className="flex flex-col items-end gap-0.5 text-right">+ {metric === 'balance' ? (+ <p className={cn('text-sm font-bold tabular-nums', day.ending_balance < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400')}>+ {mask(formatCurrency(day.ending_balance, currency, locale))}+ </p>+ ) : (+ <DayCellActivity day={day} currency={currency} locale={locale} mask={mask} align="right" />+ )}<CalendarBadges day={day} /></div></div>@@ -631,6 +976,7 @@ function SelectedDayPanel({locale,dateLocale,mask,+ metric,onOpenTransaction,}: {day?: TransactionCalendarDay@@ -638,32 +984,96 @@ function SelectedDayPanel({locale: stringdateLocale: stringmask: (value: string) => string+ metric: CalendarMetriconOpenTransaction: (id: string) => void}) {const { t } = useTranslation()if (!day) return null+ const activity = dayActivity(day)+ const headline = metric === 'balance' ? day.ending_balance : activity.actualNet+ const headlineLabel = metric === 'balance'+ ? mask(formatCurrency(day.ending_balance, currency, locale))+ : mask(`${activity.actualNet >= 0 ? '+' : '−'}${formatCurrency(Math.abs(activity.actualNet), currency, locale)}`)return (<aside className="bg-card rounded-xl border border-border shadow-sm overflow-hidden md:sticky md:top-4 md:max-h-[calc(100vh-7rem)] md:w-[320px] md:shrink-0 md:self-start md:flex md:flex-col lg:w-[340px]"><div className="px-4 py-4 border-b border-border"><div className="flex items-end justify-between gap-3"><div className="min-w-0">- <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{t('transactions.calendarSelectedDay')}</p>+ <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {metric === 'balance' ? t('transactions.calendarSelectedDay') : t('transactions.calendarActualNet')}+ </p><h3 className="truncate text-lg font-bold text-foreground">{parseLocalDate(day.date).toLocaleDateString(dateLocale, { weekday: 'long', day: 'numeric', month: 'long' })}</h3></div><p- title={mask(formatCurrency(day.ending_balance, currency, locale))}+ title={headlineLabel}className={cn('shrink-0 text-right text-lg font-bold tabular-nums',- day.ending_balance < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400',+ headline < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400',)}>- {mask(formatCurrency(day.ending_balance, currency, locale))}+ {headlineLabel}</p></div></div>+ {metric === 'activity' && (+ <>+ <div className="space-y-2 border-b border-border px-4 py-3">+ <DayPanelRow+ label={t('transactions.summaryIncome')}+ value={mask(`+${formatCurrency(activity.actualIncome, currency, locale)}`)}+ amount={activity.actualIncome}+ />+ <DayPanelRow+ label={t('transactions.summaryExpenses')}+ value={mask(`−${formatCurrency(activity.actualExpense, currency, locale)}`)}+ amount={-activity.actualExpense}+ />+ {day.has_transfer && (+ <p className="flex items-center gap-1.5 pt-0.5 text-xs text-muted-foreground">+ <ArrowLeftRight size={12} className="shrink-0 text-sky-600 dark:text-sky-400" />+ {t('transactions.calendarTransfersExcluded')}+ </p>+ )}+ </div>++ {/* A second group of the same rows rather than a callout box. The+ divider and the violet section label already say these figures are+ forecasts, and the amounts keep the colour of their direction so+ they read the same way as the projected rows listed below. */}+ {activity.hasProjected && (+ <div className="space-y-2 border-b border-border px-4 py-3">+ <p className="text-xs font-semibold uppercase tracking-wide text-violet-600 dark:text-violet-400">+ {t('transactions.calendarProjected')}+ </p>+ {activity.projectedIncome > 0 && (+ <DayPanelRow+ label={t('transactions.summaryIncome')}+ value={mask(`+${formatCurrency(activity.projectedIncome, currency, locale)}`)}+ amount={activity.projectedIncome}+ />+ )}+ {activity.projectedExpense > 0 && (+ <DayPanelRow+ label={t('transactions.summaryExpenses')}+ value={mask(`−${formatCurrency(activity.projectedExpense, currency, locale)}`)}+ amount={-activity.projectedExpense}+ />+ )}+ {activity.projectedIncome > 0 && activity.projectedExpense > 0 && (+ <DayPanelRow+ label={t('transactions.summaryNet')}+ value={mask(`${activity.projectedNet >= 0 ? '+' : '−'}${formatCurrency(Math.abs(activity.projectedNet), currency, locale)}`)}+ amount={activity.projectedNet}+ />+ )}+ </div>+ )}+ </>+ )}+<div className="min-h-0 divide-y divide-border overflow-y-auto md:flex-1">{day.items.length === 0 ? (<p className="px-4 py-8 text-sm text-muted-foreground text-center">{t('transactions.calendarNoItems')}</p>@@ -683,6 +1093,24 @@ function SelectedDayPanel({)}+// One label/value line, the shape the rest of the panel and the page already use.+// `amount` only picks the colour, so the caller stays free to format the string.+function DayPanelRow({ label, value, amount }: { label: string; value: string; amount: number }) {+ return (+ <div className="flex items-center justify-between gap-3 text-sm">+ <span className="text-muted-foreground">{label}</span>+ <span+ className={cn(+ 'font-semibold tabular-nums',+ amount < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400',+ )}+ >+ {value}+ </span>+ </div>+ )+}+function CalendarItemRow({item,locale,diff --git a/frontend/src/lib/calendar-activity.test.ts b/frontend/src/lib/calendar-activity.test.tsnew file mode 100644index 00000000..f195af12--- /dev/null+++ b/frontend/src/lib/calendar-activity.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from 'vitest'++import type { TransactionCalendarDay } from '../types'+import { activityChartData, dayActivity } from './calendar-activity'++function day(overrides: Partial<TransactionCalendarDay>): TransactionCalendarDay {+ return {+ date: '2026-07-01',+ in_month: true,+ ending_balance: 0,+ income: 0,+ expense: 0,+ transfer_net: 0,+ actual_income: 0,+ actual_expense: 0,+ actual_transfer_net: 0,+ projected_income: 0,+ projected_expense: 0,+ projected_transfer_net: 0,+ actual_count: 0,+ projected_count: 0,+ has_income: false,+ has_expense: false,+ has_transfer: false,+ items: [],+ ...overrides,+ }+}++describe('dayActivity', () => {+ it('derives nets for a day with only actual activity', () => {+ const activity = dayActivity(day({ actual_income: 500, actual_expense: 120 }))+ expect(activity.actualNet).toBe(380)+ expect(activity.projectedNet).toBe(0)+ expect(activity.hasActual).toBe(true)+ expect(activity.hasProjected).toBe(false)+ })++ it('derives nets for a projected-only day', () => {+ const activity = dayActivity(day({ projected_income: 80, projected_expense: 50 }))+ expect(activity.actualNet).toBe(0)+ expect(activity.projectedNet).toBe(30)+ expect(activity.hasActual).toBe(false)+ expect(activity.hasProjected).toBe(true)+ })++ it('keeps actual and projected separate on a mixed day', () => {+ const activity = dayActivity(day({+ actual_income: 400, actual_expense: 100,+ projected_income: 200, projected_expense: 60,+ }))+ expect(activity.actualNet).toBe(300)+ expect(activity.projectedNet).toBe(140)+ expect(activity.hasActual).toBe(true)+ expect(activity.hasProjected).toBe(true)+ })++ it('treats a transfer-only day as no activity', () => {+ const activity = dayActivity(day({ actual_transfer_net: -250, has_transfer: true }))+ expect(activity.hasActual).toBe(false)+ expect(activity.hasProjected).toBe(false)+ expect(activity.actualNet).toBe(0)+ })++ it('handles zero amounts without flagging activity', () => {+ const activity = dayActivity(day({}))+ expect(activity.hasActual).toBe(false)+ expect(activity.actualNet).toBe(0)+ expect(activity.projectedNet).toBe(0)+ })++ it('tolerates responses without the split fields', () => {+ const legacy = day({ income: 100, expense: 40 })+ // Simulate an older payload where the split fields are absent.+ const bare = { ...legacy } as Record<string, unknown>+ delete bare.actual_income+ delete bare.actual_expense+ delete bare.projected_income+ delete bare.projected_expense+ const activity = dayActivity(bare as unknown as TransactionCalendarDay)+ expect(activity.actualNet).toBe(0)+ expect(activity.hasActual).toBe(false)+ })+})++describe('activityChartData', () => {+ it('scales to the combined actual+projected height per direction', () => {+ const data = activityChartData([+ day({ date: '2026-07-01', actual_income: 300, projected_income: 200 }),+ day({ date: '2026-07-02', actual_expense: 150, projected_expense: 100 }),+ day({ date: '2026-07-03', actual_income: 50 }),+ ])+ expect(data.maxUp).toBe(500)+ expect(data.maxDown).toBe(250)+ expect(data.hasActivity).toBe(true)+ expect(data.days).toHaveLength(3)+ })++ it('reports an empty month so the chart can show an empty state', () => {+ const data = activityChartData([+ day({ date: '2026-07-01' }),+ day({ date: '2026-07-02', actual_transfer_net: 90, has_transfer: true }),+ ])+ expect(data.maxUp).toBe(0)+ expect(data.maxDown).toBe(0)+ expect(data.hasActivity).toBe(false)+ })++ it('handles an empty day list', () => {+ const data = activityChartData([])+ expect(data.days).toEqual([])+ expect(data.hasActivity).toBe(false)+ })+})diff --git a/frontend/src/lib/calendar-activity.ts b/frontend/src/lib/calendar-activity.tsnew file mode 100644index 00000000..beb8e07c--- /dev/null+++ b/frontend/src/lib/calendar-activity.ts@@ -0,0 +1,56 @@+import type { TransactionCalendarDay } from '../types'++export interface CalendarDayActivity {+ date: string+ actualIncome: number+ actualExpense: number+ actualNet: number+ projectedIncome: number+ projectedExpense: number+ projectedNet: number+ hasActual: boolean+ hasProjected: boolean+}++export function dayActivity(day: TransactionCalendarDay): CalendarDayActivity {+ const actualIncome = day.actual_income ?? 0+ const actualExpense = day.actual_expense ?? 0+ const projectedIncome = day.projected_income ?? 0+ const projectedExpense = day.projected_expense ?? 0+ return {+ date: day.date,+ actualIncome,+ actualExpense,+ actualNet: actualIncome - actualExpense,+ projectedIncome,+ projectedExpense,+ projectedNet: projectedIncome - projectedExpense,+ hasActual: actualIncome > 0 || actualExpense > 0,+ hasProjected: projectedIncome > 0 || projectedExpense > 0,+ }+}++export interface ActivityChartData {+ days: CalendarDayActivity[]+ // Chart scale: projected amounts stack on top of the actual bar in each+ // direction, so the axis must fit the combined height.+ maxUp: number+ maxDown: number+ hasActivity: boolean+}++export function activityChartData(days: TransactionCalendarDay[]): ActivityChartData {+ const mapped = days.map(dayActivity)+ let maxUp = 0+ let maxDown = 0+ for (const day of mapped) {+ maxUp = Math.max(maxUp, day.actualIncome + day.projectedIncome)+ maxDown = Math.max(maxDown, day.actualExpense + day.projectedExpense)+ }+ return {+ days: mapped,+ maxUp,+ maxDown,+ hasActivity: maxUp > 0 || maxDown > 0,+ }+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex d2e83da7..21a5553c 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -510,7 +510,15 @@"calendarAddIncome": "Einnahme hinzufügen","calendarAddExpense": "Ausgabe hinzufügen","calendarSelectedDay": "Ausgewählter Tag",- "calendarNoItems": "Keine Transaktionen an diesem Tag"+ "calendarNoItems": "Keine Transaktionen an diesem Tag",+ "calendarMetric": "Daten",+ "calendarBalanceMode": "Saldo",+ "calendarActivityMode": "Aktivität",+ "calendarActivityTrend": "Tägliche Aktivität",+ "calendarNoActivity": "Keine Aktivität in diesem Monat",+ "calendarNoMovements": "Keine Bewegungen",+ "calendarActualNet": "Tatsächliches Netto",+ "calendarTransfersExcluded": "Umbuchungen zählen nicht als Einnahmen oder Ausgaben"},"accounts": {"title": "Konten",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex abab65c6..b0ac7a13 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -510,7 +510,15 @@"calendarAddIncome": "Add income","calendarAddExpense": "Add expense","calendarSelectedDay": "Selected day",- "calendarNoItems": "No transactions on this day"+ "calendarNoItems": "No transactions on this day",+ "calendarMetric": "Data",+ "calendarBalanceMode": "Balance",+ "calendarActivityMode": "Activity",+ "calendarActivityTrend": "Daily activity",+ "calendarNoActivity": "No activity this month",+ "calendarNoMovements": "No movements",+ "calendarActualNet": "Actual net",+ "calendarTransfersExcluded": "Transfers are not counted as income or expenses"},"accounts": {"title": "Accounts",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex bd79cf44..a11e72d6 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -510,7 +510,15 @@"calendarAddIncome": "Añadir ingreso","calendarAddExpense": "Añadir gasto","calendarSelectedDay": "Día seleccionado",- "calendarNoItems": "No hay transacciones en este día"+ "calendarNoItems": "No hay transacciones en este día",+ "calendarMetric": "Datos",+ "calendarBalanceMode": "Saldo",+ "calendarActivityMode": "Actividad",+ "calendarActivityTrend": "Actividad diaria",+ "calendarNoActivity": "Sin actividad este mes",+ "calendarNoMovements": "Sin movimientos",+ "calendarActualNet": "Neto real",+ "calendarTransfersExcluded": "Las transferencias no cuentan como ingresos ni gastos"},"accounts": {"title": "Cuentas",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex b5c0c2a0..47cd4fa5 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -510,7 +510,15 @@"calendarAddIncome": "Ajouter un revenu","calendarAddExpense": "Ajouter une dépense","calendarSelectedDay": "Jour sélectionné",- "calendarNoItems": "Aucune transaction ce jour-là"+ "calendarNoItems": "Aucune transaction ce jour-là",+ "calendarMetric": "Données",+ "calendarBalanceMode": "Solde",+ "calendarActivityMode": "Activité",+ "calendarActivityTrend": "Activité quotidienne",+ "calendarNoActivity": "Aucune activité ce mois-ci",+ "calendarNoMovements": "Aucun mouvement",+ "calendarActualNet": "Net réel",+ "calendarTransfersExcluded": "Les virements ne comptent pas comme revenus ou dépenses"},"accounts": {"title": "Comptes",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 5758aeea..a667ccea 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -510,7 +510,15 @@"calendarAddIncome": "Aggiungi entrata","calendarAddExpense": "Aggiungi spesa","calendarSelectedDay": "Giorno selezionato",- "calendarNoItems": "Nessuna transazione in questo giorno"+ "calendarNoItems": "Nessuna transazione in questo giorno",+ "calendarMetric": "Dati",+ "calendarBalanceMode": "Saldo",+ "calendarActivityMode": "Attività",+ "calendarActivityTrend": "Attività giornaliera",+ "calendarNoActivity": "Nessuna attività questo mese",+ "calendarNoMovements": "Nessun movimento",+ "calendarActualNet": "Netto effettivo",+ "calendarTransfersExcluded": "I trasferimenti non contano come entrate o spese"},"accounts": {"title": "Conti",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 63b462ff..bcee924c 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -537,7 +537,15 @@"calendarAddIncome": "Dodaj przychód","calendarAddExpense": "Dodaj wydatek","calendarSelectedDay": "Wybrany dzień",- "calendarNoItems": "Brak transakcji w tym dniu"+ "calendarNoItems": "Brak transakcji w tym dniu",+ "calendarMetric": "Dane",+ "calendarBalanceMode": "Saldo",+ "calendarActivityMode": "Aktywność",+ "calendarActivityTrend": "Dzienna aktywność",+ "calendarNoActivity": "Brak aktywności w tym miesiącu",+ "calendarNoMovements": "Brak operacji",+ "calendarActualNet": "Rzeczywiste netto",+ "calendarTransfersExcluded": "Transfery nie liczą się jako przychody ani wydatki"},"accounts": {"title": "Konta",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 3c6ef925..0bd5fbfb 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -510,7 +510,15 @@"calendarAddIncome": "Adicionar receita","calendarAddExpense": "Adicionar despesa","calendarSelectedDay": "Dia selecionado",- "calendarNoItems": "Nenhuma transação neste dia"+ "calendarNoItems": "Nenhuma transação neste dia",+ "calendarMetric": "Dados",+ "calendarBalanceMode": "Saldo",+ "calendarActivityMode": "Atividade",+ "calendarActivityTrend": "Atividade diária",+ "calendarNoActivity": "Sem atividade neste mês",+ "calendarNoMovements": "Sem movimentações",+ "calendarActualNet": "Líquido real",+ "calendarTransfersExcluded": "Transferências não contam como receitas ou despesas"},"accounts": {"title": "Contas",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 53676b2e..c8a047cd 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -507,6 +507,14 @@"calendarAddExpense": "Adicionar despesa","calendarSelectedDay": "Dia selecionado","calendarNoItems": "Nenhuma transação neste dia",+ "calendarMetric": "Dados",+ "calendarBalanceMode": "Saldo",+ "calendarActivityMode": "Atividade",+ "calendarActivityTrend": "Atividade diária",+ "calendarNoActivity": "Sem atividade neste mês",+ "calendarNoMovements": "Sem movimentos",+ "calendarActualNet": "Líquido real",+ "calendarTransfersExcluded": "As transferências não contam como receitas ou despesas","bulkAddTags": "Adicionar tags","bulkRemoveTags": "Remover tags","addTagsPlaceholder": "#tag…",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 0fc9a36a..06dab85c 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -510,7 +510,15 @@"calendarAddIncome": "Добавить доход","calendarAddExpense": "Добавить расход","calendarSelectedDay": "Выбранный день",- "calendarNoItems": "В этот день транзакций нет"+ "calendarNoItems": "В этот день транзакций нет",+ "calendarMetric": "Данные",+ "calendarBalanceMode": "Баланс",+ "calendarActivityMode": "Активность",+ "calendarActivityTrend": "Дневная активность",+ "calendarNoActivity": "В этом месяце нет активности",+ "calendarNoMovements": "Нет операций",+ "calendarActualNet": "Фактический итог",+ "calendarTransfersExcluded": "Переводы не учитываются как приход или расходы"},"accounts": {"title": "Счета",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 7508d930..44a9b812 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -510,7 +510,15 @@"calendarAddIncome": "Додати дохід","calendarAddExpense": "Додати витрату","calendarSelectedDay": "Вибраний день",- "calendarNoItems": "Немає транзакцій у цей день"+ "calendarNoItems": "Немає транзакцій у цей день",+ "calendarMetric": "Дані",+ "calendarBalanceMode": "Баланс",+ "calendarActivityMode": "Активність",+ "calendarActivityTrend": "Щоденна активність",+ "calendarNoActivity": "Цього місяця немає активності",+ "calendarNoMovements": "Немає операцій",+ "calendarActualNet": "Фактичний підсумок",+ "calendarTransfersExcluded": "Перекази не враховуються як надходження чи витрати"},"accounts": {"title": "Рахунки",diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex cb8521fa..fe58bc3a 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -482,9 +482,16 @@ export interface TransactionCalendarDay {date: stringin_month: booleanending_balance: number+ // Combined totals kept for backwards compatibility.income: numberexpense: numbertransfer_net: number+ actual_income: number+ actual_expense: number+ actual_transfer_net: number+ projected_income: number+ projected_expense: number+ projected_transfer_net: numberactual_count: numberprojected_count: numberhas_income: boolean