feat(panel): harcanabilir ve grup harcama grafikleri

- Günlük / Haftalık / Aylık sekmeli iki çizgi grafik (Recharts, ayrı parça olarak yüklenir)
- Kümülatif harcanabilir vs gerçekleşen; 4 grup (+ isteğe bağlı harcanabilir çizgisi)
- Dönem istatistiklerine grup kırılımı (spent_by_group)
- Grafik altında metin özeti, koyu tema uyumlu renkler

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 00:14:55 +03:00
parent 64c185ab96
commit 191c3e6db5
20 changed files with 952 additions and 27 deletions
+34
View File
@@ -0,0 +1,34 @@
import { cn } from '@/lib/utils'
/** Tek seçimlik düğme grubu (ör. Haftalık / Aylık). Her düğme ≥ 44 px yüksek. */
export function Segmented<T extends string>({
label,
value,
options,
onChange,
}: {
/** Ekran okuyucu için grup adı */
label: string
value: T
options: readonly { value: T; label: string }[]
onChange: (value: T) => void
}) {
return (
<div role="group" aria-label={label} className="flex rounded-lg border p-0.5">
{options.map((o) => (
<button
key={o.value}
type="button"
aria-pressed={value === o.value}
onClick={() => onChange(o.value)}
className={cn(
'min-h-11 rounded-md px-3 text-sm font-medium sm:px-4',
value === o.value ? 'bg-primary text-primary-foreground' : 'hover:bg-muted',
)}
>
{o.label}
</button>
))}
</div>
)
}
+264
View File
@@ -0,0 +1,264 @@
import { useState, type ReactNode } from 'react'
import {
CartesianGrid,
Legend,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts'
import { PageError } from '@/components/page'
import { Segmented } from '@/components/segmented'
import { Skeleton } from '@/components/skeleton'
import {
dailySeries,
lastPoint,
monthlySeries,
weeklySeries,
type ChartPoint,
type ChartRange,
} from '@/lib/charts'
import { formatCompact, formatMoney, toIsoDate } from '@/lib/format'
import { GROUPS } from '@/lib/groups'
import { useDaily, useStats } from '@/lib/periods'
import { t } from '@/lib/strings'
import { cn } from '@/lib/utils'
import type { Period } from '@/types/Period'
const s = t.charts
/**
* Renkler CSS değişkenlerinden → açık/koyu tema kendiliğinden. Ham `:root` değişkenleri
* (`--needs`, `--primary`…) kullanılır: `@theme inline` olduğundan `--color-*` derlenmiş
* CSS'te ancak bir yerde kullanılmışsa bulunur.
*/
const color = {
plan: 'var(--muted-foreground)',
spent: 'var(--primary)',
grid: 'var(--border)',
axis: 'var(--muted-foreground)',
}
/** Lejant ve ipucunda sabit sıra (Recharts varsayılanı alfabetik): harcanabilir, harcanan, 4 grup */
const ORDER = ['plan', 'spent', ...GROUPS.map((g) => g.code)]
/** Nokta: içi kart renginde (koyu temada beyaz nokta olmasın), kenarı çizgi renginde */
const dot = { r: 3, strokeWidth: 2, fill: 'var(--card)' }
const byOrder = (item: { dataKey?: unknown }) => ORDER.indexOf(String(item.dataKey))
/**
* Panel grafikleri (Recharts, ayrı parça olarak yüklenir):
* 1) harcanabilir vs gerçekleşen, 2) 4 grup + harcanabilir. Günlük / Haftalık / Aylık.
*/
export default function DashboardCharts({
period,
spendable,
}: {
period: Period
spendable: number
}) {
const [range, setRange] = useState<ChartRange>('daily')
const [today] = useState(() => toIsoDate(new Date()))
// Harcanabilir çizgisi grup çizgilerini sıfıra ezer (ölçek) → isteğe bağlı
const [showPlan, setShowPlan] = useState(false)
const daily = useDaily(period.id)
const stats = useStats()
const q = range === 'monthly' ? stats : daily
let points: ChartPoint[] | undefined
if (range === 'monthly') points = stats.data && monthlySeries(stats.data.periods)
else if (daily.data)
points =
range === 'daily'
? dailySeries(daily.data, spendable, today)
: weeklySeries(daily.data, period.weeks, spendable, today)
return (
<section aria-labelledby="charts-title" className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 id="charts-title" className="font-semibold">
<span aria-hidden>📈</span> {s.title}
</h2>
<Segmented
label={s.title}
value={range}
onChange={setRange}
options={[
{ value: 'daily', label: s.daily },
{ value: 'weekly', label: s.weekly },
{ value: 'monthly', label: s.monthly },
]}
/>
</div>
{q.isError ? (
<PageError message={q.error.message} onRetry={q.refetch} />
) : !points ? (
<div className="grid gap-4 lg:grid-cols-2">
<Skeleton className="h-80" />
<Skeleton className="h-80" />
</div>
) : (
<div className="grid gap-4 lg:grid-cols-2">
<ChartCard
title={range === 'monthly' ? s.planTitleMonthly : s.planTitle}
summary={planSummary(points, range)}
>
<Chart points={points} dots={range !== 'daily'}>
<Line
dataKey="plan"
name={s.plan}
stroke={color.plan}
strokeDasharray="6 4"
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
<Line
dataKey="spent"
name={s.spent}
stroke={color.spent}
strokeWidth={3}
dot={range !== 'daily' && dot}
isAnimationActive={false}
/>
</Chart>
</ChartCard>
<ChartCard
title={s.groupsTitle}
summary={groupSummary(points, range)}
action={
<button
type="button"
aria-pressed={showPlan}
onClick={() => setShowPlan((v) => !v)}
className={cn(
'min-h-11 rounded-lg border px-3 text-xs font-medium',
showPlan ? 'border-primary bg-primary/10' : 'hover:bg-muted',
)}
>
{s.togglePlan}
</button>
}
>
<Chart points={points} dots={range !== 'daily'}>
{showPlan && (
<Line
dataKey="plan"
name={s.plan}
stroke={color.plan}
strokeDasharray="6 4"
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
)}
{GROUPS.map((g) => (
<Line
key={g.code}
dataKey={g.code}
name={`${g.emoji} ${g.label}`}
stroke={`var(--${g.code})`}
strokeWidth={2.5}
dot={range !== 'daily' && dot}
isAnimationActive={false}
/>
))}
</Chart>
</ChartCard>
</div>
)}
</section>
)
}
function ChartCard({
title,
summary,
action,
children,
}: {
title: string
summary: string
action?: ReactNode
children: ReactNode
}) {
return (
<figure className="rounded-2xl border bg-card p-4">
<div className="mb-3 flex min-h-11 flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-medium">{title}</h3>
{action}
</div>
{/* Grafik görsel; içeriği alttaki özet anlatır (ekran okuyucu özeti okur) */}
<div className="h-80 sm:h-72" aria-hidden>
{children}
</div>
<figcaption className="mt-3 text-sm text-muted-foreground">{summary}</figcaption>
</figure>
)
}
function Chart({
points,
dots,
children,
}: {
points: ChartPoint[]
dots: boolean
children: ReactNode
}) {
return (
<ResponsiveContainer width="100%" height="100%">
<LineChart data={points} margin={{ top: 5, right: 8, bottom: 0, left: 0 }}>
<CartesianGrid stroke={color.grid} strokeDasharray="3 3" vertical={false} />
<XAxis
dataKey="label"
stroke={color.axis}
tick={{ fontSize: 12 }}
tickLine={false}
minTickGap={dots ? 4 : 16}
/>
<YAxis
stroke={color.axis}
tick={{ fontSize: 12 }}
tickLine={false}
axisLine={false}
width={48}
tickFormatter={(v: number) => formatCompact(v)}
/>
<Tooltip
itemSorter={byOrder}
formatter={(v) => (typeof v === 'number' ? formatMoney(v) : '—')}
contentStyle={{
background: 'var(--popover)',
color: 'var(--popover-foreground)',
border: '1px solid var(--border)',
borderRadius: 12,
fontSize: 13,
}}
/>
<Legend wrapperStyle={{ fontSize: 12 }} itemSorter={byOrder} />
{children}
</LineChart>
</ResponsiveContainer>
)
}
function planSummary(points: ChartPoint[], range: ChartRange): string {
const p = lastPoint(points)
if (!p || p.spent === null) return s.noData
return range === 'monthly'
? s.monthlySummary(p.label, formatMoney(p.plan), formatMoney(p.spent))
: s.cumulativeSummary(formatMoney(p.spent), formatMoney(p.plan), range === 'weekly')
}
function groupSummary(points: ChartPoint[], range: ChartRange): string {
const p = lastPoint(points)
if (!p || !p.spent) return s.noData
const top = GROUPS.map((g) => ({ g, v: p[g.code] ?? 0 })).sort((a, b) => b.v - a.v)[0]
return s.groupSummary(
range === 'monthly' ? p.label : s.untilNow,
`${top.g.emoji} ${top.g.label}`,
formatMoney(top.v),
)
}
+17 -17
View File
@@ -1,7 +1,8 @@
import { useState } from 'react'
import { lazy, Suspense, useState } from 'react'
import { Link } from 'react-router'
import { paths } from '@/components/layout/nav-items'
import { PageError } from '@/components/page'
import { Segmented } from '@/components/segmented'
import { Skeleton } from '@/components/skeleton'
import { Button } from '@/components/ui/button'
import { WeekSummary } from '@/features/ledger/week-summary'
@@ -19,6 +20,9 @@ import type { PeriodSummary } from '@/types/PeriodSummary'
const s = t.dashboard
/** Recharts büyük → grafikler ayrı parça, Panel açılınca arkadan yüklenir */
const DashboardCharts = lazy(() => import('./charts'))
/** Özet kartları: gelir, sabit gider, toplam birikim, devreden borç, anlık durum, gruplar */
export function Overview({ period, writable }: { period: Period; writable: boolean }) {
const summary = useSummary(period.id)
@@ -73,6 +77,9 @@ export function Overview({ period, writable }: { period: Period; writable: boole
writable={writable}
/>
</div>
<Suspense fallback={<Skeleton className="h-96" />}>
<DashboardCharts period={period} spendable={sum.spendable} />
</Suspense>
</div>
)
}
@@ -186,22 +193,15 @@ function GroupsCard({
<h2 id="groups-title" className="font-semibold">
<span aria-hidden>🎯</span> {s.groupsTitle}
</h2>
<div role="group" aria-label={s.groupsTitle} className="flex rounded-lg border p-0.5">
{(['week', 'month'] as const).map((m) => (
<button
key={m}
type="button"
aria-pressed={mode === m}
onClick={() => setMode(m)}
className={cn(
'min-h-11 rounded-md px-4 text-sm font-medium',
mode === m ? 'bg-primary text-primary-foreground' : 'hover:bg-muted',
)}
>
{m === 'week' ? s.weekly : s.monthly}
</button>
))}
</div>
<Segmented
label={s.groupsTitle}
value={mode}
onChange={setMode}
options={[
{ value: 'week', label: s.weekly },
{ value: 'month', label: s.monthly },
]}
/>
</div>
<p className="mb-3 text-sm text-muted-foreground">
{mode === 'week' && week
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest'
import type { DaySpent } from '@/types/DaySpent'
import type { PeriodStat } from '@/types/PeriodStat'
import { dailySeries, lastPoint, monthlySeries, weeklySeries } from './charts'
const zero = { needs: 0, wants: 0, culture: 0, unexpected: 0 }
/** 01–10 Aralık; 1. gün Zorunlu 100, 3. gün İstek 50, 6. gün Zorunlu 30 */
const days: DaySpent[] = Array.from({ length: 10 }, (_, i) => {
const date = `2026-12-${String(i + 1).padStart(2, '0')}`
const spent = { ...zero }
if (i === 0) spent.needs = 100
if (i === 2) spent.wants = 50
if (i === 5) spent.needs = 30
return { date, spent }
})
const weeks = [
{ index: 1, start_date: '2026-12-01', last_date: '2026-12-06', days: 6 },
{ index: 2, start_date: '2026-12-07', last_date: '2026-12-10', days: 4 },
]
describe('chart series', () => {
it('daily: cumulative spending stops today, plan spreads evenly', () => {
const s = dailySeries(days, 1_000, '2026-12-03')
expect(s.map((p) => p.plan)).toEqual([100, 200, 300, 400, 500, 600, 700, 800, 900, 1_000])
expect(s.map((p) => p.spent)).toEqual([100, 100, 150, null, null, null, null, null, null, null])
expect(s[2]).toMatchObject({ label: '03.12', needs: 100, wants: 50, culture: 0 })
expect(s[3].needs).toBeNull()
})
it('daily: negative spendable is drawn as zero plan', () => {
expect(dailySeries(days, -500, '2026-12-10')[9].plan).toBe(0)
})
it('weekly: week end values, current week up to today', () => {
const s = weeklySeries(days, weeks, 1_000, '2026-12-08')
expect(s[0]).toMatchObject({ label: '1. hf', plan: 600, spent: 180, needs: 130, wants: 50 })
expect(s[1]).toMatchObject({ label: '2. hf', plan: 1_000, spent: 180 })
// Henüz başlamamış hafta
const early = weeklySeries(days, weeks, 1_000, '2026-12-05')
expect(early[0].spent).toBe(150) // 5. güne kadar (6. günün 30'u yok)
expect(early[1]).toMatchObject({ plan: 1_000, spent: null, needs: null })
// Dönem bitti → son günün değeri
expect(weeklySeries(days, weeks, 1_000, '2027-01-15')[1].spent).toBe(180)
})
it('monthly: one point per period with group breakdown', () => {
const periods = [
{ name: 'Kasım 2026', spendable: 2_000, spent: 900, spent_by_group: { ...zero, needs: 900 } },
{
name: 'Aralık 2026',
spendable: 2_500,
spent: 300,
spent_by_group: { ...zero, culture: 300 },
},
] as PeriodStat[]
expect(monthlySeries(periods)).toEqual([
{
label: 'Kasım 2026',
plan: 2_000,
spent: 900,
needs: 900,
wants: 0,
culture: 0,
unexpected: 0,
},
{
label: 'Aralık 2026',
plan: 2_500,
spent: 300,
needs: 0,
wants: 0,
culture: 300,
unexpected: 0,
},
])
})
it('last point with data', () => {
const s = dailySeries(days, 1_000, '2026-12-03')
expect(lastPoint(s)?.label).toBe('03.12')
expect(lastPoint(dailySeries(days, 1_000, '2026-11-30'))).toBeNull()
})
})
+91
View File
@@ -0,0 +1,91 @@
/**
* Panel grafikleri için seriler (saf hesaplar). Tutarlar kuruş.
*
* - **Günlük / Haftalık** (bu dönem, kümülatif): harcanabilir tutar günlere eşit dağıtılır
* ("bu güne kadar en fazla bu kadar harcanmalıydı"); harcama bugüne kadar toplanır,
* gelecek günlerde `null` (çizgi bugün biter).
* - **Aylık** (son dönemler, kümülatif değil): her dönemin harcanabilir ve harcananı.
*/
import type { DaySpent } from '@/types/DaySpent'
import type { GroupAmounts } from '@/types/GroupAmounts'
import type { PeriodStat } from '@/types/PeriodStat'
import type { PeriodWeek } from '@/types/PeriodWeek'
import { formatDayMonth } from './format'
import { GROUPS, type GroupCode } from './groups'
export type ChartPoint = {
label: string
/** Harcanabilir (kümülatif ya da dönem toplamı) */
plan: number
/** Toplam harcanan; henüz gelmemiş gün/hafta için `null` */
spent: number | null
} & Record<GroupCode, number | null>
export type ChartRange = 'daily' | 'weekly' | 'monthly'
const codes = GROUPS.map((g) => g.code)
const total = (a: GroupAmounts) => codes.reduce((s, c) => s + a[c], 0)
/** `spendable × gün / toplam gün` (kuruş, yuvarlanmış); eksiyse 0'dan aşağı inmez */
const planUpTo = (spendable: number, day: number, days: number) =>
days > 0 ? Math.round((Math.max(spendable, 0) * day) / days) : 0
export function dailySeries(days: DaySpent[], spendable: number, today: string): ChartPoint[] {
const run: Record<GroupCode, number> = { needs: 0, wants: 0, culture: 0, unexpected: 0 }
return days.map((d, i) => {
const past = d.date <= today
for (const c of codes) run[c] += d.spent[c]
const groups = Object.fromEntries(codes.map((c) => [c, past ? run[c] : null])) as Record<
GroupCode,
number | null
>
return {
label: formatDayMonth(d.date),
plan: planUpTo(spendable, i + 1, days.length),
spent: past ? codes.reduce((s, c) => s + run[c], 0) : null,
...groups,
}
})
}
/** Günlük serinin her haftanın son günündeki değeri; başlamamış hafta `null` */
export function weeklySeries(
days: DaySpent[],
weeks: readonly PeriodWeek[],
spendable: number,
today: string,
): ChartPoint[] {
const daily = dailySeries(days, spendable, today)
return weeks.map((w) => {
const lastIdx = days.findIndex((d) => d.date === w.last_date)
const started = w.start_date <= today
// İçinde bulunulan hafta: bugüne kadarki değer
const idx = started && w.last_date > today ? days.findIndex((d) => d.date === today) : lastIdx
const p = daily[idx >= 0 ? idx : lastIdx]
const plan = daily[lastIdx]?.plan ?? 0
if (!p || !started) {
return { label: `${w.index}. hf`, plan, spent: null, ...nulls() }
}
return { ...p, label: `${w.index}. hf`, plan }
})
}
export function monthlySeries(periods: PeriodStat[]): ChartPoint[] {
return periods.map((p) => ({
label: p.name,
plan: p.spendable,
spent: total(p.spent_by_group),
...p.spent_by_group,
}))
}
const nulls = () =>
Object.fromEntries(codes.map((c) => [c, null])) as Record<GroupCode, number | null>
/** Ekran okuyucu ve grafiğin altı için kısa özet: son değerli nokta */
export function lastPoint(points: ChartPoint[]): ChartPoint | null {
for (let i = points.length - 1; i >= 0; i--) {
if (points[i].spent !== null) return points[i]
}
return null
}
+7
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
formatCompact,
formatWeekday,
formatDate,
formatMoney,
@@ -35,6 +36,12 @@ describe('diğer biçimler', () => {
expect(formatPercent(0.123)).toBe('%12,3')
})
it('grafik ekseni için kısa tutar', () => {
expect(formatCompact(2_700_000)).toBe('27\u00a0B') // bölünmez boşluk
expect(formatCompact(150_000_000)).toBe('1,5\u00a0Mn')
expect(formatCompact(95_000)).toBe('950')
})
it('tarih GG.AA.YYYY', () => {
expect(formatDate('2026-12-09')).toBe('09.12.2026')
expect(formatDate(new Date(2027, 0, 1))).toBe('01.01.2027')
+7
View File
@@ -34,6 +34,13 @@ export function formatNumber(value: number, decimals = 2): string {
return numberFormat(decimals).format(value)
}
const compact = new Intl.NumberFormat('tr-TR', { notation: 'compact', maximumFractionDigits: 1 })
/** Grafik ekseni için kısa tutar (kuruş → TL): `2.700.000` → `27 B`, `150.000.000` → `1,5 Mn` */
export function formatCompact(kurus: number): string {
return compact.format(kurus / 100)
}
/** Kuruş → `1.250,00 ₺`. `signed: true` ise pozitiflere `+` eklenir. */
export function formatMoney(
kurus: number,
+9
View File
@@ -6,6 +6,7 @@
*/
import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'
import type { BudgetSuggestion } from '@/types/BudgetSuggestion'
import type { DaySpent } from '@/types/DaySpent'
import type { CopyPreviousResult } from '@/types/CopyPreviousResult'
import type { GroupAmounts } from '@/types/GroupAmounts'
import type { GroupBudget } from '@/types/GroupBudget'
@@ -148,6 +149,14 @@ export function useStats(limit = 12) {
})
}
/** Dönemin her günü: 4 grubun harcaması (grafik) */
export function useDaily(periodId: string) {
return useQuery({
queryKey: queryKeys.daily(periodId),
queryFn: () => api.get<DaySpent[]>(`/periods/${periodId}/daily`),
})
}
// ---------- Özet ve bütçe ----------
export function useSummary(periodId: string) {
+2
View File
@@ -22,6 +22,8 @@ export const queryKeys = {
planItems: (id: string) => ['period', id, 'plan-items'] as const,
summary: (id: string) => ['period', id, 'summary'] as const,
review: (id: string) => ['period', id, 'review'] as const,
/** Panel grafiği: günlük harcama (kayıt değişince dönem önekiyle yenilenir) */
daily: (id: string) => ['period', id, 'daily'] as const,
budget: (id: string) => ['period', id, 'budget'] as const,
suggestion: (id: string, method: string) => ['period', id, 'suggestion', method] as const,
notes: (id: string, context: string) => ['period', id, 'notes', context] as const,
+23
View File
@@ -381,6 +381,29 @@ export const t = {
`Açık dönem yok. Son dönem (${name}) gösteriliyor; değiştirilemez.`,
},
charts: {
title: 'Grafikler',
daily: 'Günlük',
weekly: 'Haftalık',
monthly: 'Aylık',
planTitle: 'Harcanabilir ve gerçekleşen (birikerek)',
planTitleMonthly: 'Dönemlere göre harcanabilir ve harcanan',
groupsTitle: 'Gruplara göre harcama',
togglePlan: 'Harcanabilir çizgisi',
plan: 'Harcanabilir',
spent: 'Harcanan',
untilNow: 'Bugüne kadar',
cumulativeSummary: (spent: string, plan: string, weekly: boolean) =>
weekly
? `Şimdiye kadar ${spent} harcandı; plana göre bu hafta sonuna kadar en fazla ${plan}.`
: `Bugüne kadar ${spent} harcandı; plana göre bugüne kadar en fazla ${plan}.`,
monthlySummary: (name: string, plan: string, spent: string) =>
`${name}: harcanabilir ${plan}, harcanan ${spent}.`,
groupSummary: (when: string, group: string, amount: string) =>
`${when} en çok harcanan grup: ${group} (${amount}).`,
noData: 'Henüz harcama yok.',
},
periods: {
picker: 'Dönem',
status: { open: 'Açık', closed: '🔒 Kapalı', correcting: '✏️ Düzeltmede' },
+5
View File
@@ -1,4 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GroupAmounts } from "./GroupAmounts";
import type { PeriodStatus } from "./PeriodStatus";
export type PeriodStat = { id: string, name: string, start_date: string,
@@ -6,6 +7,10 @@ export type PeriodStat = { id: string, name: string, start_date: string,
* Son gün, dahil
*/
last_date: string, status: PeriodStatus, spendable: number, spent: number,
/**
* Harcanan, gruplara göre
*/
spent_by_group: GroupAmounts,
/**
* Kapanmamışsa `null`
*/