Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions client/src/components/analytics-module/Analytics.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,35 @@ describe('Analytics Projected mode', () => {
vi.useRealTimers()
})

it('scopes actual and projected totals and ignores unrelated missing exchange rates', () => {
render(<Analytics
accounts={[
{ ...accounts[0], type: 'cash' },
{ id: 'foreign', name: 'Foreign account', type: 'cash', balance: 300, currency: 'EUR' },
]}
transactions={[posted, { ...posted, id: 'foreign-posted', account_id: 'foreign', amount: 300 }]}
upcomingTransactions={[
upcoming('cash-upcoming', '2026-09-20'),
upcoming('foreign-upcoming', '2026-09-21', 50, { account_id: 'foreign' }),
upcoming('review', '2026-09-20', 20, { pending_kind: 'mcp_review' }),
]}
categories={[]}
/>)
const select = screen.getByRole('combobox', { name: 'Analytics account' })
fireEvent.change(select, { target: { value: 'cash' } })
expect(income()).toContain('+100')
fireEvent.click(screen.getByRole('button', { name: 'Projected (1)' }))
expect(income()).toContain('+110')
fireEvent.change(select, { target: { value: 'all' } })
expect(screen.getByRole('button', { name: 'Projected (2)' })).toBeInTheDocument()
expect(screen.getByText(/unavailable until exchange rates recover/)).toBeInTheDocument()
})

