Family bookkeeping PWA modelled on 木木记账
Hono + SQLite server and a React/shadcn PWA with two-level categories, who-spent/who-paid splits, settlement, one-line and voice entry, budget alerts (Web Push and Bark), monthly/annual reports, and 木木 import tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "base-nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle",
|
||||
"registries": {}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="记账" />
|
||||
<meta name="theme-color" content="#f6f7f9" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#1b1b1b" media="(prefers-color-scheme: dark)" />
|
||||
<link rel="icon" type="image/png" href="/app-icon-192.png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<title>家庭记账</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.9.0",
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.105.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"cn": "^0.5.0",
|
||||
"lucide-react": "^1.63.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-router": "^8.5.1",
|
||||
"recharts": "^3.10.1",
|
||||
"shadcn": "^4.23.0",
|
||||
"sonner": "^2.0.8",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.19.2",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"oxlint": "^1.89.0",
|
||||
"typescript": "~7.0.2",
|
||||
"vite": "^8.3.5",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"workbox-precaching": "^7.4.1",
|
||||
"workbox-routing": "^7.4.1",
|
||||
"workbox-window": "^7.4.1"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,103 @@
|
||||
import { createContext, lazy, Suspense, useContext, useState, type ReactNode } from 'react';
|
||||
import { NavLink, Route, Routes } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BarChart3, Handshake, List, Plus, User } from 'lucide-react';
|
||||
import { ApiError, api, type Bill } from '@/lib/api';
|
||||
import { MetaProvider } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { BillEditor } from '@/components/bill-editor';
|
||||
import LoginPage from '@/pages/login';
|
||||
import HomePage from '@/pages/home';
|
||||
import SettlePage from '@/pages/settle';
|
||||
import MePage from '@/pages/me';
|
||||
|
||||
// Chart pages carry the charting library, so load them on demand.
|
||||
const StatsPage = lazy(() => import('@/pages/stats'));
|
||||
const ReportPage = lazy(() => import('@/pages/report'));
|
||||
|
||||
interface EditorApi {
|
||||
open: (opts?: { bill?: Bill; text?: string }) => void;
|
||||
}
|
||||
const EditorCtx = createContext<EditorApi>({ open: () => {} });
|
||||
export const useEditor = () => useContext(EditorCtx);
|
||||
|
||||
export default function App() {
|
||||
const meta = useQuery({ queryKey: ['meta'], queryFn: api.meta });
|
||||
|
||||
if (meta.isPending) return <div className="flex h-full items-center justify-center text-muted-foreground">加载中…</div>;
|
||||
if (meta.error instanceof ApiError && meta.error.status === 401) return <LoginPage />;
|
||||
if (meta.error) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center text-muted-foreground">
|
||||
<p>无法连接服务器</p>
|
||||
<button className="text-primary" onClick={() => meta.refetch()}>重试</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MetaProvider meta={meta.data}>
|
||||
<Shell>
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/stats" element={<StatsPage />} />
|
||||
<Route path="/report/:year" element={<ReportPage />} />
|
||||
<Route path="/settle" element={<SettlePage />} />
|
||||
<Route path="/me" element={<MePage />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</Shell>
|
||||
</MetaProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function Shell({ children }: { children: ReactNode }) {
|
||||
const [editor, setEditor] = useState<{ open: boolean; bill?: Bill; text?: string }>({ open: false });
|
||||
|
||||
return (
|
||||
<EditorCtx.Provider value={{ open: (o) => setEditor({ open: true, ...o }) }}>
|
||||
<div className="mx-auto flex min-h-full max-w-lg flex-col">
|
||||
<main className="flex-1 pb-24">{children}</main>
|
||||
<nav className="pb-safe fixed inset-x-0 bottom-0 z-40 border-t bg-card/95 backdrop-blur">
|
||||
<div className="mx-auto grid h-14 max-w-lg grid-cols-5">
|
||||
<Tab to="/" icon={<List className="size-5" />} label="明细" />
|
||||
<Tab to="/stats" icon={<BarChart3 className="size-5" />} label="统计" />
|
||||
<div className="flex items-center justify-center">
|
||||
<button
|
||||
onClick={() => setEditor({ open: true })}
|
||||
aria-label="记一笔"
|
||||
className="-mt-5 flex size-13 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/30 active:scale-95"
|
||||
>
|
||||
<Plus className="size-7" />
|
||||
</button>
|
||||
</div>
|
||||
<Tab to="/settle" icon={<Handshake className="size-5" />} label="结算" />
|
||||
<Tab to="/me" icon={<User className="size-5" />} label="我的" />
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
<BillEditor
|
||||
open={editor.open}
|
||||
bill={editor.bill}
|
||||
initialText={editor.text}
|
||||
onClose={() => setEditor((e) => ({ ...e, open: false }))}
|
||||
/>
|
||||
</EditorCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function Tab({ to, icon, label }: { to: string; icon: ReactNode; label: string }) {
|
||||
return (
|
||||
<NavLink
|
||||
to={to}
|
||||
end={to === '/'}
|
||||
className={({ isActive }) =>
|
||||
cn('flex flex-col items-center justify-center gap-0.5 text-[11px]', isActive ? 'text-primary' : 'text-muted-foreground')
|
||||
}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</NavLink>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { ChevronLeft, Delete, Mic, Sparkles, Trash2 } from 'lucide-react';
|
||||
import { api, type Bill, type BillInput, type BillType, type BudgetAlert } from '@/lib/api';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { fromLocalInput, money, toLocalInput } from '@/lib/format';
|
||||
import { speechSupported, useSpeech } from '@/lib/speech';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from './category-icon';
|
||||
import { SheetPage } from './sheet-page';
|
||||
import { Button } from './ui/button';
|
||||
import {
|
||||
AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter,
|
||||
AlertDialogHeader, AlertDialogTitle,
|
||||
} from './ui/alert-dialog';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
bill?: Bill | null;
|
||||
// A phrase to fill the form from, e.g. from the quick entry box.
|
||||
initialText?: string;
|
||||
}
|
||||
|
||||
const COLS = 5;
|
||||
|
||||
// Evaluates "12+3.5-1" into cents. Returns null when incomplete.
|
||||
function evalAmount(expr: string): number | null {
|
||||
if (!expr) return null;
|
||||
const tokens = expr.match(/[+-]?[^+-]+/g);
|
||||
if (!tokens) return null;
|
||||
let total = 0;
|
||||
for (const t of tokens) {
|
||||
const v = Number(t);
|
||||
if (Number.isNaN(v)) return null;
|
||||
total += Math.round(v * 100);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function lastCategory(type: BillType): number | null {
|
||||
try {
|
||||
const v = localStorage.getItem(`lastCategory:${type}`);
|
||||
return v ? Number(v) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function useAlertToasts() {
|
||||
const meta = useMeta();
|
||||
return useCallback(
|
||||
(alerts: BudgetAlert[]) => {
|
||||
for (const a of alerts) {
|
||||
const what = a.budget.categoryId ? `「${meta.category(a.budget.categoryId)?.name}」预算` : '本月总预算';
|
||||
const detail = `已花 ¥${money(a.budget.spent)} / 预算 ¥${money(a.budget.amount)}`;
|
||||
if (a.level >= 100) toast.error(`${what}已超支`, { description: detail, duration: 6000 });
|
||||
else toast.warning(`${what}已用 ${a.budget.percent}%`, { description: detail, duration: 6000 });
|
||||
}
|
||||
},
|
||||
[meta],
|
||||
);
|
||||
}
|
||||
|
||||
export function BillEditor({ open, onClose, bill, initialText }: Props) {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const showAlerts = useAlertToasts();
|
||||
const me = meta.me.memberId;
|
||||
|
||||
const [type, setType] = useState<BillType>('expense');
|
||||
const [categoryId, setCategoryId] = useState<number | null>(null);
|
||||
const [expanded, setExpanded] = useState<number | null>(null);
|
||||
const [expr, setExpr] = useState('');
|
||||
const [time, setTime] = useState(Date.now());
|
||||
const [note, setNote] = useState('');
|
||||
const [payerId, setPayerId] = useState<number | null>(me);
|
||||
const [memberIds, setMemberIds] = useState<number[]>([me]);
|
||||
const [shares, setShares] = useState<Record<number, string> | null>(null);
|
||||
const [excludeBudget, setExcludeBudget] = useState(false);
|
||||
const [bookId, setBookId] = useState(meta.bookId);
|
||||
const [quick, setQuick] = useState('');
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
const selectCategory = useCallback(
|
||||
(id: number | null) => {
|
||||
setCategoryId(id);
|
||||
const c = meta.category(id);
|
||||
if (c) setExpanded(meta.parentOf(c).id);
|
||||
},
|
||||
[meta],
|
||||
);
|
||||
|
||||
const reset = useCallback(
|
||||
(keepContext = false) => {
|
||||
setExpr('');
|
||||
setNote('');
|
||||
setShares(null);
|
||||
setQuick('');
|
||||
if (!keepContext) {
|
||||
setType('expense');
|
||||
selectCategory(lastCategory('expense'));
|
||||
setTime(Date.now());
|
||||
setPayerId(me);
|
||||
setMemberIds([me]);
|
||||
setExcludeBudget(false);
|
||||
setBookId(meta.bookId);
|
||||
}
|
||||
},
|
||||
[me, meta.bookId, selectCategory],
|
||||
);
|
||||
|
||||
const applyParsed = useCallback(
|
||||
async (text: string) => {
|
||||
try {
|
||||
const p = await api.quick(text);
|
||||
setType(p.type);
|
||||
if (p.categoryId) selectCategory(p.categoryId);
|
||||
else selectCategory(lastCategory(p.type));
|
||||
if (p.amount) setExpr(String(p.amount / 100));
|
||||
setTime(p.time);
|
||||
setNote(p.note);
|
||||
setMemberIds(p.memberIds);
|
||||
setPayerId(p.type === 'expense' ? p.payerId : null);
|
||||
setShares(null);
|
||||
setQuick('');
|
||||
if (!p.amount) toast.info('没听出金额,请在键盘上输入');
|
||||
else if (!p.categoryId) toast.info('请选择一个分类');
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
}
|
||||
},
|
||||
[selectCategory],
|
||||
);
|
||||
|
||||
// Fill the form whenever the sheet opens.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (bill) {
|
||||
setType(bill.type);
|
||||
selectCategory(bill.categoryId);
|
||||
setExpr(String(bill.amount / 100));
|
||||
setTime(bill.time);
|
||||
setNote(bill.note);
|
||||
setPayerId(bill.payerId);
|
||||
setMemberIds(bill.members.map((m) => m.memberId));
|
||||
const even = bill.members.every((m) => Math.abs(m.share - bill.amount / bill.members.length) < 1);
|
||||
setShares(even ? null : Object.fromEntries(bill.members.map((m) => [m.memberId, String(m.share / 100)])));
|
||||
setExcludeBudget(bill.excludeBudget);
|
||||
setBookId(bill.bookId);
|
||||
setQuick('');
|
||||
} else {
|
||||
reset();
|
||||
if (initialText) applyParsed(initialText);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, bill?.id]);
|
||||
|
||||
const speech = useSpeech(applyParsed);
|
||||
const canSpeak = useMemo(speechSupported, []);
|
||||
|
||||
const amount = evalAmount(expr);
|
||||
const roots = meta.roots(type);
|
||||
const children = expanded ? meta.childrenOf(expanded) : [];
|
||||
|
||||
const switchType = (t: BillType) => {
|
||||
setType(t);
|
||||
selectCategory(lastCategory(t));
|
||||
if (t === 'income') setPayerId(null);
|
||||
else setPayerId(me);
|
||||
};
|
||||
|
||||
const allMembers = meta.members.map((m) => m.id);
|
||||
const isShared = memberIds.length === allMembers.length && allMembers.length > 1;
|
||||
|
||||
const press = (key: string) => {
|
||||
setExpr((e) => {
|
||||
if (key === 'back') return e.slice(0, -1);
|
||||
if (key === '+' || key === '-') {
|
||||
if (!e) return e;
|
||||
return /[+-]$/.test(e) ? e.slice(0, -1) + key : e + key;
|
||||
}
|
||||
const last = e.split(/[+-]/).at(-1) ?? '';
|
||||
if (key === '.') return last.includes('.') ? e : e + (last ? '.' : '0.');
|
||||
if (/\.\d{2}$/.test(last)) return e;
|
||||
if (last === '0' && key !== '.') return e.slice(0, -1) + key;
|
||||
if (last.replace('.', '').length >= 9) return e;
|
||||
return e + key;
|
||||
});
|
||||
};
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async (again: boolean) => {
|
||||
if (!categoryId) throw new Error('请选择分类');
|
||||
if (!amount || amount <= 0) throw new Error('请输入金额');
|
||||
let members: BillInput['members'] = memberIds.map((memberId) => ({ memberId }));
|
||||
if (shares && memberIds.length > 1) {
|
||||
members = memberIds.map((memberId) => ({ memberId, share: Math.round(Number(shares[memberId] || 0) * 100) }));
|
||||
const sum = members.reduce((s, m) => s + (m.share ?? 0), 0);
|
||||
if (sum !== amount) throw new Error(`分摊合计 ¥${money(sum)},与金额 ¥${money(amount)} 不一致`);
|
||||
}
|
||||
const input: BillInput = {
|
||||
bookId, type, categoryId, amount, time, note: note.trim(),
|
||||
payerId: type === 'expense' ? payerId : null, members, excludeBudget,
|
||||
};
|
||||
const res = bill ? await api.updateBill(bill.id, input) : await api.createBill(input);
|
||||
return { res, again };
|
||||
},
|
||||
onSuccess: ({ res, again }) => {
|
||||
try { localStorage.setItem(`lastCategory:${type}`, String(categoryId)); } catch { /* ignore */ }
|
||||
qc.invalidateQueries();
|
||||
showAlerts(res.alerts);
|
||||
if (again) {
|
||||
toast.success('已保存,继续记下一笔');
|
||||
reset(true);
|
||||
} else {
|
||||
toast.success(bill ? '已修改' : '已记录');
|
||||
onClose();
|
||||
}
|
||||
},
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: () => api.deleteBill(bill!.id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries();
|
||||
toast.success('已删除');
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
// Category rows, with the children panel inserted under the row of the open parent.
|
||||
const rows: (typeof roots)[] = [];
|
||||
for (let i = 0; i < roots.length; i += COLS) rows.push(roots.slice(i, i + COLS));
|
||||
|
||||
return (
|
||||
<SheetPage open={open}>
|
||||
{/* Header */}
|
||||
<div className="pt-safe shrink-0 border-b bg-card">
|
||||
<div className="flex h-12 items-center gap-2 px-2">
|
||||
<Button variant="ghost" size="icon" onClick={onClose} aria-label="返回">
|
||||
<ChevronLeft className="size-5" />
|
||||
</Button>
|
||||
<div className="mx-auto flex rounded-full bg-muted p-0.5 text-sm">
|
||||
{(['expense', 'income'] as const).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => switchType(t)}
|
||||
className={cn('rounded-full px-5 py-1 transition-colors', type === t && 'bg-card font-medium shadow-sm')}
|
||||
>
|
||||
{t === 'expense' ? '支出' : '收入'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{bill ? (
|
||||
<Button variant="ghost" size="icon" onClick={() => setConfirmDelete(true)} aria-label="删除">
|
||||
<Trash2 className="size-5 text-destructive" />
|
||||
</Button>
|
||||
) : (
|
||||
<div className="size-9" />
|
||||
)}
|
||||
</div>
|
||||
{/* Quick entry */}
|
||||
{!bill && (
|
||||
<form
|
||||
className="flex items-center gap-2 px-3 pb-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (quick.trim()) applyParsed(quick.trim());
|
||||
}}
|
||||
>
|
||||
<div className="flex h-9 flex-1 items-center gap-2 rounded-full bg-muted px-3">
|
||||
<Sparkles className="size-4 shrink-0 text-primary" />
|
||||
<input
|
||||
value={speech.listening ? speech.text : quick}
|
||||
onChange={(e) => setQuick(e.target.value)}
|
||||
placeholder={speech.listening ? '正在听…' : '一句话记账:和猪猪打车35'}
|
||||
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
|
||||
enterKeyHint="done"
|
||||
/>
|
||||
</div>
|
||||
{canSpeak && (
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={speech.listening ? 'default' : 'secondary'}
|
||||
className={cn('rounded-full', speech.listening && 'animate-pulse')}
|
||||
onClick={() => (speech.listening ? speech.stop() : speech.start())}
|
||||
aria-label="语音记账"
|
||||
>
|
||||
<Mic className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Category grid */}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-2 py-3">
|
||||
{rows.map((row, i) => (
|
||||
<Fragment key={i}>
|
||||
<div className="grid grid-cols-5 gap-y-3">
|
||||
{row.map((c) => {
|
||||
const active = expanded === c.id;
|
||||
const chosen = categoryId === c.id || meta.category(categoryId)?.parentId === c.id;
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => {
|
||||
setExpanded(active ? null : c.id);
|
||||
if (!chosen) setCategoryId(c.id);
|
||||
}}
|
||||
className="flex flex-col items-center gap-1"
|
||||
>
|
||||
<CategoryIcon
|
||||
category={c}
|
||||
className={cn('size-12 transition-all', chosen && 'bg-primary/15 ring-2 ring-primary')}
|
||||
/>
|
||||
<span className={cn('text-xs', chosen ? 'font-medium text-primary' : 'text-muted-foreground')}>
|
||||
{c.name}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{row.some((c) => c.id === expanded) && children.length > 0 && (
|
||||
<div className="my-3 grid grid-cols-5 gap-y-3 rounded-2xl bg-card p-3 shadow-sm">
|
||||
{children.map((c) => (
|
||||
<button key={c.id} onClick={() => setCategoryId(c.id)} className="flex flex-col items-center gap-1">
|
||||
<CategoryIcon
|
||||
category={c}
|
||||
className={cn('size-10', categoryId === c.id && 'bg-primary/15 ring-2 ring-primary')}
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'line-clamp-1 text-[11px]',
|
||||
categoryId === c.id ? 'font-medium text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{c.name}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{i < rows.length - 1 && <div className="h-3" />}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Details + keypad */}
|
||||
<div className="pb-safe shrink-0 border-t bg-card">
|
||||
<div className="space-y-2 px-3 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-12 shrink-0 text-xs text-muted-foreground">谁花的</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{meta.members.map((m) => (
|
||||
<Chip key={m.id} active={memberIds.includes(m.id) && !isShared} color={m.color} onClick={() => setMemberIds([m.id])}>
|
||||
{m.name}
|
||||
</Chip>
|
||||
))}
|
||||
{allMembers.length > 1 && (
|
||||
<Chip active={isShared} onClick={() => { setShares(null); setMemberIds(allMembers); }}>
|
||||
共同
|
||||
</Chip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{type === 'expense' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-12 shrink-0 text-xs text-muted-foreground">谁付的</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{meta.members.map((m) => (
|
||||
<Chip key={m.id} active={payerId === m.id} color={m.color} onClick={() => setPayerId(m.id)}>
|
||||
{m.name}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
{memberIds.length > 1 && (
|
||||
<button
|
||||
className="ml-auto text-xs text-primary"
|
||||
onClick={() =>
|
||||
setShares((s) =>
|
||||
s ? null : Object.fromEntries(memberIds.map((id) => [id, amount ? String(Math.round(amount / memberIds.length) / 100) : ''])),
|
||||
)
|
||||
}
|
||||
>
|
||||
{shares ? '改回平分' : '平分 · 修改'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{shares && memberIds.length > 1 && (
|
||||
<div className="flex gap-2">
|
||||
{memberIds.map((id) => (
|
||||
<label key={id} className="flex flex-1 items-center gap-1 rounded-lg bg-muted px-2 py-1 text-xs">
|
||||
<span className="shrink-0" style={{ color: meta.member(id)?.color }}>{meta.member(id)?.name}</span>
|
||||
<input
|
||||
inputMode="decimal"
|
||||
value={shares[id] ?? ''}
|
||||
onChange={(e) => setShares({ ...shares, [id]: e.target.value })}
|
||||
className="w-full min-w-0 bg-transparent text-right outline-none"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={toLocalInput(time)}
|
||||
onChange={(e) => e.target.value && setTime(fromLocalInput(e.target.value))}
|
||||
className="h-8 shrink-0 rounded-lg bg-muted px-2 text-xs outline-none"
|
||||
/>
|
||||
{meta.books.length > 1 && (
|
||||
<select
|
||||
value={bookId}
|
||||
onChange={(e) => setBookId(Number(e.target.value))}
|
||||
className="h-8 max-w-24 shrink-0 truncate rounded-lg bg-muted px-2 text-xs outline-none"
|
||||
>
|
||||
{meta.books.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{type === 'expense' && (
|
||||
<Chip active={excludeBudget} onClick={() => setExcludeBudget(!excludeBudget)}>不计预算</Chip>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder="备注"
|
||||
maxLength={200}
|
||||
className="h-9 min-w-0 flex-1 rounded-lg bg-muted px-3 text-sm outline-none"
|
||||
/>
|
||||
<div className={cn('tabular shrink-0 text-right text-2xl font-semibold', type === 'expense' ? 'text-expense' : 'text-income')}>
|
||||
{expr ? (/[+-]/.test(expr.slice(1)) ? `${expr} = ${amount !== null ? money(amount) : '…'}` : expr) : '0'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 grid grid-cols-4 gap-px bg-border">
|
||||
{['1', '2', '3', 'back', '4', '5', '6', '+', '7', '8', '9', '-', '.', '0'].map((k) => (
|
||||
<button
|
||||
key={k}
|
||||
onClick={() => press(k)}
|
||||
className="flex h-12 items-center justify-center bg-card text-xl active:bg-muted"
|
||||
>
|
||||
{k === 'back' ? <Delete className="size-5" /> : k}
|
||||
</button>
|
||||
))}
|
||||
{bill ? (
|
||||
<div className="bg-card" />
|
||||
) : (
|
||||
<button
|
||||
onClick={() => save.mutate(true)}
|
||||
disabled={save.isPending}
|
||||
className="h-12 bg-card text-base active:bg-muted"
|
||||
>
|
||||
再记
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => save.mutate(false)}
|
||||
disabled={save.isPending}
|
||||
className="h-12 bg-primary text-base font-medium text-primary-foreground active:opacity-80"
|
||||
>
|
||||
{save.isPending ? '保存中' : '完成'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>删除这笔账单?</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={() => remove.mutate()}>删除</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</SheetPage>
|
||||
);
|
||||
}
|
||||
|
||||
function Chip({
|
||||
active, color, onClick, children,
|
||||
}: { active: boolean; color?: string; onClick: () => void; children: React.ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'h-7 rounded-full border px-3 text-xs transition-colors',
|
||||
active ? 'border-transparent font-medium text-white' : 'border-border text-muted-foreground',
|
||||
)}
|
||||
style={active ? { backgroundColor: color ?? 'var(--primary)' } : undefined}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useEditor } from '@/App';
|
||||
import type { Bill } from '@/lib/api';
|
||||
import { dayKey, dayLabel, money, timeLabel } from '@/lib/format';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from './category-icon';
|
||||
import { MemberChips } from './member-chips';
|
||||
|
||||
// Bills grouped by day, with per-day expense/income totals.
|
||||
export function BillList({ bills, memberId }: { bills: Bill[]; memberId?: number | null }) {
|
||||
const groups: { key: string; time: number; bills: Bill[] }[] = [];
|
||||
for (const b of bills) {
|
||||
const key = dayKey(b.time);
|
||||
if (groups.at(-1)?.key !== key) groups.push({ key, time: b.time, bills: [] });
|
||||
groups.at(-1)!.bills.push(b);
|
||||
}
|
||||
|
||||
// When filtering by member, show that member's share instead of the whole bill.
|
||||
const amountOf = (b: Bill) => (memberId ? b.members.find((m) => m.memberId === memberId)?.share ?? 0 : b.amount);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{groups.map((g) => {
|
||||
const out = g.bills.filter((b) => b.type === 'expense').reduce((s, b) => s + amountOf(b), 0);
|
||||
const inc = g.bills.filter((b) => b.type === 'income').reduce((s, b) => s + amountOf(b), 0);
|
||||
return (
|
||||
<section key={g.key} className="overflow-hidden rounded-2xl bg-card shadow-sm">
|
||||
<header className="flex items-center justify-between px-4 pt-3 pb-1 text-xs text-muted-foreground">
|
||||
<span>{dayLabel(g.time)}</span>
|
||||
<span className="tabular space-x-2">
|
||||
{out > 0 && <span>支 {money(out)}</span>}
|
||||
{inc > 0 && <span>收 {money(inc)}</span>}
|
||||
</span>
|
||||
</header>
|
||||
{g.bills.map((b) => <BillRow key={b.id} bill={b} amount={amountOf(b)} />)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BillRow({ bill, amount }: { bill: Bill; amount: number }) {
|
||||
const meta = useMeta();
|
||||
const editor = useEditor();
|
||||
const cat = meta.category(bill.categoryId);
|
||||
const payer = meta.member(bill.payerId);
|
||||
const shared = bill.members.length > 1;
|
||||
return (
|
||||
<button onClick={() => editor.open({ bill })} className="flex w-full items-center gap-3 px-4 py-2.5 text-left active:bg-muted">
|
||||
<CategoryIcon category={cat} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-[15px]">{cat?.name ?? '未知'}</span>
|
||||
<MemberChips members={bill.members} />
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted-foreground">
|
||||
{timeLabel(bill.time)}
|
||||
{shared && payer && <> · {payer.name}付</>}
|
||||
{bill.note && <> · {bill.note}</>}
|
||||
</div>
|
||||
</div>
|
||||
<span className={cn('tabular shrink-0 text-[15px] font-medium', bill.type === 'income' ? 'text-income' : 'text-foreground')}>
|
||||
{bill.type === 'income' ? '+' : '-'}
|
||||
{money(amount)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||