chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)

This commit is contained in:
mapleferry committed 2026-11-29 21:29:06 +08:00
commit 4a5db3f1f9
167 files changed
+21732

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
import { lazy, Suspense } from 'react'
import type { ReactNode } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { AppProvider } from '@/context/AppContext'
import { Layout } from '@/components/layout/Layout'
import { ErrorBoundary } from '@/components/ErrorBoundary'
import Dashboard from '@/pages/Dashboard'
const TransactionList = lazy(() => import('@/pages/TransactionList'))
const BudgetBoard = lazy(() => import('@/pages/BudgetBoard'))
const Report = lazy(() => import('@/pages/Report'))
const AssetOverview = lazy(() => import('@/pages/AssetOverview'))
const PolicyList = lazy(() => import('@/pages/PolicyList'))
const Lifecycle = lazy(() => import('@/pages/Lifecycle'))
const Settings = lazy(() => import('@/pages/Settings'))
function PageBoundary({ children }: { children: ReactNode }) {
return (
<ErrorBoundary>
<Suspense
fallback={
<div className="app-page">
<div className="premium-panel p-8 text-sm text-ink-300">页面加载中…</div>
</div>
}
>
{children}
</Suspense>
</ErrorBoundary>
)
}
function App() {
return (
<BrowserRouter>
<AppProvider>
<Routes>
<Route element={<Layout />}>
<Route index element={<Dashboard />} />
<Route
path="transactions"
element={
<PageBoundary>
<TransactionList />
</PageBoundary>
}
/>
<Route
path="budget"
element={
<PageBoundary>
<BudgetBoard />
</PageBoundary>
}
/>
<Route
path="reports"
element={
<PageBoundary>
<Report />
</PageBoundary>
}
/>
<Route
path="assets"
element={
<PageBoundary>
<AssetOverview />
</PageBoundary>
}
/>
<Route
path="policies"
element={
<PageBoundary>
<PolicyList />
</PageBoundary>
}
/>
<Route
path="lifecycle"
element={
<PageBoundary>
<Lifecycle />
</PageBoundary>
}
/>
<Route
path="settings"
element={
<PageBoundary>
<Settings />
</PageBoundary>
}
/>
</Route>
</Routes>
</AppProvider>
</BrowserRouter>
)
}
export default App
+18
View File
@@ -0,0 +1,18 @@
import { formatCents } from '@/lib/utils'
interface Props {
cents: number
type?: 'income' | 'expense' | 'transfer'
className?: string
}
export function AmountDisplay({ cents, type, className = '' }: Props) {
const sign = type === 'income' ? '+' : type === 'expense' ? '-' : ''
const color = type === 'income' ? 'text-income' : type === 'expense' ? 'text-expense' : 'text-muted'
return (
<span className={`tabular-nums font-medium ${color} ${className}`}>
{sign}{formatCents(cents)}
</span>
)
}
+27
View File
@@ -0,0 +1,27 @@
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBookOpen, faHouseChimney, faWallet } from '@fortawesome/free-solid-svg-icons'
interface Props {
compact?: boolean
}
export function BrandLogo({ compact = false }: Props) {
return (
<div className="flex items-center gap-3">
<div className="relative grid h-10 w-10 place-items-center rounded-lg border border-primary/30 bg-[linear-gradient(145deg,#25221a,#111317_52%,#0b0d10)] shadow-[0_18px_45px_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.08)]">
<div className="absolute inset-1 rounded-md border border-white/5 bg-primary/5" />
<FontAwesomeIcon icon={faBookOpen} className="relative h-5 w-5 text-primary" />
<FontAwesomeIcon icon={faHouseChimney} className="absolute -right-1 -top-1 h-4 w-4 rounded-full border border-primary/30 bg-background p-1 text-income shadow-lg" />
</div>
{!compact && (
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-semibold tracking-wide text-foreground">家庭记账本</span>
<FontAwesomeIcon icon={faWallet} className="h-3 w-3 text-primary/80" />
</div>
<p className="mt-0.5 text-[10px] uppercase tracking-[0.22em] text-muted">Household Budget</p>
</div>
)}
</div>
)
}
+21
View File
@@ -0,0 +1,21 @@
import { Badge } from '@/components/ui/badge'
interface Props {
name: string
isActive?: boolean
className?: string
}
/** 分类名称;已停用分类显示角标。 */
export function CategoryLabel({ name, isActive = true, className }: Props) {
return (
<span className={`inline-flex items-center gap-1.5 ${className ?? ''}`}>
<span>{name}</span>
{!isActive && (
<Badge variant="outline" className="border-muted/50 px-1.5 py-0 text-[10px] font-normal text-muted">
已停用
</Badge>
)}
</span>
)
}
+39
View File
@@ -0,0 +1,39 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
title: string
description: string
onConfirm: () => void
loading?: boolean
}
export function ConfirmDialog({ open, onOpenChange, title, description, onConfirm, loading }: Props) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
取消
</Button>
<Button variant="destructive" onClick={onConfirm} disabled={loading}>
{loading ? '删除中…' : '确认删除'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+19
View File
@@ -0,0 +1,19 @@
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faInbox } from '@fortawesome/free-solid-svg-icons'
interface Props {
message?: string
action?: React.ReactNode
}
export function EmptyState({ message = '暂无数据', action }: Props) {
return (
<div className="flex flex-col items-center justify-center py-16 text-muted">
<div className="mb-3 grid h-12 w-12 place-items-center rounded-lg border border-border bg-white/[0.03]">
<FontAwesomeIcon icon={faInbox} className="h-5 w-5 text-primary/70" />
</div>
<p className="text-sm">{message}</p>
{action && <div className="mt-4">{action}</div>}
</div>
)
}
+37
View File
@@ -0,0 +1,37 @@
import { Component, type ReactNode } from 'react'
interface Props {
children: ReactNode
}
interface State {
hasError: boolean
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(): State {
return { hasError: true }
}
render() {
if (this.state.hasError) {
return (
<div className="flex flex-col items-center justify-center py-24">
<p className="text-muted text-sm">页面加载出现错误</p>
<button
className="mt-4 text-sm text-primary hover:underline"
onClick={() => this.setState({ hasError: false })}
>
重试
</button>
</div>
)
}
return this.props.children
}
}
+217
View File
@@ -0,0 +1,217 @@
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { api, ApiError, type Account, type ImportPreviewResult } from '@/lib/api'
import { formatDate } from '@/lib/utils'
import { importIsCSV, sourceKindMatchesAccount, type ImportSourceKind } from '@/lib/importUtils'
import { AmountDisplay } from '@/components/AmountDisplay'
import { useCategories } from '@/hooks/useCategories'
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
accounts: Account[]
onImported: () => void
}
export function ImportDialog({ open, onOpenChange, accounts, onImported }: Props) {
const { categories } = useCategories()
const [importFile, setImportFile] = useState<File | null>(null)
const [importSourceKind, setImportSourceKind] = useState<ImportSourceKind>('cmb_debit')
const [importAccountID, setImportAccountID] = useState('')
const [preview, setPreview] = useState<ImportPreviewResult | null>(null)
const [importError, setImportError] = useState<string | null>(null)
const [importMessage, setImportMessage] = useState<string | null>(null)
const [categoryOverrides, setCategoryOverrides] = useState<Record<string, number>>({})
const resetState = () => {
setImportFile(null)
setPreview(null)
setImportError(null)
setImportMessage(null)
}
const buildFormData = () => {
const formData = new FormData()
if (!importFile) throw new Error('请选择文件')
formData.append('file', importFile)
formData.append('source_kind', importSourceKind)
if (importAccountID) formData.append('account_id', importAccountID)
if (Object.keys(categoryOverrides).length) formData.append('category_overrides', JSON.stringify(categoryOverrides))
return formData
}
const previewMutation = useMutation({
mutationFn: () => api.previewImportTransactions(buildFormData()),
onMutate: () => setImportError(null),
onSuccess: (data) => {
setPreview(data)
setImportMessage(null)
},
onError: (e) => {
setPreview(null)
setImportError(e instanceof ApiError ? e.message : '预览失败')
},
})
const importMutation = useMutation({
mutationFn: () => api.importTransactions(buildFormData()),
onMutate: () => {
setImportError(null)
setImportMessage(null)
},
onSuccess: (result) => {
setImportMessage(`导入成功:新增 ${result.imported_count} 条,跳过重复 ${result.skipped_count} 条`)
setPreview(null)
onImported()
},
onError: (e) => {
setImportError(e instanceof ApiError ? e.message : '导入失败')
},
})
const handleOpenChange = (next: boolean) => {
if (!next) resetState()
onOpenChange(next)
}
const handleFileChange = (file: File | null) => {
setImportFile(file)
setPreview(null)
setImportMessage(null)
setCategoryOverrides({})
setImportError(null)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>导入账单</DialogTitle>
</DialogHeader>
<div className="app-form">
<div>
<label className="app-form-label">导入来源</label>
<select
value={importSourceKind}
onChange={(e) => {
setImportSourceKind(e.target.value as ImportSourceKind)
handleFileChange(null)
}}
className="app-select mt-1 w-full"
>
<option value="cmb_debit">招商银行储蓄卡(PDF 流水)</option>
<option value="cmb_credit">招商银行信用卡(PDF 账单)</option>
<option value="alipay">支付宝(CSV 账单)</option>
<option value="wechat">微信支付(CSV 账单)</option>
</select>
</div>
<div>
<label className="app-form-label">
{importIsCSV(importSourceKind) ? '账单 CSV' : '账单 PDF'}
</label>
<Input
key={importSourceKind}
type="file"
accept={importIsCSV(importSourceKind) ? '.csv,text/csv' : 'application/pdf,.pdf'}
className="h-9 text-sm mt-1"
onChange={(e) => handleFileChange(e.target.files?.[0] ?? null)}
/>
</div>
<div>
<label className="app-form-label">导入账户</label>
<select
value={importAccountID}
onChange={(e) => setImportAccountID(e.target.value)}
className="app-select-muted mt-1 w-full"
>
<option value="">自动匹配或创建账户</option>
{accounts
.filter((a) => sourceKindMatchesAccount(importSourceKind, a.type))
.map((a) => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
</div>
{preview && (
<div className="rounded-md border border-border/80 bg-[#0c1016]/60 p-3 space-y-2">
<p className="text-xs text-muted">
解析 {preview.total_count} 条 · 预计新增 {preview.new_count} 条 · 重复跳过 {preview.duplicate_count} 条
</p>
<p className="text-xs text-foreground">
目标账户:{preview.account_name}
{preview.will_create_account && (
<span className="ml-1 text-primary">(将自动创建)</span>
)}
</p>
{preview.items.length > 0 && (
<ul className="max-h-80 space-y-1.5 overflow-y-auto text-xs">
{preview.items.map((item, i) => (
<li key={i} className="flex items-start justify-between gap-2 border-b border-border/40 pb-1.5 last:border-0">
<div className="min-w-0">
<p className="truncate text-foreground">{item.description || item.counterparty || '—'}</p>
<p className="text-muted">
{formatDate(item.date)}
{item.status === 'duplicate_database' ? ' · 数据库已有' : item.status === 'duplicate_file' ? ' · 文件内重复' : ''}
</p>
{item.status === 'new' && (
<div className="mt-1 flex items-center gap-2">
<select
value={categoryOverrides[item.source_key] ?? item.category_id}
onChange={(e) => setCategoryOverrides(p => ({ ...p, [item.source_key]: Number(e.target.value) }))}
className="app-select-muted h-7 max-w-40 text-xs"
>
{categories.filter(c => c.type === item.type && c.parent_id !== null && c.is_active).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
<span className="text-[11px] text-muted">{item.category_reason}</span>
</div>
)}
</div>
<AmountDisplay cents={item.amount} type={item.type} />
</li>
))}
</ul>
)}
{preview.total_count > preview.items.length && (
<p className="text-[11px] text-muted">
仅展示前 {preview.items.length} 条样本,确认后将处理全部 {preview.total_count} 条。
</p>
)}
</div>
)}
{importError && <p className="app-error">{importError}</p>}
{importMessage && <p className="app-success">{importMessage}</p>}
<div className="flex gap-2">
<Button
type="button"
variant="outline"
className="flex-1"
disabled={!importFile || previewMutation.isPending || importMutation.isPending}
onClick={() => previewMutation.mutate()}
>
{previewMutation.isPending ? '解析中...' : '预览'}
</Button>
<Button
type="button"
className="flex-1"
disabled={!importFile || !preview || preview.new_count === 0 || importMutation.isPending}
onClick={() => importMutation.mutate()}
>
{importMutation.isPending ? '导入中...' : `确认导入${preview ? ` (${preview.new_count})` : ''}`}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,21 @@
import { Skeleton } from '@/components/ui/skeleton'
export function TableSkeleton({ rows = 5 }: { rows?: number }) {
return (
<div className="space-y-2">
{Array.from({ length: rows }).map((_, i) => (
<Skeleton key={i} className="h-10 w-full bg-[#1f1f1f]" />
))}
</div>
)
}
export function CardSkeleton({ count = 3 }: { count?: number }) {
return (
<div className="summary-skeleton-grid">
{Array.from({ length: count }).map((_, i) => (
<Skeleton key={i} className="h-24 rounded-lg bg-white/10" />
))}
</div>
)
}
+42
View File
@@ -0,0 +1,42 @@
import { useAppContext } from '@/context/useAppContext'
import { Button } from '@/components/ui/button'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChevronLeft, faChevronRight, faCalendarDays } from '@fortawesome/free-solid-svg-icons'
export function MonthPicker() {
const { state, dispatch } = useAppContext()
const year = parseInt(state.selectedYear)
const month = parseInt(state.selectedMonth)
const prevMonth = () => {
let m = month - 1
let y = year
if (m < 1) { m = 12; y-- }
dispatch({ type: 'SET_YEAR', year: y.toString() })
dispatch({ type: 'SET_MONTH', month: m.toString().padStart(2, '0') })
}
const nextMonth = () => {
let m = month + 1
let y = year
if (m > 12) { m = 1; y++ }
dispatch({ type: 'SET_YEAR', year: y.toString() })
dispatch({ type: 'SET_MONTH', month: m.toString().padStart(2, '0') })
}
return (
<div className="segment-control items-center gap-2 rounded-lg px-1.5 py-1">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={prevMonth}>
<FontAwesomeIcon icon={faChevronLeft} className="h-3.5 w-3.5" />
</Button>
<span className="flex min-w-[100px] items-center justify-center gap-2 text-sm font-medium tabular-nums">
<FontAwesomeIcon icon={faCalendarDays} className="h-3.5 w-3.5 text-primary" />
{year}年{month}月
</span>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={nextMonth}>
<FontAwesomeIcon icon={faChevronRight} className="h-3.5 w-3.5" />
</Button>
</div>
)
}
@@ -0,0 +1,87 @@
import {
CartesianGrid,
Legend,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts'
import type { AssetSnapshot } from '@/lib/api'
import { formatCents } from '@/lib/utils'
interface Props {
snapshots: AssetSnapshot[]
}
export default function NetWorthTrendChart({ snapshots }: Props) {
if (snapshots.length < 2) {
return (
<p className="text-sm text-muted">
系统会持续刷新当月最新净值,进入下月后冻结上月快照;需累积至少两个月才能绘制趋势曲线。当前已有 {snapshots.length} 条快照。
</p>
)
}
const data = snapshots.map((snapshot) => ({
date: snapshot.date.slice(0, 7),
资产: snapshot.total_asset / 100,
负债: snapshot.total_debt / 100,
净值: snapshot.net_worth / 100,
}))
return (
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={data}>
<CartesianGrid
strokeDasharray="3 3"
stroke="rgba(255,255,255,0.06)"
/>
<XAxis
dataKey="date"
tick={{ fill: 'currentColor', fontSize: 11 }}
stroke="rgba(255,255,255,0.2)"
/>
<YAxis
tick={{ fill: 'currentColor', fontSize: 11 }}
stroke="rgba(255,255,255,0.2)"
tickFormatter={(value) => `${(value / 10000).toFixed(0)}万`}
/>
<Tooltip
contentStyle={{
background: '#0f0f0f',
border: '1px solid rgba(255,255,255,0.1)',
fontSize: 12,
}}
formatter={(value: number) => formatCents(Math.round(value * 100))}
/>
<Legend wrapperStyle={{ fontSize: 12 }} />
<Line
type="monotone"
dataKey="资产"
stroke="#22c55e"
strokeWidth={2}
dot={{ r: 3 }}
/>
<Line
type="monotone"
dataKey="负债"
stroke="#ef4444"
strokeWidth={2}
dot={{ r: 3 }}
/>
<Line
type="monotone"
dataKey="净值"
stroke="#d4af37"
strokeWidth={2}
dot={{ r: 4 }}
/>
</LineChart>
</ResponsiveContainer>
</div>
)
}
+189
View File
@@ -0,0 +1,189 @@
import { useState } from 'react'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { TreeSelect, type TreeSelectNode } from '@/components/ui/tree-select'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faArrowDown, faArrowUp, faPenNib } from '@fortawesome/free-solid-svg-icons'
import { useAppContext } from '@/context/useAppContext'
import { useCategories } from '@/hooks/useCategories'
import { useAccounts } from '@/hooks/useAccounts'
import { formatLocalDate } from '@/lib/utils'
import type { Category, CreateTransactionRequest } from '@/lib/api'
const schema = z.object({
amountYuan: z.string().refine(v => {
const n = parseFloat(v)
return !isNaN(n) && n > 0 && /^\d+(\.\d{1,2})?$/.test(v)
}, '请输入有效金额'),
type: z.enum(['expense', 'income']),
category_id: z.string().min(1, '请选择分类'),
account_id: z.string().optional(),
description: z.string().optional(),
})
type FormData = z.infer<typeof schema>
interface Props {
onSubmit: (req: CreateTransactionRequest) => Promise<unknown>
onSuccess?: () => void
submitting?: boolean
}
export function QuickAdd({ onSubmit, onSuccess, submitting: submittingProp }: Props) {
const { state } = useAppContext()
const { categories } = useCategories()
const { accounts } = useAccounts()
const [submittingLocal, setSubmittingLocal] = useState(false)
const submitting = submittingProp ?? submittingLocal
const [txType, setTxType] = useState<'expense' | 'income'>('expense')
const filteredCategories = categories.filter(c => c.type === txType)
const categoryNodes = buildQuickAddTree(filteredCategories)
const { register, handleSubmit, reset, control, formState: { errors } } = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
type: 'expense',
amountYuan: '',
category_id: '',
account_id: '',
description: '',
},
})
const handleFormSubmit = async (data: FormData) => {
const amount = Math.round(parseFloat(data.amountYuan) * 100)
const currentMonth = `${state.selectedYear}-${state.selectedMonth}`
const today = formatLocalDate()
const date = today.startsWith(currentMonth) ? today : `${currentMonth}-01`
if (submittingProp === undefined) setSubmittingLocal(true)
try {
await onSubmit({
type: data.type,
amount,
category_id: parseInt(data.category_id),
account_id: data.account_id ? parseInt(data.account_id) : null,
date,
description: data.description || '',
})
reset({ amountYuan: '', category_id: '', account_id: '', description: '', type: data.type })
onSuccess?.()
} finally {
if (submittingProp === undefined) setSubmittingLocal(false)
}
}
return (
<form onSubmit={handleSubmit(handleFormSubmit)} className="premium-panel rounded-lg p-4">
<div className="app-section-title mb-3">
<FontAwesomeIcon icon={faPenNib} className="app-section-icon" />
快速记账
</div>
<div className="flex items-start gap-3 flex-wrap">
{/* Type toggle */}
<div className="segment-control">
<button
type="button"
className={`segment-option ${
txType === 'expense' ? 'segment-option-expense' : 'segment-option-muted'
}`}
onClick={() => { setTxType('expense'); reset({ type: 'expense', category_id: '' }) }}
>
<FontAwesomeIcon icon={faArrowDown} className="h-3 w-3" />
支出
</button>
<button
type="button"
className={`segment-option ${
txType === 'income' ? 'segment-option-income' : 'segment-option-muted'
}`}
onClick={() => { setTxType('income'); reset({ type: 'income', category_id: '' }) }}
>
<FontAwesomeIcon icon={faArrowUp} className="h-3 w-3" />
收入
</button>
</div>
<input type="hidden" {...register('type')} value={txType} />
{/* Amount */}
<div className="flex-1 min-w-[120px]">
<Input
{...register('amountYuan')}
placeholder="金额"
className="h-9 text-sm"
inputMode="decimal"
/>
{errors.amountYuan && <p className="app-error">{errors.amountYuan.message}</p>}
</div>
{/* Category */}
<div className="min-w-[140px] w-44">
<Controller
name="category_id"
control={control}
render={({ field }) => (
<TreeSelect
value={field.value}
onChange={field.onChange}
nodes={categoryNodes}
placeholder="分类"
/>
)}
/>
{errors.category_id && <p className="app-error">{errors.category_id.message}</p>}
</div>
{/* Account */}
<div className="min-w-[90px]">
<select
{...register('account_id')}
className="app-select-muted"
>
<option value="">账户</option>
{accounts.map(a => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
</div>
{/* Description */}
<div className="flex-1 min-w-[150px]">
<Input
{...register('description')}
placeholder="备注"
className="h-9 text-sm"
/>
</div>
<Button type="submit" size="sm" disabled={submitting}>
{submitting ? '...' : '记一笔'}
</Button>
</div>
</form>
)
}
function buildQuickAddTree(categories: Category[]): TreeSelectNode[] {
const top = categories
.filter(c => c.parent_id === null)
.sort((a, b) => a.sort_order - b.sort_order || a.id - b.id)
const children = categories
.filter(c => c.parent_id !== null)
.sort((a, b) => a.sort_order - b.sort_order || a.id - b.id)
return top.map(parent => {
const kids = children.filter(c => c.parent_id === parent.id)
if (kids.length === 0) {
return { id: String(parent.id), label: parent.name, selectable: true }
}
return {
id: String(parent.id),
label: parent.name,
selectable: false,
children: kids.map(child => ({ id: String(child.id), label: child.name, selectable: true })),
}
})
}
+41
View File
@@ -0,0 +1,41 @@
import { Card } from '@/components/ui/card'
import { formatCents } from '@/lib/utils'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChartLine, faArrowTrendUp, faArrowTrendDown } from '@fortawesome/free-solid-svg-icons'
import type { DashboardSummary } from '@/lib/api'
interface Props {
summary: DashboardSummary | null
loading: boolean
}
export function SummaryCards({ summary, loading }: Props) {
const cards = [
{ label: '本月结余', amount: summary?.balance ?? 0, color: 'text-foreground', icon: faChartLine, tone: 'bg-primary/12 text-primary' },
{ label: '本月收入', amount: summary?.income ?? 0, color: 'text-income', icon: faArrowTrendUp, tone: 'bg-income/12 text-income' },
{ label: '本月支出', amount: summary?.expense ?? 0, color: 'text-expense', icon: faArrowTrendDown, tone: 'bg-expense/12 text-expense' },
]
return (
<div className="summary-grid">
{cards.map(card => (
<Card key={card.label} className="relative overflow-hidden p-5">
<div className="summary-card-glow" />
<div className="mb-4 flex items-center justify-between">
<p className="text-xs text-muted">{card.label}</p>
<span className={`metric-icon ${card.tone}`}>
<FontAwesomeIcon icon={card.icon} className="h-4 w-4" />
</span>
</div>
{loading ? (
<div className="h-8 w-28 rounded bg-white/10 animate-pulse" />
) : (
<p className={`text-2xl font-semibold tabular-nums ${card.color}`}>
{formatCents(card.amount)}
</p>
)}
</Card>
))}
</div>
)
}
+166
View File
@@ -0,0 +1,166 @@
import { Controller, useForm, type DefaultValues } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { TreeSelect } from '@/components/ui/tree-select'
import { DatePicker } from '@/components/ui/date-picker'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faArrowDown, faArrowUp, faRightLeft } from '@fortawesome/free-solid-svg-icons'
import type { Account, Category } from '@/lib/api'
import { buildCategoryTree } from '@/lib/categoryTree'
import {
defaultTransactionFormValues,
transactionFormSchema,
type TransactionFormData,
} from '@/lib/transactionForm'
interface Props {
categories: Category[]
accounts: Account[]
defaultValues?: DefaultValues<TransactionFormData>
submitting?: boolean
onSubmit: (data: TransactionFormData) => void | Promise<void>
}
export function TransactionForm({
categories,
accounts,
defaultValues,
submitting = false,
onSubmit,
}: Props) {
const {
register,
control,
handleSubmit,
setValue,
watch,
formState: { errors },
} = useForm<TransactionFormData>({
resolver: zodResolver(transactionFormSchema),
defaultValues: defaultValues ?? defaultTransactionFormValues,
})
const txType = watch('type') ?? 'expense'
const accountId = watch('account_id')
const isTransfer = txType === 'transfer'
const expenseCats = categories.filter((c) => c.type === 'expense')
const incomeCats = categories.filter((c) => c.type === 'income')
const cats = txType === 'expense' ? expenseCats : incomeCats
const categoryNodes = buildCategoryTree(cats, { allowParentSelect: false })
const setTxType = (type: 'expense' | 'income' | 'transfer') => {
setValue('type', type, { shouldDirty: true, shouldValidate: true })
setValue('category_id', '', { shouldDirty: true, shouldValidate: true })
if (type !== 'transfer') {
setValue('to_account_id', '', { shouldDirty: true, shouldValidate: true })
}
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="app-form">
<div className="segment-control w-fit">
<button
type="button"
className={`segment-option ${txType === 'expense' ? 'segment-option-expense' : 'segment-option-muted'}`}
onClick={() => setTxType('expense')}
>
<FontAwesomeIcon icon={faArrowDown} className="h-3 w-3" />
支出
</button>
<button
type="button"
className={`segment-option ${txType === 'income' ? 'segment-option-income' : 'segment-option-muted'}`}
onClick={() => setTxType('income')}
>
<FontAwesomeIcon icon={faArrowUp} className="h-3 w-3" />
收入
</button>
<button
type="button"
className={`segment-option ${isTransfer ? 'segment-option-primary' : 'segment-option-muted'}`}
onClick={() => setTxType('transfer')}
>
<FontAwesomeIcon icon={faRightLeft} className="h-3 w-3" />
转账
</button>
</div>
<input type="hidden" {...register('type')} />
<div>
<label className="app-form-label">金额</label>
<Input {...register('amountYuan')} placeholder="0.00" className="h-9 text-sm mt-1" inputMode="decimal" />
{errors.amountYuan && <p className="app-error">{errors.amountYuan.message}</p>}
</div>
{!isTransfer && (
<div>
<label className="app-form-label">分类</label>
<div className="mt-1">
<Controller
name="category_id"
control={control}
render={({ field }) => (
<TreeSelect
value={field.value ?? ''}
onChange={field.onChange}
nodes={categoryNodes}
placeholder="选择分类"
/>
)}
/>
</div>
{errors.category_id && <p className="app-error">{errors.category_id.message}</p>}
</div>
)}
<div>
<label className="app-form-label">{isTransfer ? '转出账户' : '账户'}</label>
<select {...register('account_id')} className="app-select-muted mt-1 w-full">
<option value="">选择账户</option>
{accounts.map((a) => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
{errors.account_id && <p className="app-error">{errors.account_id.message}</p>}
</div>
{isTransfer && (
<div>
<label className="app-form-label">转入账户</label>
<select {...register('to_account_id')} className="app-select-muted mt-1 w-full">
<option value="">选择账户</option>
{accounts
.filter((a) => String(a.id) !== accountId)
.map((a) => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
{errors.to_account_id && <p className="app-error">{errors.to_account_id.message}</p>}
</div>
)}
<div>
<label className="app-form-label">日期</label>
<div className="mt-1">
<Controller
name="date"
control={control}
render={({ field }) => (
<DatePicker value={field.value} onChange={field.onChange} placeholder="选择日期" />
)}
/>
</div>
{errors.date && <p className="app-error">{errors.date.message}</p>}
</div>
{!isTransfer && (
<div>
<label className="app-form-label">对手方</label>
<Input {...register('counterparty')} placeholder="商户、付款人或收款人" className="h-9 text-sm mt-1" />
</div>
)}
<div>
<label className="app-form-label">备注</label>
<Input {...register('description')} placeholder="可选" className="h-9 text-sm mt-1" />
</div>
<Button type="submit" className="w-full" disabled={submitting}>
{submitting ? '保存中...' : '保存'}
</Button>
</form>
)
}
@@ -0,0 +1,108 @@
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { AmountDisplay } from '@/components/AmountDisplay'
import { CategoryLabel } from '@/components/CategoryLabel'
import { formatDate } from '@/lib/utils'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPenToSquare, faTrashCan } from '@fortawesome/free-solid-svg-icons'
import type { TransactionListItem } from '@/lib/api'
interface Props {
items: TransactionListItem[]
onEdit?: (item: TransactionListItem) => void
onDelete?: (item: TransactionListItem) => void
selectedIds?: number[]
onToggleSelect?: (id: number) => void
onToggleSelectAll?: () => void
compact?: boolean
}
export function TransactionTable({ items, onEdit, onDelete, selectedIds = [], onToggleSelect, onToggleSelectAll, compact }: Props) {
if (items.length === 0) return null
const selectable = !!onToggleSelect
const allSelected = selectable && items.every(item => selectedIds.includes(item.id))
return (
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
{selectable && (
<TableHead className="w-[36px]">
<input type="checkbox" checked={allSelected} onChange={onToggleSelectAll} />
</TableHead>
)}
<TableHead className="table-muted w-[130px]">日期</TableHead>
<TableHead className="table-muted">分类</TableHead>
<TableHead className="table-muted">描述</TableHead>
{!compact && <TableHead className="table-muted">对手方</TableHead>}
{!compact && <TableHead className="table-muted">账户</TableHead>}
<TableHead className="table-muted text-right">金额</TableHead>
{(onEdit || onDelete) && <TableHead className="w-[60px]" />}
</TableRow>
</TableHeader>
<TableBody>
{items.map(item => (
<TableRow key={item.id} className="group">
{selectable && (
<TableCell>
<input type="checkbox" checked={selectedIds.includes(item.id)} onChange={() => onToggleSelect?.(item.id)} />
</TableCell>
)}
<TableCell className="table-muted tabular-nums">
{formatDate(item.date)}
</TableCell>
<TableCell className="text-sm">
{item.type === 'transfer' ? (
<span className="text-muted">转账</span>
) : (
<CategoryLabel name={item.category_name} isActive={item.category_is_active} />
)}
</TableCell>
<TableCell className="text-sm max-w-[200px] truncate">
{item.description}
</TableCell>
{!compact && (
<TableCell className="table-muted max-w-[140px] truncate">{item.counterparty || '-'}</TableCell>
)}
{!compact && (
<TableCell className="table-muted">
{item.type === 'transfer'
? `${item.account_name || '-'} → ${item.to_account_name || '-'}`
: item.account_name}
</TableCell>
)}
<TableCell className="text-right">
<AmountDisplay
cents={item.amount}
type={item.type}
/>
</TableCell>
{(onEdit || onDelete) && (
<TableCell>
<div className="fade-actions">
{onEdit && (
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => onEdit(item)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" />
</Button>
)}
{onDelete && (
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => onDelete(item)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5 text-expense" />
</Button>
)}
</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { useLocation } from 'react-router-dom'
import { MonthPicker } from '@/components/MonthPicker'
const pageTitles: Record<string, string> = {
'/': '首页',
'/transactions': '收支记录',
'/budget': '预算看板',
'/assets': '资产总览',
'/policies': '保单管理',
'/lifecycle': '人生周期',
'/reports': '报表分析',
'/settings': '设置',
}
export function Header() {
const location = useLocation()
const title = pageTitles[location.pathname] || ''
return (
<header className="h-16 border-b border-border/80 bg-[#0d1117]/82 flex items-center justify-between px-6 shrink-0 backdrop-blur">
<div>
<p className="text-[11px] uppercase tracking-[0.24em] text-primary/75">Household Budget Book</p>
<h1 className="mt-1 text-base font-semibold">{title}</h1>
</div>
<MonthPicker />
</header>
)
}
+17
View File
@@ -0,0 +1,17 @@
import { Outlet } from 'react-router-dom'
import { Sidebar } from './Sidebar'
import { Header } from './Header'
export function Layout() {
return (
<div className="flex h-screen bg-background text-foreground">
<Sidebar />
<div className="flex-1 flex flex-col min-w-0">
<Header />
<main className="flex-1 overflow-auto p-6">
<Outlet />
</main>
</div>
</div>
)
}
@@ -0,0 +1,48 @@
import { NavLink } from 'react-router-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChartLine, faChartPie, faCoins, faFileShield, faHouseChimney, faReceipt, faSliders, faTimeline } from '@fortawesome/free-solid-svg-icons'
import { BrandLogo } from '@/components/BrandLogo'
const links = [
{ to: '/', icon: faChartPie, label: '首页' },
{ to: '/transactions', icon: faReceipt, label: '收支' },
{ to: '/budget', icon: faCoins, label: '预算' },
{ to: '/assets', icon: faHouseChimney, label: '资产' },
{ to: '/policies', icon: faFileShield, label: '保单' },
{ to: '/lifecycle', icon: faTimeline, label: '人生' },
{ to: '/reports', icon: faChartLine, label: '报表' },
{ to: '/settings', icon: faSliders, label: '设置' },
]
export function Sidebar() {
return (
<aside className="w-64 border-r border-border/80 bg-[#0b0f15]/92 flex flex-col shrink-0 shadow-[12px_0_50px_rgba(0,0,0,0.22)] backdrop-blur">
<div className="h-20 flex items-center px-5 border-b border-border/70">
<BrandLogo />
</div>
<nav className="flex-1 p-3 space-y-1.5">
{links.map(link => (
<NavLink
key={link.to}
to={link.to}
end={link.to === '/'}
className={({ isActive }) =>
`flex items-center gap-3 px-3.5 py-2.5 rounded-md text-sm transition-all duration-150 ${
isActive
? 'bg-primary/12 text-foreground font-medium shadow-[inset_3px_0_0_#d9b86f]'
: 'text-muted hover:text-foreground hover:bg-white/[0.04]'
}`
}
>
<FontAwesomeIcon icon={link.icon} className="h-4 w-4 text-primary/85" />
{link.label}
</NavLink>
))}
</nav>
<div className="m-3 rounded-lg border border-border/70 bg-white/[0.035] p-3">
<p className="text-[11px] text-muted">家庭资产视图</p>
<p className="mt-1 text-sm font-medium text-foreground">稳健管理每月现金流</p>
</div>
</aside>
)
}
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge }
+57
View File
@@ -0,0 +1,57 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-[0_10px_28px_rgba(217,184,111,0.22)] hover:bg-[#e7c77f]",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-[#0c1016] shadow-sm hover:border-primary/50 hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button }
+76
View File
@@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg premium-panel text-card-foreground",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-5", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-normal", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-5 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-5 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+403
View File
@@ -0,0 +1,403 @@
import * as React from 'react'
import { createPortal } from 'react-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCalendarDays,
faChevronLeft,
faChevronRight,
faAnglesLeft,
faAnglesRight,
faXmark,
} from '@fortawesome/free-solid-svg-icons'
import { cn, formatLocalDate } from '@/lib/utils'
export interface DatePickerProps {
value: string
onChange: (value: string) => void
placeholder?: string
disabled?: boolean
className?: string
clearable?: boolean
size?: 'sm' | 'md'
/** YYYY-MM-DD; dates outside [min, max] are disabled */
min?: string
max?: string
}
const WEEKDAYS = ['日', '一', '二', '三', '四', '五', '六']
const MONTHS = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
type ViewMode = 'day' | 'month' | 'year'
function parseDateString(s: string): Date | null {
if (!s) return null
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)
if (!m) return null
const d = new Date(parseInt(m[1]), parseInt(m[2]) - 1, parseInt(m[3]))
return isNaN(d.getTime()) ? null : d
}
function sameDay(a: Date, b: Date) {
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
}
function startOfMonth(d: Date) {
return new Date(d.getFullYear(), d.getMonth(), 1)
}
function addMonths(d: Date, n: number) {
return new Date(d.getFullYear(), d.getMonth() + n, 1)
}
export function DatePicker({
value,
onChange,
placeholder = '选择日期',
disabled,
className,
clearable = false,
size = 'md',
min,
max,
}: DatePickerProps) {
const [open, setOpen] = React.useState(false)
const [view, setView] = React.useState<ViewMode>('day')
const selected = React.useMemo(() => parseDateString(value), [value])
const today = React.useMemo(() => new Date(), [])
const [cursor, setCursor] = React.useState<Date>(() => selected || new Date())
const triggerRef = React.useRef<HTMLButtonElement | null>(null)
const popupRef = React.useRef<HTMLDivElement | null>(null)
const [popupStyle, setPopupStyle] = React.useState<React.CSSProperties>({})
const openPopup = () => {
if (disabled) return
setCursor(selected || new Date())
setView('day')
setOpen(true)
}
const togglePopup = () => {
if (open) setOpen(false)
else openPopup()
}
const updatePosition = React.useCallback(() => {
if (!triggerRef.current) return
const rect = triggerRef.current.getBoundingClientRect()
const viewportH = window.innerHeight
const popupH = 320
const openUp = viewportH - rect.bottom < popupH + 12 && rect.top > popupH + 12
setPopupStyle({
position: 'fixed',
left: rect.left,
top: openUp ? Math.max(8, rect.top - popupH - 6) : rect.bottom + 6,
minWidth: Math.max(rect.width, 280),
zIndex: 80,
pointerEvents: 'auto',
})
}, [])
React.useEffect(() => {
if (!open) return
updatePosition()
const handler = () => updatePosition()
window.addEventListener('resize', handler)
window.addEventListener('scroll', handler, true)
return () => {
window.removeEventListener('resize', handler)
window.removeEventListener('scroll', handler, true)
}
}, [open, updatePosition])
React.useEffect(() => {
if (!open) return
const onDoc = (e: MouseEvent) => {
const t = e.target as Node
if (triggerRef.current && triggerRef.current.contains(t)) return
if (popupRef.current && popupRef.current.contains(t)) return
setOpen(false)
}
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false)
}
document.addEventListener('mousedown', onDoc)
document.addEventListener('keydown', onKey)
return () => {
document.removeEventListener('mousedown', onDoc)
document.removeEventListener('keydown', onKey)
}
}, [open])
const minDate = React.useMemo(() => parseDateString(min || ''), [min])
const maxDate = React.useMemo(() => parseDateString(max || ''), [max])
const isOutOfRange = (d: Date) => {
if (minDate && d < minDate) return true
if (maxDate && d > maxDate) return true
return false
}
const renderTrigger = () => {
const labelText = selected
? `${selected.getFullYear()}年${selected.getMonth() + 1}月${selected.getDate()}日`
: null
return (
<button
ref={triggerRef}
type="button"
disabled={disabled}
onClick={togglePopup}
className={cn(
'date-picker-trigger',
size === 'sm' && 'h-8 text-xs',
open && 'date-picker-trigger-open',
className,
)}
>
<span className="flex items-center gap-2 truncate">
<FontAwesomeIcon icon={faCalendarDays} className="h-3.5 w-3.5 text-primary" />
<span className={cn('truncate', !labelText && 'text-muted')}>{labelText ?? placeholder}</span>
</span>
{clearable && labelText && !disabled && (
<span
role="button"
tabIndex={-1}
className="tree-select-clear"
onClick={e => {
e.stopPropagation()
onChange('')
}}
>
<FontAwesomeIcon icon={faXmark} className="h-3 w-3" />
</span>
)}
</button>
)
}
const renderDayView = () => {
const monthStart = startOfMonth(cursor)
const startWeekday = monthStart.getDay()
const gridStart = new Date(monthStart)
gridStart.setDate(gridStart.getDate() - startWeekday)
const days: Date[] = []
for (let i = 0; i < 42; i++) {
const d = new Date(gridStart)
d.setDate(gridStart.getDate() + i)
days.push(d)
}
return (
<>
<div className="date-picker-header">
<div className="flex items-center gap-1">
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(addMonths(cursor, -12))}
aria-label="上一年"
>
<FontAwesomeIcon icon={faAnglesLeft} className="h-3 w-3" />
</button>
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(addMonths(cursor, -1))}
aria-label="上个月"
>
<FontAwesomeIcon icon={faChevronLeft} className="h-3 w-3" />
</button>
</div>
<div className="date-picker-title">
<button type="button" className="date-picker-title-btn" onClick={() => setView('year')}>
{cursor.getFullYear()} 年
</button>
<button type="button" className="date-picker-title-btn" onClick={() => setView('month')}>
{cursor.getMonth() + 1} 月
</button>
</div>
<div className="flex items-center gap-1">
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(addMonths(cursor, 1))}
aria-label="下个月"
>
<FontAwesomeIcon icon={faChevronRight} className="h-3 w-3" />
</button>
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(addMonths(cursor, 12))}
aria-label="下一年"
>
<FontAwesomeIcon icon={faAnglesRight} className="h-3 w-3" />
</button>
</div>
</div>
<div className="date-picker-grid">
{WEEKDAYS.map(w => (
<div key={w} className="date-picker-weekday">{w}</div>
))}
{days.map((d, i) => {
const inMonth = d.getMonth() === cursor.getMonth()
const isToday = sameDay(d, today)
const isSelected = selected ? sameDay(d, selected) : false
const dayDisabled = isOutOfRange(d)
return (
<button
key={i}
type="button"
disabled={dayDisabled}
className={cn(
'date-picker-day',
!inMonth && 'date-picker-day-outside',
isToday && !isSelected && 'date-picker-day-today',
isSelected && 'date-picker-day-selected',
dayDisabled && 'cursor-not-allowed opacity-30',
)}
onClick={() => {
onChange(formatLocalDate(d))
setOpen(false)
}}
>
{d.getDate()}
</button>
)
})}
</div>
<div className="date-picker-footer">
<button
type="button"
className="date-picker-footer-btn"
onClick={() => {
onChange(formatLocalDate(today))
setOpen(false)
}}
>
今天
</button>
{clearable && (
<button
type="button"
className="date-picker-footer-btn"
onClick={() => {
onChange('')
setOpen(false)
}}
>
清除
</button>
)}
</div>
</>
)
}
const renderMonthView = () => (
<>
<div className="date-picker-header">
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(new Date(cursor.getFullYear() - 1, cursor.getMonth(), 1))}
>
<FontAwesomeIcon icon={faChevronLeft} className="h-3 w-3" />
</button>
<button type="button" className="date-picker-title-btn date-picker-title" onClick={() => setView('year')}>
{cursor.getFullYear()} 年
</button>
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(new Date(cursor.getFullYear() + 1, cursor.getMonth(), 1))}
>
<FontAwesomeIcon icon={faChevronRight} className="h-3 w-3" />
</button>
</div>
<div className="date-picker-month-grid">
{MONTHS.map((m, idx) => {
const isActive = selected && selected.getFullYear() === cursor.getFullYear() && selected.getMonth() === idx
return (
<button
key={m}
type="button"
className={cn('date-picker-month-cell', isActive && 'date-picker-cell-active')}
onClick={() => {
setCursor(new Date(cursor.getFullYear(), idx, 1))
setView('day')
}}
>
{m}
</button>
)
})}
</div>
</>
)
const renderYearView = () => {
const start = Math.floor(cursor.getFullYear() / 12) * 12
const years = Array.from({ length: 12 }, (_, i) => start + i)
return (
<>
<div className="date-picker-header">
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(new Date(cursor.getFullYear() - 12, cursor.getMonth(), 1))}
>
<FontAwesomeIcon icon={faChevronLeft} className="h-3 w-3" />
</button>
<span className="date-picker-title">{start} - {start + 11}</span>
<button
type="button"
className="date-picker-nav-btn"
onClick={() => setCursor(new Date(cursor.getFullYear() + 12, cursor.getMonth(), 1))}
>
<FontAwesomeIcon icon={faChevronRight} className="h-3 w-3" />
</button>
</div>
<div className="date-picker-year-grid">
{years.map(y => {
const isActive = selected && selected.getFullYear() === y
return (
<button
key={y}
type="button"
className={cn('date-picker-year-cell', isActive && 'date-picker-cell-active')}
onClick={() => {
setCursor(new Date(y, cursor.getMonth(), 1))
setView('month')
}}
>
{y}
</button>
)
})}
</div>
</>
)
}
return (
<>
{renderTrigger()}
{open &&
createPortal(
<div
ref={popupRef}
className="date-picker-popup"
style={popupStyle}
onPointerDown={e => e.stopPropagation()}
onMouseDown={e => e.stopPropagation()}
onClick={e => e.stopPropagation()}
>
{view === 'day' && renderDayView()}
{view === 'month' && renderMonthView()}
{view === 'year' && renderYearView()}
</div>,
document.body,
)}
</>
)
}
+121
View File
@@ -0,0 +1,121 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faXmark } from "@fortawesome/free-solid-svg-icons"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 premium-panel bg-card p-6 shadow-2xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 grid h-8 w-8 place-items-center rounded-md text-muted transition-colors hover:bg-accent hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<FontAwesomeIcon icon={faXmark} className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+23
View File
@@ -0,0 +1,23 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md premium-field px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted focus-visible:outline-none focus-visible:ring-1 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
type === "date" && "app-date-input",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+26
View File
@@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+15
View File
@@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-primary/10", className)}
{...props}
/>
)
}
export { Skeleton }
+120
View File
@@ -0,0 +1,120 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto rounded-lg border border-border/70 bg-[#0c1016]/60">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b [&_tr]:border-border/70", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b border-border/60 transition-colors hover:bg-white/[0.035] data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-10 px-3 text-left align-middle font-medium text-muted [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn(
"p-3 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+53
View File
@@ -0,0 +1,53 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-lg premium-segment p-1 text-muted",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+363
View File
@@ -0,0 +1,363 @@
import * as React from 'react'
import { createPortal } from 'react-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faChevronDown,
faChevronRight,
faMagnifyingGlass,
faCheck,
faXmark,
} from '@fortawesome/free-solid-svg-icons'
import { cn } from '@/lib/utils'
export interface TreeSelectNode {
id: string
label: string
children?: TreeSelectNode[]
selectable?: boolean
meta?: string
}
export interface TreeSelectProps {
value: string
onChange: (value: string) => void
nodes: TreeSelectNode[]
placeholder?: string
disabled?: boolean
className?: string
variant?: 'default' | 'muted'
clearable?: boolean
emptyText?: string
searchable?: boolean
size?: 'sm' | 'md'
}
interface FlatNode extends TreeSelectNode {
parentId: string | null
depth: number
hasChildren: boolean
}
function flattenTree(nodes: TreeSelectNode[], parentId: string | null = null, depth = 0): FlatNode[] {
const result: FlatNode[] = []
for (const node of nodes) {
const hasChildren = !!node.children && node.children.length > 0
result.push({ ...node, parentId, depth, hasChildren })
if (hasChildren) {
result.push(...flattenTree(node.children!, node.id, depth + 1))
}
}
return result
}
function findNode(nodes: TreeSelectNode[], id: string): TreeSelectNode | null {
for (const node of nodes) {
if (node.id === id) return node
if (node.children) {
const hit = findNode(node.children, id)
if (hit) return hit
}
}
return null
}
function getDescendantIds(node: TreeSelectNode): string[] {
const ids: string[] = []
if (node.children) {
for (const child of node.children) {
ids.push(child.id)
ids.push(...getDescendantIds(child))
}
}
return ids
}
export function TreeSelect({
value,
onChange,
nodes,
placeholder = '请选择',
disabled,
className,
variant = 'default',
clearable = false,
emptyText = '暂无可选项',
searchable = true,
size = 'md',
}: TreeSelectProps) {
const [open, setOpen] = React.useState(false)
const [keyword, setKeyword] = React.useState('')
const [collapsed, setCollapsed] = React.useState<Set<string>>(() => new Set())
const triggerRef = React.useRef<HTMLButtonElement | null>(null)
const popupRef = React.useRef<HTMLDivElement | null>(null)
const [popupStyle, setPopupStyle] = React.useState<React.CSSProperties>({})
const flat = React.useMemo(() => flattenTree(nodes), [nodes])
const selectedNode = React.useMemo(() => (value ? findNode(nodes, value) : null), [nodes, value])
// Filtered visible ids based on keyword
const visibleIds = React.useMemo(() => {
if (!keyword.trim()) return null
const kw = keyword.trim().toLowerCase()
const visible = new Set<string>()
for (const node of flat) {
if (node.label.toLowerCase().includes(kw)) {
visible.add(node.id)
// include all ancestors
let pid = node.parentId
while (pid) {
visible.add(pid)
const parent = flat.find(n => n.id === pid)
pid = parent ? parent.parentId : null
}
// include all descendants
const target = findNode(nodes, node.id)
if (target) {
for (const id of getDescendantIds(target)) visible.add(id)
}
}
}
return visible
}, [flat, keyword, nodes])
const updatePopupPosition = React.useCallback(() => {
if (!triggerRef.current) return
const rect = triggerRef.current.getBoundingClientRect()
const viewportH = window.innerHeight
const spaceBelow = viewportH - rect.bottom
const popupMaxH = 320
const openUp = spaceBelow < popupMaxH + 12 && rect.top > popupMaxH + 12
setPopupStyle({
position: 'fixed',
left: rect.left,
top: openUp ? Math.max(8, rect.top - popupMaxH - 6) : rect.bottom + 6,
width: Math.max(rect.width, 240),
maxHeight: popupMaxH,
zIndex: 80,
pointerEvents: 'auto',
})
}, [])
React.useEffect(() => {
if (!open) return
updatePopupPosition()
const handler = () => updatePopupPosition()
window.addEventListener('resize', handler)
window.addEventListener('scroll', handler, true)
return () => {
window.removeEventListener('resize', handler)
window.removeEventListener('scroll', handler, true)
}
}, [open, updatePopupPosition])
React.useEffect(() => {
if (!open) return
const onDocClick = (e: MouseEvent) => {
const target = e.target as Node
if (
triggerRef.current && triggerRef.current.contains(target)
) return
if (popupRef.current && popupRef.current.contains(target)) return
setOpen(false)
}
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false)
}
document.addEventListener('mousedown', onDocClick)
document.addEventListener('keydown', onKey)
return () => {
document.removeEventListener('mousedown', onDocClick)
document.removeEventListener('keydown', onKey)
}
}, [open])
const expandAncestors = React.useCallback(
(id: string) => {
setCollapsed(prev => {
const next = new Set(prev)
let pid: string | null = null
const inFlat = flat.find(n => n.id === id)
pid = inFlat?.parentId ?? null
while (pid) {
next.delete(pid)
const parent = flat.find(n => n.id === pid)
pid = parent ? parent.parentId : null
}
return next
})
},
[flat],
)
const togglePopup = () => {
if (disabled) return
if (!open) {
if (selectedNode) expandAncestors(selectedNode.id)
setOpen(true)
} else {
setOpen(false)
}
}
const toggleCollapse = (id: string) => {
setCollapsed(prev => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const handleSelect = (node: FlatNode) => {
if (node.selectable === false) {
toggleCollapse(node.id)
return
}
onChange(node.id)
setOpen(false)
setKeyword('')
}
const renderRows = () => {
const rows: React.ReactNode[] = []
for (const node of flat) {
// Hide if any ancestor is collapsed
let pid = node.parentId
let hidden = false
while (pid) {
if (collapsed.has(pid)) {
hidden = true
break
}
const parent = flat.find(n => n.id === pid)
pid = parent ? parent.parentId : null
}
if (hidden) continue
if (visibleIds && !visibleIds.has(node.id)) continue
const isSelected = node.id === value
const isParent = node.hasChildren
const isCollapsed = collapsed.has(node.id)
const isSelectable = node.selectable !== false
rows.push(
<button
key={node.id}
type="button"
className={cn(
'tree-select-row',
isSelected && 'tree-select-row-selected',
!isSelectable && 'tree-select-row-parent',
)}
style={{ paddingLeft: 8 + node.depth * 16 }}
onClick={() => handleSelect(node)}
>
<span
className="tree-select-chevron"
onClick={e => {
if (isParent) {
e.stopPropagation()
toggleCollapse(node.id)
}
}}
>
{isParent ? (
<FontAwesomeIcon
icon={isCollapsed ? faChevronRight : faChevronDown}
className="h-3 w-3"
/>
) : (
<span className="block h-3 w-3" />
)}
</span>
<span className="tree-select-label">{node.label}</span>
{node.meta && <span className="tree-select-meta">{node.meta}</span>}
{isSelected && (
<FontAwesomeIcon icon={faCheck} className="h-3 w-3 text-primary" />
)}
</button>,
)
}
return rows
}
const rows = renderRows()
const triggerLabel = selectedNode?.label
return (
<>
<button
ref={triggerRef}
type="button"
disabled={disabled}
onClick={togglePopup}
className={cn(
'tree-select-trigger',
variant === 'muted' && 'tree-select-trigger-muted',
size === 'sm' && 'h-8 text-xs',
open && 'tree-select-trigger-open',
className,
)}
>
<span className={cn('tree-select-trigger-text', !triggerLabel && 'text-muted')}>
{triggerLabel ?? placeholder}
</span>
<span className="ml-2 flex items-center gap-1">
{clearable && triggerLabel && !disabled && (
<span
role="button"
tabIndex={-1}
className="tree-select-clear"
onClick={e => {
e.stopPropagation()
onChange('')
}}
>
<FontAwesomeIcon icon={faXmark} className="h-3 w-3" />
</span>
)}
<FontAwesomeIcon
icon={faChevronDown}
className={cn('h-3 w-3 opacity-60 transition-transform', open && 'rotate-180')}
/>
</span>
</button>
{open &&
createPortal(
<div
ref={popupRef}
className="tree-select-popup"
style={popupStyle}
onPointerDown={e => e.stopPropagation()}
onMouseDown={e => e.stopPropagation()}
onClick={e => e.stopPropagation()}
>
{searchable && (
<div className="tree-select-search">
<FontAwesomeIcon icon={faMagnifyingGlass} className="h-3 w-3 text-muted" />
<input
value={keyword}
onChange={e => setKeyword(e.target.value)}
placeholder="搜索分类..."
className="tree-select-search-input"
/>
{keyword && (
<button
type="button"
className="tree-select-clear"
onClick={() => setKeyword('')}
>
<FontAwesomeIcon icon={faXmark} className="h-3 w-3" />
</button>
)}
</div>
)}
<div className="tree-select-list">
{rows.length > 0 ? rows : <div className="tree-select-empty">{emptyText}</div>}
</div>
</div>,
document.body,
)}
</>
)
}
+22
View File
@@ -0,0 +1,22 @@
import { useReducer, type ReactNode } from 'react'
import { AppCtx, initialState, type AppAction, type AppState } from '@/context/contextState'
function appReducer(state: AppState, action: AppAction): AppState {
switch (action.type) {
case 'SET_YEAR':
return { ...state, selectedYear: action.year }
case 'SET_MONTH':
return { ...state, selectedMonth: action.month }
default:
return state
}
}
export function AppProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(appReducer, initialState)
return (
<AppCtx.Provider value={{ state, dispatch }}>
{children}
</AppCtx.Provider>
)
}
+23
View File
@@ -0,0 +1,23 @@
import { createContext, type Dispatch } from 'react'
export interface AppState {
selectedYear: string
selectedMonth: string
}
export type AppAction =
| { type: 'SET_YEAR'; year: string }
| { type: 'SET_MONTH'; month: string }
export const initialState: AppState = (() => {
const now = new Date()
return {
selectedYear: now.getFullYear().toString(),
selectedMonth: (now.getMonth() + 1).toString().padStart(2, '0'),
}
})()
export const AppCtx = createContext<{
state: AppState
dispatch: Dispatch<AppAction>
}>({ state: initialState, dispatch: () => {} })
+6
View File
@@ -0,0 +1,6 @@
import { useContext } from 'react'
import { AppCtx } from '@/context/contextState'
export function useAppContext() {
return useContext(AppCtx)
}
+38
View File
@@ -0,0 +1,38 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, ApiError, type CreateAccountRequest, type UpdateAccountRequest } from '@/lib/api'
import { accountMutationInvalidation, invalidateKeys } from '@/lib/queryInvalidation'
import { queryKeys } from '@/lib/queryKeys'
export function useAccounts() {
const qc = useQueryClient()
const query = useQuery({
queryKey: queryKeys.accounts,
queryFn: () => api.getAccounts(),
staleTime: 5 * 60_000,
})
const createMutation = useMutation({
mutationFn: (req: CreateAccountRequest) => api.createAccount(req),
onSuccess: () => invalidateKeys(qc, accountMutationInvalidation()),
})
const updateMutation = useMutation({
mutationFn: ({ id, req }: { id: number; req: UpdateAccountRequest }) => api.updateAccount(id, req),
onSuccess: () => invalidateKeys(qc, accountMutationInvalidation()),
})
const deleteMutation = useMutation({
mutationFn: (id: number) => api.deleteAccount(id),
onSuccess: () => invalidateKeys(qc, accountMutationInvalidation()),
})
return {
accounts: query.data ?? [],
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取账户列表失败' : null,
createAccount: createMutation.mutateAsync,
updateAccount: (id: number, req: UpdateAccountRequest) => updateMutation.mutateAsync({ id, req }),
deleteAccount: deleteMutation.mutateAsync,
refetch: () => qc.invalidateQueries({ queryKey: queryKeys.accounts }),
}
}
+57
View File
@@ -0,0 +1,57 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { api, type Asset, type Liability } from '@/lib/api'
import {
assetMutationInvalidation,
invalidateKeys,
} from '@/lib/queryInvalidation'
interface SaveAssetInput {
id?: number
payload: Partial<Asset>
}
interface SaveLiabilityInput {
id?: number
payload: Partial<Liability>
}
export function useAssetMutations() {
const queryClient = useQueryClient()
const saveAssetMutation = useMutation({
mutationFn: ({ id, payload }: SaveAssetInput) =>
id === undefined ? api.createAsset(payload) : api.updateAsset(id, payload),
onSuccess: () =>
invalidateKeys(queryClient, assetMutationInvalidation('asset')),
})
const deleteAssetMutation = useMutation({
mutationFn: (id: number) => api.deleteAsset(id),
onSuccess: () =>
invalidateKeys(queryClient, assetMutationInvalidation('asset')),
})
const saveLiabilityMutation = useMutation({
mutationFn: ({ id, payload }: SaveLiabilityInput) =>
id === undefined
? api.createLiability(payload)
: api.updateLiability(id, payload),
onSuccess: () =>
invalidateKeys(queryClient, assetMutationInvalidation('liability')),
})
const deleteLiabilityMutation = useMutation({
mutationFn: (id: number) => api.deleteLiability(id),
onSuccess: () =>
invalidateKeys(queryClient, assetMutationInvalidation('liability')),
})
return {
saveAsset: saveAssetMutation.mutateAsync,
deleteAsset: deleteAssetMutation.mutateAsync,
saveLiability: saveLiabilityMutation.mutateAsync,
deleteLiability: deleteLiabilityMutation.mutateAsync,
assetPending:
saveAssetMutation.isPending || deleteAssetMutation.isPending,
liabilityPending:
saveLiabilityMutation.isPending || deleteLiabilityMutation.isPending,
}
}
+30
View File
@@ -0,0 +1,30 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, ApiError, type UpsertBudgetRequest } from '@/lib/api'
import { queryKeys } from '@/lib/queryKeys'
export function useBudgetOverview(year: number, month: number) {
const qc = useQueryClient()
const query = useQuery({
queryKey: queryKeys.budgets.month(year, month),
queryFn: () => api.getBudgetOverview(year, month),
})
const upsertMutation = useMutation({
mutationFn: (req: UpsertBudgetRequest) => api.upsertBudget(req),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.budgets.month(year, month) }),
})
const deleteMutation = useMutation({
mutationFn: (id: number) => api.deleteBudget(id),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.budgets.month(year, month) }),
})
return {
overview: query.data ?? null,
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取预算看板失败' : null,
upsertBudget: upsertMutation.mutateAsync,
deleteBudget: deleteMutation.mutateAsync,
refetch: () => qc.invalidateQueries({ queryKey: queryKeys.budgets.month(year, month) }),
}
}
+37
View File
@@ -0,0 +1,37 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, ApiError, type CreateCategoryRequest, type UpdateCategoryRequest } from '@/lib/api'
import { queryKeys } from '@/lib/queryKeys'
export function useCategories() {
const qc = useQueryClient()
const query = useQuery({
queryKey: queryKeys.categories,
queryFn: () => api.getCategories(),
staleTime: 5 * 60_000,
})
const createMutation = useMutation({
mutationFn: (req: CreateCategoryRequest) => api.createCategory(req),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.categories }),
})
const updateMutation = useMutation({
mutationFn: ({ id, req }: { id: number; req: UpdateCategoryRequest }) => api.updateCategory(id, req),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.categories }),
})
const deleteMutation = useMutation({
mutationFn: (id: number) => api.deleteCategory(id),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.categories }),
})
return {
categories: query.data ?? [],
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取分类列表失败' : null,
createCategory: createMutation.mutateAsync,
updateCategory: (id: number, req: UpdateCategoryRequest) => updateMutation.mutateAsync({ id, req }),
deleteCategory: deleteMutation.mutateAsync,
refetch: () => qc.invalidateQueries({ queryKey: queryKeys.categories }),
}
}
+26
View File
@@ -0,0 +1,26 @@
import { useQuery } from '@tanstack/react-query'
import { api, ApiError } from '@/lib/api'
import { queryKeys } from '@/lib/queryKeys'
export function useDashboardSummary(year: string, month: string) {
const query = useQuery({
queryKey: queryKeys.dashboard.summary(year, month),
queryFn: () => api.getDashboardSummary(year, month),
})
return {
summary: query.data ?? null,
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : null,
}
}
export function useDashboardRecent(limit = 5) {
const query = useQuery({
queryKey: queryKeys.dashboard.recent(limit),
queryFn: () => api.getDashboardRecent(limit),
})
return {
recentItems: query.data ?? [],
loading: query.isLoading,
}
}
@@ -0,0 +1,30 @@
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useDebouncedValue } from './useDebouncedValue'
describe('useDebouncedValue', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('连续变化时仅在延迟结束后提交最终值', async () => {
const { result, rerender } = renderHook(
({ value }) => useDebouncedValue(value, 300),
{ initialProps: { value: '' } },
)
rerender({ value: '餐' })
await act(() => vi.advanceTimersByTimeAsync(200))
rerender({ value: '餐饮' })
await act(() => vi.advanceTimersByTimeAsync(299))
expect(result.current).toBe('')
await act(() => vi.advanceTimersByTimeAsync(1))
expect(result.current).toBe('餐饮')
})
})
+12
View File
@@ -0,0 +1,12 @@
import { useEffect, useState } from 'react'
export function useDebouncedValue<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value)
useEffect(() => {
const timer = window.setTimeout(() => setDebounced(value), delay)
return () => window.clearTimeout(timer)
}, [value, delay])
return debounced
}
+37
View File
@@ -0,0 +1,37 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, ApiError, type CreateMemberRequest, type UpdateMemberRequest } from '@/lib/api'
import { queryKeys } from '@/lib/queryKeys'
export function useMembers() {
const qc = useQueryClient()
const query = useQuery({
queryKey: queryKeys.members,
queryFn: () => api.getMembers(),
staleTime: 5 * 60_000,
})
const createMutation = useMutation({
mutationFn: (req: CreateMemberRequest) => api.createMember(req),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.members }),
})
const updateMutation = useMutation({
mutationFn: ({ id, req }: { id: number; req: UpdateMemberRequest }) => api.updateMember(id, req),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.members }),
})
const deleteMutation = useMutation({
mutationFn: (id: number) => api.deleteMember(id),
onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.members }),
})
return {
members: query.data ?? [],
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取成员列表失败' : null,
createMember: createMutation.mutateAsync,
updateMember: (id: number, req: UpdateMemberRequest) => updateMutation.mutateAsync({ id, req }),
deleteMember: deleteMutation.mutateAsync,
refetch: () => qc.invalidateQueries({ queryKey: queryKeys.members }),
}
}
+46
View File
@@ -0,0 +1,46 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
const apiMocks = vi.hoisted(() => ({
getAssets: vi.fn(),
getLiabilities: vi.fn(),
getNetWorth: vi.fn(),
getAccounts: vi.fn(),
getAssetSnapshots: vi.fn(),
}))
vi.mock('@/lib/api', () => ({
api: apiMocks,
ApiError: class ApiError extends Error {},
}))
import { useAssetsOverview } from './usePhase3'
describe('useAssetsOverview', () => {
it('keeps only snapshots loading after asset data has resolved', async () => {
apiMocks.getAssets.mockResolvedValue([{ id: 1, name: '存款' }])
apiMocks.getLiabilities.mockResolvedValue([])
apiMocks.getNetWorth.mockResolvedValue({ net_worth: 100 })
apiMocks.getAccounts.mockResolvedValue([])
apiMocks.getAssetSnapshots.mockReturnValue(new Promise(() => {}))
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(() => useAssetsOverview(), { wrapper })
await waitFor(() => expect(result.current.assets).toHaveLength(1))
expect(result.current.assetsLoading).toBe(false)
expect(result.current.liabilitiesLoading).toBe(false)
expect(result.current.netWorthLoading).toBe(false)
expect(result.current.accountsLoading).toBe(false)
expect(result.current.snapshotsLoading).toBe(true)
})
})
+92
View File
@@ -0,0 +1,92 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, ApiError } from '@/lib/api'
import { queryKeys } from '@/lib/queryKeys'
export function useAssetsOverview() {
const assetsQuery = useQuery({
queryKey: queryKeys.assets.list,
queryFn: api.getAssets,
})
const liabilitiesQuery = useQuery({
queryKey: queryKeys.assets.liabilities,
queryFn: api.getLiabilities,
})
const netWorthQuery = useQuery({
queryKey: queryKeys.assets.netWorth,
queryFn: api.getNetWorth,
})
const accountsQuery = useQuery({
queryKey: queryKeys.accounts,
queryFn: api.getAccounts,
staleTime: 5 * 60_000,
})
const snapshotsQuery = useQuery({
queryKey: queryKeys.assets.snapshots,
queryFn: api.getAssetSnapshots,
})
const queries = [
assetsQuery,
liabilitiesQuery,
netWorthQuery,
accountsQuery,
snapshotsQuery,
]
const firstError = queries.find((query) => query.error)?.error
return {
assets: assetsQuery.data ?? [],
liabilities: liabilitiesQuery.data ?? [],
netWorth: netWorthQuery.data ?? null,
accounts: accountsQuery.data ?? [],
snapshots: snapshotsQuery.data ?? [],
assetsLoading: assetsQuery.isLoading,
liabilitiesLoading: liabilitiesQuery.isLoading,
netWorthLoading: netWorthQuery.isLoading,
accountsLoading: accountsQuery.isLoading,
snapshotsLoading: snapshotsQuery.isLoading,
loading: queries.some((query) => query.isLoading),
refreshing: queries.some((query) => query.isFetching),
error: firstError instanceof ApiError
? firstError.message
: firstError
? '获取资产数据失败'
: null,
}
}
export function usePolicies() {
const qc = useQueryClient()
const query = useQuery({
queryKey: ['policies'] as const,
queryFn: async () => {
const [policies, upcoming] = await Promise.all([
api.getPolicies(),
api.getUpcomingPolicies(30),
])
return { policies, upcoming }
},
})
return {
policies: query.data?.policies ?? [],
upcoming: query.data?.upcoming ?? [],
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取保单数据失败' : null,
fetchAll: () => qc.invalidateQueries({ queryKey: ['policies'] }),
}
}
export function useLifecycleEvents() {
const qc = useQueryClient()
const query = useQuery({
queryKey: ['lifecycle'] as const,
queryFn: () => api.getLifecycleEvents(),
})
return {
events: query.data ?? [],
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取人生周期失败' : null,
fetchAll: () => qc.invalidateQueries({ queryKey: ['lifecycle'] }),
}
}
+24
View File
@@ -0,0 +1,24 @@
import { useQuery } from '@tanstack/react-query'
import { api, ApiError } from '@/lib/api'
import { queryKeys } from '@/lib/queryKeys'
export function useReports() {
const fetchOverview = async (year: number, month: number, type: 'income' | 'expense' = 'expense') => {
return api.getReportOverview(year, month, type)
}
return { fetchOverview }
}
export function useReportOverview(year: number, month: number, type: 'income' | 'expense') {
const query = useQuery({
queryKey: queryKeys.reports.overview(year, month, type),
queryFn: () => api.getReportOverview(year, month, type),
})
return {
overview: query.data ?? null,
loading: query.isLoading,
error: query.error instanceof ApiError ? query.error.message : query.error ? '获取报表失败' : null,
}
}
+325
View File
@@ -0,0 +1,325 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground antialiased;
background:
radial-gradient(circle at 18% -12%, rgba(217, 184, 111, 0.12), transparent 32rem),
radial-gradient(circle at 86% 8%, rgba(56, 211, 159, 0.08), transparent 26rem),
linear-gradient(135deg, #090b0f 0%, #0d1117 46%, #080a0d 100%);
font-feature-settings: "tnum";
}
html {
color-scheme: dark;
}
::selection {
@apply bg-primary/30 text-foreground;
}
}
@layer components {
.premium-panel {
@apply border border-border/80 bg-card/90 shadow-[0_18px_60px_rgba(0,0,0,0.28),inset_0_1px_0_rgba(255,255,255,0.04)] backdrop-blur;
}
.premium-field {
@apply border-input bg-[#0c1016] text-foreground placeholder:text-muted focus:border-primary focus:ring-primary/40;
}
.premium-segment {
@apply border border-border/80 bg-[#0c1016] shadow-inner shadow-black/30;
}
.app-page {
@apply max-w-6xl space-y-6;
}
.app-page-compact {
@apply max-w-6xl space-y-4;
}
.app-toolbar {
@apply flex flex-wrap items-center gap-3 rounded-lg border border-border/80 bg-card/90 p-3 shadow-[0_18px_60px_rgba(0,0,0,0.28),inset_0_1px_0_rgba(255,255,255,0.04)] backdrop-blur;
}
.app-stack {
@apply space-y-4;
}
.app-section-title {
@apply flex items-center gap-2 text-sm font-medium;
}
.app-section-icon {
@apply h-4 w-4 text-primary;
}
.app-form {
@apply space-y-4;
}
.app-form-label {
@apply text-xs text-muted;
}
.table-muted {
@apply text-xs text-muted;
}
.app-error {
@apply mt-1 text-xs text-expense;
}
.app-success {
@apply rounded-md border border-income/30 bg-income/10 px-3 py-2 text-xs text-income;
}
.app-select {
@apply h-9 rounded-md border-input bg-[#0c1016] px-3 text-sm text-foreground placeholder:text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/40;
}
.app-select-muted {
@apply h-9 rounded-md border-input bg-[#0c1016] px-3 text-sm text-muted placeholder:text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/40;
}
.app-date-input {
@apply min-w-36 cursor-pointer border-border/80 bg-[#0c1016] text-foreground shadow-inner shadow-black/20;
color-scheme: dark;
}
.app-date-input::-webkit-calendar-picker-indicator {
cursor: pointer;
border-radius: 6px;
padding: 4px;
filter: invert(82%) sepia(29%) saturate(740%) hue-rotate(358deg) brightness(94%) contrast(92%);
opacity: 0.9;
}
.app-date-input::-webkit-calendar-picker-indicator:hover {
background: rgba(217, 184, 111, 0.14);
opacity: 1;
}
.segment-control {
@apply flex rounded-md border border-border/80 bg-[#0c1016] p-0.5 shadow-inner shadow-black/30;
}
.segment-option {
@apply flex items-center gap-1.5 rounded px-3 py-1.5 text-xs font-medium transition-colors duration-150;
}
.segment-option-muted {
@apply text-muted hover:text-foreground;
}
.segment-option-primary {
@apply bg-primary text-primary-foreground shadow;
}
.segment-option-expense {
@apply bg-expense text-white shadow;
}
.segment-option-income {
@apply bg-income text-[#06130f] shadow;
}
.summary-grid {
@apply grid grid-cols-1 gap-4 md:grid-cols-3;
}
.summary-skeleton-grid {
@apply grid grid-cols-1 gap-4 md:grid-cols-3;
}
.summary-card-glow {
@apply absolute right-0 top-0 h-24 w-24 translate-x-8 -translate-y-8 rounded-full bg-primary/10 blur-2xl;
}
.metric-icon {
@apply grid h-8 w-8 place-items-center rounded-md;
}
.settings-grid {
@apply grid grid-cols-1 gap-6 lg:grid-cols-2;
}
.account-grid {
@apply grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4;
}
.inline-actions {
@apply flex gap-1;
}
.fade-actions {
@apply flex gap-1 opacity-0 transition-opacity duration-150 group-hover:opacity-100;
}
/* Tree select */
.tree-select-trigger {
@apply flex h-9 w-full items-center justify-between rounded-md border border-input bg-[#0c1016] px-3 text-sm text-foreground transition-colors hover:border-primary/40 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50;
}
.tree-select-trigger-muted {
@apply text-muted hover:text-foreground;
}
.tree-select-trigger-open {
@apply border-primary/60 ring-1 ring-primary/30;
}
.tree-select-trigger-text {
@apply truncate text-left;
}
.tree-select-popup {
@apply flex flex-col overflow-hidden rounded-lg border border-border/80 bg-[#0c1016]/95 shadow-[0_24px_60px_rgba(0,0,0,0.55)] backdrop-blur-xl;
animation: treeSelectFadeIn 0.15s ease-out;
}
.tree-select-search {
@apply flex items-center gap-2 border-b border-border/60 px-3 py-2;
}
.tree-select-search-input {
@apply flex-1 border-0 bg-transparent text-sm text-foreground outline-none placeholder:text-muted;
}
.tree-select-list {
@apply flex-1 overflow-y-auto p-1;
}
.tree-select-row {
@apply flex w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left text-sm text-foreground/90 transition-colors hover:bg-white/[0.04] focus:bg-white/[0.06] focus:outline-none;
}
.tree-select-row-selected {
@apply bg-primary/10 text-primary;
}
.tree-select-row-parent {
@apply text-xs font-medium uppercase tracking-wider text-muted hover:bg-white/[0.03];
}
.tree-select-chevron {
@apply flex h-4 w-4 shrink-0 items-center justify-center rounded-sm text-muted hover:text-foreground;
}
.tree-select-label {
@apply flex-1 truncate;
}
.tree-select-meta {
@apply text-xs tabular-nums text-muted;
}
.tree-select-empty {
@apply px-3 py-6 text-center text-xs text-muted;
}
.tree-select-clear {
@apply grid h-5 w-5 place-items-center rounded-full text-muted transition-colors hover:bg-white/10 hover:text-foreground;
}
/* Date picker */
.date-picker-trigger {
@apply flex h-9 w-full items-center justify-between rounded-md border border-input bg-[#0c1016] px-3 text-sm text-foreground transition-colors hover:border-primary/40 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50;
}
.date-picker-trigger-open {
@apply border-primary/60 ring-1 ring-primary/30;
}
.date-picker-popup {
@apply rounded-xl border border-border/80 bg-[#0c1016]/95 p-3 shadow-[0_24px_60px_rgba(0,0,0,0.55)] backdrop-blur-xl;
animation: treeSelectFadeIn 0.15s ease-out;
}
.date-picker-header {
@apply mb-2 flex items-center justify-between gap-2;
}
.date-picker-nav-btn {
@apply grid h-7 w-7 place-items-center rounded-md text-muted transition-colors hover:bg-white/[0.06] hover:text-foreground focus:outline-none focus:ring-1 focus:ring-primary/40;
}
.date-picker-title {
@apply flex items-center gap-1 text-sm font-medium text-foreground;
}
.date-picker-title-btn {
@apply rounded px-2 py-1 transition-colors hover:bg-white/[0.06] focus:outline-none;
}
.date-picker-grid {
@apply grid grid-cols-7 gap-0.5;
}
.date-picker-weekday {
@apply grid h-8 place-items-center text-xs text-muted;
}
.date-picker-day {
@apply grid h-8 w-8 place-items-center rounded-md text-sm tabular-nums text-foreground/85 transition-colors hover:bg-white/[0.06] focus:outline-none;
}
.date-picker-day-outside {
@apply text-muted/40;
}
.date-picker-day-today {
@apply ring-1 ring-primary/40;
}
.date-picker-day-selected {
@apply bg-primary text-primary-foreground hover:bg-primary;
}
.date-picker-month-grid {
@apply grid grid-cols-3 gap-1.5;
}
.date-picker-month-cell {
@apply rounded-md px-2 py-2 text-sm text-foreground/85 transition-colors hover:bg-white/[0.06] focus:outline-none;
}
.date-picker-year-grid {
@apply grid grid-cols-4 gap-1.5;
}
.date-picker-year-cell {
@apply rounded-md px-2 py-2 text-sm text-foreground/85 transition-colors hover:bg-white/[0.06] focus:outline-none;
}
.date-picker-cell-active {
@apply bg-primary text-primary-foreground hover:bg-primary;
}
.date-picker-footer {
@apply mt-2 flex items-center justify-between border-t border-border/60 pt-2;
}
.date-picker-footer-btn {
@apply rounded-md px-2 py-1 text-xs text-muted transition-colors hover:bg-white/[0.06] hover:text-foreground focus:outline-none;
}
}
@keyframes treeSelectFadeIn {
from {
opacity: 0;
transform: translateY(-4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
+36
View File
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { api, ApiError } from './api'
describe('api.getTransactions', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it('把 AbortSignal 传给 fetch', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ items: [], total: 0, page: 1, page_size: 20 }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
)
vi.stubGlobal('fetch', fetchMock)
const controller = new AbortController()
await api.getTransactions({ page: '2' }, controller.signal)
expect(fetchMock).toHaveBeenCalledWith(
'/api/transactions?page=2',
expect.objectContaining({ signal: controller.signal }),
)
})
it('请求取消时保留 AbortError 而不包装为 ApiError', async () => {
const abortError = new DOMException('已取消', 'AbortError')
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(abortError))
const request = api.getTransactions({}, new AbortController().signal)
await expect(request).rejects.toBe(abortError)
await expect(request).rejects.not.toBeInstanceOf(ApiError)
})
})
+199
View File
@@ -0,0 +1,199 @@
import type {
Account, Category, CreateAccountRequest, CreateCategoryRequest,
CreateMemberRequest, CreateTransactionRequest, DashboardSummary,
Member, Transaction, TransactionListItem, TransactionListResponse,
BudgetOverview, UpsertBudgetRequest, Budget, ReportOverview, CategoryRankingItem, TrendItem,
Asset, AssetSnapshot, Liability, NetWorthSummary, Policy, LifecycleEvent,
ImportTransactionsResult, ImportPreviewResult, ImportBatch, DeleteTransactionsResult,
UpdateAccountRequest, UpdateCategoryRequest, UpdateMemberRequest,
UpdateTransactionRequest, AccountReconciliation, BackupStatus, PolicyPayment,
} from '@/types/index'
const BASE_URL = ''
class ApiError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.status = status
this.name = 'ApiError'
}
}
async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
let res: Response
try {
res = await fetch(BASE_URL + path, {
headers: { 'Content-Type': 'application/json' },
...options,
})
} catch (e) {
if (e instanceof DOMException && e.name === 'AbortError') throw e
throw new ApiError(e instanceof Error ? `网络请求失败:${e.message}` : '网络请求失败', 0)
}
if (res.status === 204) return undefined as T
let data: { error?: string } | unknown = null
try {
data = await res.json()
} catch {
// 非 JSON 响应(如 502 网关返回 HTML),保持 data 为 null
}
if (!res.ok) {
const msg = (data && typeof data === 'object' && 'error' in data ? (data as { error?: string }).error : null) || `请求失败 (${res.status})`
throw new ApiError(msg, res.status)
}
return data as T
}
async function apiUpload<T>(path: string, formData: FormData): Promise<T> {
let res: Response
try {
res = await fetch(BASE_URL + path, { method: 'POST', body: formData })
} catch (e) {
throw new ApiError(e instanceof Error ? `网络请求失败:${e.message}` : '网络请求失败', 0)
}
let data: { error?: string } | unknown = null
try {
data = await res.json()
} catch {
// 非 JSON 响应
}
if (!res.ok) {
const msg = (data && typeof data === 'object' && 'error' in data ? (data as { error?: string }).error : null) || `请求失败 (${res.status})`
throw new ApiError(msg, res.status)
}
return data as T
}
export const api = {
// Members
getMembers: () => apiFetch<Member[]>('/api/members'),
createMember: (req: CreateMemberRequest) =>
apiFetch<Member>('/api/members', { method: 'POST', body: JSON.stringify(req) }),
updateMember: (id: number, req: UpdateMemberRequest) =>
apiFetch<Member>(`/api/members/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteMember: (id: number) =>
apiFetch<void>(`/api/members/${id}`, { method: 'DELETE' }),
// Categories
getCategories: (type?: string) =>
apiFetch<Category[]>(`/api/categories${type ? `?type=${type}` : ''}`),
createCategory: (req: CreateCategoryRequest) =>
apiFetch<Category>('/api/categories', { method: 'POST', body: JSON.stringify(req) }),
updateCategory: (id: number, req: UpdateCategoryRequest) =>
apiFetch<Category>(`/api/categories/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteCategory: (id: number) =>
apiFetch<void>(`/api/categories/${id}`, { method: 'DELETE' }),
// Accounts
getAccounts: () => apiFetch<Account[]>('/api/accounts'),
createAccount: (req: CreateAccountRequest) =>
apiFetch<Account>('/api/accounts', { method: 'POST', body: JSON.stringify(req) }),
updateAccount: (id: number, req: UpdateAccountRequest) =>
apiFetch<Account>(`/api/accounts/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteAccount: (id: number) =>
apiFetch<void>(`/api/accounts/${id}`, { method: 'DELETE' }),
reconcileAccount: (id: number, actual_balance: number, note = '', create_adjustment = true) =>
apiFetch<AccountReconciliation>(`/api/accounts/${id}/reconcile`, { method: 'POST', body: JSON.stringify({ actual_balance, note, create_adjustment }) }),
getAccountReconciliations: (id: number) => apiFetch<AccountReconciliation[]>(`/api/accounts/${id}/reconciliations`),
// Transactions
getTransactions: (params: Record<string, string>, signal?: AbortSignal) => {
const qs = new URLSearchParams(params).toString()
return apiFetch<TransactionListResponse>(
`/api/transactions${qs ? `?${qs}` : ''}`,
{ signal },
)
},
createTransaction: (req: CreateTransactionRequest) =>
apiFetch<Transaction>('/api/transactions', { method: 'POST', body: JSON.stringify(req) }),
previewImportTransactions: (formData: FormData) =>
apiUpload<ImportPreviewResult>('/api/transactions/import/preview', formData),
importTransactions: (formData: FormData) =>
apiUpload<ImportTransactionsResult>('/api/transactions/import', formData),
getImportBatches: () =>
apiFetch<ImportBatch[]>('/api/transactions/import-batches'),
deleteTransactionsBatch: (ids: number[]) =>
apiFetch<DeleteTransactionsResult>('/api/transactions/batch-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
deleteImportBatch: (id: number) =>
apiFetch<DeleteTransactionsResult>(`/api/transactions/import-batches/${id}`, { method: 'DELETE' }),
updateTransaction: (id: number, req: UpdateTransactionRequest) =>
apiFetch<Transaction>(`/api/transactions/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteTransaction: (id: number) =>
apiFetch<void>(`/api/transactions/${id}`, { method: 'DELETE' }),
// Dashboard
getDashboardSummary: (year?: string, month?: string) => {
const params = new URLSearchParams()
if (year) params.set('year', year)
if (month) params.set('month', month)
const qs = params.toString()
return apiFetch<DashboardSummary>(`/api/dashboard/summary${qs ? `?${qs}` : ''}`)
},
getDashboardRecent: (limit = 5) =>
apiFetch<TransactionListItem[]>(`/api/dashboard/recent?limit=${limit}`),
// Budgets
getBudgetOverview: (year: number, month: number) =>
apiFetch<BudgetOverview>(`/api/budgets/${year}/${month}`),
upsertBudget: (req: UpsertBudgetRequest) =>
apiFetch<Budget>('/api/budgets', { method: 'PUT', body: JSON.stringify(req) }),
deleteBudget: (id: number) => apiFetch<void>(`/api/budgets/${id}`, { method: 'DELETE' }),
// Reports
getReportOverview: (year: number, month: number, type: 'income' | 'expense' = 'expense') =>
apiFetch<ReportOverview>(`/api/reports/overview?year=${year}&month=${month}&type=${type}`),
getCategoryRanking: (year: number, month: number, type = 'expense') =>
apiFetch<CategoryRankingItem[]>(`/api/reports/category-ranking?year=${year}&month=${month}&type=${type}`),
getTrend: (year: number) =>
apiFetch<TrendItem[]>(`/api/reports/trend?year=${year}`),
// Assets & liabilities
getAssets: () => apiFetch<Asset[]>('/api/assets'),
createAsset: (req: Partial<Asset>) =>
apiFetch<Asset>('/api/assets', { method: 'POST', body: JSON.stringify(req) }),
updateAsset: (id: number, req: Partial<Asset>) =>
apiFetch<Asset>(`/api/assets/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteAsset: (id: number) => apiFetch<void>(`/api/assets/${id}`, { method: 'DELETE' }),
getLiabilities: () => apiFetch<Liability[]>('/api/liabilities'),
createLiability: (req: Partial<Liability>) =>
apiFetch<Liability>('/api/liabilities', { method: 'POST', body: JSON.stringify(req) }),
updateLiability: (id: number, req: Partial<Liability>) =>
apiFetch<Liability>(`/api/liabilities/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteLiability: (id: number) => apiFetch<void>(`/api/liabilities/${id}`, { method: 'DELETE' }),
getNetWorth: () => apiFetch<NetWorthSummary>('/api/assets/net-worth'),
getAssetSnapshots: () => apiFetch<AssetSnapshot[]>('/api/assets/snapshots'),
// Policies
getPolicies: () => apiFetch<Policy[]>('/api/policies'),
getUpcomingPolicies: (days = 30) => apiFetch<Policy[]>(`/api/policies/upcoming?days=${days}`),
createPolicy: (req: Partial<Policy>) =>
apiFetch<Policy>('/api/policies', { method: 'POST', body: JSON.stringify(req) }),
updatePolicy: (id: number, req: Partial<Policy>) =>
apiFetch<Policy>(`/api/policies/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deletePolicy: (id: number) => apiFetch<void>(`/api/policies/${id}`, { method: 'DELETE' }),
getPolicyPayments: (id: number) => apiFetch<PolicyPayment[]>(`/api/policies/${id}/payments`),
createPolicyPayment: (id: number, req: Partial<PolicyPayment>) => apiFetch<PolicyPayment>(`/api/policies/${id}/payments`, { method: 'POST', body: JSON.stringify(req) }),
updatePolicyPayment: (id: number, req: Partial<PolicyPayment>) => apiFetch<PolicyPayment>(`/api/policy-payments/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
getBackupStatus: () => apiFetch<BackupStatus>('/api/backups/status'),
createBackup: () => apiFetch<BackupStatus>('/api/backups', { method: 'POST' }),
// Lifecycle
getLifecycleEvents: () => apiFetch<LifecycleEvent[]>('/api/lifecycle'),
createLifecycleEvent: (req: Partial<LifecycleEvent>) =>
apiFetch<LifecycleEvent>('/api/lifecycle/events', { method: 'POST', body: JSON.stringify(req) }),
updateLifecycleEvent: (id: number, req: Partial<LifecycleEvent>) =>
apiFetch<LifecycleEvent>(`/api/lifecycle/events/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
deleteLifecycleEvent: (id: number) => apiFetch<void>(`/api/lifecycle/events/${id}`, { method: 'DELETE' }),
}
export type { Account, AccountReconciliation, BackupStatus, Category, CreateAccountRequest, CreateCategoryRequest, CreateMemberRequest, CreateTransactionRequest, DashboardSummary, Member, Transaction, TransactionListItem, TransactionListResponse, UpdateAccountRequest, UpdateCategoryRequest, UpdateMemberRequest, UpdateTransactionRequest, BudgetOverview, UpsertBudgetRequest, Budget, ReportOverview, CategoryRankingItem, TrendItem, Asset, AssetSnapshot, Liability, NetWorthSummary, Policy, PolicyPayment, LifecycleEvent, ImportTransactionsResult, ImportPreviewResult, ImportBatch, DeleteTransactionsResult }
export { ApiError }
+51
View File
@@ -0,0 +1,51 @@
import type { Category } from '@/lib/api'
import type { TreeSelectNode } from '@/components/ui/tree-select'
export function buildCategoryTree(
categories: Category[],
config: { allowParentSelect: boolean },
): TreeSelectNode[] {
const typeRank = (t: string) => (t === 'expense' ? 0 : 1)
const top = categories
.filter((c) => c.parent_id === null)
.sort(
(a, b) =>
typeRank(a.type) - typeRank(b.type) ||
a.sort_order - b.sort_order ||
a.id - b.id,
)
const children = categories
.filter((c) => c.parent_id !== null)
.sort(
(a, b) =>
typeRank(a.type) - typeRank(b.type) ||
a.sort_order - b.sort_order ||
a.id - b.id,
)
const orphanParentIds = new Set(
children
.filter((c) => !top.some((parent) => parent.id === c.parent_id))
.map((c) => c.id),
)
const orphans = children.filter((c) => orphanParentIds.has(c.id))
const tree: TreeSelectNode[] = top.map((parent) => {
const kids = children.filter((c) => c.parent_id === parent.id)
if (kids.length === 0) {
return { id: String(parent.id), label: parent.name, selectable: true }
}
return {
id: String(parent.id),
label: parent.name,
selectable: config.allowParentSelect,
children: kids.map((child) => ({
id: String(child.id),
label: child.name,
selectable: true,
})),
}
})
for (const orphan of orphans) {
tree.push({ id: String(orphan.id), label: orphan.name, selectable: true })
}
return tree
}
+20
View File
@@ -0,0 +1,20 @@
export type ImportSourceKind = 'cmb_debit' | 'cmb_credit' | 'alipay' | 'wechat'
export function importIsCSV(kind: string): boolean {
return kind === 'alipay' || kind === 'wechat'
}
export function sourceKindMatchesAccount(kind: string, accountType: string): boolean {
switch (kind) {
case 'cmb_debit':
return accountType === 'debit_card' || accountType === 'bank_card'
case 'cmb_credit':
return accountType === 'credit_card'
case 'alipay':
return accountType === 'alipay'
case 'wechat':
return accountType === 'wechat'
default:
return true
}
}
+11
View File
@@ -0,0 +1,11 @@
import { QueryClient } from '@tanstack/react-query'
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
retry: 1,
refetchOnWindowFocus: false,
},
},
})
@@ -0,0 +1,73 @@
import { QueryClient } from '@tanstack/react-query'
import { describe, expect, it } from 'vitest'
import {
accountMutationInvalidation,
assetMutationInvalidation,
invalidateKeys,
transactionMutationInvalidation,
} from './queryInvalidation'
import { queryKeys } from './queryKeys'
describe('query invalidation', () => {
it('defines hierarchical asset query keys', () => {
expect(queryKeys.assets).toEqual({
all: ['assets'],
list: ['assets', 'list'],
liabilities: ['assets', 'liabilities'],
netWorth: ['assets', 'netWorth'],
snapshots: ['assets', 'snapshots'],
})
})
it('invalidates only asset list and net worth for asset mutations', () => {
expect(assetMutationInvalidation('asset')).toEqual([
queryKeys.assets.list,
queryKeys.assets.netWorth,
])
expect(assetMutationInvalidation('asset')).not.toContain(queryKeys.accounts)
expect(assetMutationInvalidation('asset')).not.toContain(queryKeys.assets.snapshots)
})
it('invalidates only liability list and net worth for liability mutations', () => {
expect(assetMutationInvalidation('liability')).toEqual([
queryKeys.assets.liabilities,
queryKeys.assets.netWorth,
])
expect(assetMutationInvalidation('liability')).not.toContain(queryKeys.assets.list)
})
it('invalidates only accounts and net worth for account mutations', () => {
expect(accountMutationInvalidation()).toEqual([
queryKeys.accounts,
queryKeys.assets.netWorth,
])
expect(accountMutationInvalidation()).not.toContain(queryKeys.assets.list)
expect(accountMutationInvalidation()).not.toContain(queryKeys.assets.snapshots)
})
it('invalidates every transaction-dependent query root', () => {
expect(transactionMutationInvalidation()).toEqual([
queryKeys.transactions.all,
queryKeys.importBatches,
queryKeys.accounts,
queryKeys.assets.netWorth,
queryKeys.dashboard.all,
queryKeys.budgets.all,
queryKeys.reports.all,
])
})
it('invalidates every supplied query key', async () => {
const queryClient = new QueryClient()
const keys = [queryKeys.assets.list, queryKeys.assets.netWorth] as const
keys.forEach((queryKey) => queryClient.setQueryData(queryKey, 'cached'))
await invalidateKeys(queryClient, keys)
keys.forEach((queryKey) => {
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)
})
})
})
+39
View File
@@ -0,0 +1,39 @@
import type { QueryClient, QueryKey } from '@tanstack/react-query'
import { queryKeys } from './queryKeys'
export type AssetMutationKind = 'asset' | 'liability'
export function assetMutationInvalidation(
kind: AssetMutationKind,
): readonly QueryKey[] {
return [
kind === 'asset' ? queryKeys.assets.list : queryKeys.assets.liabilities,
queryKeys.assets.netWorth,
]
}
export function accountMutationInvalidation(): readonly QueryKey[] {
return [queryKeys.accounts, queryKeys.assets.netWorth]
}
export function transactionMutationInvalidation(): readonly QueryKey[] {
return [
queryKeys.transactions.all,
queryKeys.importBatches,
queryKeys.accounts,
queryKeys.assets.netWorth,
queryKeys.dashboard.all,
queryKeys.budgets.all,
queryKeys.reports.all,
]
}
export async function invalidateKeys(
queryClient: QueryClient,
keys: readonly QueryKey[],
): Promise<void> {
await Promise.all(
keys.map((queryKey) => queryClient.invalidateQueries({ queryKey })),
)
}
+31
View File
@@ -0,0 +1,31 @@
export const queryKeys = {
categories: ['categories'] as const,
accounts: ['accounts'] as const,
members: ['members'] as const,
importBatches: ['importBatches'] as const,
transactions: {
all: ['transactions'] as const,
list: (params: Record<string, string>) => ['transactions', 'list', params] as const,
},
dashboard: {
all: ['dashboard'] as const,
summary: (year: string, month: string) => ['dashboard', 'summary', year, month] as const,
recent: (limit: number) => ['dashboard', 'recent', limit] as const,
},
reports: {
all: ['reports'] as const,
overview: (year: number, month: number, type: string) =>
['reports', 'overview', year, month, type] as const,
},
budgets: {
all: ['budgets'] as const,
month: (year: number, month: number) => ['budgets', year, month] as const,
},
assets: {
all: ['assets'] as const,
list: ['assets', 'list'] as const,
liabilities: ['assets', 'liabilities'] as const,
netWorth: ['assets', 'netWorth'] as const,
snapshots: ['assets', 'snapshots'] as const,
},
}
+60
View File
@@ -0,0 +1,60 @@
import { z } from 'zod'
import type { CreateTransactionRequest } from '@/lib/api'
export const transactionFormSchema = z
.object({
amountYuan: z.string().refine((v) => {
const n = parseFloat(v)
return !isNaN(n) && n > 0 && /^\d+(\.\d{1,2})?$/.test(v)
}, '请输入有效金额'),
type: z.enum(['expense', 'income', 'transfer']),
category_id: z.string().optional(),
account_id: z.string().optional(),
to_account_id: z.string().optional(),
date: z.string().min(1, '请选择日期'),
description: z.string().optional(),
counterparty: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.type === 'transfer') {
if (!data.account_id) {
ctx.addIssue({ code: 'custom', path: ['account_id'], message: '请选择转出账户' })
}
if (!data.to_account_id) {
ctx.addIssue({ code: 'custom', path: ['to_account_id'], message: '请选择转入账户' })
}
if (data.account_id && data.to_account_id && data.account_id === data.to_account_id) {
ctx.addIssue({ code: 'custom', path: ['to_account_id'], message: '转出与转入账户不能相同' })
}
} else if (!data.category_id) {
ctx.addIssue({ code: 'custom', path: ['category_id'], message: '请选择分类' })
}
})
export type TransactionFormData = z.infer<typeof transactionFormSchema>
export function buildTransactionPayload(data: TransactionFormData): CreateTransactionRequest {
const amount = Math.round(parseFloat(data.amountYuan) * 100)
const isTransfer = data.type === 'transfer'
return {
type: data.type,
amount,
category_id: isTransfer ? null : data.category_id ? parseInt(data.category_id, 10) : null,
account_id: data.account_id ? parseInt(data.account_id, 10) : null,
to_account_id: isTransfer && data.to_account_id ? parseInt(data.to_account_id, 10) : null,
date: data.date,
description: data.description || '',
counterparty: data.counterparty || '',
}
}
export const defaultTransactionFormValues: TransactionFormData = {
type: 'expense',
amountYuan: '',
category_id: '',
account_id: '',
to_account_id: '',
date: '',
description: '',
counterparty: '',
}
+34
View File
@@ -0,0 +1,34 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatCents(cents: number): string {
const yuan = Math.abs(cents) / 100
const sign = cents < 0 ? '-' : ''
return sign + '¥' + yuan.toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
}
export function formatDate(dateStr: string): string {
if (!dateStr) return ''
const [y, m, d] = dateStr.split('-')
return `${parseInt(y, 10)}年${parseInt(m, 10)}月${parseInt(d, 10)}日`
}
export function formatMonth(dateStr: string): string {
if (!dateStr) return ''
const [y, m] = dateStr.split('-')
return `${y}年${parseInt(m, 10)}月`
}
export function formatLocalDate(date = new Date()): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
+14
View File
@@ -0,0 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClientProvider } from '@tanstack/react-query'
import './index.css'
import App from './App.tsx'
import { queryClient } from '@/lib/queryClient'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</StrictMode>,
)
+68
View File
@@ -0,0 +1,68 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
const mutationMocks = vi.hoisted(() => ({
saveAsset: vi.fn(),
deleteAsset: vi.fn(),
saveLiability: vi.fn(),
deleteLiability: vi.fn(),
}))
vi.mock('@/hooks/usePhase3', () => ({
useAssetsOverview: () => ({
assets: [],
liabilities: [],
netWorth: {
total_assets: 0,
total_debt: 0,
liquid_assets: 0,
liquid_debt: 0,
net_worth: 0,
},
accounts: [],
snapshots: [],
assetsLoading: false,
liabilitiesLoading: false,
netWorthLoading: false,
accountsLoading: false,
snapshotsLoading: false,
loading: false,
refreshing: false,
error: null,
}),
}))
vi.mock('@/hooks/useAssetMutations', () => ({
useAssetMutations: () => ({
...mutationMocks,
assetPending: false,
liabilityPending: false,
}),
}))
vi.mock('@/components/NetWorthTrendChart', () => ({
default: () => <div>趋势图</div>,
}))
import AssetOverview from './AssetOverview'
describe('AssetOverview', () => {
it('guards an in-flight asset save from rapid duplicate submission', () => {
mutationMocks.saveAsset.mockReturnValue(new Promise(() => {}))
render(<AssetOverview />)
fireEvent.change(screen.getByPlaceholderText('资产名称'), {
target: { value: '应急金' },
})
fireEvent.change(screen.getByPlaceholderText('当前估值'), {
target: { value: '1000' },
})
const saveButton = screen.getAllByRole('button', { name: '保存' })[0]
fireEvent.click(saveButton)
fireEvent.click(saveButton)
expect(mutationMocks.saveAsset).toHaveBeenCalledTimes(1)
})
})
+355
View File
@@ -0,0 +1,355 @@
import { lazy, Suspense, useRef, useState } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBuildingColumns, faChartLine, faCreditCard, faHouseChimney, faLink, faMinusCircle, faPenToSquare, faPiggyBank, faPlus, faScaleBalanced, faTrashCan, faXmark } from '@fortawesome/free-solid-svg-icons'
import { type Asset, type Liability } from '@/lib/api'
import { useAssetMutations } from '@/hooks/useAssetMutations'
import { useAssetsOverview } from '@/hooks/usePhase3'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { EmptyState } from '@/components/EmptyState'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { formatCents } from '@/lib/utils'
const NetWorthTrendChart = lazy(() => import('@/components/NetWorthTrendChart'))
export default function AssetOverview() {
const {
assets,
liabilities,
netWorth,
accounts,
snapshots,
assetsLoading,
liabilitiesLoading,
netWorthLoading,
accountsLoading,
snapshotsLoading,
loading,
refreshing,
error,
} = useAssetsOverview()
const {
saveAsset: mutateAsset,
deleteAsset,
saveLiability,
deleteLiability,
assetPending,
liabilityPending,
} = useAssetMutations()
const [assetName, setAssetName] = useState('')
const [assetValue, setAssetValue] = useState('')
const [assetType, setAssetType] = useState('deposit')
const [assetAccountID, setAssetAccountID] = useState('')
const [editingAsset, setEditingAsset] = useState<Asset | null>(null)
const [debtName, setDebtName] = useState('')
const [debtValue, setDebtValue] = useState('')
const [debtType, setDebtType] = useState('mortgage')
const [editingDebt, setEditingDebt] = useState<Liability | null>(null)
const [deleteAssetTarget, setDeleteAssetTarget] = useState<Asset | null>(null)
const [deleteDebtTarget, setDeleteDebtTarget] = useState<Liability | null>(null)
const [mutationError, setMutationError] = useState<string | null>(null)
const assetOperationRef = useRef(false)
const liabilityOperationRef = useRef(false)
const saveAsset = async () => {
if (assetPending || assetOperationRef.current || !assetName.trim()) return
const isBound = !!assetAccountID
if (!isBound && !assetValue) return
const payload: Partial<Asset> = {
name: assetName,
type: assetType,
value: isBound ? 0 : Math.round(parseFloat(assetValue) * 100),
account_id: isBound ? parseInt(assetAccountID, 10) : null,
}
assetOperationRef.current = true
setMutationError(null)
try {
await mutateAsset({ id: editingAsset?.id, payload })
resetAssetForm()
} catch (saveError) {
setMutationError(saveError instanceof Error ? saveError.message : '保存资产失败')
} finally {
assetOperationRef.current = false
}
}
const saveDebt = async () => {
if (liabilityPending || liabilityOperationRef.current || !debtName.trim() || !debtValue) return
const payload = { name: debtName, type: debtType, principal: Math.round(parseFloat(debtValue) * 100) }
liabilityOperationRef.current = true
setMutationError(null)
try {
await saveLiability({ id: editingDebt?.id, payload })
resetDebtForm()
} catch (saveError) {
setMutationError(saveError instanceof Error ? saveError.message : '保存负债失败')
} finally {
liabilityOperationRef.current = false
}
}
const editAsset = (asset: Asset) => {
setEditingAsset(asset)
setAssetName(asset.name)
setAssetType(asset.type)
setAssetValue(asset.account_id ? '' : (asset.value / 100).toFixed(2))
setAssetAccountID(asset.account_id ? String(asset.account_id) : '')
}
const editDebt = (debt: Liability) => {
setEditingDebt(debt)
setDebtName(debt.name)
setDebtType(debt.type)
setDebtValue((debt.principal / 100).toFixed(2))
}
const resetAssetForm = () => {
setEditingAsset(null)
setAssetName('')
setAssetValue('')
setAssetType('deposit')
setAssetAccountID('')
}
const resetDebtForm = () => {
setEditingDebt(null)
setDebtName('')
setDebtValue('')
setDebtType('mortgage')
}
const handleDeleteAsset = async () => {
if (!deleteAssetTarget || assetPending || assetOperationRef.current) return
const targetID = deleteAssetTarget.id
assetOperationRef.current = true
setMutationError(null)
try {
await deleteAsset(targetID)
setDeleteAssetTarget(null)
if (editingAsset?.id === targetID) resetAssetForm()
} catch (deleteError) {
setMutationError(deleteError instanceof Error ? deleteError.message : '删除资产失败')
} finally {
assetOperationRef.current = false
}
}
const handleDeleteDebt = async () => {
if (!deleteDebtTarget || liabilityPending || liabilityOperationRef.current) return
const targetID = deleteDebtTarget.id
liabilityOperationRef.current = true
setMutationError(null)
try {
await deleteLiability(targetID)
setDeleteDebtTarget(null)
if (editingDebt?.id === targetID) resetDebtForm()
} catch (deleteError) {
setMutationError(deleteError instanceof Error ? deleteError.message : '删除负债失败')
} finally {
liabilityOperationRef.current = false
}
}
return (
<div className="app-page">
<div className="summary-grid">
<Metric
title="总资产"
value={netWorth ? formatCents(netWorth.total_assets + netWorth.liquid_assets) : null}
loading={netWorthLoading}
icon={faHouseChimney}
hint={netWorth ? `其中流动资产 ${formatCents(netWorth.liquid_assets)}` : undefined}
/>
<Metric
title="总负债"
value={netWorth ? formatCents(netWorth.total_debt + netWorth.liquid_debt) : null}
loading={netWorthLoading}
icon={faMinusCircle}
tone="text-expense"
hint={netWorth && netWorth.liquid_debt > 0 ? `其中信用卡欠款 ${formatCents(netWorth.liquid_debt)}` : undefined}
/>
<Metric
title="家庭净值"
value={netWorth ? formatCents(netWorth.net_worth) : null}
loading={netWorthLoading}
icon={faScaleBalanced}
tone={!netWorth || netWorth.net_worth >= 0 ? 'text-income' : 'text-expense'}
/>
</div>
<div className="summary-grid">
<Metric
title="流动资产(账户派生)"
value={netWorth ? formatCents(netWorth.liquid_assets) : null}
loading={netWorthLoading}
icon={faPiggyBank}
hint="储蓄卡、支付宝、微信、现金等账户的当前余额合计;按流水自动更新。"
/>
<Metric
title="信用卡欠款(账户派生)"
value={netWorth ? formatCents(netWorth.liquid_debt) : null}
loading={netWorthLoading}
icon={faCreditCard}
tone={netWorth && netWorth.liquid_debt > 0 ? 'text-expense' : 'text-muted'}
hint="信用卡账户当前余额为负时的欠款绝对值。"
/>
</div>
{(error || mutationError) && <p className="app-error">{error || mutationError}</p>}
{!loading && refreshing && <p className="text-xs text-muted">资产数据更新中…</p>}
<div className="settings-grid">
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faPlus} className="app-section-icon" />{editingAsset ? '修改资产' : '登记资产'}</CardTitle></CardHeader>
<CardContent>
<div className="app-toolbar">
<select value={assetType} onChange={e => setAssetType(e.target.value)} className="app-select-muted">
<option value="property">房产</option>
<option value="deposit">存款</option>
<option value="investment">理财</option>
<option value="other">其他</option>
</select>
<Input value={assetName} onChange={e => setAssetName(e.target.value)} placeholder="资产名称" className="h-9 text-sm" />
<select
value={assetAccountID}
disabled={accountsLoading}
onChange={e => {
setAssetAccountID(e.target.value)
if (e.target.value) setAssetValue('')
}}
className="app-select-muted"
title="绑定账户后,资产金额由该账户当前余额实时派生"
>
<option value="">{accountsLoading ? '账户加载中…' : '手工录入金额'}</option>
{accounts.filter(a => a.is_active && a.type !== 'credit_card').map(a => (
<option key={a.id} value={a.id}>绑定 {a.name}</option>
))}
</select>
{!assetAccountID && (
<Input value={assetValue} onChange={e => setAssetValue(e.target.value)} placeholder="当前估值" inputMode="decimal" className="h-9 text-sm" />
)}
<Button size="sm" onClick={saveAsset} disabled={assetPending}>{assetPending ? '保存中…' : '保存'}</Button>
{editingAsset && <Button size="icon" variant="ghost" onClick={resetAssetForm} disabled={assetPending}><FontAwesomeIcon icon={faXmark} /></Button>}
</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faMinusCircle} className="app-section-icon" />{editingDebt ? '修改负债' : '登记负债'}</CardTitle></CardHeader>
<CardContent>
<div className="app-toolbar">
<select value={debtType} onChange={e => setDebtType(e.target.value)} className="app-select-muted">
<option value="mortgage">房贷</option>
<option value="car_loan">车贷</option>
<option value="credit">信用贷</option>
<option value="other">其他</option>
</select>
<Input value={debtName} onChange={e => setDebtName(e.target.value)} placeholder="负债名称" className="h-9 text-sm" />
<Input value={debtValue} onChange={e => setDebtValue(e.target.value)} placeholder="剩余本金" inputMode="decimal" className="h-9 text-sm" />
<Button size="sm" onClick={saveDebt} disabled={liabilityPending}>{liabilityPending ? '保存中…' : '保存'}</Button>
{editingDebt && <Button size="icon" variant="ghost" onClick={resetDebtForm} disabled={liabilityPending}><FontAwesomeIcon icon={faXmark} /></Button>}
</div>
</CardContent>
</Card>
</div>
<div className="settings-grid">
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faBuildingColumns} className="app-section-icon" />资产列表</CardTitle></CardHeader>
<CardContent>
{assetsLoading ? <div className="h-24 rounded-lg bg-white/10 animate-pulse" /> : assets.length > 0 ? (
<div className="space-y-2">{assets.map(a => (
<Row
key={a.id}
title={a.name}
sub={a.is_derived ? `${a.type} · 绑定 ${a.account_name}` : a.type}
badge={a.is_derived ? <FontAwesomeIcon icon={faLink} className="h-3 w-3 text-primary" title="实时派生于账户余额" /> : undefined}
value={formatCents(a.value)}
onEdit={() => editAsset(a)}
onDelete={() => setDeleteAssetTarget(a)}
disabled={assetPending}
/>
))}</div>
) : <EmptyState message="暂无资产" />}
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faMinusCircle} className="app-section-icon" />负债列表</CardTitle></CardHeader>
<CardContent>
{liabilitiesLoading ? <div className="h-24 rounded-lg bg-white/10 animate-pulse" /> : liabilities.length > 0 ? (
<div className="space-y-2">{liabilities.map(d => <Row key={d.id} title={d.name} sub={d.type} value={formatCents(d.principal)} tone="text-expense" onEdit={() => editDebt(d)} onDelete={() => setDeleteDebtTarget(d)} disabled={liabilityPending} />)}</div>
) : <EmptyState message="暂无负债" />}
</CardContent>
</Card>
</div>
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faChartLine} className="app-section-icon" />净值趋势</CardTitle></CardHeader>
<CardContent>
{snapshotsLoading
? <div className="h-72 animate-pulse rounded-xl bg-white/5" />
: (
<Suspense fallback={<div className="h-72 animate-pulse rounded-xl bg-white/5" />}>
<NetWorthTrendChart snapshots={snapshots} />
</Suspense>
)}
</CardContent>
</Card>
<ConfirmDialog
open={!!deleteAssetTarget}
onOpenChange={() => setDeleteAssetTarget(null)}
title="删除资产"
description={`确认删除资产「${deleteAssetTarget?.name ?? ''}」(${formatCents(deleteAssetTarget?.value ?? 0)})吗?`}
onConfirm={handleDeleteAsset}
loading={assetPending}
/>
<ConfirmDialog
open={!!deleteDebtTarget}
onOpenChange={() => setDeleteDebtTarget(null)}
title="删除负债"
description={`确认删除负债「${deleteDebtTarget?.name ?? ''}」(${formatCents(deleteDebtTarget?.principal ?? 0)})吗?`}
onConfirm={handleDeleteDebt}
loading={liabilityPending}
/>
</div>
)
}
function Metric({ title, value, icon, tone = 'text-primary', hint, loading = false }: { title: string; value: string | null; icon: Parameters<typeof FontAwesomeIcon>[0]['icon']; tone?: string; hint?: string; loading?: boolean }) {
return (
<Card className="p-5">
<div className="mb-4 flex items-center justify-between">
<p className="text-xs text-muted">{title}</p>
<span className={`metric-icon bg-primary/12 ${tone}`}><FontAwesomeIcon icon={icon} /></span>
</div>
{loading || value === null
? <div className="h-8 w-32 animate-pulse rounded-lg bg-white/10" />
: <p className={`text-2xl font-semibold tabular-nums ${tone}`}>{value}</p>}
{hint && <p className="mt-2 text-[11px] text-muted">{hint}</p>}
</Card>
)
}
function Row({ title, sub, value, tone = 'text-foreground', onEdit, onDelete, badge, disabled = false }: { title: string; sub: string; value: string; tone?: string; onEdit: () => void; onDelete?: () => void; badge?: React.ReactNode; disabled?: boolean }) {
return (
<div className="flex items-center justify-between premium-segment rounded-lg p-3">
<div className="min-w-0">
<p className="flex items-center gap-1.5 text-sm font-medium">{title}{badge}</p>
<p className="app-form-label">{sub}</p>
</div>
<div className="flex items-center gap-2">
<p className={`text-sm font-semibold tabular-nums ${tone}`}>{value}</p>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={onEdit} disabled={disabled}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" />
</Button>
{onDelete && (
<Button variant="ghost" size="icon" className="h-7 w-7 text-expense hover:text-expense" onClick={onDelete} disabled={disabled}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5" />
</Button>
)}
</div>
</div>
)
}
+234
View File
@@ -0,0 +1,234 @@
import { useMemo, useState } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBell, faCalendarCheck, faChartSimple, faCoins, faFloppyDisk, faPenToSquare, faTrashCan } from '@fortawesome/free-solid-svg-icons'
import { useAppContext } from '@/context/useAppContext'
import { useBudgetOverview } from '@/hooks/useBudgets'
import { useCategories } from '@/hooks/useCategories'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { EmptyState } from '@/components/EmptyState'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { formatCents } from '@/lib/utils'
import type { Budget } from '@/lib/api'
export default function BudgetBoard() {
const { state } = useAppContext()
const { categories } = useCategories()
const year = parseInt(state.selectedYear)
const month = parseInt(state.selectedMonth)
const { overview, loading, error, upsertBudget, deleteBudget } = useBudgetOverview(year, month)
const [scope, setScope] = useState<'annual_total' | 'annual_category' | 'monthly_category'>('annual_total')
const [categoryID, setCategoryID] = useState('')
const [amountYuan, setAmountYuan] = useState('')
const [note, setNote] = useState('')
const [saving, setSaving] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<Budget | null>(null)
const [deleting, setDeleting] = useState(false)
const expenseCategories = useMemo(
() => categories.filter(c => c.type === 'expense' && c.parent_id !== null && c.is_active),
[categories],
)
const saveBudget = async () => {
const amount = Math.round(parseFloat(amountYuan || '0') * 100)
if (amount < 0) return
if (scope !== 'annual_total' && !categoryID) return
setSaving(true)
try {
await upsertBudget({
year,
month: scope === 'monthly_category' ? month : null,
category_id: scope === 'annual_total' ? null : parseInt(categoryID),
amount,
note,
})
setAmountYuan('')
setNote('')
} finally {
setSaving(false)
}
}
const budgetItems = overview?.items ?? []
const editBudget = (item: typeof budgetItems[number]) => {
setScope(item.month === month ? 'monthly_category' : 'annual_category')
setCategoryID(item.category_id?.toString() ?? '')
setAmountYuan((item.amount / 100).toFixed(2))
setNote(item.note)
}
const handleDelete = async () => {
if (!deleteTarget || !deleteTarget.id) return
setDeleting(true)
try {
await deleteBudget(deleteTarget.id)
setDeleteTarget(null)
} finally {
setDeleting(false)
}
}
return (
<div className="app-page">
<div className="summary-grid">
<MetricCard title="年度预算" value={formatCents(overview?.annual_budget ?? 0)} icon={faCoins} />
<MetricCard title="年度已用" value={formatCents(overview?.annual_spent ?? 0)} icon={faChartSimple} tone="text-expense" />
<MetricCard title="本月额度" value={formatCents(overview?.monthly_budget ?? 0)} icon={faCalendarCheck} tone="text-primary" />
</div>
<Card>
<CardHeader>
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faFloppyDisk} className="app-section-icon" />
年度设定
</CardTitle>
</CardHeader>
<CardContent>
<div className="app-toolbar">
<div className="segment-control">
<button className={`segment-option ${scope === 'annual_total' ? 'segment-option-primary' : 'segment-option-muted'}`} onClick={() => setScope('annual_total')}>年度总额</button>
<button className={`segment-option ${scope === 'annual_category' ? 'segment-option-primary' : 'segment-option-muted'}`} onClick={() => setScope('annual_category')}>分类年度</button>
<button className={`segment-option ${scope === 'monthly_category' ? 'segment-option-primary' : 'segment-option-muted'}`} onClick={() => setScope('monthly_category')}>本月覆盖</button>
</div>
{scope !== 'annual_total' && (
<select value={categoryID} onChange={e => setCategoryID(e.target.value)} className="app-select-muted min-w-[160px]">
<option value="">选择支出分类</option>
{expenseCategories.map(category => (
<option key={category.id} value={category.id}>{category.name}</option>
))}
</select>
)}
<Input value={amountYuan} onChange={e => setAmountYuan(e.target.value)} placeholder="预算金额" inputMode="decimal" className="h-9 w-36 text-sm" />
<Input value={note} onChange={e => setNote(e.target.value)} placeholder="备注" className="h-9 min-w-[180px] flex-1 text-sm" />
<Button size="sm" onClick={saveBudget} disabled={!amountYuan || saving || (scope !== 'annual_total' && !categoryID)}>
{saving ? '保存中...' : '保存预算'}
</Button>
</div>
<p className="mt-2 text-xs text-muted">
年度分类预算会按 12 个月折算为月度目标;“本月覆盖”用于临时调整单月分类额度。
</p>
{error && <p className="app-error">{error}</p>}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faBell} className="app-section-icon" />
月度看板与超支预警
</CardTitle>
</CardHeader>
<CardContent>
<div className="mb-4 premium-segment rounded-lg p-3">
<div className="mb-2 flex items-center justify-between">
<span className="text-sm font-medium">本月总执行率</span>
<span className={`text-sm font-semibold tabular-nums ${toneByUsage(overview?.monthly_usage_percent ?? 0)}`}>
{(overview?.monthly_usage_percent ?? 0).toFixed(0)}%
</span>
</div>
<ProgressBar value={overview?.monthly_usage_percent ?? 0} />
<p className="mt-2 text-xs text-muted">
已用 {formatCents(overview?.monthly_spent ?? 0)} / 预算 {formatCents(overview?.monthly_budget ?? 0)}
{' · '}
{(overview?.monthly_remaining ?? 0) >= 0 ? `剩余 ${formatCents(overview?.monthly_remaining ?? 0)}` : `超支 ${formatCents(Math.abs(overview?.monthly_remaining ?? 0))}`}
</p>
{(overview?.monthly_unbudgeted_spent ?? 0) > 0 && (
<p className="mt-2 text-xs text-warning">
其中预算外支出 {formatCents(overview?.monthly_unbudgeted_spent ?? 0)}
</p>
)}
</div>
{loading ? (
<div className="space-y-2">
{Array.from({ length: 4 }).map((_, index) => (
<div key={index} className="h-14 rounded-lg bg-white/10 animate-pulse" />
))}
</div>
) : budgetItems.length > 0 ? (
<div className="space-y-3">
{budgetItems.map(item => (
<div key={`${item.category_id}-${item.month ?? 'annual'}`} className="premium-segment rounded-lg p-3">
<div className="mb-2 flex items-center justify-between gap-3">
<div>
<p className="text-sm font-medium">{item.category_name}</p>
<p className="app-form-label">
已用 {formatCents(item.spent)} / 月目标 {formatCents(item.amount)}
</p>
</div>
<span className={`text-sm font-medium tabular-nums ${toneByUsage(item.usage_percent)}`}>
{item.usage_percent.toFixed(0)}%
</span>
</div>
<ProgressBar value={item.usage_percent} />
<div className="mt-2 flex items-center justify-between gap-3">
<p className="text-xs text-muted">
{item.remaining >= 0 ? `剩余 ${formatCents(item.remaining)}` : `超支 ${formatCents(Math.abs(item.remaining))}`}
{item.note ? ` · ${item.note}` : ''}
</p>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" onClick={() => editBudget(item)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" />
修改
</Button>
<Button variant="ghost" size="sm" className="text-expense hover:text-expense" onClick={() => setDeleteTarget(item)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5" />
删除
</Button>
</div>
</div>
</div>
))}
</div>
) : (
<EmptyState message="暂无预算,先设置年度总额或分类年度预算" />
)}
</CardContent>
</Card>
<ConfirmDialog
open={!!deleteTarget}
onOpenChange={() => setDeleteTarget(null)}
title="删除预算"
description={`确认删除 ${deleteTarget?.category_name ?? ''} ${deleteTarget?.month ? '本月' : '年度'} 预算 ${formatCents(deleteTarget?.amount ?? 0)} 吗?`}
onConfirm={handleDelete}
loading={deleting}
/>
</div>
)
}
function MetricCard({ title, value, icon, tone = 'text-primary' }: {
title: string
value: string
icon: Parameters<typeof FontAwesomeIcon>[0]['icon']
tone?: string
}) {
return (
<Card className="p-5">
<div className="mb-4 flex items-center justify-between">
<p className="text-xs text-muted">{title}</p>
<span className={`metric-icon bg-primary/12 ${tone}`}>
<FontAwesomeIcon icon={icon} className="h-4 w-4" />
</span>
</div>
<p className={`text-2xl font-semibold tabular-nums ${tone}`}>{value}</p>
</Card>
)
}
function ProgressBar({ value }: { value: number }) {
return (
<div className="h-2 overflow-hidden rounded-full bg-white/10">
<div className={`h-full rounded-full ${value >= 100 ? 'bg-expense' : value >= 80 ? 'bg-warning' : 'bg-income'}`} style={{ width: `${Math.min(value, 100)}%` }} />
</div>
)
}
function toneByUsage(value: number) {
if (value >= 100) return 'text-expense'
if (value >= 80) return 'text-warning'
return 'text-income'
}
+54
View File
@@ -0,0 +1,54 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useAppContext } from '@/context/useAppContext'
import { useDashboardSummary, useDashboardRecent } from '@/hooks/useDashboard'
import { SummaryCards } from '@/components/SummaryCards'
import { QuickAdd } from '@/components/QuickAdd'
import { TransactionTable } from '@/components/TransactionTable'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { EmptyState } from '@/components/EmptyState'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faClockRotateLeft } from '@fortawesome/free-solid-svg-icons'
import { api } from '@/lib/api'
import {
invalidateKeys,
transactionMutationInvalidation,
} from '@/lib/queryInvalidation'
export default function Dashboard() {
const { state } = useAppContext()
const qc = useQueryClient()
const { summary, loading } = useDashboardSummary(state.selectedYear, state.selectedMonth)
const { recentItems } = useDashboardRecent(5)
const createMutation = useMutation({
mutationFn: api.createTransaction,
onSuccess: () => invalidateKeys(qc, transactionMutationInvalidation()),
})
return (
<div className="app-page">
<SummaryCards summary={summary} loading={loading} />
<QuickAdd
onSubmit={(req) => createMutation.mutateAsync(req)}
submitting={createMutation.isPending}
/>
<Card>
<CardHeader className="pb-3">
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faClockRotateLeft} className="app-section-icon" />
最近记录
</CardTitle>
</CardHeader>
<CardContent>
{recentItems.length > 0 ? (
<TransactionTable items={recentItems} compact />
) : (
<EmptyState message="暂无收支记录,记一笔吧" />
)}
</CardContent>
</Card>
</div>
)
}
+121
View File
@@ -0,0 +1,121 @@
import { useState } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPenToSquare, faPlus, faTimeline, faTrashCan, faXmark } from '@fortawesome/free-solid-svg-icons'
import { api, type LifecycleEvent } from '@/lib/api'
import { useLifecycleEvents } from '@/hooks/usePhase3'
import { useMembers } from '@/hooks/useMembers'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { EmptyState } from '@/components/EmptyState'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { formatCents } from '@/lib/utils'
export default function Lifecycle() {
const { events, loading, error, fetchAll } = useLifecycleEvents()
const { members } = useMembers()
const [year, setYear] = useState(new Date().getFullYear().toString())
const [memberID, setMemberID] = useState('')
const [event, setEvent] = useState('')
const [cost, setCost] = useState('')
const [editingEvent, setEditingEvent] = useState<LifecycleEvent | null>(null)
const [deleteTarget, setDeleteTarget] = useState<LifecycleEvent | null>(null)
const [deleting, setDeleting] = useState(false)
const saveEvent = async () => {
if (!event.trim()) return
const payload = { year: parseInt(year), member_id: memberID ? parseInt(memberID) : null, event, estimated_cost: Math.round(parseFloat(cost || '0') * 100) }
if (editingEvent) {
await api.updateLifecycleEvent(editingEvent.id, payload)
} else {
await api.createLifecycleEvent(payload)
}
resetForm()
await fetchAll()
}
const editEvent = (item: LifecycleEvent) => {
setEditingEvent(item)
setYear(item.year.toString())
setMemberID(item.member_id?.toString() ?? '')
setEvent(item.event)
setCost((item.estimated_cost / 100).toFixed(2))
}
const resetForm = () => {
setEditingEvent(null)
setYear(new Date().getFullYear().toString())
setMemberID('')
setEvent('')
setCost('')
}
const handleDelete = async () => {
if (!deleteTarget) return
setDeleting(true)
try {
await api.deleteLifecycleEvent(deleteTarget.id)
setDeleteTarget(null)
if (editingEvent?.id === deleteTarget.id) resetForm()
await fetchAll()
} finally {
setDeleting(false)
}
}
return (
<div className="app-page">
{error && <p className="app-error">{error}</p>}
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faPlus} className="app-section-icon" />{editingEvent ? '修改人生事件' : '添加人生事件'}</CardTitle></CardHeader>
<CardContent>
<div className="app-toolbar">
<Input value={year} onChange={e => setYear(e.target.value)} placeholder="年份" className="h-9 w-24 text-sm" />
<select value={memberID} onChange={e => setMemberID(e.target.value)} className="app-select-muted">
<option value="">家庭整体</option>
{members.map(member => <option key={member.id} value={member.id}>{member.name}</option>)}
</select>
<Input value={event} onChange={e => setEvent(e.target.value)} placeholder="事件描述" className="h-9 min-w-[220px] flex-1 text-sm" />
<Input value={cost} onChange={e => setCost(e.target.value)} placeholder="预估费用" inputMode="decimal" className="h-9 w-32 text-sm" />
<Button size="sm" onClick={saveEvent}>保存</Button>
{editingEvent && <Button size="icon" variant="ghost" onClick={resetForm}><FontAwesomeIcon icon={faXmark} /></Button>}
</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faTimeline} className="app-section-icon" />家庭时间线</CardTitle></CardHeader>
<CardContent>
{loading ? <div className="h-28 rounded-lg bg-white/10 animate-pulse" /> : events.length > 0 ? (
<div className="space-y-3">
{events.map(item => (
<div key={item.id} className="grid grid-cols-[72px_1fr_auto] items-center gap-3 premium-segment rounded-lg p-3">
<p className="text-sm font-semibold tabular-nums text-primary">{item.year}</p>
<div><p className="text-sm font-medium">{item.event}</p><p className="app-form-label">{item.member_name || '家庭整体'}{item.note ? ` · ${item.note}` : ''}</p></div>
<div className="flex items-center gap-2">
<p className="text-sm font-semibold tabular-nums">{formatCents(item.estimated_cost)}</p>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => editEvent(item)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-expense hover:text-expense" onClick={() => setDeleteTarget(item)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5" />
</Button>
</div>
</div>
))}
</div>
) : <EmptyState message="暂无人生周期事件" />}
</CardContent>
</Card>
<ConfirmDialog
open={!!deleteTarget}
onOpenChange={() => setDeleteTarget(null)}
title="删除人生事件"
description={`确认删除 ${deleteTarget?.year ?? ''} 年「${deleteTarget?.event ?? ''}」吗?`}
onConfirm={handleDelete}
loading={deleting}
/>
</div>
)
}
+168
View File
@@ -0,0 +1,168 @@
import { useState } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBell, faFileShield, faPenToSquare, faPlus, faTrashCan, faXmark } from '@fortawesome/free-solid-svg-icons'
import { api, type Policy, type PolicyPayment } from '@/lib/api'
import { usePolicies } from '@/hooks/usePhase3'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DatePicker } from '@/components/ui/date-picker'
import { EmptyState } from '@/components/EmptyState'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { formatCents } from '@/lib/utils'
export default function PolicyList() {
const { policies, upcoming, loading, error, fetchAll } = usePolicies()
const [name, setName] = useState('')
const [policyType, setPolicyType] = useState('health')
const [premium, setPremium] = useState('')
const [endDate, setEndDate] = useState('')
const [nextPaymentDate, setNextPaymentDate] = useState('')
const [paymentFrequency, setPaymentFrequency] = useState('annual')
const [insured, setInsured] = useState('')
const [editingPolicy, setEditingPolicy] = useState<Policy | null>(null)
const [deleteTarget, setDeleteTarget] = useState<Policy | null>(null)
const [deleting, setDeleting] = useState(false)
const [paymentPolicy, setPaymentPolicy] = useState<Policy | null>(null)
const [payments, setPayments] = useState<PolicyPayment[]>([])
const savePolicy = async () => {
if (!name.trim()) return
const payload = { name, type: policyType, insured_person: insured, premium: Math.round(parseFloat(premium || '0') * 100), end_date: endDate, next_payment_date: nextPaymentDate, payment_frequency: paymentFrequency, status: 'active' }
if (editingPolicy) {
await api.updatePolicy(editingPolicy.id, payload)
} else {
await api.createPolicy(payload)
}
resetForm()
await fetchAll()
}
const editPolicy = (policy: Policy) => {
setEditingPolicy(policy)
setName(policy.name)
setPolicyType(policy.type || 'other')
setInsured(policy.insured_person)
setPremium((policy.premium / 100).toFixed(2))
setEndDate(policy.end_date)
setNextPaymentDate(policy.next_payment_date)
setPaymentFrequency(policy.payment_frequency || 'annual')
}
const resetForm = () => {
setEditingPolicy(null)
setName('')
setPolicyType('health')
setPremium('')
setEndDate('')
setNextPaymentDate('')
setPaymentFrequency('annual')
setInsured('')
}
const handleDelete = async () => {
if (!deleteTarget) return
setDeleting(true)
try {
await api.deletePolicy(deleteTarget.id)
setDeleteTarget(null)
if (editingPolicy?.id === deleteTarget.id) resetForm()
await fetchAll()
} finally {
setDeleting(false)
}
}
return (
<div className="app-page">
{error && <p className="app-error">{error}</p>}
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faBell} className="app-section-icon" />未来 30 天续费提醒</CardTitle></CardHeader>
<CardContent>
{upcoming.length > 0 ? <div className="space-y-2">{upcoming.map(p => <PolicyRow key={p.id} policy={p} onPayment={async () => { setPaymentPolicy(p); setPayments(await api.getPolicyPayments(p.id)) }} />)}</div> : <EmptyState message="未来 30 天暂无待缴保费" />}
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faPlus} className="app-section-icon" />{editingPolicy ? '修改保单' : '登记保单'}</CardTitle></CardHeader>
<CardContent>
<div className="app-toolbar">
<select value={policyType} onChange={e => setPolicyType(e.target.value)} className="app-select-muted">
{POLICY_TYPES.map(item => <option key={item.value} value={item.value}>{item.label}</option>)}
</select>
<Input value={name} onChange={e => setName(e.target.value)} placeholder="保单名称" className="h-9 text-sm" />
<Input value={insured} onChange={e => setInsured(e.target.value)} placeholder="被保险人" className="h-9 text-sm" />
<Input value={premium} onChange={e => setPremium(e.target.value)} placeholder="年保费" inputMode="decimal" className="h-9 text-sm" />
<select value={paymentFrequency} onChange={e => setPaymentFrequency(e.target.value)} className="app-select-muted">
<option value="monthly">月缴</option><option value="quarterly">季缴</option><option value="semiannual">半年缴</option><option value="annual">年缴</option><option value="single">趸缴</option>
</select>
<div className="w-44"><DatePicker value={nextPaymentDate} onChange={setNextPaymentDate} placeholder="下次缴费日" clearable /></div>
<div className="w-44"><DatePicker value={endDate} onChange={setEndDate} placeholder="保障截止日" clearable /></div>
<Button size="sm" onClick={savePolicy}>保存</Button>
{editingPolicy && <Button size="icon" variant="ghost" onClick={resetForm}><FontAwesomeIcon icon={faXmark} /></Button>}
</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faFileShield} className="app-section-icon" />保单列表</CardTitle></CardHeader>
<CardContent>
{loading ? <div className="h-24 rounded-lg bg-white/10 animate-pulse" /> : policies.length > 0 ? <div className="space-y-2">{policies.map(p => <PolicyRow key={p.id} policy={p} onEdit={() => editPolicy(p)} onDelete={() => setDeleteTarget(p)} onPayment={async () => { setPaymentPolicy(p); setPayments(await api.getPolicyPayments(p.id)) }} />)}</div> : <EmptyState message="暂无保单" />}
</CardContent>
</Card>
<ConfirmDialog
open={!!deleteTarget}
onOpenChange={() => setDeleteTarget(null)}
title="删除保单"
description={`确认删除保单「${deleteTarget?.name ?? ''}」吗?年保费 ${formatCents(deleteTarget?.premium ?? 0)}`}
onConfirm={handleDelete}
loading={deleting}
/>
<Dialog open={!!paymentPolicy} onOpenChange={() => setPaymentPolicy(null)}>
<DialogContent><DialogHeader><DialogTitle>缴费记录 · {paymentPolicy?.name}</DialogTitle></DialogHeader><div className="space-y-3">
<Button size="sm" onClick={async () => { if (!paymentPolicy?.next_payment_date) return; await api.createPolicyPayment(paymentPolicy.id, { due_date: paymentPolicy.next_payment_date, amount: paymentPolicy.premium }); setPayments(await api.getPolicyPayments(paymentPolicy.id)) }}>生成本期待缴</Button>
{payments.map(v => <div key={v.id} className="premium-segment flex items-center justify-between rounded-lg p-3"><div><p className="text-sm">{v.due_date} · {formatCents(v.amount)}</p><p className="text-xs text-muted">{v.status === 'pending' ? '待处理' : v.status === 'paid' ? '已缴' : '已跳过'}</p></div>{v.status === 'pending' && <div className="flex gap-1"><Button size="sm" onClick={async()=>{await api.updatePolicyPayment(v.id,{status:'paid'});setPayments(await api.getPolicyPayments(v.policy_id));await fetchAll()}}>标记已缴</Button><Button size="sm" variant="ghost" onClick={async()=>{await api.updatePolicyPayment(v.id,{status:'skipped'});setPayments(await api.getPolicyPayments(v.policy_id));await fetchAll()}}>跳过</Button></div>}</div>)}
</div></DialogContent>
</Dialog>
</div>
)
}
const POLICY_TYPES = [
{ value: 'health', label: '健康险' },
{ value: 'life', label: '寿险' },
{ value: 'accident', label: '意外险' },
{ value: 'critical_illness', label: '重疾险' },
{ value: 'annuity', label: '年金险' },
{ value: 'property', label: '财产险' },
{ value: 'auto', label: '车险' },
{ value: 'other', label: '其他' },
]
function policyTypeLabel(type: string) {
return POLICY_TYPES.find(item => item.value === type)?.label || '未分类'
}
function PolicyRow({ policy, onEdit, onDelete, onPayment }: { policy: Policy; onEdit?: () => void; onDelete?: () => void; onPayment?: () => void }) {
return (
<div className="flex items-center justify-between gap-3 premium-segment rounded-lg p-3">
<div className="min-w-0">
<p className="text-sm font-medium">{policy.name}</p>
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted">
<span>分类:{policyTypeLabel(policy.type)}</span>
<span>下次缴费:{policy.next_payment_date || '未设置'}</span>
<span>保障截止:{policy.end_date || '长期'}</span>
<span>被保险人:{policy.insured_person || '未填'}</span>
</div>
</div>
<div className="flex items-center gap-2">
<p className="text-sm font-semibold tabular-nums text-primary">{formatCents(policy.premium)}</p>
{onPayment && <Button variant="outline" size="sm" onClick={onPayment}>缴费</Button>}
{onEdit && <Button variant="ghost" size="icon" className="h-7 w-7" onClick={onEdit}><FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" /></Button>}
{onDelete && <Button variant="ghost" size="icon" className="h-7 w-7 text-expense hover:text-expense" onClick={onDelete}><FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5" /></Button>}
</div>
</div>
)
}
+206
View File
@@ -0,0 +1,206 @@
import { useState } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faArrowDown, faArrowUp, faChartLine, faChartPie, faRankingStar } from '@fortawesome/free-solid-svg-icons'
import {
Bar,
BarChart,
CartesianGrid,
Cell,
LabelList,
Legend,
Line,
LineChart,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts'
import { useAppContext } from '@/context/useAppContext'
import { useReportOverview } from '@/hooks/useReports'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { EmptyState } from '@/components/EmptyState'
import { formatCents } from '@/lib/utils'
const chartColors = ['#d9b86f', '#38d39f', '#ff6b6b', '#f2b84b', '#7aa2f7', '#a78bfa', '#f472b6', '#94a3b8']
type RankingType = 'expense' | 'income'
export default function Report() {
const { state } = useAppContext()
const [rankingType, setRankingType] = useState<RankingType>('expense')
const year = parseInt(state.selectedYear)
const month = parseInt(state.selectedMonth)
const { overview, loading, error } = useReportOverview(year, month, rankingType)
const ranking = overview?.category_ranking ?? []
const trend = overview?.trend ?? []
const typeLabel = rankingType === 'expense' ? '支出' : '收入'
const trendData = trend.map(item => ({
...item,
label: `${parseInt(item.month.slice(5, 7))}月`,
incomeYuan: item.income / 100,
expenseYuan: item.expense / 100,
balanceYuan: item.balance / 100,
}))
const rankingData = ranking.map(item => ({
...item,
categoryLabel: item.category_is_active === false ? `${item.category_name}(已停用)` : item.category_name,
amountYuan: item.amount / 100,
displayLabel: `${formatCents(item.amount)} · ${item.percent.toFixed(1)}%`,
}))
const rankingTotal = ranking.reduce((sum, item) => sum + item.amount, 0)
const rankingCovered = ranking.length > 0 ? ranking.reduce((sum, item) => sum + item.percent, 0) : 0
const barChartHeight = Math.max(288, rankingData.length * 36)
return (
<div className="app-page">
{error && <p className="app-error">{error}</p>}
<div className="app-toolbar">
<span className="text-xs text-muted">分类统计</span>
<div className="segment-control">
<button
type="button"
className={`segment-option ${rankingType === 'expense' ? 'segment-option-expense' : 'segment-option-muted'}`}
onClick={() => setRankingType('expense')}
>
<FontAwesomeIcon icon={faArrowDown} className="h-3 w-3" />
支出
</button>
<button
type="button"
className={`segment-option ${rankingType === 'income' ? 'segment-option-income' : 'segment-option-muted'}`}
onClick={() => setRankingType('income')}
>
<FontAwesomeIcon icon={faArrowUp} className="h-3 w-3" />
收入
</button>
</div>
<p className="text-[11px] text-muted">仅统计叶子分类,与预算看板口径一致。</p>
</div>
<div className="settings-grid">
<Card>
<CardHeader>
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faChartPie} className="app-section-icon" />
{typeLabel}分类饼图
</CardTitle>
</CardHeader>
<CardContent>
{loading ? (
<div className="h-72 rounded-lg bg-white/10 animate-pulse" />
) : rankingData.length > 0 ? (
<>
<ResponsiveContainer width="100%" height={288}>
<PieChart>
<Pie data={rankingData} dataKey="amountYuan" nameKey="categoryLabel" innerRadius={56} outerRadius={98} paddingAngle={2}>
{rankingData.map((_, index) => (
<Cell key={index} fill={chartColors[index % chartColors.length]} />
))}
</Pie>
<Tooltip
formatter={(value: number, _name, entry) => {
const pct = (entry?.payload as { percent?: number } | undefined)?.percent ?? 0
return [`${formatCents(Math.round(value * 100))}(${pct.toFixed(1)}%)`, '金额']
}}
contentStyle={tooltipStyle}
/>
<Legend
verticalAlign="bottom"
iconSize={10}
wrapperStyle={{ fontSize: 11, color: '#aab2bd', paddingTop: 8 }}
/>
</PieChart>
</ResponsiveContainer>
{rankingCovered < 99.5 && (
<p className="mt-2 text-[11px] text-muted">
Top {rankingData.length} 占 {rankingCovered.toFixed(1)}%,其余{typeLabel}合计 {(100 - rankingCovered).toFixed(1)}% 未在图中显示(含未列入 Top 的叶子分类及挂在父分类上的金额)。
</p>
)}
</>
) : (
<EmptyState message={`本月暂无${typeLabel}数据`} />
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faRankingStar} className="app-section-icon" />
{typeLabel}分类排行
</CardTitle>
</CardHeader>
<CardContent>
{rankingData.length > 0 ? (
<ResponsiveContainer width="100%" height={barChartHeight}>
<BarChart data={rankingData} layout="vertical" margin={{ left: 16, right: 110 }}>
<CartesianGrid stroke="#28303a" horizontal={false} />
<XAxis type="number" hide />
<YAxis type="category" dataKey="categoryLabel" width={88} tick={{ fill: '#aab2bd', fontSize: 12 }} />
<Tooltip
formatter={(value: number, _name, entry) => {
const pct = (entry?.payload as { percent?: number } | undefined)?.percent ?? 0
return [`${formatCents(Math.round(value * 100))}(${pct.toFixed(1)}%)`, '金额']
}}
contentStyle={tooltipStyle}
/>
<Bar dataKey="amountYuan" radius={[0, 4, 4, 0]}>
{rankingData.map((_, index) => (
<Cell key={index} fill={chartColors[index % chartColors.length]} />
))}
<LabelList dataKey="displayLabel" position="right" fill="#cdd5e0" fontSize={11} />
</Bar>
</BarChart>
</ResponsiveContainer>
) : (
<EmptyState message={`暂无${typeLabel}分类排行`} />
)}
{rankingTotal > 0 && (
<p className="mt-2 text-[11px] text-muted">
合计 {formatCents(rankingTotal)}({rankingCovered.toFixed(1)}%),分母为当月全部{typeLabel}金额。
</p>
)}
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faChartLine} className="app-section-icon" />
月度趋势折线图
</CardTitle>
</CardHeader>
<CardContent>
{trendData.length > 0 ? (
<ResponsiveContainer width="100%" height={320}>
<LineChart data={trendData} margin={{ top: 8, right: 24, left: 0, bottom: 0 }}>
<CartesianGrid stroke="#28303a" vertical={false} />
<XAxis dataKey="label" tick={{ fill: '#aab2bd', fontSize: 12 }} />
<YAxis tick={{ fill: '#aab2bd', fontSize: 12 }} tickFormatter={value => `${value}`} />
<Tooltip formatter={(value: number) => formatCents(Math.round(value * 100))} contentStyle={tooltipStyle} />
<Line type="monotone" dataKey="incomeYuan" name="收入" stroke="#38d39f" strokeWidth={2} dot={false} />
<Line type="monotone" dataKey="expenseYuan" name="支出" stroke="#ff6b6b" strokeWidth={2} dot={false} />
<Line type="monotone" dataKey="balanceYuan" name="结余" stroke="#d9b86f" strokeWidth={2} dot={false} />
</LineChart>
</ResponsiveContainer>
) : (
<EmptyState message="暂无趋势数据" />
)}
</CardContent>
</Card>
</div>
)
}
const tooltipStyle = {
backgroundColor: '#11151c',
border: '1px solid #28303a',
borderRadius: '6px',
color: '#f8f3e8',
}
+583
View File
@@ -0,0 +1,583 @@
import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { DatePicker } from '@/components/ui/date-picker'
import {
Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { EmptyState } from '@/components/EmptyState'
import { useMembers } from '@/hooks/useMembers'
import { useCategories } from '@/hooks/useCategories'
import { useAccounts } from '@/hooks/useAccounts'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faBuildingColumns,
faCreditCard,
faFolderTree,
faPenToSquare,
faPlus,
faTrashCan,
faUserGroup,
faDatabase,
faScaleBalanced,
} from '@fortawesome/free-solid-svg-icons'
import { api, ApiError, type Category, type Member, type Account } from '@/lib/api'
import { formatCents } from '@/lib/utils'
const CARD_TYPES = ['debit_card', 'credit_card']
function isBankCardType(type: string) {
return type === 'bank_card' || CARD_TYPES.includes(type)
}
function accountTypeLabel(type: string) {
switch (type) {
case 'alipay': return '支付宝'
case 'wechat': return '微信'
case 'debit_card':
case 'bank_card': return '储蓄卡'
case 'credit_card': return '信用卡'
case 'cash': return '现金'
default: return '其他'
}
}
function MemberSettings() {
const { members, createMember, updateMember, deleteMember } = useMembers()
const [open, setOpen] = useState(false)
const [editItem, setEditItem] = useState<Member | null>(null)
const [delItem, setDelItem] = useState<Member | null>(null)
const [name, setName] = useState('')
const [relation, setRelation] = useState('')
const [birthday, setBirthday] = useState('')
const [phone, setPhone] = useState('')
const [success, setSuccess] = useState<string | null>(null)
const resetForm = () => {
setEditItem(null)
setName('')
setRelation('')
setBirthday('')
setPhone('')
}
const save = async () => {
if (!name.trim()) return
if (editItem) {
await updateMember(editItem.id, { name, relation, birthday, phone })
setSuccess('成员信息已更新')
} else {
await createMember({ name, relation, birthday, phone })
setSuccess('成员添加成功')
}
setOpen(false)
resetForm()
}
const openEdit = (m: Member) => {
setEditItem(m)
setName(m.name)
setRelation(m.relation)
setBirthday(m.birthday)
setPhone(m.phone)
setOpen(true)
}
return (
<div className="app-stack">
<div className="flex justify-end">
<Button size="sm" onClick={() => { resetForm(); setOpen(true) }}>
<FontAwesomeIcon icon={faPlus} className="h-3.5 w-3.5" />添加成员
</Button>
</div>
{success && <p className="app-success">{success}</p>}
{members.length === 0 ? (
<EmptyState message="暂无家庭成员" />
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>姓名</TableHead>
<TableHead>关系</TableHead>
<TableHead>出生日期</TableHead>
<TableHead>电话</TableHead>
<TableHead className="w-[80px]" />
</TableRow>
</TableHeader>
<TableBody>
{members.map(m => (
<TableRow key={m.id}>
<TableCell className="text-sm">{m.name}</TableCell>
<TableCell className="text-sm text-muted">{m.relation || '-'}</TableCell>
<TableCell className="text-sm text-muted">{m.birthday || '-'}</TableCell>
<TableCell className="text-sm text-muted">{m.phone || '-'}</TableCell>
<TableCell>
<div className="inline-actions">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(m)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setDelItem(m)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5 text-expense" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader><DialogTitle>{editItem ? '编辑成员' : '添加成员'}</DialogTitle></DialogHeader>
<div className="app-form">
<div><Label className="app-form-label">姓名</Label><Input value={name} onChange={e => setName(e.target.value)} className="h-9 mt-1" /></div>
<div><Label className="app-form-label">关系</Label><Input value={relation} onChange={e => setRelation(e.target.value)} placeholder="如:配偶、子女" className="h-9 mt-1" /></div>
<div><Label className="app-form-label">出生日期</Label><div className="mt-1"><DatePicker value={birthday} onChange={setBirthday} placeholder="选择出生日期" clearable /></div></div>
<div><Label className="app-form-label">电话</Label><Input value={phone} onChange={e => setPhone(e.target.value)} placeholder="可选" className="h-9 mt-1" /></div>
<Button onClick={save} className="w-full" disabled={!name.trim()}>保存</Button>
</div>
</DialogContent>
</Dialog>
<ConfirmDialog open={!!delItem} onOpenChange={() => setDelItem(null)}
title="确认删除" description={`确定删除成员「${delItem?.name}」吗?`}
onConfirm={async () => { if (delItem) { await deleteMember(delItem.id); setDelItem(null) } }} />
</div>
)
}
function CategorySettings() {
const { categories, createCategory, updateCategory, deleteCategory } = useCategories()
const [open, setOpen] = useState(false)
const [editItem, setEditItem] = useState<Category | null>(null)
const [delItem, setDelItem] = useState<Category | null>(null)
const [name, setName] = useState('')
const [catType, setCatType] = useState<'expense' | 'income'>('expense')
const [parentId, setParentId] = useState<string>('')
const [keywords, setKeywords] = useState('')
const [isActive, setIsActive] = useState(true)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState<string | null>(null)
const expenseCats = categories.filter(c => c.type === 'expense')
const incomeCats = categories.filter(c => c.type === 'income')
const parentOptions = categories.filter(c =>
c.parent_id === null && c.type === catType && c.id !== editItem?.id
)
const resetForm = () => {
setEditItem(null)
setName('')
setCatType('expense')
setParentId('')
setKeywords('')
setIsActive(true)
}
const save = async () => {
if (!name.trim()) return
setError(null)
if (editItem) {
await updateCategory(editItem.id, {
name,
parent_id: parentId ? parseInt(parentId, 10) : null,
keywords,
is_active: isActive,
})
setSuccess('分类信息已更新')
} else {
await createCategory({
name,
type: catType,
parent_id: parentId ? parseInt(parentId, 10) : null,
keywords,
})
setSuccess('分类添加成功')
}
setOpen(false)
resetForm()
}
const toggleActive = async (c: Category) => {
setError(null)
await updateCategory(c.id, { is_active: !c.is_active })
}
const confirmDelete = async () => {
if (!delItem) return
setError(null)
try {
await deleteCategory(delItem.id)
setDelItem(null)
} catch (e) {
setError(e instanceof ApiError ? e.message : '删除分类失败')
}
}
const openAdd = () => {
resetForm()
setOpen(true)
}
const openEdit = (c: Category) => {
setEditItem(c)
setName(c.name)
setCatType(c.type)
setParentId(c.parent_id?.toString() ?? '')
setKeywords(c.keywords ?? '')
setIsActive(c.is_active)
setOpen(true)
}
return (
<div className="app-stack">
<div className="flex justify-end">
<Button size="sm" onClick={openAdd}>
<FontAwesomeIcon icon={faPlus} className="h-3.5 w-3.5" />添加分类
</Button>
</div>
{error && <p className="app-error">{error}</p>}
{success && <p className="app-success">{success}</p>}
<div className="settings-grid">
{(['expense', 'income'] as const).map(type => {
const topItems = (type === 'expense' ? expenseCats : incomeCats).filter(c => c.parent_id === null)
const children = (type === 'expense' ? expenseCats : incomeCats).filter(c => c.parent_id !== null)
return (
<Card key={type}>
<CardHeader className="pb-2">
<CardTitle className="app-section-title">
<FontAwesomeIcon icon={faFolderTree} className="app-section-icon" />
{type === 'expense' ? '支出分类' : '收入分类'}
</CardTitle>
</CardHeader>
<CardContent>
{topItems.map(top => (
<div key={top.id} className="mb-3">
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-medium">{top.name}</span>
<Badge variant={top.is_active ? 'default' : 'secondary'} className="text-[10px] cursor-pointer" onClick={() => toggleActive(top)}>
{top.is_active ? '启用' : '禁用'}
</Badge>
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => openEdit(top)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3 w-3" />
</Button>
</div>
<div className="ml-3 space-y-0.5">
{children.filter(c => c.parent_id === top.id).map(child => (
<div key={child.id} className="flex items-center justify-between group py-0.5">
<div className="flex min-w-0 items-center gap-2">
<span className="text-sm text-muted">{child.name}</span>
{child.keywords && (
<span className="truncate text-[11px] text-muted/70" title={child.keywords}>
· {child.keywords}
</span>
)}
</div>
<div className="fade-actions">
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => openEdit(child)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3 w-3" />
</Button>
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setDelItem(child)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3 w-3 text-expense" />
</Button>
</div>
</div>
))}
</div>
</div>
))}
</CardContent>
</Card>
)
})}
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader><DialogTitle>{editItem ? '编辑分类' : '添加分类'}</DialogTitle></DialogHeader>
<div className="app-form">
<div className="inline-actions">
<Button size="sm" variant={catType === 'expense' ? 'default' : 'outline'} disabled={!!editItem} onClick={() => setCatType('expense')}>支出</Button>
<Button size="sm" variant={catType === 'income' ? 'default' : 'outline'} disabled={!!editItem} onClick={() => setCatType('income')}>收入</Button>
</div>
<div><Label className="app-form-label">分类名称</Label><Input value={name} onChange={e => setName(e.target.value)} className="h-9 mt-1" /></div>
<div><Label className="app-form-label">父分类</Label>
<select value={parentId} onChange={e => setParentId(e.target.value)}
className="app-select-muted mt-1 w-full">
<option value="">无(顶级分类)</option>
{parentOptions.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div>
<Label className="app-form-label">导入识别关键字</Label>
<Input value={keywords} onChange={e => setKeywords(e.target.value)} placeholder="多个关键字以英文逗号分隔,如:餐,美团,饿了么" className="h-9 mt-1" />
<p className="mt-1 text-[11px] text-muted">PDF 导入时按描述匹配;命中后自动归入该分类。</p>
</div>
<label className="flex items-center gap-2 text-sm text-muted">
<input type="checkbox" checked={isActive} onChange={e => setIsActive(e.target.checked)} />
启用分类
</label>
<Button onClick={save} className="w-full" disabled={!name.trim()}>保存</Button>
</div>
</DialogContent>
</Dialog>
<ConfirmDialog open={!!delItem} onOpenChange={() => setDelItem(null)}
title="确认删除" description={`确定删除分类「${delItem?.name}」吗?`}
onConfirm={confirmDelete} />
</div>
)
}
function AccountSettings() {
const { accounts, createAccount, updateAccount, deleteAccount } = useAccounts()
const [open, setOpen] = useState(false)
const [editItem, setEditItem] = useState<Account | null>(null)
const [delItem, setDelItem] = useState<Account | null>(null)
const [name, setName] = useState('')
const [acctType, setAcctType] = useState('other')
const [bankName, setBankName] = useState('')
const [cardNumber, setCardNumber] = useState('')
const [branchName, setBranchName] = useState('')
const [openingBalanceYuan, setOpeningBalanceYuan] = useState('')
const [note, setNote] = useState('')
const [isActive, setIsActive] = useState(true)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState<string | null>(null)
const [reconcileAccount, setReconcileAccount] = useState<Account | null>(null)
const [actualBalance, setActualBalance] = useState('')
const resetForm = () => {
setEditItem(null)
setName('')
setAcctType('other')
setBankName('')
setCardNumber('')
setBranchName('')
setOpeningBalanceYuan('')
setNote('')
setIsActive(true)
}
const save = async () => {
if (!name.trim()) return
setError(null)
const trimmedBalance = openingBalanceYuan.trim()
const balanceCents = trimmedBalance === ''
? 0
: Math.round(parseFloat(trimmedBalance) * 100)
if (Number.isNaN(balanceCents)) {
setError('开账余额格式不正确')
return
}
const payload = {
name,
type: acctType,
balance: balanceCents,
bank_name: isBankCardType(acctType) ? bankName : '',
card_number: isBankCardType(acctType) ? cardNumber : '',
branch_name: isBankCardType(acctType) ? branchName : '',
note,
is_active: isActive,
}
if (editItem) {
await updateAccount(editItem.id, payload)
setSuccess('账户信息已更新')
} else {
await createAccount(payload)
setSuccess('账户添加成功')
}
setOpen(false)
resetForm()
}
const confirmDelete = async () => {
if (!delItem) return
setError(null)
try {
await deleteAccount(delItem.id)
setDelItem(null)
} catch (e) {
setError(e instanceof ApiError ? e.message : '删除账户失败')
}
}
const openAdd = () => {
resetForm()
setOpen(true)
}
const openEdit = (account: Account) => {
setEditItem(account)
setName(account.name)
setAcctType(account.type)
setBankName(account.bank_name)
setCardNumber(account.card_number)
setBranchName(account.branch_name)
setOpeningBalanceYuan(account.balance ? (account.balance / 100).toFixed(2) : '')
setNote(account.note)
setIsActive(account.is_active)
setOpen(true)
}
const maskCardNumber = (value: string) => {
const digits = value.replace(/\s+/g, '')
if (digits.length <= 4) return digits || '-'
return `**** ${digits.slice(-4)}`
}
return (
<div className="app-stack">
<div className="flex justify-end">
<Button size="sm" onClick={openAdd}>
<FontAwesomeIcon icon={faPlus} className="h-3.5 w-3.5" />添加账户
</Button>
</div>
{error && <p className="app-error">{error}</p>}
{success && <p className="app-success">{success}</p>}
<div className="account-grid">
{accounts.map(a => (
<Card key={a.id} className="p-4 relative group">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<p className="truncate text-sm font-medium">{a.name}</p>
<Badge variant={a.is_active ? 'default' : 'secondary'} className="text-[10px]">
{a.is_active ? '启用' : '禁用'}
</Badge>
</div>
<p className="app-form-label mt-0.5">{accountTypeLabel(a.type)}</p>
<div className="mt-1 space-y-0.5 text-xs">
<p className="tabular-nums" title="实时计算:开账余额 + 历史流水净额">
<span className="text-muted">当前余额:</span>
<span className="font-medium">{formatCents(a.current_balance)}</span>
</p>
{a.balance !== a.current_balance && (
<p className="tabular-nums text-muted">开账:{formatCents(a.balance)}</p>
)}
</div>
{isBankCardType(a.type) && (
<div className="mt-2 space-y-0.5 text-xs text-muted">
<p className="flex items-center gap-1.5">
<FontAwesomeIcon icon={faCreditCard} className="h-3 w-3" />
{a.bank_name || '未填写银行'}
</p>
<p className="tabular-nums">{maskCardNumber(a.card_number)}</p>
</div>
)}
{a.note && <p className="mt-2 truncate text-xs text-muted">{a.note}</p>}
</div>
<div className="fade-actions opacity-100 group-hover:opacity-100">
<Button variant="ghost" size="icon" className="h-7 w-7" title="账户对账" onClick={() => { setReconcileAccount(a); setActualBalance((a.current_balance / 100).toFixed(2)) }}>
<FontAwesomeIcon icon={faScaleBalanced} className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(a)}>
<FontAwesomeIcon icon={faPenToSquare} className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setDelItem(a)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5 text-expense" />
</Button>
</div>
</div>
</Card>
))}
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader><DialogTitle>{editItem ? '编辑账户' : '添加账户'}</DialogTitle></DialogHeader>
<div className="app-form">
<div><Label className="app-form-label">账户名称</Label><Input value={name} onChange={e => setName(e.target.value)} className="h-9 mt-1" /></div>
<div><Label className="app-form-label">类型</Label>
<select value={acctType} onChange={e => setAcctType(e.target.value)}
className="app-select mt-1 w-full">
<option value="alipay">支付宝</option>
<option value="wechat">微信</option>
<option value="debit_card">储蓄卡</option>
<option value="credit_card">信用卡</option>
<option value="cash">现金</option>
<option value="other">其他</option>
</select>
</div>
{isBankCardType(acctType) && (
<>
<div><Label className="app-form-label">银行</Label><Input value={bankName} onChange={e => setBankName(e.target.value)} placeholder="如:中国工商银行" className="h-9 mt-1" /></div>
<div><Label className="app-form-label">银行卡号</Label><Input value={cardNumber} onChange={e => setCardNumber(e.target.value)} placeholder="可输入完整卡号或尾号" className="h-9 mt-1" /></div>
<div><Label className="app-form-label">开户行</Label><Input value={branchName} onChange={e => setBranchName(e.target.value)} placeholder="可选" className="h-9 mt-1" /></div>
</>
)}
<div>
<Label className="app-form-label">开账余额</Label>
<Input value={openingBalanceYuan} onChange={e => setOpeningBalanceYuan(e.target.value)} placeholder="0.00" className="h-9 mt-1" inputMode="decimal" />
<p className="mt-1 text-[11px] text-muted">账户在录入到本系统前的初始余额;当前余额会按流水自动更新。</p>
</div>
<div><Label className="app-form-label">备注</Label><Input value={note} onChange={e => setNote(e.target.value)} placeholder="可选" className="h-9 mt-1" /></div>
<label className="flex items-center gap-2 text-sm text-muted">
<input type="checkbox" checked={isActive} onChange={e => setIsActive(e.target.checked)} />
启用账户
</label>
<Button onClick={save} className="w-full" disabled={!name.trim()}>保存</Button>
</div>
</DialogContent>
</Dialog>
<Dialog open={!!reconcileAccount} onOpenChange={() => setReconcileAccount(null)}>
<DialogContent>
<DialogHeader><DialogTitle>账户对账 · {reconcileAccount?.name}</DialogTitle></DialogHeader>
<div className="app-form">
<p className="text-sm text-muted">系统余额:{formatCents(reconcileAccount?.current_balance ?? 0)}</p>
<div><Label className="app-form-label">实际余额</Label><Input value={actualBalance} onChange={e => setActualBalance(e.target.value)} inputMode="decimal" className="mt-1" /></div>
<p className="text-xs text-muted">确认后保存对账记录,并自动生成余额调整交易。</p>
<Button onClick={async () => { if (!reconcileAccount) return; await api.reconcileAccount(reconcileAccount.id, Math.round(Number(actualBalance) * 100)); setReconcileAccount(null); setSuccess('对账完成,账户余额已调整') }}>确认对账</Button>
</div>
</DialogContent>
</Dialog>
<ConfirmDialog open={!!delItem} onOpenChange={() => setDelItem(null)}
title="确认删除" description={`确定删除账户「${delItem?.name}」吗?`}
onConfirm={confirmDelete} />
</div>
)
}
function DataSettings() {
const query = useQuery({ queryKey: ['backup-status'], queryFn: api.getBackupStatus })
const backup = useMutation({ mutationFn: api.createBackup, onSuccess: () => query.refetch() })
return <Card><CardHeader><CardTitle className="app-section-title"><FontAwesomeIcon icon={faDatabase} className="app-section-icon" />数据备份</CardTitle></CardHeader><CardContent className="space-y-3">
<p className="text-sm">最近备份:{query.data?.last_backup || '尚未备份'}</p>
<p className="break-all text-xs text-muted">目录:{query.data?.directory || '加载中…'} · 保留 {query.data?.retention_days ?? 30} 天</p>
<Button size="sm" onClick={() => backup.mutate()} disabled={backup.isPending}>{backup.isPending ? '备份中…' : '立即备份'}</Button>
</CardContent></Card>
}
export default function Settings() {
return (
<div className="app-page-compact">
<Tabs defaultValue="members">
<TabsList>
<TabsTrigger value="members" className="gap-2 text-xs">
<FontAwesomeIcon icon={faUserGroup} className="h-3.5 w-3.5" />
家庭成员
</TabsTrigger>
<TabsTrigger value="categories" className="gap-2 text-xs">
<FontAwesomeIcon icon={faFolderTree} className="h-3.5 w-3.5" />
收支分类
</TabsTrigger>
<TabsTrigger value="accounts" className="gap-2 text-xs">
<FontAwesomeIcon icon={faBuildingColumns} className="h-3.5 w-3.5" />
支付账户
</TabsTrigger>
<TabsTrigger value="data" className="gap-2 text-xs"><FontAwesomeIcon icon={faDatabase} className="h-3.5 w-3.5" />数据安全</TabsTrigger>
</TabsList>
<TabsContent value="members" className="mt-4"><MemberSettings /></TabsContent>
<TabsContent value="categories" className="mt-4"><CategorySettings /></TabsContent>
<TabsContent value="accounts" className="mt-4"><AccountSettings /></TabsContent>
<TabsContent value="data" className="mt-4"><DataSettings /></TabsContent>
</Tabs>
</div>
)
}
+238
View File
@@ -0,0 +1,238 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const apiMocks = vi.hoisted(() => ({
getTransactions: vi.fn(),
getImportBatches: vi.fn().mockResolvedValue([]),
}))
vi.mock('@/lib/api', () => ({
api: apiMocks,
ApiError: class ApiError extends Error {},
}))
vi.mock('@/context/useAppContext', () => ({
useAppContext: () => ({
state: { selectedYear: '2026', selectedMonth: '08' },
}),
}))
vi.mock('@/hooks/useCategories', () => ({ useCategories: () => ({ categories: [] }) }))
vi.mock('@/hooks/useAccounts', () => ({ useAccounts: () => ({ accounts: [] }) }))
vi.mock('@/hooks/useMembers', () => ({ useMembers: () => ({ members: [] }) }))
vi.mock('@/components/TransactionTable', () => ({
TransactionTable: ({
items,
selectedIds,
onToggleSelect,
}: {
items: Array<{ id: number; description: string }>
selectedIds: number[]
onToggleSelect: (id: number) => void
}) => (
<div>
<span>{items.map((item) => item.description).join(',')}</span>
<span>已选择:{selectedIds.length}</span>
{items[0] && <button onClick={() => onToggleSelect(items[0].id)}>选择首条</button>}
</div>
),
}))
vi.mock('@/components/TransactionForm', () => ({ TransactionForm: () => null }))
vi.mock('@/components/ImportDialog', () => ({ ImportDialog: () => null }))
vi.mock('@/components/ConfirmDialog', () => ({ ConfirmDialog: () => null }))
import TransactionList from './TransactionList'
function transaction(id: number, description: string) {
return {
id,
type: 'expense' as const,
amount: 100,
category_id: 1,
category_name: '餐饮',
category_is_active: true,
account_id: 1,
account_name: '现金',
to_account_id: null,
to_account_name: '',
member_id: null,
member_name: '',
date: '2026-08-09',
description,
counterparty: '',
import_batch_id: null,
import_filename: '',
created_at: '',
updated_at: '',
}
}
function listResponse(page: number, description = `第${page}页记录`, total = 40) {
return {
items: [transaction(page, description)],
total,
page,
page_size: 20,
}
}
function pendingUntilAbort(signal?: AbortSignal): Promise<never> {
return new Promise((_, reject) => {
if (!signal) return
const rejectAbort = () => reject(new DOMException('已取消', 'AbortError'))
if (signal.aborted) {
rejectAbort()
return
}
signal.addEventListener('abort', rejectAbort, { once: true })
})
}
function renderList() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
})
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
return render(<TransactionList />, { wrapper })
}
describe('TransactionList', () => {
beforeEach(() => {
apiMocks.getTransactions.mockReset()
apiMocks.getImportBatches.mockReset()
apiMocks.getImportBatches.mockResolvedValue([])
})
afterEach(() => {
vi.useRealTimers()
})
it('翻页请求期间保留旧表格、显示刷新状态并传递 signal', async () => {
apiMocks.getTransactions.mockImplementation(
(params: Record<string, string>, signal?: AbortSignal) => {
if (params.page === '1') {
return Promise.resolve(listResponse(1, '第一页记录'))
}
return pendingUntilAbort(signal)
},
)
renderList()
expect(await screen.findByText('第一页记录')).toBeTruthy()
const nextButton = screen.getByRole('button', { name: '下一页' })
fireEvent.click(nextButton)
await waitFor(() => expect(apiMocks.getTransactions).toHaveBeenCalledTimes(2))
expect(apiMocks.getTransactions.mock.calls[1][1]).toBeInstanceOf(AbortSignal)
expect(screen.getByText('第一页记录')).toBeTruthy()
expect(screen.getByText('更新中…')).toBeTruthy()
expect(nextButton).toHaveProperty('disabled', true)
})
it('300ms 内连续输入只请求最终关键词', async () => {
apiMocks.getTransactions.mockResolvedValue(listResponse(1))
renderList()
expect(await screen.findByText('第1页记录')).toBeTruthy()
apiMocks.getTransactions.mockClear()
vi.useFakeTimers()
const input = screen.getByPlaceholderText('搜索描述...')
fireEvent.change(input, { target: { value: '餐' } })
await act(() => vi.advanceTimersByTimeAsync(200))
fireEvent.change(input, { target: { value: '餐饮' } })
await act(() => vi.advanceTimersByTimeAsync(299))
expect(apiMocks.getTransactions).not.toHaveBeenCalled()
await act(() => vi.advanceTimersByTimeAsync(1))
await act(() => vi.advanceTimersByTimeAsync(0))
expect(apiMocks.getTransactions).toHaveBeenCalledTimes(1)
expect(apiMocks.getTransactions.mock.calls[0][0]).toMatchObject({
keyword: '餐饮',
page: '1',
})
})
it('非第一页搜索时不请求新关键词与旧页码组合', async () => {
apiMocks.getTransactions.mockImplementation((params: Record<string, string>) =>
Promise.resolve(listResponse(Number(params.page))),
)
renderList()
expect(await screen.findByText('第1页记录')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '下一页' }))
expect(await screen.findByText('第2页记录')).toBeTruthy()
apiMocks.getTransactions.mockClear()
vi.useFakeTimers()
fireEvent.change(screen.getByPlaceholderText('搜索描述...'), {
target: { value: '餐饮' },
})
await act(() => vi.advanceTimersByTimeAsync(300))
await act(() => vi.advanceTimersByTimeAsync(0))
expect(apiMocks.getTransactions).toHaveBeenCalledTimes(1)
expect(apiMocks.getTransactions.mock.calls[0][0]).toMatchObject({
keyword: '餐饮',
page: '1',
})
})
it('快速切换筛选时取消前一个请求', async () => {
let expenseSignal: AbortSignal | undefined
apiMocks.getTransactions.mockImplementation(
(params: Record<string, string>, signal?: AbortSignal) => {
if (!params.type) return Promise.resolve(listResponse(1))
if (params.type === 'expense') expenseSignal = signal
return pendingUntilAbort(signal)
},
)
renderList()
expect(await screen.findByText('第1页记录')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '支出' }))
await waitFor(() => expect(expenseSignal).toBeDefined())
fireEvent.click(screen.getByRole('button', { name: '收入' }))
await waitFor(() => expect(expenseSignal?.aborted).toBe(true))
})
it('翻页时清空已选择记录', async () => {
apiMocks.getTransactions.mockImplementation(
(params: Record<string, string>, signal?: AbortSignal) =>
params.page === '1'
? Promise.resolve(listResponse(1))
: pendingUntilAbort(signal),
)
renderList()
expect(await screen.findByText('第1页记录')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '选择首条' }))
expect(screen.getByText('已选择:1')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '下一页' }))
expect(screen.getByText('已选择:0')).toBeTruthy()
})
it('旧结果为空的后台刷新也显示更新状态', async () => {
apiMocks.getTransactions.mockImplementation(
(params: Record<string, string>, signal?: AbortSignal) => {
if (!params.type) {
return Promise.resolve({ items: [], total: 0, page: 1, page_size: 20 })
}
return pendingUntilAbort(signal)
},
)
renderList()
expect(await screen.findByText('暂无收支记录')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '支出' }))
expect(await screen.findByText('更新中…')).toBeTruthy()
expect(screen.getByText('暂无收支记录')).toBeTruthy()
})
})
+494
View File
@@ -0,0 +1,494 @@
import { useMemo, useState } from 'react'
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAppContext } from '@/context/useAppContext'
import { useCategories } from '@/hooks/useCategories'
import { useAccounts } from '@/hooks/useAccounts'
import { useMembers } from '@/hooks/useMembers'
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
import { TransactionTable } from '@/components/TransactionTable'
import { TransactionForm } from '@/components/TransactionForm'
import { buildTransactionPayload } from '@/lib/transactionForm'
import { ImportDialog } from '@/components/ImportDialog'
import { EmptyState } from '@/components/EmptyState'
import { TableSkeleton } from '@/components/LoadingSkeleton'
import { ConfirmDialog } from '@/components/ConfirmDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { TreeSelect } from '@/components/ui/tree-select'
import { DatePicker } from '@/components/ui/date-picker'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faPlus,
faMagnifyingGlass,
faArrowDown,
faArrowUp,
faFileImport,
faTrashCan,
faRightLeft,
faDownload,
} from '@fortawesome/free-solid-svg-icons'
import { api, type ImportBatch, type TransactionListItem } from '@/lib/api'
import { buildCategoryTree } from '@/lib/categoryTree'
import {
invalidateKeys,
transactionMutationInvalidation,
} from '@/lib/queryInvalidation'
import { queryKeys } from '@/lib/queryKeys'
import { defaultTransactionFormValues, type TransactionFormData } from '@/lib/transactionForm'
import { formatCents } from '@/lib/utils'
export default function TransactionList() {
const { state } = useAppContext()
const qc = useQueryClient()
const { categories } = useCategories()
const { accounts } = useAccounts()
const { members } = useMembers()
const [page, setPage] = useState(1)
const [filters, setFilters] = useState({
keyword: '',
type: '',
category_id: '',
date_from: '',
date_to: '',
import_batch_id: '',
account_id: '',
member_id: '',
})
const [keywordInput, setKeywordInput] = useState('')
const debouncedKeyword = useDebouncedValue(keywordInput, 300)
const [editOpen, setEditOpen] = useState(false)
const [addOpen, setAddOpen] = useState(false)
const [importOpen, setImportOpen] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<TransactionListItem | null>(null)
const [editingItem, setEditingItem] = useState<TransactionListItem | null>(null)
const [selectedIds, setSelectedIds] = useState<number[]>([])
const [batchDeleteOpen, setBatchDeleteOpen] = useState(false)
const [deleteImportBatchTarget, setDeleteImportBatchTarget] = useState<ImportBatch | null>(null)
const currentMonth = `${state.selectedYear}-${state.selectedMonth}`
const [listResetKey, setListResetKey] = useState(`${currentMonth}\0${debouncedKeyword}`)
const nextListResetKey = `${currentMonth}\0${debouncedKeyword}`
if (listResetKey !== nextListResetKey) {
setListResetKey(nextListResetKey)
setPage(1)
setSelectedIds([])
}
const effectiveFilters = useMemo(
() => ({ ...filters, keyword: debouncedKeyword }),
[filters, debouncedKeyword],
)
const listParams = useMemo(() => {
const params: Record<string, string> = {
page: page.toString(),
page_size: '20',
}
if (!effectiveFilters.date_from && !effectiveFilters.date_to) {
params.month = currentMonth
}
if (effectiveFilters.type) params.type = effectiveFilters.type
if (effectiveFilters.category_id) params.category_id = effectiveFilters.category_id
if (effectiveFilters.keyword) params.keyword = effectiveFilters.keyword
if (effectiveFilters.date_from) params.date_from = effectiveFilters.date_from
if (effectiveFilters.date_to) params.date_to = effectiveFilters.date_to
if (effectiveFilters.import_batch_id) params.import_batch_id = effectiveFilters.import_batch_id
if (effectiveFilters.account_id) params.account_id = effectiveFilters.account_id
if (effectiveFilters.member_id) params.member_id = effectiveFilters.member_id
return params
}, [page, currentMonth, effectiveFilters])
const {
data: listData,
isLoading,
isFetching,
isPlaceholderData,
} = useQuery({
queryKey: queryKeys.transactions.list(listParams),
queryFn: ({ signal }) => api.getTransactions(listParams, signal),
placeholderData: keepPreviousData,
})
const { data: importBatches = [] } = useQuery({
queryKey: queryKeys.importBatches,
queryFn: () => api.getImportBatches(),
})
const invalidateTransactions = () =>
invalidateKeys(qc, transactionMutationInvalidation())
const createMutation = useMutation({
mutationFn: api.createTransaction,
onSuccess: () => {
setAddOpen(false)
setPage(1)
invalidateTransactions()
},
})
const updateMutation = useMutation({
mutationFn: ({ id, req }: { id: number; req: ReturnType<typeof buildTransactionPayload> }) =>
api.updateTransaction(id, req),
onSuccess: () => {
setEditOpen(false)
setEditingItem(null)
invalidateTransactions()
},
})
const deleteMutation = useMutation({
mutationFn: api.deleteTransaction,
onSuccess: () => {
setDeleteTarget(null)
invalidateTransactions()
},
})
const batchDeleteMutation = useMutation({
mutationFn: api.deleteTransactionsBatch,
onSuccess: () => {
setSelectedIds([])
setBatchDeleteOpen(false)
invalidateTransactions()
},
})
const deleteBatchMutation = useMutation({
mutationFn: api.deleteImportBatch,
onSuccess: (_data, batchId) => {
setDeleteImportBatchTarget(null)
setFilters((prev) =>
prev.import_batch_id === String(batchId) ? { ...prev, import_batch_id: '' } : prev,
)
setPage(1)
qc.invalidateQueries({ queryKey: queryKeys.importBatches })
invalidateTransactions()
},
})
const transactions = listData?.items ?? []
const total = listData?.total ?? 0
const pageSize = listData?.page_size ?? 20
const totalPages = Math.ceil(total / pageSize)
const resetListState = () => {
setPage(1)
setSelectedIds([])
}
const handleFilterType = (t: string) => {
setFilters((prev) => ({ ...prev, type: t }))
resetListState()
}
const changePage = (nextPage: number) => {
setSelectedIds([])
setPage(nextPage)
}
const filteredCategories = categories.filter(
(c) => !filters.type || c.type === filters.type,
)
const filterCategoryNodes = buildCategoryTree(filteredCategories, { allowParentSelect: true })
const openEdit = (item: TransactionListItem) => {
setEditingItem(item)
setEditOpen(true)
}
const editDefaults: TransactionFormData | undefined = editingItem
? {
type: editingItem.type,
amountYuan: (editingItem.amount / 100).toFixed(2),
category_id: editingItem.category_id?.toString() ?? '',
account_id: editingItem.account_id?.toString() || '',
to_account_id: editingItem.to_account_id?.toString() || '',
date: editingItem.date,
description: editingItem.description,
counterparty: editingItem.counterparty,
}
: undefined
const deleteLoading =
deleteMutation.isPending || batchDeleteMutation.isPending || deleteBatchMutation.isPending
return (
<div className="app-page-compact">
<div className="app-toolbar">
<div className="segment-control">
{(['', 'expense', 'income', 'transfer'] as const).map((t) => (
<button
key={t}
type="button"
className={`segment-option ${
filters.type === t ? 'segment-option-primary' : 'segment-option-muted'
}`}
onClick={() => handleFilterType(t)}
>
{t === 'expense' && <FontAwesomeIcon icon={faArrowDown} className="h-3 w-3" />}
{t === 'income' && <FontAwesomeIcon icon={faArrowUp} className="h-3 w-3" />}
{t === 'transfer' && <FontAwesomeIcon icon={faRightLeft} className="h-3 w-3" />}
{t === '' ? '全部' : t === 'expense' ? '支出' : t === 'income' ? '收入' : '转账'}
</button>
))}
</div>
<div className="w-44">
<TreeSelect
value={filters.category_id}
onChange={(v) => {
setFilters((p) => ({ ...p, category_id: v }))
resetListState()
}}
nodes={filterCategoryNodes}
placeholder="全部分类"
variant="muted"
clearable
/>
</div>
<div className="w-40">
<DatePicker
value={filters.date_from}
onChange={(v) => {
setFilters((p) => ({ ...p, date_from: v }))
resetListState()
}}
placeholder="开始日期"
clearable
/>
</div>
<div className="w-40">
<DatePicker
value={filters.date_to}
onChange={(v) => {
setFilters((p) => ({ ...p, date_to: v }))
resetListState()
}}
placeholder="结束日期"
clearable
/>
</div>
<select
value={filters.import_batch_id}
onChange={(e) => {
setFilters((p) => ({ ...p, import_batch_id: e.target.value }))
resetListState()
}}
className="app-select-muted max-w-[180px]"
>
<option value="">全部导入文件</option>
{importBatches.map((batch) => (
<option key={batch.id} value={batch.id}>{batch.filename}</option>
))}
</select>
<select
value={filters.account_id}
onChange={(e) => {
setFilters((p) => ({ ...p, account_id: e.target.value }))
resetListState()
}}
className="app-select-muted max-w-[160px]"
>
<option value="">全部账户</option>
{accounts.map((account) => (
<option key={account.id} value={account.id}>{account.name}</option>
))}
</select>
<select
value={filters.member_id}
onChange={(e) => {
setFilters((p) => ({ ...p, member_id: e.target.value }))
resetListState()
}}
className="app-select-muted max-w-[140px]"
>
<option value="">全部成员</option>
{members.map((member) => (
<option key={member.id} value={member.id}>{member.name}</option>
))}
</select>
<div className="relative">
<FontAwesomeIcon
icon={faMagnifyingGlass}
className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted"
/>
<Input
placeholder="搜索描述..."
value={keywordInput}
onChange={(e) => setKeywordInput(e.target.value)}
className="h-9 w-44 pl-9 text-sm"
/>
</div>
<div className="flex-1" />
{selectedIds.length > 0 && (
<Button size="sm" variant="destructive" onClick={() => setBatchDeleteOpen(true)}>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5" />
删除 {selectedIds.length} 条
</Button>
)}
{filters.import_batch_id && (
<Button
size="sm"
variant="outline"
onClick={() => {
const batch = importBatches.find((b) => String(b.id) === filters.import_batch_id)
if (batch) setDeleteImportBatchTarget(batch)
}}
>
<FontAwesomeIcon icon={faTrashCan} className="h-3.5 w-3.5" />
删除导入文件
</Button>
)}
<Button size="sm" variant="outline" onClick={() => setImportOpen(true)}>
<FontAwesomeIcon icon={faFileImport} className="h-3.5 w-3.5" />
导入
</Button>
<Button size="sm" variant="outline" asChild>
<a href={`/api/transactions?${new URLSearchParams({ ...listParams, page: '1', page_size: '100', format: 'csv' }).toString()}`} download>
<FontAwesomeIcon icon={faDownload} className="h-3.5 w-3.5" />导出 CSV
</a>
</Button>
<Button size="sm" onClick={() => setAddOpen(true)}>
<FontAwesomeIcon icon={faPlus} className="h-3.5 w-3.5" />
记一笔
</Button>
</div>
{isLoading ? (
<TableSkeleton rows={8} />
) : (
<>
{(isFetching || isPlaceholderData) && (
<div className="text-right text-xs text-muted" aria-live="polite">更新中…</div>
)}
{transactions.length > 0 ? (
<>
<TransactionTable
items={transactions}
onEdit={openEdit}
onDelete={setDeleteTarget}
selectedIds={selectedIds}
onToggleSelect={(id) =>
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
)
}
onToggleSelectAll={() =>
setSelectedIds((prev) =>
transactions.every((item) => prev.includes(item.id))
? []
: transactions.map((item) => item.id),
)
}
/>
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2">
<Button
variant="outline"
size="sm"
disabled={page <= 1 || isFetching || isPlaceholderData}
onClick={() => changePage(page - 1)}
>
上一页
</Button>
<span className="app-form-label">{page} / {totalPages}</span>
<Button
variant="outline"
size="sm"
disabled={page >= totalPages || isFetching || isPlaceholderData}
onClick={() => changePage(page + 1)}
>
下一页
</Button>
</div>
)}
</>
) : (
<EmptyState
message="暂无收支记录"
action={<Button size="sm" onClick={() => setAddOpen(true)}>记一笔</Button>}
/>
)}
</>
)}
<Dialog open={addOpen} onOpenChange={setAddOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>记一笔</DialogTitle>
</DialogHeader>
<TransactionForm
key="add"
categories={categories}
accounts={accounts}
defaultValues={defaultTransactionFormValues}
submitting={createMutation.isPending}
onSubmit={(data) => createMutation.mutate(buildTransactionPayload(data))}
/>
</DialogContent>
</Dialog>
<Dialog open={editOpen} onOpenChange={setEditOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>编辑记录</DialogTitle>
</DialogHeader>
{editDefaults && (
<TransactionForm
key={editingItem?.id}
categories={categories}
accounts={accounts}
defaultValues={editDefaults}
submitting={updateMutation.isPending}
onSubmit={(data) => {
if (!editingItem) return
updateMutation.mutate({ id: editingItem.id, req: buildTransactionPayload(data) })
}}
/>
)}
</DialogContent>
</Dialog>
<ImportDialog
open={importOpen}
onOpenChange={setImportOpen}
accounts={accounts}
onImported={invalidateTransactions}
/>
<ConfirmDialog
open={!!deleteTarget}
onOpenChange={() => setDeleteTarget(null)}
title="确认删除"
description={`确定要删除这条${deleteTarget?.type === 'income' ? '收入' : deleteTarget?.type === 'transfer' ? '转账' : '支出'}记录吗?金额:${formatCents(deleteTarget?.amount ?? 0)}`}
onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)}
loading={deleteLoading}
/>
<ConfirmDialog
open={batchDeleteOpen}
onOpenChange={setBatchDeleteOpen}
title="批量删除"
description={`确定删除已选择的 ${selectedIds.length} 条收支记录吗?`}
onConfirm={() => batchDeleteMutation.mutate(selectedIds)}
loading={deleteLoading}
/>
<ConfirmDialog
open={!!deleteImportBatchTarget}
onOpenChange={() => setDeleteImportBatchTarget(null)}
title="按导入文件删除"
description={`确定删除「${deleteImportBatchTarget?.filename}」导入的全部收支记录吗?`}
onConfirm={() =>
deleteImportBatchTarget && deleteBatchMutation.mutate(deleteImportBatchTarget.id)
}
loading={deleteLoading}
/>
</div>
)
}
+4
View File
@@ -0,0 +1,4 @@
import { cleanup } from '@testing-library/react'
import { afterEach } from 'vitest'
afterEach(cleanup)
+362
View File
@@ -0,0 +1,362 @@
export interface Member {
id: number
name: string
relation: string
birthday: string
phone: string
created_at: string
updated_at: string
}
export interface CreateMemberRequest {
name: string
relation?: string
birthday?: string
phone?: string
}
export interface UpdateMemberRequest {
name?: string
relation?: string
birthday?: string
phone?: string
}
export interface Category {
id: number
name: string
type: 'income' | 'expense'
parent_id: number | null
sort_order: number
keywords: string
is_active: boolean
created_at: string
updated_at: string
}
export interface CreateCategoryRequest {
name: string
type: 'income' | 'expense'
parent_id?: number | null
sort_order?: number
keywords?: string
}
export interface UpdateCategoryRequest {
name?: string
parent_id?: number | null
sort_order?: number
keywords?: string
is_active?: boolean
}
export interface Account {
id: number
name: string
type: string
balance: number
current_balance: number
bank_name: string
card_number: string
branch_name: string
note: string
is_active: boolean
created_at: string
updated_at: string
}
export interface CreateAccountRequest {
name: string
type: string
balance?: number
bank_name?: string
card_number?: string
branch_name?: string
note?: string
}
export interface UpdateAccountRequest {
name?: string
type?: string
balance?: number
bank_name?: string
card_number?: string
branch_name?: string
note?: string
is_active?: boolean
}
export interface AccountReconciliation {
id: number; account_id: number; system_balance: number; actual_balance: number
difference: number; transaction_id: number | null; note: string; created_at: string
}
export interface BackupStatus {
directory: string; last_backup: string; last_backup_at: string; retention_days: number
}
export type TransactionType = 'income' | 'expense' | 'transfer'
export interface Transaction {
id: number
type: TransactionType
amount: number
category_id: number | null
account_id: number | null
to_account_id: number | null
member_id: number | null
date: string
description: string
counterparty: string
import_batch_id: number | null
created_at: string
updated_at: string
}
export interface TransactionListItem {
id: number
type: TransactionType
amount: number
category_id: number | null
category_name: string
category_is_active: boolean
account_id: number | null
account_name: string
to_account_id: number | null
to_account_name: string
member_id: number | null
member_name: string
date: string
description: string
counterparty: string
import_batch_id: number | null
import_filename: string
created_at: string
updated_at: string
}
export interface CreateTransactionRequest {
type: TransactionType
amount: number
category_id?: number | null
account_id?: number | null
to_account_id?: number | null
member_id?: number | null
date: string
description?: string
counterparty?: string
}
export interface UpdateTransactionRequest {
type?: TransactionType
amount?: number
category_id?: number | null
account_id?: number | null
to_account_id?: number | null
member_id?: number | null
date?: string
description?: string
counterparty?: string
}
export interface TransactionListResponse {
items: TransactionListItem[]
total: number
page: number
page_size: number
}
export interface ImportPreviewItem {
readonly source_key: string
type: TransactionType
amount: number
date: string
description: string
counterparty: string
category_name: string
category_id: number
category_reason: string
status: 'new' | 'duplicate_database' | 'duplicate_file'
}
export interface ImportPreviewResult {
total_count: number
new_count: number
duplicate_count: number
account_name: string
will_create_account: boolean
items: ImportPreviewItem[]
}
export interface ImportTransactionsResult {
imported_count: number
skipped_count: number
account_id: number
import_batch_id: number
items: TransactionListItem[]
}
export interface ImportBatch {
id: number
filename: string
bank_name: string
card_type: string
account_id: number | null
account_name: string
imported_count: number
skipped_count: number
created_at: string
}
export interface DeleteTransactionsResult {
deleted_count: number
}
export interface DashboardSummary {
income: number
expense: number
balance: number
transaction_count: number
}
export interface Budget {
id: number
year: number
month: number | null
category_id: number | null
category_name: string
category_type: 'income' | 'expense' | ''
amount: number
spent: number
remaining: number
usage_percent: number
note: string
created_at: string
updated_at: string
}
export interface UpsertBudgetRequest {
year: number
month?: number | null
category_id?: number | null
amount: number
note?: string
}
export interface BudgetOverview {
year: number
month: number
annual_budget: number
annual_spent: number
annual_remaining: number
annual_usage_percent: number
monthly_budget: number
monthly_spent: number
monthly_budgeted_spent: number
monthly_unbudgeted_spent: number
monthly_remaining: number
monthly_usage_percent: number
items: Budget[]
}
export interface CategoryRankingItem {
category_id: number
category_name: string
category_is_active: boolean
amount: number
percent: number
}
export interface TrendItem {
month: string
income: number
expense: number
balance: number
}
export interface ReportOverview {
year: number
month: number
category_ranking: CategoryRankingItem[]
trend: TrendItem[]
}
export interface Asset {
id: number
name: string
type: string
value: number
account_id: number | null
account_name: string
is_derived: boolean
note: string
created_at: string
updated_at: string
}
export interface AssetSnapshot {
id: number
date: string
total_asset: number
total_debt: number
net_worth: number
created_at: string
}
export interface Liability {
id: number
name: string
type: string
principal: number
interest_rate: number
monthly_payment: number
remaining_terms: number
note: string
created_at: string
updated_at: string
}
export interface NetWorthSummary {
total_assets: number
total_debt: number
liquid_assets: number
liquid_debt: number
net_worth: number
}
export interface Policy {
id: number
name: string
type: string
insured_person: string
premium: number
coverage_amount: number
start_date: string
end_date: string
payment_frequency: string
next_payment_date: string
payment_term_end: string
beneficiary: string
status: string
note: string
created_at: string
updated_at: string
}
export interface PolicyPayment {
id: number; policy_id: number; policy_name: string; due_date: string; amount: number
status: 'pending' | 'paid' | 'skipped'; paid_date: string; note: string
created_at: string; updated_at: string
}
export interface LifecycleEvent {
id: number
year: number
member_id: number | null
member_name: string
event: string
estimated_cost: number
note: string
created_at: string
updated_at: string
}