it('applies the chart range pill to the page filters and returns projected data to Actual in one update', () => {
localStorage.setItem('analytics-widget-visibility', JSON.stringify({ 'cash-balance-trend': true }))
const onFiltersChange = vi.fn()
render(<Analytics transactions={[posted]} upcomingTransactions={[upcoming('future', '2026-09-20')]} accounts={accounts} categories={[]}
filters={{ period: 'month', date: '2026-09-01', pinned: false, mode: 'projected', expenseCategory: 'all', incomeCategory: 'all', resolution: 'quarter' }} onFiltersChange={onFiltersChange} />)
filters={{ account: 'all', period: 'month', date: '2026-09-01', pinned: false, mode: 'projected', expenseCategory: 'all', incomeCategory: 'all', resolution: 'quarter' }} onFiltersChange={onFiltersChange} />)
fireEvent.click(within(screen.getByRole('group', { name: 'Cash balance range' })).getByRole('button', { name: '1Y' }))
expect(onFiltersChange).toHaveBeenCalledExactlyOnceWith({ period: 'year', mode: 'actual', resolution: 'default' }, false)
})
Expand Down Expand Up @@ -210,7 +234,7 @@ describe('Analytics Projected mode', () => {
{ id: 'september', account_id: 'cash', date: '2026-09-05', amount: -100, status: 'posted' },
]
const cash: Account = { id: 'cash', name: 'Cash', type: 'checking', balance: 1000, currency: 'HUF' }
const filters = (date: string) => ({ period: 'month' as const, date, pinned: false, mode: 'actual' as const, expenseCategory: 'all', incomeCategory: 'all', resolution: 'default' as const })
const filters = (date: string) => ({ account: 'all', period: 'month' as const, date, pinned: false, mode: 'actual' as const, expenseCategory: 'all', incomeCategory: 'all', resolution: 'default' as const })
const points = () => JSON.parse(screen.getByTestId('account-trend-cash').getAttribute('data-points')!)
const { rerender } = render(<Analytics accounts={[cash]} transactions={ledger} categories={[]} filters={filters('2026-09-01')} onFiltersChange={vi.fn()} />)
expect(points()).toHaveLength(15)
Expand Down
31 changes: 22 additions & 9 deletions client/src/components/analytics-module/Analytics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { FinanceDataBoundary } from '../common/FinanceDataStatus'
import type { useFinancialOutlookData } from '../../hooks/useFinancialOutlookData'
import { useState, useMemo, useEffect, useCallback } from 'react'
import { Card, CardContent } from '../common/card'
import { AccountFilterSelect } from '../common/AccountFilterSelect'
import { Button } from '../common/button'
import { Calendar, ChevronLeft, ChevronRight, SlidersHorizontal } from 'lucide-react'
import { loadWidgetVisibility, saveWidgetVisibility, type WidgetId } from './widgetConfig'
Expand Down Expand Up @@ -52,10 +53,10 @@ type AnalyticsProps = {
}

export function Analytics({
transactions,
upcomingTransactions = [],
transactions: allTransactions,
upcomingTransactions: allUpcomingTransactions = [],
categories,
accounts,
accounts: allAccounts,
masterCurrency = 'HUF',
exchangeRates = {},
loading = false,
Expand All @@ -68,13 +69,20 @@ export function Analytics({
}: AnalyticsProps) {
const [localFilters, setLocalFilters] = useState<AnalyticsFilters>(() => ({
period: 'month', date: format(startOfMonth(new Date()), 'yyyy-MM-dd'), pinned: false,
mode: 'actual', expenseCategory: 'all', incomeCategory: 'all', resolution: 'default',
account: 'all', mode: 'actual', expenseCategory: 'all', incomeCategory: 'all', resolution: 'default',
}))
const viewFilters = filters ?? localFilters
const changeFilters = useCallback((patch: Partial<AnalyticsFilters>, replace = false) => {
if (onFiltersChange) onFiltersChange(patch, replace)
else setLocalFilters(previous => ({ ...previous, ...patch }))
}, [onFiltersChange])
const accountFilter = viewFilters.account
const accounts = useMemo(() => accountFilter === 'all' ? allAccounts
: allAccounts.filter(account => account.id === accountFilter), [allAccounts, accountFilter])
const transactions = useMemo(() => accountFilter === 'all' ? allTransactions
: allTransactions.filter(tx => tx.account_id === accountFilter), [allTransactions, accountFilter])
const upcomingTransactions = useMemo(() => accountFilter === 'all' ? allUpcomingTransactions
: allUpcomingTransactions.filter(tx => tx.account_id === accountFilter), [allUpcomingTransactions, accountFilter])
const period = viewFilters.period
const projectionMode = viewFilters.mode
const selectedExpenseCategory = viewFilters.expenseCategory
Expand Down Expand Up @@ -217,11 +225,11 @@ export function Analytics({
)

const convertToHuf = useCallback((amount: number, accountId: string): number | null => {
const account = accounts.find(item => item.id === accountId)
const account = allAccounts.find(item => item.id === accountId)
if (!account) return null
if (account.currency === 'HUF') return amount
return convertCurrency(amount, account.currency, 'HUF', exchangeRates, masterCurrency).value
}, [accounts, exchangeRates, masterCurrency])
}, [allAccounts, exchangeRates, masterCurrency])

// Filter transactions by period (exclude investment accounts only)
const filteredTransactions = useMemo(() => {
Expand Down Expand Up @@ -909,6 +917,8 @@ export function Analytics({
*/}
<div className="sticky top-[76px] lg:top-0 z-40 w-full border-b border-border/70 bg-canvas py-2.5">
<div className="flex flex-wrap items-center gap-2">
<AccountFilterSelect accounts={allAccounts} value={accountFilter} onChange={account => changeFilters({ account })}
label="Analytics account" className="w-full min-[430px]:w-52" />
<div className="flex gap-1 p-1 rounded-xl bg-background/80 border border-border/70 shadow-inner w-full min-[430px]:w-auto">
{(Object.keys(periodLabels) as TimePeriod[]).map((p) => (
<button
Expand Down Expand Up @@ -995,7 +1005,9 @@ export function Analytics({
<Calendar className="h-6 w-6 text-muted-foreground" />
</div>
<p className="text-sm text-muted-foreground">No transactions for {period === 'allTime' ? 'all time' : periodDisplayLabel.toLowerCase()}</p>
<p className="text-xs text-muted-foreground/70 mt-1">Add some transactions to see analytics</p>
{accountFilter === 'all' ? <p className="text-xs text-muted-foreground/70 mt-1">Add some transactions to see analytics</p>
: <><p className="mt-1 text-xs text-muted-foreground">This account has no activity in the selected period.</p>
<Button variant="outline" size="sm" className="mt-3" onClick={() => changeFilters({ account: 'all' })}>Show all accounts</Button></>}
</div>
</CardContent>
</Card>
Expand Down Expand Up @@ -1093,6 +1105,7 @@ export function Analytics({

{show('ai-financial-forecast') && (
<FinanceDataBoundary label="AI Financial Forecast" datasets={outlook ? [{ label: 'Financial forecasts', status: outlook.status }] : []}>
{accountFilter !== 'all' && <p className="mb-2 text-sm text-muted-foreground">The saved forecast covers all accounts.</p>}
<FinancialOutlook
snapshot={selectedOutlook}
history={outlookHistory}
Expand All @@ -1101,8 +1114,8 @@ export function Analytics({
onSelect={setSelectedOutlookId}
onLoadMore={loadMoreOutlooks}
hasMore={Boolean(outlookNextCursor)}
transactions={transactions}
accounts={accounts}
transactions={allTransactions}
accounts={allAccounts}
convertToHuf={convertToHuf}
/>
</FinanceDataBoundary>
Expand Down
33 changes: 33 additions & 0 deletions client/src/components/common/AccountFilterSelect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Select } from './select'

type AccountOption = {
id: string
name: string
currency: string
type: string
archived_at?: number | null
}

export function AccountFilterSelect({ accounts, value, onChange, label, className, selectClassName }: {
accounts: AccountOption[]
value: string
onChange: (value: string) => void
label: string
className?: string
selectClassName?: string
}) {
const cashAccounts = accounts.filter(account => account.type === 'cash')
.sort((a, b) => Number(a.archived_at != null) - Number(b.archived_at != null) || a.name.localeCompare(b.name))

return <div className={className}>
<Select aria-label={label} value={value} onChange={event => onChange(event.target.value)} className={`truncate ${selectClassName ?? ''}`}>
<option value="all">All accounts</option>
{value !== 'all' && !cashAccounts.some(account => account.id === value) && (
<option value={value}>Selected account (unavailable)</option>
)}
{cashAccounts.map(account => <option key={account.id} value={account.id}>
{account.name} ({account.currency}){account.archived_at != null ? ' · Archived' : ''}
</option>)}
</Select>
</div>
}
16 changes: 10 additions & 6 deletions client/src/components/dashboard-module/TransactionCalendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ const dateKey = (date: Date) => format(date, 'yyyy-MM-dd')

export function TransactionCalendar({
transactions,
linkedTransactions = transactions,
accountFiltered = false,
accounts,
currentMonth,
privacyMode,
Expand All @@ -38,6 +40,8 @@ export function TransactionCalendar({
sortOrder,
}: {
transactions: Transaction[]
linkedTransactions?: Transaction[]
accountFiltered?: boolean
accounts: Account[]
currentMonth: Date
privacyMode: 'visible' | 'hidden'
Expand All @@ -58,7 +62,7 @@ export function TransactionCalendar({

const displayTransactions = useMemo(() => {
const all = transactions
const byId = new Map(all.map(tx => [tx.id, tx]))
const byId = new Map(linkedTransactions.map(tx => [tx.id, tx]))
const consumedIds = new Set<string>()

return all.flatMap(tx => {
Expand All @@ -75,13 +79,13 @@ export function TransactionCalendar({
return [tx]
}

const primary = tx.amount < 0 ? tx : related.amount < 0 ? related : tx.amount <= related.amount ? tx : related
const primary = accountFiltered ? tx : tx.amount < 0 ? tx : related.amount < 0 ? related : tx.amount <= related.amount ? tx : related
const secondary = primary.id === tx.id ? related : tx
consumedIds.add(primary.id)
consumedIds.add(secondary.id)
return [{ ...primary, relatedTx: secondary }]
})
}, [transactions])
}, [transactions, linkedTransactions, accountFiltered])

const transactionsByDay = useMemo(() => displayTransactions.reduce<Record<string, CalendarTransaction[]>>((days, tx) => {
const key = tx.date.slice(0, 10)
Expand Down Expand Up @@ -171,7 +175,7 @@ export function TransactionCalendar({

<div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_18rem]">
<div className="overflow-hidden rounded-xl border border-border/60 bg-background/20">
<div className="border-b border-border/60 px-3 py-2.5">
{!accountFiltered && <div className="border-b border-border/60 px-3 py-2.5">
<div className="mb-1 flex items-center gap-1.5 text-[10px] font-semibold tracking-wide text-muted-foreground"><TrendingUp className="h-3.5 w-3.5 text-success" />BALANCE TREND</div>
<div className="h-20 cursor-pointer sm:h-24" aria-label="Animated balance trend chart. Click a day to select it.">
{baseline === null ? <p className="text-xs text-muted-foreground">Balance trend unavailable: missing exchange rates.</p> : <ResponsiveContainer width="100%" height="100%">
Expand Down Expand Up @@ -220,7 +224,7 @@ export function TransactionCalendar({
</AreaChart>
</ResponsiveContainer>}
</div>
</div>
</div>}

<div className="grid grid-cols-7 border-b border-border/60 bg-secondary/30">
{['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map(day => <div key={day} className="py-2 text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground sm:text-[10px]">{day}</div>)}
Expand Down Expand Up @@ -280,7 +284,7 @@ export function TransactionCalendar({
<div className="max-h-[22rem] divide-y divide-border/60 overflow-y-auto">
{selectedTransactions.length ? selectedTransactions.map(tx => {
const transfer = !!tx.linked_transaction_id
const label = transfer ? `Transfer to ${tx.relatedTx ? getAccountName(tx.relatedTx.account_id) : 'account'}` : (tx.description || getCategoryName(tx.category_id))
const label = transfer ? `Transfer ${tx.amount < 0 || !accountFiltered ? 'to' : 'from'} ${tx.relatedTx ? getAccountName(tx.relatedTx.account_id) : 'account'}` : (tx.description || getCategoryName(tx.category_id))
return <div key={tx.id} className="flex items-center gap-2.5 p-3">
<div className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg text-sm ${transfer ? 'bg-primary/10 text-primary' : tx.amount >= 0 ? 'bg-success/10' : 'bg-secondary'}`}>{transfer ? <ArrowRightLeft className="h-4 w-4" /> : getCategoryIcon(tx.category_id)}</div>
<div className="min-w-0 flex-1"><div className="truncate text-xs font-medium">{label}</div><div className="truncate text-[10px] text-muted-foreground">{getAccountName(tx.account_id)} · {transfer ? 'Transfer' : getCategoryName(tx.category_id)}</div></div>
Expand Down
22 changes: 22 additions & 0 deletions client/src/components/dashboard-module/TransactionList.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,28 @@ function mockRates(rate = 0.2) {
}

describe('TransactionList redesigned transfers', () => {
it('filters the list and calendar by receiving account without losing the transfer pair', async () => {
const user = userEvent.setup()
renderTransfers({ transactions: [...postedTransfer,
{ id: 'other-expense', account_id: 'other', amount: -50, date: '2020-01-01', description: 'Other expense' },
] })
const filter = screen.getByRole('combobox', { name: 'Transaction account' })
expect(within(filter).getByRole('option', { name: 'Archived cash (HUF) · Archived' })).toBeInTheDocument()
await user.selectOptions(filter, 'destination')
expect(screen.queryByText('Other expense')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Edit transfer' })).toBeInTheDocument()
expect(screen.getByText('1 posted')).toBeInTheDocument()

await user.click(screen.getByRole('button', { name: 'Calendar', exact: true }))
expect(screen.getByText('Transfer from Savings')).toBeInTheDocument()
expect(screen.queryByText('Other expense')).not.toBeInTheDocument()

await user.selectOptions(filter, 'archived')
await user.click(screen.getByRole('button', { name: 'Show all accounts' }))
expect(filter).toHaveValue('all')
expect(screen.getByText('Other expense')).toBeInTheDocument()
})

it('previews posted edit deltas, preserves both native amounts when swapping, and reverts the full edit', async () => {
mockRates()
const user = userEvent.setup()
Expand Down
Loading
Loading