commit 4a5db3f1f940f403a4e6a2432136aa52d2ac5683 Author: mapleferry Date: Sun Nov 29 21:29:06 2026 +0800 chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..636a6a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# Binaries +*.exe +*.exe~ +*.dll +*.so +*.dylib +household-book +backend/household-book + +# Database +*.db +*.db-journal +*.db-wal +*.db-shm +data/ + +# Frontend build output +frontend/dist/ +frontend/node_modules/ +backend/static/ + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Temp +.gocache/ +.gocache2/ +.pnpm-store/ +docs/~$* +~$* +vite-dev*.log +frontend/vite-dev*.log + +# Local personal documents / statements (not committed) +docs/ +.claude/settings.local.json diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..75a8cb2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,273 @@ +# CLAUDE.md - 家庭记账本项目指南 + +## 项目概要 + +家庭记账本(Household Budget Book)是一个本地优先的家庭财务管理系统,使用 Go + React + SQLite 构建。当前 Web 版本已经实现产品规划中的 Phase 1、Phase 2、Phase 3:基础记账、预算报表、资产负债、保单、人生周期。 + +在产品规划基线之上,已扩展以下能力:账户间转账(transfer 类型)、账户余额按流水实时派生、资产绑定与净值快照、多来源账单导入及预览整理、每日数据库备份、交易 CSV 导出、保单缴费记录和账户对账。 + +开发时应尊重现有实现:深色高端金融风格、Font Awesome 图标体系、整数金额模型、SQLite 自动迁移、前后端类型同步。 + +## 技术栈 + +| 层 | 选型 | 说明 | +|---|---|---| +| 后端 | Go 1.25 + Gin | REST API,单一二进制 | +| 数据库 | SQLite + modernc.org/sqlite | 纯 Go,无 CGO | +| 前端 | React 19 + TypeScript + Vite 5 | SPA | +| UI | Tailwind CSS v3 + Radix/shadcn-style 组件 | 本地设计系统 | +| 图标 | Font Awesome React | 导航、按钮、业务图标 | +| 图表 | Recharts | 报表和预算可视化 | +| 桌面 | Wails 配置骨架 | Web 为当前主要运行目标 | + +## 构建与运行 + +```bash +# 后端开发 +cd backend +go run . -mode=dev + +# 前端开发 +cd frontend +pnpm install +pnpm run dev + +# 后端测试 +cd backend +go test ./... + +# 前端验证 +cd frontend +pnpm run lint +pnpm run build + +# 生产构建 +bash scripts/build.sh +./household-book -mode=prod -static=backend/static +``` + +`frontend` 的 `build` 脚本在 `vite build` 之后执行 `scripts/precompress.mjs`,为 `dist/` 下的文本资源生成 `.br` / `.gz` 预压缩副本。生产静态资源应由 `backend/api/router.go` 的静态中间件提供:`/assets/*`(文件名自带内容 hash)下发 `Cache-Control: public, max-age=31536000, immutable`,`index.html` 为 `no-cache, must-revalidate`,并按 `Accept-Encoding` 优先返回 brotli、其次 gzip。改用 `vite preview` 或其它静态服务器不会走到这套缓存与预压缩逻辑。 + +Vite 开发服务器通过 `frontend/vite.config.ts` 将 `/api` 代理到 `http://localhost:8080`。前端 API 客户端使用相对路径,不应硬编码后端地址。 + +`frontend/pnpm-workspace.yaml` 通过 `allowBuilds` 只放行 `esbuild`。若 pnpm 报 `ERR_PNPM_IGNORED_BUILDS`,应确认工作目录和仓库配置,必要时用 `pnpm approve-builds` 只批准 `esbuild`,不要全局关闭构建脚本检查。 + +后端启动参数: + +- `-mode=dev|prod`:dev 模式自动允许 `localhost:5173` 跨域。 +- `-port=8080`:监听端口。 +- `-db=./data/family_book.db`:SQLite 路径。 +- `-static=...`:生产模式下的前端静态资源目录。 +- `-cors-origin=https://a.com,https://b.com`:自定义 CORS 来源(逗号分隔)。dev 模式下未设置时自动允许本地 Vite 端口。 + +后端启动净值快照和数据库备份两个后台任务:净值快照启动时执行,数据库备份在 HTTP 服务启动 30 秒后首次检查,二者随后每 6 小时复检;关闭时通过同一 `context` 取消。 + +SQLite 使用 WAL 模式和最多 4 个连接(最大空闲连接同为 4),允许页面并行读取。账户 `current_balance` 使用共享聚合 CTE 一次汇总收入、支出、转出和转入影响;不要恢复为逐账户相关子查询。 + +## 项目结构 + +```text +backend/ + main.go # 参数、数据库、迁移、seed、HTTP server、快照/备份后台、优雅退出 + api/ # Gin handler 与路由 + db/ # SQLite 连接、迁移、默认数据 + middleware/ # CORS、recover、日志 + model/ # Go DTO 和实体 + service/ + transaction.go # 收支 CRUD、批次删除、孤儿账户清理 + transaction_import.go # 导入入口分发 + PDF 解析(招行储蓄/信用卡) + csv_import.go # 支付宝(GBK)/ 微信(UTF-8 BOM)CSV 解析 + asset.go # 资产、负债、净值汇总、净值快照后台 + backup.go # VACUUM INTO 每日备份及保留期清理 + account.go # 账户 CRUD、余额派生和对账 + policy.go # 保单、续费提醒和缴费记录 + ... # budget、category、dashboard、report 等 +frontend/ + src/ + components/ # 通用组件(TransactionTable、AmountDisplay 等) + components/ui/ # UI primitives + components/layout/ # 页面框架 + lib/ # API client、金额/日期格式化工具 + pages/ # 业务页面 + types/ # TypeScript 接口 +docs/ # 产品规划、示例账单、源数据 +scripts/ # 构建脚本 +desktop/ # Wails 桌面壳说明 +``` + +## 功能清单 + +### 基础记账 + +- 家庭成员新增、编辑、删除。 +- 收入/支出分类新增、编辑、删除,支持树形层级;`sort_order` 按 `(type, parent_id)` 自增。每个分类可配置 `keywords`(逗号分隔),导入时按描述匹配自动归类。 +- 支付账户新增、编辑、删除,账户类型包含现金、储蓄卡、信用卡、支付宝、微信等。 +- 银行卡账户可维护银行、银行卡号、支行、备注。 +- 账户既存开账初值(`balance` 字段,手工录入),又返回当前余额(`current_balance`,按流水实时派生:开账 + 收入 - 支出 - 转出 + 转入)。 +- 收支记录支持三种类型:**income / expense / transfer**。转账(transfer)必须同时指定 `account_id` 和 `to_account_id` 且不相同,且不挂分类;income / expense 必须挂分类,`to_account_id` 必须为空。 +- 收支列表支持日期范围、类型(含转账)、分类、账户、成员、关键词、导入批次筛选;keyword 在前端 300ms 防抖。 +- 支持批量删除、按导入文件删除;按导入文件删除会自动清理"由收支导入自动创建"且不再被任何流水或批次引用的孤儿账户。 +- 收支列表默认按交易日期和 ID 倒序展示;账户筛选同时匹配转出与转入账户。 +- 收支列表可按当前筛选条件导出 CSV;账户可保存对账差异,并按需生成余额调整流水。 + +### 预算与报表 + +- 预算管理支持年度预算、分类预算、月度看板和超支预警。预算与报表的统计 SQL 全部排除 `transfer` 类型(显式 `type IN ('income','expense')` 或隐式 `type='expense'`),避免转账被算成开支。 +- 报表页提供支出分类饼图(带 Legend)、分类排行(横向条形 + LabelList 显示金额和百分比)、月度趋势折线图。 +- `category_ranking` 接口的 `percent` 用当月该类型的全部金额作分母,与 `LIMIT` 解耦:top-N 之外的分类不会被强行凑到 100%。 + +### 资产、保单、人生周期 + +- 资产登记可"手工录入金额"或"绑定账户"(`assets.account_id`)。绑定时 `value` 由 `account.current_balance` 实时派生,记录列表用 `is_derived` 标识。 +- 净值汇总(`/api/assets/net-worth`)返回五个字段: + - `total_assets`:assets 表汇总(手工 value + 绑定账户的 current_balance)。 + - `total_debt`:liabilities 表 principal 汇总。 + - `liquid_assets`:活跃账户当前余额派生(非信用卡 + `current_balance > 0`,且账户未被任何 assets 行绑定,避免双计)。 + - `liquid_debt`:活跃信用卡账户 `current_balance < 0` 的绝对值汇总。 + - `net_worth = total_assets + liquid_assets - total_debt - liquid_debt`。 +- 净值快照:`asset_snapshots.date` 以当月 1 日作为月份键;进程启动及后台每 6 小时 upsert 当月最新净值,跨月后历史月份自然冻结。 +- 保单管理:续费提醒使用 `next_payment_date`,与保障截止日分离;缴费记录支持待处理、已缴和跳过,状态完成后按缴费频率推进下次缴费日。 +- 人生周期:按年份维护家庭事件和预计成本。 + +### 数据安全 + +- `BackupService` 在 HTTP 服务启动 30 秒后首次检查当日备份,随后每 6 小时检查,使用 SQLite `VACUUM INTO` 写入数据库同级的 `backups/YYYY-MM-DD.db`,每个自然日最多一份并保留 30 天。 +- 设置页支持查看状态和检查/创建当日备份。当前没有恢复接口;恢复校验与回滚属于后续高优先级工作。 + +### 收支导入 + +支持四种来源,前端通过单一"导入来源"下拉切换;后端通过 `source_kind` 表单字段调度解析器: + +| 来源 | 格式 | 编码 | 入口函数 | +|---|---|---|---| +| `cmb_debit` | PDF 流水 | – | `parseDebitStatement` | +| `cmb_credit` | PDF 账单 | – | `parseCreditCardStatement` + `parseCreditRawAmounts` | +| `alipay` | CSV | GBK | `parseAlipayCSV`(`csv_import.go`) | +| `wechat` | CSV | UTF-8 BOM | `parseWechatCSV`(`csv_import.go`) | + +- 导入批次写入 `import_batches`;交易记录写入 `import_batch_id` 和 `source_key`。 +- `source_key` 基于来源与稳定交易身份生成,不依赖整份文件内容;支付宝、微信优先使用平台交易单号,银行账单使用规范化交易字段。唯一约束错误用 `errors.As(*sqlite.Error)` + `Code()` 判断,不使用字符串匹配。 +- 预览状态区分文件内重复和数据库已有记录,展示关键词命中/兜底原因,并允许用 `category_overrides` 修正单条分类;单次预览上限为 1000 条。 +- 自动归类:`findCategoryID` 按 `categories.keywords`(逗号分隔)匹配描述;落空则使用同类型下"其他"分类。 +- 导入批次的 `imported_count` / `skipped_count` 在事务内一次性更新,避免主流程提交后状态分裂。 +- 交易记录包含 `counterparty` 对手方字段,导入解析会清理页脚、温馨提示等说明文字。 + +新增银行或第三方支付格式时:PDF 在 `transaction_import.go` 增加 `parseXxx`,CSV 在 `csv_import.go` 增加 `parseXxxCSV`;在 `Import()` 主入口的 `switch req.SourceKind` 加分支;`ensureImportAccount` / `importAccountName` 处理新的 `CardType`;并补充测试样本到 `docs/` 下、增加用例。 + +## API 路由 + +| Method | Path | 说明 | +|---|---|---| +| GET/POST | `/api/members` | 查询/新增家庭成员 | +| PUT/DELETE | `/api/members/:id` | 编辑/删除家庭成员 | +| GET/POST | `/api/categories` | 查询/新增收支分类 | +| PUT/DELETE | `/api/categories/:id` | 编辑/删除收支分类 | +| GET/POST | `/api/accounts` | 查询/新增支付账户 | +| PUT/DELETE | `/api/accounts/:id` | 编辑/删除支付账户 | +| GET | `/api/accounts/:id/reconciliations` | 对账历史 | +| POST | `/api/accounts/:id/reconcile` | 执行账户对账 | +| GET/POST | `/api/transactions` | 查询/新增收支记录(含 transfer 类型) | +| PUT/DELETE | `/api/transactions/:id` | 编辑/删除收支记录 | +| GET | `/api/transactions?format=csv` | 按筛选条件导出 CSV | +| GET | `/api/transactions/import-batches` | 导入批次 | +| POST | `/api/transactions/import/preview` | 账单预览、重复检测与分类建议 | +| POST | `/api/transactions/import` | 多来源账单导入(multipart:file + source_kind) | +| POST | `/api/transactions/batch-delete` | 批量删除 | +| DELETE | `/api/transactions/import-batches/:id` | 删除导入批次(同步清理孤儿账户) | +| GET | `/api/dashboard/summary` | 首页摘要 | +| GET | `/api/dashboard/recent` | 首页最近流水 | +| GET | `/api/budgets/:year/:month` | 预算看板 | +| PUT | `/api/budgets` | 新增/更新预算 | +| DELETE | `/api/budgets/:id` | 删除预算 | +| GET | `/api/reports/overview` | 报表概览 | +| GET | `/api/reports/category-ranking` | 分类排行 | +| GET | `/api/reports/trend` | 月度趋势 | +| GET/POST | `/api/assets` | 查询/新增资产(支持 `account_id` 绑定账户) | +| PUT/DELETE | `/api/assets/:id` | 编辑/删除资产 | +| GET | `/api/assets/net-worth` | 净值(含 liquid_assets / liquid_debt) | +| GET | `/api/assets/snapshots` | 历史净值快照(按月落库) | +| GET/POST | `/api/liabilities` | 查询/新增负债 | +| PUT/DELETE | `/api/liabilities/:id` | 编辑/删除负债 | +| GET/POST | `/api/policies` | 查询/新增保单 | +| PUT/DELETE | `/api/policies/:id` | 编辑/删除保单 | +| GET | `/api/policies/upcoming` | 续费提醒 | +| GET/POST | `/api/policies/:id/payments` | 查询/生成缴费记录 | +| PUT | `/api/policy-payments/:id` | 更新缴费状态 | +| GET | `/api/backups/status` | 备份状态 | +| POST | `/api/backups` | 检查或创建当日备份 | +| GET | `/api/lifecycle` | 人生周期列表 | +| POST | `/api/lifecycle/events` | 新增人生周期事件 | +| PUT/DELETE | `/api/lifecycle/events/:id` | 编辑/删除人生周期事件 | + +## 数据库 + +迁移目录:`backend/db/migrations/` + +- `001_initial.sql`:基础表和默认数据。 +- `002_account_bank_details.sql`:账户银行扩展字段。 +- `003_budgets.sql`:预算表 + 4 个部分唯一索引(年/月/分类的 NULL 组合)。 +- `004_phase3_financial_overview.sql`:资产、负债、保单、生命周期 + `asset_snapshots(date)` 唯一索引。 +- `005_card_types_and_transaction_imports.sql`:银行卡类型和 `transactions.source_key` 部分唯一索引。 +- `006_transaction_batches_and_counterparty.sql`:导入批次和 `transactions.counterparty`。 +- `007_category_keywords.sql`:分类关键词字段,并对默认分类回填示例关键词。 +- `008_transfer_transactions.sql`:重建 `transactions` 表,`type` CHECK 加入 `transfer`,新增 `to_account_id`,`category_id` 改为 NULLABLE。 +- `009_assets_bind_account.sql`:`assets.account_id` 绑定字段。 +- `010_assets_account_unique.sql`:资产绑定账户的部分唯一索引。 +- `011_policy_payment_fields.sql`:保单缴费频率、下次缴费日和缴费期结束日。 +- `012_payments_and_reconciliation.sql`:保单缴费记录和账户对账历史。 + +启动时 `db.RunMigrations` 自动执行迁移,`db.Seed` 在事务内写入默认账户与分类(含关键词)。数据库文件不应提交到版本控制。 + +迁移规则: + +- SQLite 不支持改 CHECK / 列约束,需要重建表(参考 `008`)。重建时先关 `PRAGMA foreign_keys`,建新表→`INSERT ... SELECT`→`DROP`→`RENAME`→重建索引。 +- 涉及现有数据列语义变化时(如 `accounts.balance` 由"当前余额"改为"开账余额"),优先在文档和注释里阐明,避免双重含义。 + +## 前端设计规范 + +整体风格:深色、克制、高端家庭金融工具。主背景墨色,强调色香槟金,收入为绿色,支出为红色。业务图标统一使用 Font Awesome React。 + +共享 CSS 位于 `frontend/src/index.css` 的 `@layer components`: + +- `premium-panel`、`premium-field`、`premium-segment` 是底层视觉 token。 +- `app-page`、`app-toolbar`、`app-stack` 负责页面布局。 +- `app-form`、`app-form-label`、`app-error`、`app-success` 负责表单反馈。 +- `app-select`、`app-select-muted`、`app-date-input` 负责输入控件。 +- `segment-control`、`segment-option-*` 负责分段筛选。 +- `summary-grid`、`settings-grid`、`account-grid` 负责响应式网格。 + +金额展示统一使用 `formatCents`,输出人民币符号、两位小数和千分符。日期展示统一使用 `formatDate`,输出 `2026年2月10日` 这类中文格式。 + +## 开发约定 + +- Go handler 返回错误统一为 `{"error":"..."}`。 +- SQL 必须参数化;涉及多表写入时使用事务(包括 seed)。 +- 唯一约束错误判断使用 `errors.As(*sqlite.Error)` + `Code()`(参见 `transaction_import.go:isUniqueConstraintError`),禁止字符串匹配 "unique"。 +- 金额使用整数分,禁止用 JS 浮点数承载业务金额。 +- 日期接口格式为 `YYYY-MM-DD`,展示层负责本地化。 +- 前端请求集中在 `frontend/src/lib/api.ts`;`apiFetch` 已用 try/catch 包裹 `fetch` 与 `res.json()`,所有错误归一化为 `ApiError`。 +- 新增接口时同步更新 Go model、前端 `types/index.ts` 和 API client。 +- 新增表或字段必须通过迁移实现,不依赖本地数据库手工改动。 +- 后端导入解析、净值计算、预算计算等业务逻辑要补 Go 单元测试;CSV / PDF 样本放 `docs/`,测试用 `t.Skipf` 在样本缺失时跳过。 +- 报表统计 SQL 显式 / 隐式排除 `transfer` 类型;新增报表时延续此约定。 +- `accounts.balance` 字段语义为"开账初值",当前余额由 `current_balance` 派生(API 响应字段)。不要把交易写入额外更新 `balance`。 +- 删除账户前必须检查其作为转出和 `to_account_id` 转入账户的引用,以及资产、导入批次和对账记录,不能依赖外键置空维持转账语义。 +- 对账记录和可选调整流水必须在同一事务中提交;涉及撤销时也要保持二者一致。 +- 保单缴费推进使用 `next_payment_date`、`payment_frequency` 和 `payment_term_end`,不要复用保障截止日 `end_date`。 +- 备份清理只能作用于由数据库路径派生的 `backups` 目录及符合日期命名规则的文件;备份生成不代表恢复已经验证。 +- 快照和备份后台任务应记录失败并暴露最近运行状态,不能长期静默吞掉调度错误。 +- 不提交 `.db`、`.db-wal`、`.db-shm`、`node_modules`、构建产物或本地二进制。 + +## 验证要求 + +- 后端改动:优先运行 `go test ./...`。 +- 前端改动:优先运行 `pnpm run lint` 和 `pnpm run build`。 +- 只改文档时,无需运行构建,但最终说明未运行测试。 + +## 参考资料 + +- 产品规划:`docs/家庭记账本产品规划.md` +- 示例记账数据:`docs/家庭记账簿.xlsx` +- 示例 PDF:`docs/2025年10月信用卡账单.pdf`、`docs/招商银行交易流水(申请时间2026年04月12日16时46分05秒).pdf` +- 示例 CSV:`docs/alipay_record_20250723_2030_1.csv`(GBK)、`docs/微信支付账单(20241001-20250101).csv`(UTF-8 BOM) +- 待办与未来路线:`README.md` 的 "待办事项" 段 diff --git a/CODEX.md b/CODEX.md new file mode 100644 index 0000000..ee14169 --- /dev/null +++ b/CODEX.md @@ -0,0 +1,287 @@ +# CODEX.md - 家庭记账本 Codex 开发指南 + +## 项目定位 + +家庭记账本(Household Budget Book)是一个本地优先的家庭财务管理系统,使用 Go + React + SQLite 实现。当前 Web 版本已经覆盖产品规划 Phase 1、Phase 2、Phase 3 的核心交付物:基础记账、预算与报表、资产与保单、人生周期时间线。 + +在产品规划基线之上,已扩展:账户间转账(transfer 类型)、账户余额按流水实时派生、资产可绑定到账户、净值快照定时落库、流动资产与信用卡欠款自动汇总、多来源账单导入与预览整理、每日数据库备份、交易 CSV 导出、保单缴费记录和账户对账。 + +Codex 在本仓库工作时,应优先保持现有架构、深色高端金融视觉系统、整数金额模型和 SQLite 迁移体系一致。修改前先读相关代码,修改后运行与变更范围匹配的验证命令。 + +## 技术栈 + +| 层 | 选型 | 说明 | +|---|---|---| +| 后端 | Go 1.25 + Gin | REST API,单一二进制运行 | +| 数据库 | SQLite + modernc.org/sqlite | 纯 Go SQLite,无 CGO | +| 前端 | React 19 + TypeScript + Vite 5 | SPA,Vite 代理 `/api` 到后端 | +| UI | Tailwind CSS v3 + Radix/shadcn-style 组件 | 本地组件封装 | +| 图标 | Font Awesome React | 统一图标体系 | +| 图表 | Recharts | 预算和报表可视化 | +| 桌面 | Wails 配置骨架 | `wails.json` 已存在,当前主交付仍是 Web | + +## 常用命令 + +```bash +# 后端开发,默认数据库 ./data/family_book.db +cd backend +go run . -mode=dev + +# 前端开发,默认 http://localhost:5173 +cd frontend +pnpm install +pnpm run dev + +# 验证 +cd backend && go test ./... +cd frontend && pnpm run lint +cd frontend && pnpm run build + +# 生产构建 +bash scripts/build.sh +./household-book -mode=prod -static=backend/static +``` + +Windows 下生产二进制可能为 `household-book.exe`。`scripts/build.sh` 会构建前端、复制到 `backend/static`,再编译 Go 后端。 + +`frontend/pnpm-workspace.yaml` 通过 `allowBuilds` 只放行 `esbuild`。遇到 `ERR_PNPM_IGNORED_BUILDS` 时,先确认在 `frontend` 目录执行且仓库配置未被用户级配置覆盖;必要时运行 `pnpm approve-builds` 并只批准 `esbuild`,不要全局禁用构建脚本安全检查。 + +后端启动参数: + +- `-mode=dev|prod`:dev 模式默认允许 `localhost:5173` 跨域。 +- `-port=8080`:监听端口。 +- `-db=./data/family_book.db`:SQLite 路径。 +- `-static=...`:生产模式下的前端静态资源目录。 +- `-cors-origin=https://a.com,https://b.com`:自定义 CORS 来源(逗号分隔)。dev 模式下未设置时自动允许本地 Vite 端口;prod 模式下不设置则禁用 CORS。 + +后端主进程同时启动净值快照与数据库备份两个后台 goroutine。`AssetService.RunSnapshotScheduler` 在启动时及每 6 小时 upsert 当月快照;`BackupService.RunScheduler` 在 HTTP 服务启动 30 秒后首次检查,随后每 6 小时检查当日备份,每个自然日最多保留一份并清理 30 天前的文件。`Shutdown` 通过 `context.WithCancel` 联动退出。 + +SQLite 使用 WAL 模式和最多 4 个连接(最大空闲连接同为 4),允许页面并行读取。账户 `current_balance` 使用共享聚合 CTE 一次汇总收入、支出、转出和转入影响;不要恢复为逐账户相关子查询。 + +## 目录结构 + +```text +backend/ + main.go # 启动入口;参数、迁移、seed、HTTP server、快照/备份后台、优雅退出 + api/ # Gin handlers 和路由 + db/ # SQLite 连接、迁移、默认数据 + middleware/ # CORS、日志、recover + model/ # Go 请求/响应/实体结构(含 Nullable 帮助类型) + service/ + transaction.go # 收支 CRUD、批次删除、孤儿账户清理 + transaction_import.go # 导入入口(resolveSourceKind 调度)+ 招行 PDF 解析 + csv_import.go # 支付宝(GBK)/ 微信(UTF-8 BOM)CSV 解析 + csv_import_test.go # CSV 解析测试,使用 docs/ 下真实样本 + asset.go # 资产、负债、净值汇总、净值快照后台 + account.go # 账户 CRUD、current_balance、对账及调整流水 + backup.go # VACUUM INTO 每日备份、状态和保留期清理 + policy.go # 保单 CRUD、续费提醒和缴费记录 + budget.go / report.go # 预算 / 报表,统计 SQL 排除 transfer + category.go # 分类 CRUD(含 keywords) + dashboard.go # 首页摘要 / 最近流水 +frontend/ + src/ + components/ # 通用组件(TransactionTable、AmountDisplay、QuickAdd 等) + components/ui/ # 本地 UI primitives + components/layout/ # Layout/Header/Sidebar + lib/ # API client(apiFetch / apiUpload)、格式化工具 + pages/ # Dashboard、收支、预算、报表、资产、保单、生命周期、设置 + types/ # TypeScript 类型 +desktop/ # Wails 桌面壳说明 +docs/ # 产品规划、示例账单/流水、源数据(含 CSV 样本) +scripts/ # 构建脚本 +``` + +## 当前功能状态 + +### Phase 1:基础记账 + +已完成: + +- 家庭成员 CRUD。 +- 收入/支出分类 CRUD,支持父子层级;`sort_order` 按 `(type, parent_id)` 自增;分类支持 `keywords`(逗号分隔),用于导入时按描述匹配自动归类。 +- 支付账户 CRUD;账户卡片显示开账余额(`balance`)和当前余额(`current_balance`,按流水实时派生)。 +- 收支记录 CRUD,支持三种类型:**income / expense / transfer**。转账须同时指定 `account_id` + `to_account_id` 且不相同,且不挂分类;income / expense 必须挂分类。 +- 收支列表筛选支持类型(含转账)、日期范围、分类、账户、成员、关键词(前端 300ms 防抖)、导入批次。 +- 首页月度摘要、快速记账(不含 transfer)、最近流水。 +- 批量删除、按导入批次删除;按导入批次删除会自动清理"由收支导入自动创建"且无引用的孤儿账户。 +- 账户对账保存系统余额、实际余额和差额;可选择生成收入/支出调整流水,并提供对账历史接口。 +- 收支列表可按当前筛选条件导出带 UTF-8 BOM 的 CSV。 + +### Phase 2:预算 + 报表 + +已完成: + +- 预算管理:年度预算设定、分类预算、月度预算看板、超支预警。 +- 报表页:分类饼图(带 Legend)、月度趋势折线图、分类排行(横向条形 + LabelList 显示金额和百分比)。 +- `category_ranking` 接口的 `percent` 用当月该类型的全部金额作分母,与 `LIMIT` 解耦:top-N 之外的分类不会被强行凑到 100%。 +- 支付账户管理:账户类型包括现金、储蓄卡、信用卡、支付宝、微信等;银行卡账户支持银行、银行卡号、支行、备注等信息。 +- 所有预算与报表的统计 SQL 显式 / 隐式排除 `transfer` 类型(`type IN ('income','expense')` 或 `type='expense'`)。 + +### Phase 3:资产 + 保单 + 人生周期 + +已完成: + +- 资产登记可"手工录入金额"或"绑定账户"(`assets.account_id`)。绑定时 `value` 由 `account.current_balance` 派生,列表用 `is_derived` 标识。 +- 负债登记、编辑、删除。 +- 净值汇总(`/api/assets/net-worth`)返回: + - `total_assets`:assets 表汇总(手工 value + 绑定账户的 current_balance)。 + - `total_debt`:liabilities 表 principal 汇总。 + - `liquid_assets`:活跃账户当前余额派生(非信用卡 + 正向余额,且账户未被任何 assets 行绑定,避免双计)。 + - `liquid_debt`:活跃信用卡账户当前余额为负的绝对值汇总。 + - `net_worth = total_assets + liquid_assets - total_debt - liquid_debt`。 +- 净值快照:`asset_snapshots.date` 以当月 1 日作为月份键;进程启动及后台每 6 小时 upsert 当月最新净值,跨月后历史月份自然冻结。 +- 保单登记、编辑、删除;续费提醒使用 `next_payment_date`,与保障截止日 `end_date` 分离,并记录 `payment_frequency` / `payment_term_end`。 +- 保单缴费记录支持 `pending` / `paid` / `skipped`;标记已缴或跳过后按缴费频率推进 `next_payment_date`。 +- 人生周期时间线事件登记、编辑、删除。 + +### 数据安全 + +- `BackupService` 使用 SQLite `VACUUM INTO` 将数据库写入同级 `backups/YYYY-MM-DD.db`;HTTP 服务启动 30 秒后首次检查,随后每 6 小时检查,每个自然日最多一份,保留 30 天。 +- `/api/backups/status` 返回最近备份和保留策略,`POST /api/backups` 检查或创建当日备份。当前只实现备份创建与状态查看,尚无恢复接口。 + +### 导入能力 + +支持四种来源,前端通过单一"导入来源"下拉切换;后端通过 `source_kind` form 字段调度解析器: + +| 来源 | 格式 | 编码 | 入口函数 | +|---|---|---|---| +| `cmb_debit` | PDF 流水 | – | `parseDebitStatement` | +| `cmb_credit` | PDF 账单 | – | `parseCreditCardStatement` + `parseCreditRawAmounts` | +| `alipay` | CSV | GBK | `parseAlipayCSV`(`csv_import.go`) | +| `wechat` | CSV | UTF-8 BOM | `parseWechatCSV`(`csv_import.go`) | + +约定: + +- 示例文件位于 `docs/`;测试用 `t.Skipf` 在样本缺失时跳过。 +- 导入记录写入 `import_batches`,交易记录写入 `import_batch_id` 和 `source_key`。`source_key` 基于来源与稳定交易身份生成,不依赖整份文件内容;支付宝、微信优先使用平台交易单号,银行账单使用规范化交易字段,因此不同日期范围的重叠文件也能防重。 +- 唯一约束错误用 `errors.As(*sqlite.Error)` + `Code() == SQLITE_CONSTRAINT_UNIQUE` 判断,禁止字符串匹配。 +- 导入批次的 `imported_count` / `skipped_count` 在事务内一次性更新。 +- 预览最多返回 1000 条,状态区分 `new`、`duplicate_file` 和 `duplicate_database`;同时返回关键词命中或兜底原因,确认导入时可通过 `category_overrides` 覆盖单条分类。 +- 自动归类:`findCategoryID` 遍历 `categories` 同类型且 `keywords <> ''` 的子分类,按 `keywords` 字符串包含匹配;落空使用同类型下"其他"。 +- 交易记录保存 `counterparty` 对手方字段;导入解析会清理页脚、温馨提示等说明性文字。 + +新增银行或第三方支付格式时:PDF 在 `transaction_import.go` 增加 `parseXxx`,CSV 在 `csv_import.go` 增加 `parseXxxCSV`;在 `Import()` 主入口的 `switch req.SourceKind` 加分支;`ensureImportAccount` / `importAccountName` 处理新的 `CardType`;并补充 `docs/` 下样本和单元测试。 + +## API 概览 + +| Method | Path | 说明 | +|---|---|---| +| GET/POST | `/api/members` | 查询/新增家庭成员 | +| PUT/DELETE | `/api/members/:id` | 编辑/删除家庭成员 | +| GET/POST | `/api/categories` | 查询/新增收支分类 | +| PUT/DELETE | `/api/categories/:id` | 编辑/删除收支分类 | +| GET/POST | `/api/accounts` | 查询/新增支付账户 | +| PUT/DELETE | `/api/accounts/:id` | 编辑/删除支付账户 | +| GET | `/api/accounts/:id/reconciliations` | 对账历史 | +| POST | `/api/accounts/:id/reconcile` | 执行账户对账 | +| GET/POST | `/api/transactions` | 查询/新增收支记录(含 transfer 类型) | +| PUT/DELETE | `/api/transactions/:id` | 编辑/删除收支记录 | +| GET | `/api/transactions?format=csv` | 按筛选条件导出 CSV | +| GET | `/api/transactions/import-batches` | 导入批次 | +| POST | `/api/transactions/import/preview` | 账单预览、重复检测与分类建议 | +| POST | `/api/transactions/import` | 多来源账单导入(multipart:file + source_kind) | +| POST | `/api/transactions/batch-delete` | 批量删除 | +| DELETE | `/api/transactions/import-batches/:id` | 删除导入批次(同步清理孤儿账户) | +| GET | `/api/dashboard/summary` | 首页月度摘要 | +| GET | `/api/dashboard/recent` | 首页最近流水 | +| GET | `/api/budgets/:year/:month` | 预算看板 | +| PUT | `/api/budgets` | 新增/更新预算 | +| DELETE | `/api/budgets/:id` | 删除预算 | +| GET | `/api/reports/overview` | 报表概览 | +| GET | `/api/reports/category-ranking` | 分类排行 | +| GET | `/api/reports/trend` | 月度趋势 | +| GET/POST | `/api/assets` | 查询/新增资产(支持 `account_id` 绑定账户) | +| PUT/DELETE | `/api/assets/:id` | 编辑/删除资产 | +| GET | `/api/assets/net-worth` | 净值(含 `liquid_assets` / `liquid_debt`) | +| GET | `/api/assets/snapshots` | 历史净值快照(按月落库) | +| GET/POST | `/api/liabilities` | 查询/新增负债 | +| PUT/DELETE | `/api/liabilities/:id` | 编辑/删除负债 | +| GET/POST | `/api/policies` | 查询/新增保单 | +| PUT/DELETE | `/api/policies/:id` | 编辑/删除保单 | +| GET | `/api/policies/upcoming` | 续费提醒 | +| GET/POST | `/api/policies/:id/payments` | 查询/生成缴费记录 | +| PUT | `/api/policy-payments/:id` | 更新缴费状态 | +| GET | `/api/backups/status` | 备份状态 | +| POST | `/api/backups` | 检查或创建当日备份 | +| GET | `/api/lifecycle` | 人生周期时间线 | +| POST | `/api/lifecycle/events` | 新增人生周期事件 | +| PUT/DELETE | `/api/lifecycle/events/:id` | 编辑/删除人生周期事件 | + +## 数据库与迁移 + +迁移文件位于 `backend/db/migrations/`,启动时自动执行未应用迁移: + +- `001_initial.sql`:成员、分类、账户、收支记录等基础表。 +- `002_account_bank_details.sql`:账户银行信息。 +- `003_budgets.sql`:预算 + 4 个部分唯一索引(年/月/分类的 NULL 组合)。 +- `004_phase3_financial_overview.sql`:资产、负债、保单、生命周期 + `asset_snapshots(date)` 唯一索引。 +- `005_card_types_and_transaction_imports.sql`:银行卡类型、`transactions.source_key` 部分唯一索引。 +- `006_transaction_batches_and_counterparty.sql`:导入批次、交易对手方。 +- `007_category_keywords.sql`:分类关键词字段;对默认分类回填示例关键词。 +- `008_transfer_transactions.sql`:重建 `transactions` 表,`type` CHECK 加入 `transfer`,新增 `to_account_id`,`category_id` 改为 NULLABLE。 +- `009_assets_bind_account.sql`:`assets.account_id` 绑定字段。 +- `010_assets_account_unique.sql`:资产绑定账户的部分唯一索引。 +- `011_policy_payment_fields.sql`:保单缴费频率、下次缴费日、缴费期结束日。 +- `012_payments_and_reconciliation.sql`:保单缴费记录与账户对账历史。 + +数据库默认路径为 `backend/data/family_book.db`(从 `backend` 目录运行时)或启动参数 `-db` 指定路径。不要提交 `.db`、`.db-wal`、`.db-shm`。 + +迁移规则: + +- SQLite 不支持改 CHECK / 列约束。需要重建表时(如 `008`),先 `PRAGMA foreign_keys = OFF`,建新表→`INSERT ... SELECT`→`DROP`→`RENAME`→重建索引。 +- 涉及现有数据列语义变化时(如 `accounts.balance` 由"当前余额"改为"开账初值"),优先在文档和注释里阐明,避免双重含义。 +- 默认数据写入(`db.Seed`)必须在事务里执行,部分失败时不留半截脏数据。 + +## 前端设计系统 + +整体视觉是深色高端家庭金融工具:墨色背景、香槟金强调、收入绿、支出红、低饱和边框和克制阴影。业务图标统一使用 Font Awesome,不混用其他图标库。 + +共享样式集中在 `frontend/src/index.css` 的 `@layer components`: + +- 页面容器:`app-page`、`app-page-compact` +- 工具栏和布局:`app-toolbar`、`app-stack` +- 标题:`app-section-title`、`app-section-icon` +- 表单:`app-form`、`app-form-label`、`app-error`、`app-success` +- 输入和选择:`premium-field`、`app-select`、`app-select-muted`、`app-date-input` +- 分段控件:`segment-control`、`segment-option-*` +- 网格:`summary-grid`、`settings-grid`、`account-grid` +- 表格辅助:`table-muted`、`inline-actions`、`fade-actions` + +新页面优先复用这些语义类,避免重复堆长 Tailwind 字符串。金额展示统一用 `formatCents`,带人民币符号和千分符;日期展示统一用 `formatDate`,格式为 `2026年2月10日`。 + +## 开发约定 + +- 手工编辑文件使用补丁,保持变更小而完整。 +- 不回滚用户已有改动,不使用 `git reset --hard` 或 `git checkout --`。 +- 后端 SQL 使用参数化查询;写操作涉及多表时使用事务(包括 seed)。 +- 唯一约束错误判断使用 `errors.As(*sqlite.Error)` + `Code()`(参见 `transaction_import.go:isUniqueConstraintError`),禁止字符串匹配 "unique"。 +- Handler 返回错误统一为 `{"error":"..."}` 和合适 HTTP 状态码。 +- 前端 API 使用 `frontend/src/lib/api.ts` 的相对路径封装,禁止硬编码 `localhost:8080`。`apiFetch` 已用 try/catch 包裹 `fetch` 与 `res.json()`,所有错误归一化为 `ApiError`。 +- 金额在后端和前端类型中都使用整数分,不用浮点做业务计算。 +- 日期存储和接口传输使用 `YYYY-MM-DD`;展示层再格式化为中文日期。 +- 新增数据表 / 列必须增加迁移,不能直接依赖本地数据库手工改表。 +- 涉及导入解析、预算计算、净值计算等业务逻辑时,优先补 Go 单元测试;样本数据放 `docs/`。 +- 报表统计 SQL 显式 / 隐式排除 `transfer` 类型;新增报表延续此约定。 +- `accounts.balance` 字段语义为"开账初值",当前余额由 API 响应的 `current_balance` 派生计算。不要把交易写入额外更新 `balance`。 +- 删除账户必须同时考虑其作为转出账户和 `to_account_id` 转入账户的引用,以及资产绑定、导入批次和对账记录;不能依赖 `ON DELETE SET NULL` 修复领域关系。 +- 新增 PDF / CSV 导入来源时,使用 `source_kind` 调度路径,避免给老的 `bank_name + card_type` 字段塞新含义。 +- 账户对账若生成调整流水,必须与 `account_reconciliations` 在同一事务提交;后续撤销能力也应保持双向一致。 +- 保单缴费状态推进必须以应缴日和 `payment_frequency` 为基准,并尊重 `payment_term_end`;不要把保障截止日作为续费日期。 +- 备份路径必须从已确认的数据库路径派生;清理保留期文件时只处理备份目录内符合日期命名规则的数据库文件。恢复功能落地前,不能把“已生成备份”等同于“已验证可恢复”。 +- 后台快照和备份任务不得永久静默吞错;新增调度逻辑时应保留最近运行状态并提供日志或状态接口。 + +## 验证策略 + +- 后端业务或 API 变更:运行 `cd backend && go test ./...`。 +- 前端页面或类型变更:运行 `cd frontend && pnpm run lint` 和 `cd frontend && pnpm run build`。 +- 纯文档变更:说明未运行测试即可。 +- Vite 可能提示 chunk 超过 500KB,当前主要来自图表/UI 依赖,不等同构建失败。 + +## 参考资料 + +- 产品规划:`docs/家庭记账本产品规划.md` +- 示例源数据:`docs/家庭记账簿.xlsx` +- 招商银行示例流水/账单:`docs/*.pdf` +- 第三方支付样本:`docs/alipay_record_20250723_2030_1.csv`(GBK)、`docs/微信支付账单(20241001-20250101).csv`(UTF-8 BOM) +- 待办与未来路线:`README.md` 的 "待办事项" 段 diff --git a/README.md b/README.md new file mode 100644 index 0000000..5e0d765 --- /dev/null +++ b/README.md @@ -0,0 +1,221 @@ +# 家庭记账本 (Household Budget Book) + +本地优先的家庭财务管理系统,使用 Go + React + SQLite 构建。当前 Web 版本覆盖基础记账、预算报表、资产负债、保单管理和人生周期规划,界面采用深色高端金融风格,并统一使用 Font Awesome 图标。 + +## 功能特性 + +- 家庭成员、收支分类、支付账户管理;分类支持关键词配置以指导自动归类。 +- 储蓄卡、信用卡、支付宝、微信、现金等账户类型;银行卡可维护银行、卡号、支行;账户列表显示开账余额与按流水实时派生的当前余额。 +- 收支记录新增、编辑、删除,支持收入 / 支出 / **转账(A→B)** 三种类型;转账不计入收支统计。 +- 收支列表支持日期范围、类型(含转账)、分类、账户(同时匹配转出/转入)、成员、关键词、导入批次筛选,默认按最新交易倒序展示。 +- 支持批量删除、按导入文件删除;按导入文件删除会自动清理仅服务该批次的孤儿账户。 +- 账单导入支持四种来源:招商银行储蓄卡流水 PDF、招商银行信用卡账单 PDF、支付宝 CSV、微信支付 CSV。 +- 首页月度摘要、快速记账、最近流水。 +- 预算管理:年度预算、分类预算、月度看板、超支预警;月度总执行统计全部支出,并单列预算外支出。 +- 报表分析:分类饼图、月度趋势折线图、分类排行。 +- 资产管理:手工录入或绑定到账户(金额由账户当前余额实时派生);自动汇总信用卡欠款;当月快照持续刷新、跨月后冻结并绘制净值趋势曲线。 +- 负债管理、家庭净值(含流动资产 / 信用卡欠款)。 +- 保单登记和续费提醒;区分保障截止日与下次缴费日,支持月缴、季缴、半年缴、年缴和趸缴。 +- 每日 SQLite 自动备份(每个自然日最多一份,保留 30 天)、备份状态查看、立即检查/创建当日备份,以及按当前筛选条件导出交易 CSV。 +- 导入预览支持逐条修正分类、显示归类原因,并区分文件内重复与数据库已有记录。 +- 保单缴费记录支持待处理、已缴、跳过,并按缴费频率推进下次缴费日。 +- 账户支持实际余额对账,差额可自动生成余额调整交易并保留对账历史。 +- 人生周期时间线。 + +## 快速开始 + +### 后端 + +```bash +cd backend +go run . -mode=dev +``` + +默认监听 `http://localhost:8080`,默认数据库为 `./data/family_book.db`。可通过参数覆盖: + +```bash +go run . -mode=dev -port=8080 -db=./data/family_book.db +``` + +SQLite 使用 WAL 模式和最多 4 个连接,允许页面的并行读取真正并发执行。账户 `current_balance` 通过一次流水聚合 CTE 实时派生;自动备份在 HTTP 服务启动 30 秒后首次检查,随后每 6 小时检查,避免首屏请求与 `VACUUM INTO` 争用数据库资源。 + +### 前端 + +```bash +cd frontend +pnpm install +pnpm run dev +``` + +前端默认运行在 `http://localhost:5173`。Vite 会把 `/api` 代理到 Go 后端。 + +仓库通过 `frontend/pnpm-workspace.yaml` 仅允许 `esbuild` 执行依赖构建脚本。若 pnpm 10/11 报 `ERR_PNPM_IGNORED_BUILDS`,请确认从 `frontend` 目录运行且该文件包含 `allowBuilds.esbuild: true`;自定义 pnpm 安全策略覆盖仓库配置时,可运行 `pnpm approve-builds` 并只批准 `esbuild`,随后重新执行 `pnpm install`。不要用全局关闭脚本检查的方式绕过此限制。 + +## 生产构建 + +```bash +bash scripts/build.sh +./household-book -mode=prod -static=backend/static +``` + +构建脚本会安装/检查前端依赖、构建前端静态资源、复制到 `backend/static`,再编译 Go 后端。Windows 环境下二进制名称可能为 `household-book.exe`。 + +## 验证 + +```bash +cd backend +go test ./... + +cd frontend +pnpm run lint +pnpm run build +``` + +Vite 构建时可能提示 chunk 超过 500KB,这通常来自图表和 UI 依赖,不代表构建失败。 + +## 技术栈 + +- 后端:Go 1.25、Gin、modernc.org/sqlite +- 数据库:SQLite,启动时自动迁移和 seed +- 前端:React 19、TypeScript、Vite 5 +- UI:Tailwind CSS v3、Radix/shadcn-style 本地组件 +- 图标:Font Awesome React +- 图表:Recharts +- 桌面:Wails 配置骨架,当前主要交付目标为 Web + +## 项目结构 + +```text +backend/ + api/ HTTP handlers 和路由 + db/ SQLite 连接、迁移、默认数据 + middleware/ CORS、recover、日志 + model/ Go 类型 + service/ 业务逻辑、SQL、PDF 导入解析 + static/ 生产构建后的前端资源 +frontend/ + src/ + components/ 通用组件、Logo、表格、快速记账 + lib/ API client、金额/日期格式化 + pages/ 首页、收支、预算、报表、资产、保单、生命周期、设置 + types/ TypeScript 类型 +docs/ 产品规划、示例账单和源数据 +scripts/ 构建脚本 +desktop/ Wails 桌面壳说明 +wails.json Wails 配置骨架 +``` + +## API 概览 + +| Method | Path | Description | +|---|---|---| +| GET/POST | `/api/members` | 查询/新增家庭成员 | +| PUT/DELETE | `/api/members/:id` | 编辑/删除家庭成员 | +| GET/POST | `/api/categories` | 查询/新增收支分类 | +| PUT/DELETE | `/api/categories/:id` | 编辑/删除收支分类 | +| GET/POST | `/api/accounts` | 查询/新增支付账户 | +| PUT/DELETE | `/api/accounts/:id` | 编辑/删除支付账户 | +| GET/POST | `/api/transactions` | 查询/新增收支记录 | +| PUT/DELETE | `/api/transactions/:id` | 编辑/删除收支记录 | +| GET | `/api/transactions/import-batches` | 导入批次 | +| POST | `/api/transactions/import/preview` | 解析账单并预览分类、归类原因和重复状态 | +| POST | `/api/transactions/import` | 多来源账单导入 | +| POST | `/api/transactions/batch-delete` | 批量删除 | +| DELETE | `/api/transactions/import-batches/:id` | 删除导入批次及其流水 | +| GET | `/api/transactions?format=csv` | 按筛选条件导出交易 CSV | +| GET | `/api/dashboard/summary` | 首页月度摘要 | +| GET | `/api/dashboard/recent` | 首页最近流水 | +| GET | `/api/budgets/:year/:month` | 预算看板 | +| PUT | `/api/budgets` | 新增/更新预算 | +| DELETE | `/api/budgets/:id` | 删除预算 | +| GET | `/api/reports/overview` | 报表概览 | +| GET | `/api/reports/category-ranking` | 分类排行 | +| GET | `/api/reports/trend` | 月度趋势 | +| GET/POST | `/api/assets` | 查询/新增资产(支持绑定账户) | +| PUT/DELETE | `/api/assets/:id` | 编辑/删除资产 | +| GET | `/api/assets/net-worth` | 家庭净值(含流动资产、信用卡欠款) | +| GET | `/api/assets/snapshots` | 历史净值快照(每月自动落库) | +| GET/POST | `/api/liabilities` | 查询/新增负债 | +| PUT/DELETE | `/api/liabilities/:id` | 编辑/删除负债 | +| GET/POST | `/api/policies` | 查询/新增保单 | +| PUT/DELETE | `/api/policies/:id` | 编辑/删除保单 | +| GET | `/api/policies/upcoming` | 续费提醒 | +| GET/POST | `/api/policies/:id/payments` | 保单缴费记录 | +| PUT | `/api/policy-payments/:id` | 更新缴费状态 | +| GET | `/api/backups/status` | 查看备份状态 | +| POST | `/api/backups` | 检查或创建当日备份 | +| GET | `/api/accounts/:id/reconciliations` | 查看账户对账历史 | +| POST | `/api/accounts/:id/reconcile` | 执行账户对账 | +| GET | `/api/lifecycle` | 人生周期 | +| POST | `/api/lifecycle/events` | 新增人生周期事件 | +| PUT/DELETE | `/api/lifecycle/events/:id` | 编辑/删除人生周期事件 | + +## 导入说明 + +收支页面支持四种来源导入,前端通过单一"导入来源"下拉切换: + +| 来源 | 格式 | 编码 | 示例 | +|---|---|---|---| +| 招商银行储蓄卡 | PDF 流水 | – | `docs/招商银行交易流水(申请时间2026年04月12日16时46分05秒).pdf` | +| 招商银行信用卡 | PDF 账单 | – | `docs/2025年10月信用卡账单.pdf` | +| 支付宝 | CSV | GBK | `docs/alipay_record_20250723_2030_1.csv` | +| 微信支付 | CSV | UTF-8 with BOM | `docs/微信支付账单(20241001-20250101).csv` | + +导入时会生成导入批次,交易记录保存 `import_batch_id`、`source_key` 和 `counterparty`。`source_key` 用于跳过重复记录:支付宝、微信优先使用平台交易单号,银行账单使用规范化交易字段,均不依赖整份文件内容,因此重叠日期范围的不同账单文件也能防重。`import_batch_id` 用于按文件删除导入数据。`findCategoryID` 会按 `categories.keywords` 字段(逗号分隔)自动归类,匹配不到时落到"其他"分类。 + +## 设计系统 + +前端共享样式位于 `frontend/src/index.css` 的 `@layer components`。新页面应优先复用语义类: + +- `app-page`、`app-page-compact` +- `app-toolbar`、`app-stack` +- `app-form`、`app-form-label`、`app-error`、`app-success` +- `app-select`、`app-select-muted`、`app-date-input` +- `segment-control`、`segment-option-*` +- `summary-grid`、`settings-grid`、`account-grid` + +金额展示使用 `formatCents`,带人民币符号、两位小数和千分符。日期展示使用 `formatDate`,格式如 `2026年2月10日`。 + +## 路线图状态 + +- Phase 1 基础记账:已完成 Web 版本。 +- Phase 2 预算 + 报表:已完成 Web 版本。 +- Phase 3 资产 + 保单 + 人生周期:已完成 Web 版本。 +- Phase 4 数据安全与桌面交付:自动备份、CSV 导出、缴费记录和账户对账已完成;备份恢复、完整桌面发布和高级分析仍待实施。 + +详细规划见 `docs/家庭记账本产品规划.md`。 + +## 待办事项 + +### P0:业务闭环与数据安全 + +- **备份恢复与校验**:在现有每日 `VACUUM INTO` 备份之上增加恢复前预检、`PRAGMA integrity_check`、恢复确认和失败回滚;明确“立即备份”在当日备份已存在时只返回现有文件,并提供可验证的恢复演练流程。 +- **后台任务可观测性**:净值快照和备份调度不得静默丢弃错误;记录最近成功/失败时间与错误信息,并在设置页显示备份过期、目录不可写和快照失败状态。 +- **保单缴费计划完整性**:按频率自动生成待缴记录;为“保单 + 应缴日”增加唯一约束;到达 `payment_term_end` 后停止推进;补齐逾期状态、实缴日期、备注修改及误操作撤销。 +- **账户对账审计闭环**:在设置页展示对账历史,允许“仅记录差异”或“生成调整流水”;校验实际余额输入;为调整流水增加明确来源标识,并支持撤销时同步回滚对账记录与调整流水。 +- **导入规则与覆盖校验**:服务端校验分类覆盖必须与交易类型一致、属于可用叶子分类;把确认过的“对手方/描述 → 分类”沉淀为可管理规则;支持超过 1000 条记录的分段预览和导入。 +- **大数据量导出**:将 CSV 导出由一次性加载大结果集改为流式写出,避免交易量增长后占用过多内存,并增加导出字段与筛选条件的回归测试。 + +### P1:产品能力 + +- **周期性账单**:为房贷、保费、会员等建立规则,支持自动生成、提前提醒、暂停和跳过,并保证重复执行幂等。 +- **高级报表**:增加同环比、预算执行趋势、现金流预测和可解释的异常支出提示;继续排除 `transfer`,统一统计口径。 +- **人生目标**:增加目标金额、目标日期、已准备金额和资金缺口,并与现金流预测联动。 +- **标签系统**:以 tags 补充单一分类维度,支持筛选、报表聚合和导入规则赋标签。 +- **移动端与无障碍**:实现响应式导航和交易卡片;统一图表颜色 token、键盘焦点、图标按钮可访问名称及触屏操作可见性。 + +### P2:工程与交付 + +- **测试覆盖**:补充后台任务失败、备份恢复、缴费计划边界、对账撤销、分类覆盖校验和 CSV 流式导出的服务/API 测试。 +- **单记录余额查询**:账户或资产保存后的单记录回读当前仍聚合全部流水;当 `transactions` 超过 10 万行或保存操作 p95 超过 100ms 时,改为按目标账户下推过滤的聚合 CTE。 +- **前端体积与性能**:按路由拆分图表和管理页面,降低当前大 chunk;对长交易列表评估分页或虚拟滚动。 +- **表单订阅优化**:将 `TransactionForm` 中的整表 `watch()` 改为 `useWatch` 精确订阅交易类型和账户字段,减少无关字段变化引起的重渲染。 +- **服务层复用**:只对无领域副作用的简单 CRUD 抽取泛型 helper;交易、导入、缴费和对账继续保留显式事务与领域校验。 +- **桌面发布**:完成 Wails 数据目录、备份目录、升级迁移、签名和 Windows 安装包验证。 + +### 近期已完成 + +- 统一预算总执行口径、交易编辑领域校验、跨文件导入防重、收支筛选排序和月度净值快照语义。 +- 完成资产账户唯一绑定、余额 SQL 复用、TanStack Query 数据层和交易表单组件化。 +- 完成账单预览与分类修正、每日备份与 CSV 导出、保单缴费记录和账户对账基础流程。 +- 完成报表类型切换、叶子分类口径、停用分类标识和分类排行自适应布局。 diff --git a/backend/api/account.go b/backend/api/account.go new file mode 100644 index 0000000..f8a4e3d --- /dev/null +++ b/backend/api/account.go @@ -0,0 +1,159 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type AccountHandler struct { + svc *service.AccountService +} + +func (h *AccountHandler) Reconcile(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + var req model.ReconcileAccountRequest + if c.ShouldBindJSON(&req) != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + v, e := h.svc.Reconcile(c.Request.Context(), id, req) + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "账户对账失败"}) + return + } + c.JSON(http.StatusCreated, v) +} +func (h *AccountHandler) ListReconciliations(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + v, e := h.svc.ListReconciliations(c.Request.Context(), id) + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取对账记录失败"}) + return + } + c.JSON(http.StatusOK, v) +} + +func NewAccountHandler(svc *service.AccountService) *AccountHandler { + return &AccountHandler{svc: svc} +} + +func (h *AccountHandler) List(c *gin.Context) { + accounts, err := h.svc.List(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取账户列表失败"}) + return + } + c.JSON(http.StatusOK, accounts) +} + +func (h *AccountHandler) Create(c *gin.Context) { + var req model.CreateAccountRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "账户名称不能为空"}) + return + } + if req.Type == "" { + req.Type = "other" + } + if req.Type == "bank_card" { + req.Type = "debit_card" + } + if !validAccountType(req.Type) { + c.JSON(http.StatusBadRequest, gin.H{"error": "账户类型无效"}) + return + } + + account, err := h.svc.Create(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加账户失败"}) + return + } + c.JSON(http.StatusCreated, account) +} + +func (h *AccountHandler) Update(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + var req model.UpdateAccountRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name != nil && *req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "账户名称不能为空"}) + return + } + if req.Type != nil { + if *req.Type == "bank_card" { + *req.Type = "debit_card" + } + if !validAccountType(*req.Type) { + c.JSON(http.StatusBadRequest, gin.H{"error": "账户类型无效"}) + return + } + } + + account, err := h.svc.Update(c.Request.Context(), id, req) + if err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "账户不存在"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "更新账户失败"}) + return + } + c.JSON(http.StatusOK, account) +} + +func (h *AccountHandler) Delete(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "账户不存在"}) + return + } + if errors.Is(err, service.ErrHasTransactions) { + c.JSON(http.StatusConflict, gin.H{"error": "该账户仍被收支记录、资产、导入批次或对账记录引用,无法删除"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "删除账户失败"}) + return + } + c.Status(http.StatusNoContent) +} + +func validAccountType(typ string) bool { + switch typ { + case "alipay", "wechat", "debit_card", "credit_card", "cash", "other": + return true + default: + return false + } +} diff --git a/backend/api/asset.go b/backend/api/asset.go new file mode 100644 index 0000000..b33e551 --- /dev/null +++ b/backend/api/asset.go @@ -0,0 +1,173 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type AssetHandler struct{ svc *service.AssetService } + +func NewAssetHandler(svc *service.AssetService) *AssetHandler { return &AssetHandler{svc: svc} } + +func (h *AssetHandler) ListAssets(c *gin.Context) { + items, err := h.svc.ListAssets(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取资产列表失败"}) + return + } + c.JSON(http.StatusOK, items) +} + +func (h *AssetHandler) CreateAsset(c *gin.Context) { + var req model.CreateAssetRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "资产名称不能为空"}) + return + } + item, err := h.svc.CreateAsset(c.Request.Context(), req) + if err != nil { + if errors.Is(err, service.ErrAccountAlreadyBound) { + c.JSON(http.StatusConflict, gin.H{"error": "该账户已绑定其他资产"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加资产失败"}) + return + } + c.JSON(http.StatusCreated, item) +} + +func (h *AssetHandler) UpdateAsset(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + var req model.UpdateAssetRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + item, err := h.svc.UpdateAsset(c.Request.Context(), id, req) + if err != nil { + if errors.Is(err, service.ErrAccountAlreadyBound) { + c.JSON(http.StatusConflict, gin.H{"error": "该账户已绑定其他资产"}) + return + } + writeEntityError(c, err, "更新资产失败", "资产不存在") + return + } + c.JSON(http.StatusOK, item) +} + +func (h *AssetHandler) DeleteAsset(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + if err := h.svc.DeleteAsset(c.Request.Context(), id); err != nil { + writeEntityError(c, err, "删除资产失败", "资产不存在") + return + } + c.Status(http.StatusNoContent) +} + +func (h *AssetHandler) ListLiabilities(c *gin.Context) { + items, err := h.svc.ListLiabilities(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取负债列表失败"}) + return + } + c.JSON(http.StatusOK, items) +} + +func (h *AssetHandler) CreateLiability(c *gin.Context) { + var req model.CreateLiabilityRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "负债名称不能为空"}) + return + } + item, err := h.svc.CreateLiability(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加负债失败"}) + return + } + c.JSON(http.StatusCreated, item) +} + +func (h *AssetHandler) UpdateLiability(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + var req model.UpdateLiabilityRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + item, err := h.svc.UpdateLiability(c.Request.Context(), id, req) + if err != nil { + writeEntityError(c, err, "更新负债失败", "负债不存在") + return + } + c.JSON(http.StatusOK, item) +} + +func (h *AssetHandler) DeleteLiability(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + if err := h.svc.DeleteLiability(c.Request.Context(), id); err != nil { + writeEntityError(c, err, "删除负债失败", "负债不存在") + return + } + c.Status(http.StatusNoContent) +} + +func (h *AssetHandler) NetWorth(c *gin.Context) { + data, err := h.svc.NetWorth(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "计算净值失败"}) + return + } + c.JSON(http.StatusOK, data) +} + +func (h *AssetHandler) ListSnapshots(c *gin.Context) { + data, err := h.svc.ListSnapshots(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取净值快照失败"}) + return + } + c.JSON(http.StatusOK, data) +} + +func parseID(c *gin.Context) (int64, bool) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return 0, false + } + return id, true +} + +func writeEntityError(c *gin.Context, err error, generic, notFound string) { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": notFound}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": generic}) +} diff --git a/backend/api/backup.go b/backend/api/backup.go new file mode 100644 index 0000000..7dfdede --- /dev/null +++ b/backend/api/backup.go @@ -0,0 +1,27 @@ +package api + +import ( + "github.com/gin-gonic/gin" + "household-book/service" + "net/http" +) + +type BackupHandler struct{ svc *service.BackupService } + +func NewBackupHandler(s *service.BackupService) *BackupHandler { return &BackupHandler{svc: s} } +func (h *BackupHandler) Status(c *gin.Context) { + v, e := h.svc.Status() + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取备份状态失败"}) + return + } + c.JSON(http.StatusOK, v) +} +func (h *BackupHandler) Create(c *gin.Context) { + v, e := h.svc.Create(c.Request.Context()) + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "创建备份失败"}) + return + } + c.JSON(http.StatusOK, v) +} diff --git a/backend/api/budget.go b/backend/api/budget.go new file mode 100644 index 0000000..d3c5840 --- /dev/null +++ b/backend/api/budget.go @@ -0,0 +1,88 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type BudgetHandler struct { + svc *service.BudgetService +} + +func NewBudgetHandler(svc *service.BudgetService) *BudgetHandler { + return &BudgetHandler{svc: svc} +} + +func (h *BudgetHandler) Overview(c *gin.Context) { + year, err := strconv.Atoi(c.Param("year")) + if err != nil || year < 2000 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"}) + return + } + month, err := strconv.Atoi(c.Param("month")) + if err != nil || month < 1 || month > 12 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的月份"}) + return + } + + overview, err := h.svc.Overview(c.Request.Context(), year, month) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取预算看板失败"}) + return + } + c.JSON(http.StatusOK, overview) +} + +func (h *BudgetHandler) Upsert(c *gin.Context) { + var req model.UpsertBudgetRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Year < 2000 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"}) + return + } + if req.Month != nil && (*req.Month < 1 || *req.Month > 12) { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的月份"}) + return + } + if req.Amount < 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "预算金额不能为负数"}) + return + } + + budget, err := h.svc.Upsert(c.Request.Context(), req) + if err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "预算不存在"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "保存预算失败"}) + return + } + c.JSON(http.StatusOK, budget) +} + +func (h *BudgetHandler) Delete(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的预算ID"}) + return + } + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "预算不存在"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "删除预算失败"}) + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/api/category.go b/backend/api/category.go new file mode 100644 index 0000000..d7f84b6 --- /dev/null +++ b/backend/api/category.go @@ -0,0 +1,104 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type CategoryHandler struct { + svc *service.CategoryService +} + +func NewCategoryHandler(svc *service.CategoryService) *CategoryHandler { + return &CategoryHandler{svc: svc} +} + +func (h *CategoryHandler) List(c *gin.Context) { + typ := c.Query("type") + categories, err := h.svc.List(c.Request.Context(), typ) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取分类列表失败"}) + return + } + c.JSON(http.StatusOK, categories) +} + +func (h *CategoryHandler) Create(c *gin.Context) { + var req model.CreateCategoryRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "分类名称不能为空"}) + return + } + if req.Type != "income" && req.Type != "expense" { + c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income 或 expense"}) + return + } + + cat, err := h.svc.Create(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加分类失败"}) + return + } + c.JSON(http.StatusCreated, cat) +} + +func (h *CategoryHandler) Update(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + var req model.UpdateCategoryRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + + cat, err := h.svc.Update(c.Request.Context(), id, req) + if err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "分类不存在"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "更新分类失败"}) + return + } + c.JSON(http.StatusOK, cat) +} + +func (h *CategoryHandler) Delete(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "分类不存在"}) + return + } + if errors.Is(err, service.ErrHasTransactions) { + c.JSON(http.StatusConflict, gin.H{"error": "该分类有关联的收支记录,无法删除"}) + return + } + if errors.Is(err, service.ErrHasChildren) { + c.JSON(http.StatusConflict, gin.H{"error": "该分类下有子分类,无法删除"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "删除分类失败"}) + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/api/dashboard.go b/backend/api/dashboard.go new file mode 100644 index 0000000..b883614 --- /dev/null +++ b/backend/api/dashboard.go @@ -0,0 +1,46 @@ +package api + +import ( + "net/http" + "strconv" + + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type DashboardHandler struct { + svc *service.DashboardService +} + +func NewDashboardHandler(svc *service.DashboardService) *DashboardHandler { + return &DashboardHandler{svc: svc} +} + +func (h *DashboardHandler) Summary(c *gin.Context) { + year := c.Query("year") + month := c.Query("month") + + summary, err := h.svc.Summary(c.Request.Context(), year, month) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取摘要数据失败"}) + return + } + c.JSON(http.StatusOK, summary) +} + +func (h *DashboardHandler) Recent(c *gin.Context) { + limit := 5 + if l := c.Query("limit"); l != "" { + if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 && parsed <= 50 { + limit = parsed + } + } + + items, err := h.svc.Recent(c.Request.Context(), limit) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取最近记录失败"}) + return + } + c.JSON(http.StatusOK, items) +} diff --git a/backend/api/lifecycle.go b/backend/api/lifecycle.go new file mode 100644 index 0000000..1c0aad9 --- /dev/null +++ b/backend/api/lifecycle.go @@ -0,0 +1,73 @@ +package api + +import ( + "net/http" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type LifecycleHandler struct{ svc *service.LifecycleService } + +func NewLifecycleHandler(svc *service.LifecycleService) *LifecycleHandler { + return &LifecycleHandler{svc: svc} +} + +func (h *LifecycleHandler) List(c *gin.Context) { + items, err := h.svc.List(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取人生周期失败"}) + return + } + c.JSON(http.StatusOK, items) +} + +func (h *LifecycleHandler) Create(c *gin.Context) { + var req model.CreateLifecycleEventRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Year < 1900 || req.Event == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "年份和事件不能为空"}) + return + } + item, err := h.svc.Create(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加事件失败"}) + return + } + c.JSON(http.StatusCreated, item) +} + +func (h *LifecycleHandler) Update(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + var req model.UpdateLifecycleEventRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + item, err := h.svc.Update(c.Request.Context(), id, req) + if err != nil { + writeEntityError(c, err, "更新事件失败", "事件不存在") + return + } + c.JSON(http.StatusOK, item) +} + +func (h *LifecycleHandler) Delete(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + writeEntityError(c, err, "删除事件失败", "事件不存在") + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/api/member.go b/backend/api/member.go new file mode 100644 index 0000000..b0e74f2 --- /dev/null +++ b/backend/api/member.go @@ -0,0 +1,99 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type MemberHandler struct { + svc *service.MemberService +} + +func NewMemberHandler(svc *service.MemberService) *MemberHandler { + return &MemberHandler{svc: svc} +} + +func (h *MemberHandler) List(c *gin.Context) { + members, err := h.svc.List(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取成员列表失败"}) + return + } + c.JSON(http.StatusOK, members) +} + +func (h *MemberHandler) Create(c *gin.Context) { + var req model.CreateMemberRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "姓名不能为空"}) + return + } + if len(req.Name) > 50 { + c.JSON(http.StatusBadRequest, gin.H{"error": "姓名不能超过50个字符"}) + return + } + + member, err := h.svc.Create(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加成员失败"}) + return + } + c.JSON(http.StatusCreated, member) +} + +func (h *MemberHandler) Update(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + var req model.UpdateMemberRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + + member, err := h.svc.Update(c.Request.Context(), id, req) + if err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "成员不存在"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "更新成员失败"}) + return + } + c.JSON(http.StatusOK, member) +} + +func (h *MemberHandler) Delete(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "成员不存在"}) + return + } + if errors.Is(err, service.ErrHasTransactions) { + c.JSON(http.StatusConflict, gin.H{"error": "该成员有关联的收支记录,无法删除"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "删除成员失败"}) + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/api/policy.go b/backend/api/policy.go new file mode 100644 index 0000000..d9d0cb8 --- /dev/null +++ b/backend/api/policy.go @@ -0,0 +1,157 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type PolicyHandler struct{ svc *service.PolicyService } + +func NewPolicyHandler(svc *service.PolicyService) *PolicyHandler { return &PolicyHandler{svc: svc} } + +func (h *PolicyHandler) List(c *gin.Context) { + items, err := h.svc.List(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取保单列表失败"}) + return + } + c.JSON(http.StatusOK, items) +} + +func (h *PolicyHandler) ListPayments(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + v, e := h.svc.ListPayments(c.Request.Context(), id) + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取缴费记录失败"}) + return + } + c.JSON(http.StatusOK, v) +} +func (h *PolicyHandler) CreatePayment(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + var req model.CreatePolicyPaymentRequest + if c.ShouldBindJSON(&req) != nil || req.DueDate == "" || req.Amount < 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "缴费日期或金额无效"}) + return + } + v, e := h.svc.CreatePayment(c.Request.Context(), id, req) + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "创建缴费记录失败"}) + return + } + c.JSON(http.StatusCreated, v) +} +func (h *PolicyHandler) UpdatePayment(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + var req model.UpdatePolicyPaymentRequest + if c.ShouldBindJSON(&req) != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + v, e := h.svc.UpdatePayment(c.Request.Context(), id, req) + if errors.Is(e, service.ErrInvalidPaymentStatus) { + c.JSON(http.StatusBadRequest, gin.H{"error": "缴费状态无效"}) + return + } + if e != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "更新缴费记录失败"}) + return + } + c.JSON(http.StatusOK, v) +} + +func (h *PolicyHandler) Upcoming(c *gin.Context) { + days, _ := strconv.Atoi(c.DefaultQuery("days", "30")) + items, err := h.svc.Upcoming(c.Request.Context(), days) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取续费提醒失败"}) + return + } + c.JSON(http.StatusOK, items) +} + +func (h *PolicyHandler) Create(c *gin.Context) { + var req model.CreatePolicyRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "保单名称不能为空"}) + return + } + if req.Status == "" { + req.Status = "active" + } + if req.PaymentFrequency == "" { + req.PaymentFrequency = "annual" + } + if !validPaymentFrequency(req.PaymentFrequency) { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的缴费频率"}) + return + } + item, err := h.svc.Create(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加保单失败"}) + return + } + c.JSON(http.StatusCreated, item) +} + +func (h *PolicyHandler) Update(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + var req model.UpdatePolicyRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.PaymentFrequency != nil && !validPaymentFrequency(*req.PaymentFrequency) { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的缴费频率"}) + return + } + item, err := h.svc.Update(c.Request.Context(), id, req) + if err != nil { + writeEntityError(c, err, "更新保单失败", "保单不存在") + return + } + c.JSON(http.StatusOK, item) +} + +func validPaymentFrequency(value string) bool { + switch value { + case "monthly", "quarterly", "semiannual", "annual", "single": + return true + default: + return false + } +} + +func (h *PolicyHandler) Delete(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + writeEntityError(c, err, "删除保单失败", "保单不存在") + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/api/report.go b/backend/api/report.go new file mode 100644 index 0000000..885b460 --- /dev/null +++ b/backend/api/report.go @@ -0,0 +1,78 @@ +package api + +import ( + "net/http" + "strconv" + + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type ReportHandler struct { + svc *service.ReportService +} + +func NewReportHandler(svc *service.ReportService) *ReportHandler { + return &ReportHandler{svc: svc} +} + +func (h *ReportHandler) Overview(c *gin.Context) { + year, month, ok := parseReportYearMonth(c) + if !ok { + return + } + typ := c.DefaultQuery("type", "expense") + if typ != "income" && typ != "expense" { + c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income 或 expense"}) + return + } + data, err := h.svc.Overview(c.Request.Context(), year, month, typ) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取报表失败"}) + return + } + c.JSON(http.StatusOK, data) +} + +func (h *ReportHandler) CategoryRanking(c *gin.Context) { + year, month, ok := parseReportYearMonth(c) + if !ok { + return + } + typ := c.DefaultQuery("type", "expense") + data, err := h.svc.CategoryRanking(c.Request.Context(), year, month, typ, 10) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取分类排行失败"}) + return + } + c.JSON(http.StatusOK, data) +} + +func (h *ReportHandler) Trend(c *gin.Context) { + year, err := strconv.Atoi(c.Query("year")) + if err != nil || year < 2000 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"}) + return + } + data, err := h.svc.Trend(c.Request.Context(), year) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取收支趋势失败"}) + return + } + c.JSON(http.StatusOK, data) +} + +func parseReportYearMonth(c *gin.Context) (int, int, bool) { + year, err := strconv.Atoi(c.Query("year")) + if err != nil || year < 2000 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"}) + return 0, 0, false + } + month, err := strconv.Atoi(c.Query("month")) + if err != nil || month < 1 || month > 12 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的月份"}) + return 0, 0, false + } + return year, month, true +} diff --git a/backend/api/router.go b/backend/api/router.go new file mode 100644 index 0000000..a2c54ed --- /dev/null +++ b/backend/api/router.go @@ -0,0 +1,262 @@ +package api + +import ( + "database/sql" + "io" + "mime" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + + "household-book/middleware" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +func SetupRouter(db *sql.DB, dbPath string, mode string, staticDir string, corsOrigins string) *gin.Engine { + if mode == "prod" { + gin.SetMode(gin.ReleaseMode) + } else { + gin.SetMode(gin.DebugMode) + } + + r := gin.New() + middleware.Setup(r, mode, corsOrigins) + + memberSvc := service.NewMemberService(db) + categorySvc := service.NewCategoryService(db) + accountSvc := service.NewAccountService(db) + transactionSvc := service.NewTransactionService(db) + dashboardSvc := service.NewDashboardService(db) + budgetSvc := service.NewBudgetService(db) + reportSvc := service.NewReportService(db) + assetSvc := service.NewAssetService(db) + policySvc := service.NewPolicyService(db) + lifecycleSvc := service.NewLifecycleService(db) + backupSvc := service.NewBackupService(db, dbPath) + + memberH := NewMemberHandler(memberSvc) + categoryH := NewCategoryHandler(categorySvc) + accountH := NewAccountHandler(accountSvc) + transactionH := NewTransactionHandler(transactionSvc) + dashboardH := NewDashboardHandler(dashboardSvc) + budgetH := NewBudgetHandler(budgetSvc) + reportH := NewReportHandler(reportSvc) + assetH := NewAssetHandler(assetSvc) + policyH := NewPolicyHandler(policySvc) + lifecycleH := NewLifecycleHandler(lifecycleSvc) + backupH := NewBackupHandler(backupSvc) + + api := r.Group("/api") + { + api.GET("/members", memberH.List) + api.POST("/members", memberH.Create) + api.PUT("/members/:id", memberH.Update) + api.DELETE("/members/:id", memberH.Delete) + + api.GET("/categories", categoryH.List) + api.POST("/categories", categoryH.Create) + api.PUT("/categories/:id", categoryH.Update) + api.DELETE("/categories/:id", categoryH.Delete) + + api.GET("/accounts", accountH.List) + api.POST("/accounts", accountH.Create) + api.PUT("/accounts/:id", accountH.Update) + api.DELETE("/accounts/:id", accountH.Delete) + api.POST("/accounts/:id/reconcile", accountH.Reconcile) + api.GET("/accounts/:id/reconciliations", accountH.ListReconciliations) + + api.GET("/transactions", transactionH.List) + api.GET("/transactions/import-batches", transactionH.ListImportBatches) + api.POST("/transactions/import/preview", transactionH.PreviewImport) + api.POST("/transactions/import", transactionH.Import) + api.POST("/transactions/batch-delete", transactionH.DeleteBatch) + api.POST("/transactions", transactionH.Create) + api.PUT("/transactions/:id", transactionH.Update) + api.DELETE("/transactions/:id", transactionH.Delete) + api.DELETE("/transactions/import-batches/:id", transactionH.DeleteImportBatch) + + api.GET("/dashboard/summary", dashboardH.Summary) + api.GET("/dashboard/recent", dashboardH.Recent) + + api.GET("/budgets/:year/:month", budgetH.Overview) + api.PUT("/budgets", budgetH.Upsert) + api.DELETE("/budgets/:id", budgetH.Delete) + + api.GET("/reports/overview", reportH.Overview) + api.GET("/reports/category-ranking", reportH.CategoryRanking) + api.GET("/reports/trend", reportH.Trend) + + api.GET("/assets", assetH.ListAssets) + api.POST("/assets", assetH.CreateAsset) + api.PUT("/assets/:id", assetH.UpdateAsset) + api.DELETE("/assets/:id", assetH.DeleteAsset) + api.GET("/assets/net-worth", assetH.NetWorth) + api.GET("/assets/snapshots", assetH.ListSnapshots) + + api.GET("/liabilities", assetH.ListLiabilities) + api.POST("/liabilities", assetH.CreateLiability) + api.PUT("/liabilities/:id", assetH.UpdateLiability) + api.DELETE("/liabilities/:id", assetH.DeleteLiability) + + api.GET("/policies", policyH.List) + api.POST("/policies", policyH.Create) + api.PUT("/policies/:id", policyH.Update) + api.DELETE("/policies/:id", policyH.Delete) + api.GET("/policies/upcoming", policyH.Upcoming) + api.GET("/policies/:id/payments", policyH.ListPayments) + api.POST("/policies/:id/payments", policyH.CreatePayment) + api.PUT("/policy-payments/:id", policyH.UpdatePayment) + + api.GET("/lifecycle", lifecycleH.List) + api.POST("/lifecycle/events", lifecycleH.Create) + api.PUT("/lifecycle/events/:id", lifecycleH.Update) + api.DELETE("/lifecycle/events/:id", lifecycleH.Delete) + + api.GET("/backups/status", backupH.Status) + api.POST("/backups", backupH.Create) + } + + // Production: serve static files + if staticDir != "" { + r.Use(staticFileMiddleware(staticDir)) + } + + return r +} + +// immutableAssetPrefix 是 Vite 构建产物目录,文件名自带内容 hash,可长期强缓存。 +const immutableAssetPrefix = "/assets/" + +func staticFileMiddleware(staticDir string) gin.HandlerFunc { + fs := http.FileServer(http.Dir(staticDir)) + root, err := filepath.Abs(staticDir) + if err != nil { + root = staticDir + } + indexPath := filepath.Join(root, "index.html") + + return func(c *gin.Context) { + requestPath := c.Request.URL.Path + if strings.HasPrefix(requestPath, "/api") { + c.Next() + return + } + + // 根路径与入口页直接返回 index.html,省掉文件服务器的目录重定向; + // 入口页必须每次协商,否则前端发版后用户会继续使用旧 bundle。 + if requestPath == "/" || requestPath == "/index.html" { + if serveIndexHTML(c, indexPath) { + c.Abort() + return + } + c.Next() + return + } + + clean := filepath.Clean("/" + requestPath) + candidate := filepath.Join(root, clean) + if !strings.HasPrefix(candidate, root) { + c.Next() + return + } + if info, err := os.Stat(candidate); err == nil && !info.IsDir() { + setStaticCacheHeaders(c, requestPath) + if servePrecompressed(c, candidate) { + c.Abort() + return + } + fs.ServeHTTP(c.Writer, c.Request) + c.Abort() + return + } + + // SPA fallback + if serveIndexHTML(c, indexPath) { + c.Abort() + return + } + + c.Next() + } +} + +// serveIndexHTML 返回入口页;文件不存在时返回 false,交回路由继续处理。 +func serveIndexHTML(c *gin.Context, indexPath string) bool { + if _, err := os.Stat(indexPath); err != nil { + return false + } + c.Header("Cache-Control", "no-cache, must-revalidate") + c.File(indexPath) + return true +} + +func setStaticCacheHeaders(c *gin.Context, requestPath string) { + if strings.HasPrefix(requestPath, immutableAssetPrefix) { + c.Header("Cache-Control", "public, max-age=31536000, immutable") + return + } + c.Header("Cache-Control", "public, max-age=3600") +} + +// servePrecompressed 在存在 .br/.gz 预压缩副本时直接返回;返回 true 表示已写入响应。 +func servePrecompressed(c *gin.Context, filePath string) bool { + encoding := preferredEncoding(c.GetHeader("Accept-Encoding")) + if encoding == "" { + return false + } + + compressedPath := filePath + "." + compressedSuffix(encoding) + info, err := os.Stat(compressedPath) + if err != nil || info.IsDir() { + return false + } + + file, err := os.Open(compressedPath) + if err != nil { + return false + } + defer file.Close() + + if contentType := mime.TypeByExtension(filepath.Ext(filePath)); contentType != "" { + c.Header("Content-Type", contentType) + } + c.Header("Content-Encoding", encoding) + c.Header("Vary", "Accept-Encoding") + c.Header("Content-Length", strconv.FormatInt(info.Size(), 10)) + c.Status(http.StatusOK) + _, _ = io.Copy(c.Writer, file) + return true +} + +func preferredEncoding(header string) string { + if header == "" { + return "" + } + + accepted := make(map[string]bool, 4) + for _, part := range strings.Split(header, ",") { + token := strings.TrimSpace(strings.SplitN(part, ";", 2)[0]) + accepted[strings.ToLower(token)] = true + } + + switch { + case accepted["br"]: + return "br" + case accepted["gzip"]: + return "gzip" + default: + return "" + } +} + +// compressedSuffix 把 Content-Encoding 映射到预压缩副本的扩展名(br / gz)。 +func compressedSuffix(encoding string) string { + if encoding == "br" { + return "br" + } + return "gz" +} diff --git a/backend/api/static_test.go b/backend/api/static_test.go new file mode 100644 index 0000000..726f593 --- /dev/null +++ b/backend/api/static_test.go @@ -0,0 +1,140 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func newStaticTestEngine(t *testing.T) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + + dir := t.TempDir() + writeTestFile(t, filepath.Join(dir, "index.html"), "
") + writeTestFile(t, filepath.Join(dir, "assets", "app.js"), "console.log('raw')") + writeTestFile(t, filepath.Join(dir, "assets", "app.js.br"), "br-payload") + writeTestFile(t, filepath.Join(dir, "assets", "app.js.gz"), "gz-payload") + + engine := gin.New() + engine.Use(staticFileMiddleware(dir)) + return engine +} + +func writeTestFile(t *testing.T, path string, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir %s: %v", filepath.Dir(path), err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +func getWithHeaders(engine *gin.Engine, target string, headers map[string]string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, target, nil) + for key, value := range headers { + req.Header.Set(key, value) + } + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, req) + return recorder +} + +func TestStaticIndexIsNotCached(t *testing.T) { + recorder := getWithHeaders(newStaticTestEngine(t), "/", nil) + + if recorder.Code != http.StatusOK { + t.Fatalf("GET / status = %d, want 200", recorder.Code) + } + if got := recorder.Header().Get("Cache-Control"); got != "no-cache, must-revalidate" { + t.Fatalf("Cache-Control = %q, want no-cache, must-revalidate", got) + } + if !strings.Contains(recorder.Body.String(), "id=\"root\"") { + t.Fatalf("index body = %q", recorder.Body.String()) + } +} + +func TestStaticAssetsAreImmutable(t *testing.T) { + recorder := getWithHeaders(newStaticTestEngine(t), "/assets/app.js", nil) + + if recorder.Code != http.StatusOK { + t.Fatalf("GET /assets/app.js status = %d, want 200", recorder.Code) + } + if got := recorder.Header().Get("Cache-Control"); got != "public, max-age=31536000, immutable" { + t.Fatalf("Cache-Control = %q, want immutable asset cache", got) + } + if got := recorder.Body.String(); got != "console.log('raw')" { + t.Fatalf("body = %q, want raw file without precompression", got) + } + if got := recorder.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding = %q, want empty", got) + } +} + +func TestStaticServesBrotliWhenAccepted(t *testing.T) { + recorder := getWithHeaders(newStaticTestEngine(t), "/assets/app.js", map[string]string{ + "Accept-Encoding": "gzip, deflate, br", + }) + + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", recorder.Code) + } + if got := recorder.Header().Get("Content-Encoding"); got != "br" { + t.Fatalf("Content-Encoding = %q, want br", got) + } + if got := recorder.Body.String(); got != "br-payload" { + t.Fatalf("body = %q, want brotli payload", got) + } + if got := recorder.Header().Get("Vary"); !strings.Contains(got, "Accept-Encoding") { + t.Fatalf("Vary = %q, want it to include Accept-Encoding", got) + } +} + +func TestStaticFallsBackToGzip(t *testing.T) { + recorder := getWithHeaders(newStaticTestEngine(t), "/assets/app.js", map[string]string{ + "Accept-Encoding": "gzip", + }) + + if got := recorder.Header().Get("Content-Encoding"); got != "gzip" { + t.Fatalf("Content-Encoding = %q, want gzip", got) + } + if got := recorder.Body.String(); got != "gz-payload" { + t.Fatalf("body = %q, want gzip payload", got) + } +} + +func TestStaticSPAFallbackServesIndex(t *testing.T) { + recorder := getWithHeaders(newStaticTestEngine(t), "/transactions", nil) + + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", recorder.Code) + } + if !strings.Contains(recorder.Body.String(), "id=\"root\"") { + t.Fatalf("fallback body = %q, want index.html", recorder.Body.String()) + } +} + +func TestPreferredEncodingPrefersBrotli(t *testing.T) { + cases := map[string]string{ + "": "", + "gzip": "gzip", + "deflate, gzip": "gzip", + "br": "br", + "gzip, br": "br", + "identity": "", + "gzip;q=1, br;q=0.5": "br", + "deflate": "", + } + + for header, want := range cases { + if got := preferredEncoding(header); got != want { + t.Errorf("preferredEncoding(%q) = %q, want %q", header, got, want) + } + } +} diff --git a/backend/api/transaction.go b/backend/api/transaction.go new file mode 100644 index 0000000..97ebb81 --- /dev/null +++ b/backend/api/transaction.go @@ -0,0 +1,354 @@ +package api + +import ( + "encoding/csv" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + + "household-book/model" + "household-book/service" + + "github.com/gin-gonic/gin" +) + +type TransactionHandler struct { + svc *service.TransactionService +} + +func NewTransactionHandler(svc *service.TransactionService) *TransactionHandler { + return &TransactionHandler{svc: svc} +} + +func (h *TransactionHandler) List(c *gin.Context) { + var req model.TransactionListRequest + req.Month = c.Query("month") + req.DateFrom = c.Query("date_from") + req.DateTo = c.Query("date_to") + if catID := c.Query("category_id"); catID != "" { + id, err := strconv.ParseInt(catID, 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的分类ID"}) + return + } + req.CategoryID = &id + } + req.Type = c.Query("type") + req.Keyword = c.Query("keyword") + if mID := c.Query("member_id"); mID != "" { + id, err := strconv.ParseInt(mID, 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的成员ID"}) + return + } + req.MemberID = &id + } + if aID := c.Query("account_id"); aID != "" { + id, err := strconv.ParseInt(aID, 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的账户ID"}) + return + } + req.AccountID = &id + } + if batchID := c.Query("import_batch_id"); batchID != "" { + id, err := strconv.ParseInt(batchID, 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的导入批次ID"}) + return + } + req.ImportBatchID = &id + } + if p := c.Query("page"); p != "" { + page, err := strconv.Atoi(p) + if err != nil || page < 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的页码"}) + return + } + req.Page = page + } else { + req.Page = 1 + } + if ps := c.Query("page_size"); ps != "" { + pageSize, err := strconv.Atoi(ps) + if err != nil || pageSize < 1 || pageSize > 100 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的每页条数(1-100)"}) + return + } + req.PageSize = pageSize + } else { + req.PageSize = 20 + } + if c.Query("format") == "csv" { + req.Page = 1 + req.PageSize = 1000000 + } + + result, err := h.svc.List(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取收支记录失败"}) + return + } + if c.Query("format") == "csv" { + writeTransactionsCSV(c, result.Items) + return + } + c.JSON(http.StatusOK, result) +} + +func writeTransactionsCSV(c *gin.Context, items []model.TransactionListItem) { + c.Header("Content-Type", "text/csv; charset=utf-8") + c.Header("Content-Disposition", `attachment; filename="transactions.csv"`) + _, _ = c.Writer.Write([]byte{0xEF, 0xBB, 0xBF}) + w := csv.NewWriter(c.Writer) + _ = w.Write([]string{"日期", "类型", "金额(元)", "分类", "账户", "转入账户", "成员", "对手方", "描述", "导入文件"}) + for _, item := range items { + _ = w.Write([]string{item.Date, item.Type, fmt.Sprintf("%.2f", float64(item.Amount)/100), item.CategoryName, item.AccountName, item.ToAccountName, item.MemberName, item.Counterparty, item.Description, item.ImportFilename}) + } + w.Flush() +} + +func (h *TransactionHandler) ListImportBatches(c *gin.Context) { + batches, err := h.svc.ListImportBatches(c.Request.Context()) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "获取导入文件列表失败"}) + return + } + c.JSON(http.StatusOK, batches) +} + +func (h *TransactionHandler) Import(c *gin.Context) { + req, ok := parseImportMultipart(c) + if !ok { + return + } + result, err := h.svc.Import(c.Request.Context(), req) + if err != nil { + writeImportError(c, err, "导入收支记录失败") + return + } + c.JSON(http.StatusOK, result) +} + +func (h *TransactionHandler) PreviewImport(c *gin.Context) { + req, ok := parseImportMultipart(c) + if !ok { + return + } + result, err := h.svc.PreviewImport(c.Request.Context(), req) + if err != nil { + writeImportError(c, err, "解析账单预览失败") + return + } + c.JSON(http.StatusOK, result) +} + +func parseImportMultipart(c *gin.Context) (model.ImportTransactionsRequest, bool) { + file, err := c.FormFile("file") + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要导入的账单文件"}) + return model.ImportTransactionsRequest{}, false + } + if file.Size <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "账单文件为空"}) + return model.ImportTransactionsRequest{}, false + } + if file.Size > 10*1024*1024 { + c.JSON(http.StatusBadRequest, gin.H{"error": "账单文件不能超过10MB"}) + return model.ImportTransactionsRequest{}, false + } + + opened, err := file.Open() + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "读取账单文件失败"}) + return model.ImportTransactionsRequest{}, false + } + defer opened.Close() + + content, err := io.ReadAll(opened) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "读取账单文件失败"}) + return model.ImportTransactionsRequest{}, false + } + + req := model.ImportTransactionsRequest{ + Filename: file.Filename, + Content: content, + SourceKind: c.PostForm("source_kind"), + BankName: c.PostForm("bank_name"), + CardType: c.PostForm("card_type"), + } + if accountID := c.PostForm("account_id"); accountID != "" { + id, err := strconv.ParseInt(accountID, 10, 64) + if err != nil || id <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的账户ID"}) + return model.ImportTransactionsRequest{}, false + } + req.AccountID = &id + } + if raw := c.PostForm("category_overrides"); raw != "" { + if err := json.Unmarshal([]byte(raw), &req.CategoryOverrides); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "分类修正格式无效"}) + return model.ImportTransactionsRequest{}, false + } + } + return req, true +} + +func writeImportError(c *gin.Context, err error, generic string) { + if errors.Is(err, service.ErrNoImportableTransactions) { + c.JSON(http.StatusBadRequest, gin.H{"error": "未从账单中识别到可导入的收支明细"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": generic}) +} + +func (h *TransactionHandler) Create(c *gin.Context) { + var req model.CreateTransactionRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if req.Type != "income" && req.Type != "expense" && req.Type != "transfer" { + c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income、expense 或 transfer"}) + return + } + if req.Amount <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "金额必须大于0"}) + return + } + if req.Date == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "日期不能为空"}) + return + } + if req.Type == "transfer" { + if req.AccountID == nil || req.ToAccountID == nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "转账必须同时选择转出账户和转入账户"}) + return + } + if *req.AccountID == *req.ToAccountID { + c.JSON(http.StatusBadRequest, gin.H{"error": "转出账户与转入账户不能相同"}) + return + } + req.CategoryID = nil + } else { + if req.CategoryID == nil || *req.CategoryID <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "必须选择分类"}) + return + } + req.ToAccountID = nil + } + + t, err := h.svc.Create(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "添加收支记录失败"}) + return + } + c.JSON(http.StatusCreated, t) +} + +func (h *TransactionHandler) Update(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + var req model.UpdateTransactionRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + + if req.Amount != nil && *req.Amount <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "金额必须大于0"}) + return + } + if req.Type != nil && *req.Type != "income" && *req.Type != "expense" && *req.Type != "transfer" { + c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income、expense 或 transfer"}) + return + } + if req.CategoryID.Set && req.CategoryID.Valid && req.CategoryID.Value <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "必须选择分类"}) + return + } + if req.Type != nil && *req.Type == "transfer" { + if req.ToAccountID.Set && !req.ToAccountID.Valid { + c.JSON(http.StatusBadRequest, gin.H{"error": "转账必须选择转入账户"}) + return + } + } + + t, err := h.svc.Update(c.Request.Context(), id, req) + if err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "收支记录不存在"}) + return + } + if errors.Is(err, service.ErrInvalidTransaction) { + c.JSON(http.StatusBadRequest, gin.H{"error": "交易类型、分类和转账账户组合不合法"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "更新收支记录失败"}) + return + } + c.JSON(http.StatusOK, t) +} + +func (h *TransactionHandler) DeleteBatch(c *gin.Context) { + var req model.DeleteTransactionsRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"}) + return + } + if len(req.IDs) == 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要删除的收支记录"}) + return + } + if len(req.IDs) > 500 { + c.JSON(http.StatusBadRequest, gin.H{"error": "单次最多删除500条记录"}) + return + } + + deleted, err := h.svc.DeleteBatch(c.Request.Context(), req.IDs) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "批量删除收支记录失败"}) + return + } + c.JSON(http.StatusOK, model.DeleteTransactionsResult{DeletedCount: deleted}) +} + +func (h *TransactionHandler) DeleteImportBatch(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的导入批次ID"}) + return + } + deleted, err := h.svc.DeleteImportBatch(c.Request.Context(), id) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "按导入文件删除失败"}) + return + } + c.JSON(http.StatusOK, model.DeleteTransactionsResult{DeletedCount: deleted}) +} + +func (h *TransactionHandler) Delete(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + if errors.Is(err, service.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "收支记录不存在"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "删除收支记录失败"}) + return + } + c.Status(http.StatusNoContent) +} diff --git a/backend/db/migrate.go b/backend/db/migrate.go new file mode 100644 index 0000000..887f55b --- /dev/null +++ b/backend/db/migrate.go @@ -0,0 +1,89 @@ +package db + +import ( + "database/sql" + "embed" + "fmt" + "io/fs" + "sort" + "strconv" + "strings" +) + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +func RunMigrations(db *sql.DB) error { + if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS migrations ( + version INTEGER PRIMARY KEY, + applied_at TEXT NOT NULL DEFAULT (datetime('now')) + )`); err != nil { + return fmt.Errorf("create migrations table: %w", err) + } + + entries, err := fs.ReadDir(migrationFiles, "migrations") + if err != nil { + return fmt.Errorf("read migration dir: %w", err) + } + + type migration struct { + version int + name string + content string + } + + var migrations []migration + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") { + continue + } + parts := strings.SplitN(entry.Name(), "_", 2) + version, err := strconv.Atoi(parts[0]) + if err != nil { + return fmt.Errorf("parse migration version from %s: %w", entry.Name(), err) + } + + data, err := migrationFiles.ReadFile("migrations/" + entry.Name()) + if err != nil { + return fmt.Errorf("read migration %s: %w", entry.Name(), err) + } + migrations = append(migrations, migration{version: version, name: entry.Name(), content: string(data)}) + } + + sort.Slice(migrations, func(i, j int) bool { + return migrations[i].version < migrations[j].version + }) + + var currentVersion int + err = db.QueryRow("SELECT COALESCE(MAX(version), 0) FROM migrations").Scan(¤tVersion) + if err != nil { + return fmt.Errorf("query current migration version: %w", err) + } + + for _, m := range migrations { + if m.version <= currentVersion { + continue + } + + tx, err := db.Begin() + if err != nil { + return fmt.Errorf("begin migration %d: %w", m.version, err) + } + + if _, err := tx.Exec(m.content); err != nil { + tx.Rollback() + return fmt.Errorf("execute migration %d (%s): %w", m.version, m.name, err) + } + + if _, err := tx.Exec("INSERT INTO migrations (version) VALUES (?)", m.version); err != nil { + tx.Rollback() + return fmt.Errorf("record migration %d: %w", m.version, err) + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit migration %d: %w", m.version, err) + } + } + + return nil +} diff --git a/backend/db/migrations/001_initial.sql b/backend/db/migrations/001_initial.sql new file mode 100644 index 0000000..7465f19 --- /dev/null +++ b/backend/db/migrations/001_initial.sql @@ -0,0 +1,50 @@ +CREATE TABLE IF NOT EXISTS members ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + relation TEXT NOT NULL DEFAULT '', + birthday TEXT DEFAULT '', + phone TEXT DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS categories ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL CHECK (type IN ('income', 'expense')), + parent_id INTEGER REFERENCES categories(id) ON DELETE SET NULL, + sort_order INTEGER NOT NULL DEFAULT 0, + is_active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_categories_parent ON categories(parent_id); +CREATE INDEX IF NOT EXISTS idx_categories_type ON categories(type); + +CREATE TABLE IF NOT EXISTS accounts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'other', + balance INTEGER NOT NULL DEFAULT 0, + is_active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS transactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT NOT NULL CHECK (type IN ('income', 'expense')), + amount INTEGER NOT NULL CHECK (amount >= 0), + category_id INTEGER NOT NULL REFERENCES categories(id), + account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL, + member_id INTEGER REFERENCES members(id) ON DELETE SET NULL, + date TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_transactions_date ON transactions(date); +CREATE INDEX IF NOT EXISTS idx_transactions_category ON transactions(category_id); +CREATE INDEX IF NOT EXISTS idx_transactions_type_date ON transactions(type, date); +CREATE INDEX IF NOT EXISTS idx_transactions_account ON transactions(account_id); +CREATE INDEX IF NOT EXISTS idx_transactions_member ON transactions(member_id); diff --git a/backend/db/migrations/002_account_bank_details.sql b/backend/db/migrations/002_account_bank_details.sql new file mode 100644 index 0000000..fb4bdf7 --- /dev/null +++ b/backend/db/migrations/002_account_bank_details.sql @@ -0,0 +1,4 @@ +ALTER TABLE accounts ADD COLUMN bank_name TEXT NOT NULL DEFAULT ''; +ALTER TABLE accounts ADD COLUMN card_number TEXT NOT NULL DEFAULT ''; +ALTER TABLE accounts ADD COLUMN branch_name TEXT NOT NULL DEFAULT ''; +ALTER TABLE accounts ADD COLUMN note TEXT NOT NULL DEFAULT ''; diff --git a/backend/db/migrations/003_budgets.sql b/backend/db/migrations/003_budgets.sql new file mode 100644 index 0000000..eef4b72 --- /dev/null +++ b/backend/db/migrations/003_budgets.sql @@ -0,0 +1,25 @@ +CREATE TABLE IF NOT EXISTS budgets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + year INTEGER NOT NULL, + month INTEGER, + category_id INTEGER REFERENCES categories(id) ON DELETE CASCADE, + amount INTEGER NOT NULL DEFAULT 0 CHECK (amount >= 0), + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS idx_budgets_year_month ON budgets(year, month); +CREATE INDEX IF NOT EXISTS idx_budgets_category ON budgets(category_id); +CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_annual_total + ON budgets(year) + WHERE month IS NULL AND category_id IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_annual_category + ON budgets(year, category_id) + WHERE month IS NULL AND category_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_monthly_total + ON budgets(year, month) + WHERE month IS NOT NULL AND category_id IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_monthly_category + ON budgets(year, month, category_id) + WHERE month IS NOT NULL AND category_id IS NOT NULL; diff --git a/backend/db/migrations/004_phase3_financial_overview.sql b/backend/db/migrations/004_phase3_financial_overview.sql new file mode 100644 index 0000000..b4e4fd6 --- /dev/null +++ b/backend/db/migrations/004_phase3_financial_overview.sql @@ -0,0 +1,65 @@ +CREATE TABLE IF NOT EXISTS assets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'other', + value INTEGER NOT NULL DEFAULT 0 CHECK (value >= 0), + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type); + +CREATE TABLE IF NOT EXISTS liabilities ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'other', + principal INTEGER NOT NULL DEFAULT 0 CHECK (principal >= 0), + interest_rate REAL NOT NULL DEFAULT 0, + monthly_payment INTEGER NOT NULL DEFAULT 0 CHECK (monthly_payment >= 0), + remaining_terms INTEGER NOT NULL DEFAULT 0 CHECK (remaining_terms >= 0), + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_liabilities_type ON liabilities(type); + +CREATE TABLE IF NOT EXISTS asset_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, + total_asset INTEGER NOT NULL DEFAULT 0, + total_debt INTEGER NOT NULL DEFAULT 0, + net_worth INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(date) +); + +CREATE TABLE IF NOT EXISTS policies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'other', + insured_person TEXT NOT NULL DEFAULT '', + premium INTEGER NOT NULL DEFAULT 0 CHECK (premium >= 0), + coverage_amount INTEGER NOT NULL DEFAULT 0 CHECK (coverage_amount >= 0), + start_date TEXT NOT NULL DEFAULT '', + end_date TEXT NOT NULL DEFAULT '', + beneficiary TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'active', + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_policies_end_date ON policies(end_date); +CREATE INDEX IF NOT EXISTS idx_policies_status ON policies(status); + +CREATE TABLE IF NOT EXISTS lifecycle_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + year INTEGER NOT NULL, + member_id INTEGER REFERENCES members(id) ON DELETE SET NULL, + event TEXT NOT NULL, + estimated_cost INTEGER NOT NULL DEFAULT 0 CHECK (estimated_cost >= 0), + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_lifecycle_year ON lifecycle_events(year); +CREATE INDEX IF NOT EXISTS idx_lifecycle_member ON lifecycle_events(member_id); diff --git a/backend/db/migrations/005_card_types_and_transaction_imports.sql b/backend/db/migrations/005_card_types_and_transaction_imports.sql new file mode 100644 index 0000000..92dc8ca --- /dev/null +++ b/backend/db/migrations/005_card_types_and_transaction_imports.sql @@ -0,0 +1,6 @@ +UPDATE accounts SET type = 'debit_card' WHERE type = 'bank_card'; + +ALTER TABLE transactions ADD COLUMN source_key TEXT NOT NULL DEFAULT ''; +CREATE UNIQUE INDEX IF NOT EXISTS ux_transactions_source_key + ON transactions(source_key) + WHERE source_key <> ''; diff --git a/backend/db/migrations/006_transaction_batches_and_counterparty.sql b/backend/db/migrations/006_transaction_batches_and_counterparty.sql new file mode 100644 index 0000000..f97d9b1 --- /dev/null +++ b/backend/db/migrations/006_transaction_batches_and_counterparty.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS import_batches ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL, + bank_name TEXT NOT NULL DEFAULT '', + card_type TEXT NOT NULL DEFAULT '', + account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL, + imported_count INTEGER NOT NULL DEFAULT 0, + skipped_count INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +ALTER TABLE transactions ADD COLUMN counterparty TEXT NOT NULL DEFAULT ''; +ALTER TABLE transactions ADD COLUMN import_batch_id INTEGER REFERENCES import_batches(id) ON DELETE SET NULL; + +CREATE INDEX IF NOT EXISTS idx_transactions_import_batch ON transactions(import_batch_id); +CREATE INDEX IF NOT EXISTS idx_transactions_counterparty ON transactions(counterparty); diff --git a/backend/db/migrations/007_category_keywords.sql b/backend/db/migrations/007_category_keywords.sql new file mode 100644 index 0000000..1bee04c --- /dev/null +++ b/backend/db/migrations/007_category_keywords.sql @@ -0,0 +1,26 @@ +ALTER TABLE categories ADD COLUMN keywords TEXT NOT NULL DEFAULT ''; + +-- Backfill keywords for default categories so the import classifier matches the legacy hard-coded rules. +UPDATE categories SET keywords = '工资' WHERE name = '工资薪酬' AND type = 'income'; +UPDATE categories SET keywords = '奖金' WHERE name = '奖金福利' AND type = 'income'; +UPDATE categories SET keywords = '利息,结息,理财' WHERE name = '银行理财' AND type = 'income'; +UPDATE categories SET keywords = '股票,基金,分红' WHERE name = '股票基金' AND type = 'income'; + +UPDATE categories SET keywords = '房贷,按揭' WHERE name = '房贷' AND type = 'expense'; +UPDATE categories SET keywords = '车贷' WHERE name = '车贷' AND type = 'expense'; +UPDATE categories SET keywords = '水费,电费,燃气,煤气' WHERE name = '水电燃气' AND type = 'expense'; +UPDATE categories SET keywords = '学费,培训' WHERE name = '学费' AND type = 'expense'; +UPDATE categories SET keywords = '保费,保险' WHERE name = '保费' AND type = 'expense'; + +UPDATE categories SET keywords = '餐,面,饭,美团,饿了么' WHERE name = '餐饮' AND type = 'expense'; +UPDATE categories SET keywords = '铁路,滴滴,骑行,出行,地铁,公交,加油' WHERE name = '交通' AND type = 'expense'; +UPDATE categories SET keywords = '话费,流量,宽带' WHERE name = '通讯' AND type = 'expense'; +UPDATE categories SET keywords = '超市,天猫,京东,日用品' WHERE name = '日用品' AND type = 'expense'; +UPDATE categories SET keywords = '聚餐,礼物' WHERE name = '社交' AND type = 'expense'; +UPDATE categories SET keywords = '医院,药店,诊所' WHERE name = '医疗' AND type = 'expense'; + +UPDATE categories SET keywords = '酒店,机票,旅游,景点' WHERE name = '旅行' AND type = 'expense'; +UPDATE categories SET keywords = '健身,瑜伽,游泳' WHERE name = '健身' AND type = 'expense'; +UPDATE categories SET keywords = '美容,美发,化妆品' WHERE name = '美容' AND type = 'expense'; +UPDATE categories SET keywords = '电影,游戏,KTV' WHERE name = '娱乐' AND type = 'expense'; +UPDATE categories SET keywords = '服装,鞋,帽' WHERE name = '服装' AND type = 'expense'; diff --git a/backend/db/migrations/008_transfer_transactions.sql b/backend/db/migrations/008_transfer_transactions.sql new file mode 100644 index 0000000..40ce067 --- /dev/null +++ b/backend/db/migrations/008_transfer_transactions.sql @@ -0,0 +1,46 @@ +-- 引入 transfer 交易类型,支持账户间转账(不参与收入/支出统计)。 +-- SQLite 不支持修改 CHECK 约束或列约束,需要重建 transactions 表。 +-- 同时把 category_id 改为 NULLABLE:transfer 类型不归属任何分类。 + +CREATE TABLE transactions_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT NOT NULL CHECK (type IN ('income', 'expense', 'transfer')), + amount INTEGER NOT NULL CHECK (amount >= 0), + category_id INTEGER REFERENCES categories(id), + account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL, + to_account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL, + member_id INTEGER REFERENCES members(id) ON DELETE SET NULL, + date TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + counterparty TEXT NOT NULL DEFAULT '', + source_key TEXT NOT NULL DEFAULT '', + import_batch_id INTEGER REFERENCES import_batches(id) ON DELETE SET NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +INSERT INTO transactions_new ( + id, type, amount, category_id, account_id, member_id, + date, description, counterparty, source_key, import_batch_id, + created_at, updated_at +) +SELECT + id, type, amount, category_id, account_id, member_id, + date, description, counterparty, source_key, import_batch_id, + created_at, updated_at +FROM transactions; + +DROP TABLE transactions; +ALTER TABLE transactions_new RENAME TO transactions; + +CREATE INDEX idx_transactions_date ON transactions(date); +CREATE INDEX idx_transactions_category ON transactions(category_id); +CREATE INDEX idx_transactions_type_date ON transactions(type, date); +CREATE INDEX idx_transactions_account ON transactions(account_id); +CREATE INDEX idx_transactions_to_account ON transactions(to_account_id); +CREATE INDEX idx_transactions_member ON transactions(member_id); +CREATE INDEX idx_transactions_import_batch ON transactions(import_batch_id); +CREATE INDEX idx_transactions_counterparty ON transactions(counterparty); +CREATE UNIQUE INDEX ux_transactions_source_key + ON transactions(source_key) + WHERE source_key <> ''; diff --git a/backend/db/migrations/009_assets_bind_account.sql b/backend/db/migrations/009_assets_bind_account.sql new file mode 100644 index 0000000..a57547f --- /dev/null +++ b/backend/db/migrations/009_assets_bind_account.sql @@ -0,0 +1,5 @@ +-- 资产可绑定到账户:当 account_id 不为 NULL 时,资产的 value 由该账户的 current_balance 实时派生。 +-- 兼容旧数据:原有手工资产保持 account_id IS NULL,行为不变。 + +ALTER TABLE assets ADD COLUMN account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL; +CREATE INDEX IF NOT EXISTS idx_assets_account_id ON assets(account_id); diff --git a/backend/db/migrations/010_assets_account_unique.sql b/backend/db/migrations/010_assets_account_unique.sql new file mode 100644 index 0000000..c54b609 --- /dev/null +++ b/backend/db/migrations/010_assets_account_unique.sql @@ -0,0 +1,2 @@ +-- 每个账户最多绑定一条资产,避免净值重复计入。 +CREATE UNIQUE INDEX IF NOT EXISTS idx_assets_account_id_unique ON assets(account_id) WHERE account_id IS NOT NULL; diff --git a/backend/db/migrations/011_policy_payment_fields.sql b/backend/db/migrations/011_policy_payment_fields.sql new file mode 100644 index 0000000..1f80432 --- /dev/null +++ b/backend/db/migrations/011_policy_payment_fields.sql @@ -0,0 +1,9 @@ +ALTER TABLE policies ADD COLUMN payment_frequency TEXT NOT NULL DEFAULT 'annual'; +ALTER TABLE policies ADD COLUMN next_payment_date TEXT NOT NULL DEFAULT ''; +ALTER TABLE policies ADD COLUMN payment_term_end TEXT NOT NULL DEFAULT ''; + +-- 旧数据此前将 end_date 同时用于“到期”和“续费提醒”,迁移后保留兼容的首次提醒日期。 +UPDATE policies SET next_payment_date = end_date +WHERE next_payment_date = '' AND end_date <> '' AND status = 'active'; + +CREATE INDEX IF NOT EXISTS idx_policies_next_payment_date ON policies(next_payment_date); diff --git a/backend/db/migrations/012_payments_and_reconciliation.sql b/backend/db/migrations/012_payments_and_reconciliation.sql new file mode 100644 index 0000000..f224ab0 --- /dev/null +++ b/backend/db/migrations/012_payments_and_reconciliation.sql @@ -0,0 +1,24 @@ +CREATE TABLE IF NOT EXISTS policy_payments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + policy_id INTEGER NOT NULL REFERENCES policies(id) ON DELETE CASCADE, + due_date TEXT NOT NULL, + amount INTEGER NOT NULL DEFAULT 0 CHECK (amount >= 0), + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','paid','skipped')), + paid_date TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_policy_payments_policy_due ON policy_payments(policy_id, due_date); + +CREATE TABLE IF NOT EXISTS account_reconciliations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + account_id INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + system_balance INTEGER NOT NULL, + actual_balance INTEGER NOT NULL, + difference INTEGER NOT NULL, + transaction_id INTEGER REFERENCES transactions(id) ON DELETE SET NULL, + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_account_reconciliations_account ON account_reconciliations(account_id, created_at); diff --git a/backend/db/seed.go b/backend/db/seed.go new file mode 100644 index 0000000..19cf3a3 --- /dev/null +++ b/backend/db/seed.go @@ -0,0 +1,144 @@ +package db + +import ( + "database/sql" + "fmt" +) + +func Seed(db *sql.DB) error { + if err := seedAccounts(db); err != nil { + return err + } + if err := seedCategories(db); err != nil { + return err + } + return nil +} + +func seedAccounts(db *sql.DB) error { + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM accounts").Scan(&count); err != nil { + return fmt.Errorf("check accounts: %w", err) + } + if count > 0 { + return nil + } + + accounts := []struct { + name string + typ string + }{ + {"支付宝", "alipay"}, + {"微信", "wechat"}, + {"储蓄卡", "debit_card"}, + {"信用卡", "credit_card"}, + {"现金", "cash"}, + } + + tx, err := db.Begin() + if err != nil { + return fmt.Errorf("begin seed accounts: %w", err) + } + defer tx.Rollback() + for _, a := range accounts { + if _, err := tx.Exec("INSERT INTO accounts (name, type) VALUES (?, ?)", a.name, a.typ); err != nil { + return fmt.Errorf("seed account %s: %w", a.name, err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit seed accounts: %w", err) + } + return nil +} + +func seedCategories(db *sql.DB) error { + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM categories").Scan(&count); err != nil { + return fmt.Errorf("check categories: %w", err) + } + if count > 0 { + return nil + } + + tx, err := db.Begin() + if err != nil { + return fmt.Errorf("begin seed categories: %w", err) + } + defer tx.Rollback() + + // Insert top-level categories first, capturing their IDs + top := []struct { + name string + typ string + order int + }{ + {"固定收入", "income", 1}, + {"不固定收入", "income", 2}, + {"固定支出", "expense", 1}, + {"不固定必须支出", "expense", 2}, + {"可有可无", "expense", 3}, + } + + parentIDs := make(map[string]int64) + + for _, t := range top { + result, err := tx.Exec( + "INSERT INTO categories (name, type, sort_order) VALUES (?, ?, ?)", + t.name, t.typ, t.order, + ) + if err != nil { + return fmt.Errorf("seed category %s: %w", t.name, err) + } + id, _ := result.LastInsertId() + parentIDs[t.name] = id + } + + children := []struct { + name string + typ string + parent string + order int + keywords string + }{ + // Income children + {"工资薪酬", "income", "固定收入", 1, "工资"}, + {"奖金福利", "income", "固定收入", 2, "奖金"}, + {"银行理财", "income", "不固定收入", 1, "利息,结息,理财"}, + {"股票基金", "income", "不固定收入", 2, "股票,基金,分红"}, + {"其他", "income", "不固定收入", 3, ""}, + // Expense children - 固定支出 + {"房贷", "expense", "固定支出", 1, "房贷,按揭"}, + {"车贷", "expense", "固定支出", 2, "车贷"}, + {"水电燃气", "expense", "固定支出", 3, "水费,电费,燃气,煤气"}, + {"学费", "expense", "固定支出", 4, "学费,培训"}, + {"保费", "expense", "固定支出", 5, "保费,保险"}, + // Expense children - 不固定必须支出 + {"餐饮", "expense", "不固定必须支出", 1, "餐,面,饭,美团,饿了么"}, + {"交通", "expense", "不固定必须支出", 2, "铁路,滴滴,骑行,出行,地铁,公交,加油"}, + {"通讯", "expense", "不固定必须支出", 3, "话费,流量,宽带"}, + {"日用品", "expense", "不固定必须支出", 4, "超市,天猫,京东,日用品"}, + {"社交", "expense", "不固定必须支出", 5, "聚餐,礼物"}, + {"医疗", "expense", "不固定必须支出", 6, "医院,药店,诊所"}, + // Expense children - 可有可无 + {"旅行", "expense", "可有可无", 1, "酒店,机票,旅游,景点"}, + {"健身", "expense", "可有可无", 2, "健身,瑜伽,游泳"}, + {"美容", "expense", "可有可无", 3, "美容,美发,化妆品"}, + {"娱乐", "expense", "可有可无", 4, "电影,游戏,KTV"}, + {"服装", "expense", "可有可无", 5, "服装,鞋,帽"}, + } + + for _, c := range children { + pid := parentIDs[c.parent] + if _, err := tx.Exec( + "INSERT INTO categories (name, type, parent_id, sort_order, keywords) VALUES (?, ?, ?, ?, ?)", + c.name, c.typ, pid, c.order, c.keywords, + ); err != nil { + return fmt.Errorf("seed category %s: %w", c.name, err) + } + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit seed categories: %w", err) + } + return nil +} diff --git a/backend/db/sqlite.go b/backend/db/sqlite.go new file mode 100644 index 0000000..d11b060 --- /dev/null +++ b/backend/db/sqlite.go @@ -0,0 +1,37 @@ +package db + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + + _ "modernc.org/sqlite" +) + +const sqlitePoolSize = 4 + +func Open(dbPath string) (*sql.DB, error) { + dir := filepath.Dir(dbPath) + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, fmt.Errorf("create db directory: %w", err) + } + + dsn := dbPath + "?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)" + conn, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, fmt.Errorf("open database: %w", err) + } + + conn.SetMaxOpenConns(sqlitePoolSize) + conn.SetMaxIdleConns(sqlitePoolSize) + conn.SetConnMaxLifetime(0) + conn.SetConnMaxIdleTime(0) + + if err := conn.Ping(); err != nil { + conn.Close() + return nil, fmt.Errorf("ping database: %w", err) + } + + return conn, nil +} diff --git a/backend/db/sqlite_test.go b/backend/db/sqlite_test.go new file mode 100644 index 0000000..81800c5 --- /dev/null +++ b/backend/db/sqlite_test.go @@ -0,0 +1,140 @@ +package db + +import ( + "context" + "errors" + "path/filepath" + "sync" + "testing" +) + +func TestOpenConfiguresBoundedWALPool(t *testing.T) { + conn, err := Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + if got := conn.Stats().MaxOpenConnections; got != 4 { + t.Fatalf("MaxOpenConnections=%d, want 4", got) + } +} + +func TestOpenAppliesPragmasToEveryPooledConnection(t *testing.T) { + conn, err := Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + for range sqlitePoolSize { + pooled, err := conn.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + // 故意延迟到测试结束再释放,确保同时占满 4 个不同连接。 + defer pooled.Close() + + var journalMode string + var foreignKeys, busyTimeout int + if err := pooled.QueryRowContext(context.Background(), "PRAGMA journal_mode").Scan(&journalMode); err != nil { + t.Fatal(err) + } + if err := pooled.QueryRowContext(context.Background(), "PRAGMA foreign_keys").Scan(&foreignKeys); err != nil { + t.Fatal(err) + } + if err := pooled.QueryRowContext(context.Background(), "PRAGMA busy_timeout").Scan(&busyTimeout); err != nil { + t.Fatal(err) + } + if journalMode != "wal" || foreignKeys != 1 || busyTimeout != 5000 { + t.Fatalf("pragmas=(%s,%d,%d), want (wal,1,5000)", journalMode, foreignKeys, busyTimeout) + } + } +} + +func TestOpenAllowsWriteDuringReadTransaction(t *testing.T) { + conn, err := Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if _, err := conn.Exec("CREATE TABLE sample(id INTEGER PRIMARY KEY)"); err != nil { + t.Fatal(err) + } + + readTx, err := conn.BeginTx(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + defer readTx.Rollback() + var count int + if err := readTx.QueryRow("SELECT COUNT(*) FROM sample").Scan(&count); err != nil { + t.Fatal(err) + } + + if _, err := conn.Exec("INSERT INTO sample(id) VALUES (1)"); err != nil { + t.Fatalf("write while read transaction is open: %v", err) + } +} + +func TestRunMigrationsWithForeignKeysEnabled(t *testing.T) { + conn, err := Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + if err := RunMigrations(conn); err != nil { + t.Fatalf("run migrations: %v", err) + } + rows, err := conn.Query("PRAGMA foreign_key_check") + if err != nil { + t.Fatal(err) + } + defer rows.Close() + if rows.Next() { + t.Fatal("freshly migrated database contains foreign key violations") + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } +} + +func TestOpenAllowsConcurrentReads(t *testing.T) { + conn, err := Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + if _, err := conn.Exec(`CREATE TABLE sample(id INTEGER PRIMARY KEY); INSERT INTO sample(id) VALUES (1)`); err != nil { + t.Fatal(err) + } + + const workers = 8 + const readsPerWorker = 20 + errs := make(chan error, workers) + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + for range readsPerWorker { + var count int + if err := conn.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM sample").Scan(&count); err != nil { + errs <- err + return + } + if count != 1 { + errs <- errors.New("unexpected sample count") + return + } + } + }() + } + wg.Wait() + close(errs) + for err := range errs { + t.Fatal(err) + } +} diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..093aeb5 --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,49 @@ +module household-book + +go 1.25.0 + +require ( + github.com/gin-contrib/cors v1.7.7 + github.com/gin-gonic/gin v1.12.0 + golang.org/x/text v0.35.0 + modernc.org/sqlite v1.37.0 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + golang.org/x/arch v0.23.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/sys v0.41.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect + modernc.org/libc v1.62.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.9.1 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..37ffd9d --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,133 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q= +github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg= +golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= +golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= +golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= +golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= +golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.25.2 h1:T2oH7sZdGvTaie0BRNFbIYsabzCxUQg8nLqCdQ2i0ic= +modernc.org/cc/v4 v4.25.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= +modernc.org/ccgo/v4 v4.25.1 h1:TFSzPrAGmDsdnhT9X2UrcPMI3N/mJ9/X9ykKXwLhDsU= +modernc.org/ccgo/v4 v4.25.1/go.mod h1:njjuAYiPflywOOrm3B7kCB444ONP5pAVr8PIEoE0uDw= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/libc v1.62.1 h1:s0+fv5E3FymN8eJVmnk0llBe6rOxCu/DEU+XygRbS8s= +modernc.org/libc v1.62.1/go.mod h1:iXhATfJQLjG3NWy56a6WVU73lWOcdYVxsvwCgoPljuo= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g= +modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= +modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI= +modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/backend/main.go b/backend/main.go new file mode 100644 index 0000000..cc917dc --- /dev/null +++ b/backend/main.go @@ -0,0 +1,80 @@ +package main + +import ( + "context" + "flag" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "household-book/api" + "household-book/db" + "household-book/service" +) + +func main() { + mode := flag.String("mode", "dev", "run mode: dev | prod") + dbPath := flag.String("db", "./data/family_book.db", "path to SQLite database") + port := flag.String("port", "8080", "server port") + staticDir := flag.String("static", "", "path to static files (production)") + corsOrigins := flag.String("cors-origin", "", "comma-separated CORS allowed origins (default: dev mode allows localhost:5173)") + flag.Parse() + + slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + Level: slog.LevelInfo, + }))) + + conn, err := db.Open(*dbPath) + if err != nil { + slog.Error("open database", "error", err) + os.Exit(1) + } + defer conn.Close() + + if err := db.RunMigrations(conn); err != nil { + slog.Error("run migrations", "error", err) + os.Exit(1) + } + + if err := db.Seed(conn); err != nil { + slog.Error("seed data", "error", err) + os.Exit(1) + } + + router := api.SetupRouter(conn, *dbPath, *mode, *staticDir, *corsOrigins) + + srv := &http.Server{ + Addr: ":" + *port, + Handler: router, + } + + bgCtx, cancelBg := context.WithCancel(context.Background()) + defer cancelBg() + go service.NewAssetService(conn).RunSnapshotScheduler(bgCtx) + go service.NewBackupService(conn, *dbPath).RunScheduler(bgCtx) + + go func() { + slog.Info("server started", "addr", srv.Addr, "mode", *mode) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + slog.Error("server error", "error", err) + os.Exit(1) + } + }() + + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + + slog.Info("shutting down...") + cancelBg() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := srv.Shutdown(ctx); err != nil { + slog.Error("forced shutdown", "error", err) + } + slog.Info("server stopped") +} diff --git a/backend/middleware/middleware.go b/backend/middleware/middleware.go new file mode 100644 index 0000000..fc7e28e --- /dev/null +++ b/backend/middleware/middleware.go @@ -0,0 +1,57 @@ +package middleware + +import ( + "log/slog" + "net/http" + "strings" + "time" + + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" +) + +func Setup(r *gin.Engine, mode string, corsOrigins string) { + r.Use(gin.CustomRecovery(func(c *gin.Context, err any) { + slog.Error("panic recovered", "error", err, "path", c.Request.URL.Path) + c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"}) + })) + + origins := parseCORSOrigins(corsOrigins, mode) + if len(origins) > 0 { + r.Use(cors.New(cors.Config{ + AllowOrigins: origins, + AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, + AllowHeaders: []string{"Origin", "Content-Type", "Accept"}, + AllowCredentials: true, + MaxAge: 12 * time.Hour, + })) + } + + r.Use(gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string { + slog.Info("request", + "method", params.Method, + "path", params.Path, + "status", params.StatusCode, + "latency", params.Latency.String(), + ) + return "" + })) +} + +func parseCORSOrigins(raw, mode string) []string { + raw = strings.TrimSpace(raw) + if raw == "" { + if mode == "dev" { + return []string{"http://localhost:5173", "http://127.0.0.1:5173"} + } + return nil + } + parts := strings.Split(raw, ",") + out := make([]string, 0, len(parts)) + for _, p := range parts { + if v := strings.TrimSpace(p); v != "" { + out = append(out, v) + } + } + return out +} diff --git a/backend/model/account.go b/backend/model/account.go new file mode 100644 index 0000000..8d8f2bf --- /dev/null +++ b/backend/model/account.go @@ -0,0 +1,53 @@ +package model + +type Account struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Balance int64 `json:"balance"` // 开账初值(手工录入) + CurrentBalance int64 `json:"current_balance"` // = balance + 历史流水净额(实时派生) + BankName string `json:"bank_name"` + CardNumber string `json:"card_number"` + BranchName string `json:"branch_name"` + Note string `json:"note"` + IsActive bool `json:"is_active"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateAccountRequest struct { + Name string `json:"name"` + Type string `json:"type"` + Balance int64 `json:"balance"` + BankName string `json:"bank_name"` + CardNumber string `json:"card_number"` + BranchName string `json:"branch_name"` + Note string `json:"note"` +} + +type UpdateAccountRequest struct { + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Balance *int64 `json:"balance,omitempty"` + BankName *string `json:"bank_name,omitempty"` + CardNumber *string `json:"card_number,omitempty"` + BranchName *string `json:"branch_name,omitempty"` + Note *string `json:"note,omitempty"` + IsActive *bool `json:"is_active,omitempty"` +} + +type ReconcileAccountRequest struct { + ActualBalance int64 `json:"actual_balance"` + Note string `json:"note"` + CreateAdjustment bool `json:"create_adjustment"` +} +type AccountReconciliation struct { + ID int64 `json:"id"` + AccountID int64 `json:"account_id"` + SystemBalance int64 `json:"system_balance"` + ActualBalance int64 `json:"actual_balance"` + Difference int64 `json:"difference"` + TransactionID *int64 `json:"transaction_id"` + Note string `json:"note"` + CreatedAt string `json:"created_at"` +} diff --git a/backend/model/asset.go b/backend/model/asset.go new file mode 100644 index 0000000..32202c9 --- /dev/null +++ b/backend/model/asset.go @@ -0,0 +1,80 @@ +package model + +type Asset struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Value int64 `json:"value"` // 绑定账户时为派生值;手工资产为录入值 + AccountID *int64 `json:"account_id"` // 若不为 NULL,value 由该账户的 current_balance 派生 + AccountName string `json:"account_name"` // 仅响应字段 + IsDerived bool `json:"is_derived"` // 仅响应字段:account_id 是否绑定 + Note string `json:"note"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateAssetRequest struct { + Name string `json:"name"` + Type string `json:"type"` + Value int64 `json:"value"` + AccountID *int64 `json:"account_id,omitempty"` + Note string `json:"note"` +} + +type UpdateAssetRequest struct { + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Value *int64 `json:"value,omitempty"` + AccountID NullableInt64 `json:"account_id,omitempty"` + Note *string `json:"note,omitempty"` +} + +type Liability struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Principal int64 `json:"principal"` + InterestRate float64 `json:"interest_rate"` + MonthlyPayment int64 `json:"monthly_payment"` + RemainingTerms int `json:"remaining_terms"` + Note string `json:"note"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateLiabilityRequest struct { + Name string `json:"name"` + Type string `json:"type"` + Principal int64 `json:"principal"` + InterestRate float64 `json:"interest_rate"` + MonthlyPayment int64 `json:"monthly_payment"` + RemainingTerms int `json:"remaining_terms"` + Note string `json:"note"` +} + +type UpdateLiabilityRequest struct { + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Principal *int64 `json:"principal,omitempty"` + InterestRate *float64 `json:"interest_rate,omitempty"` + MonthlyPayment *int64 `json:"monthly_payment,omitempty"` + RemainingTerms *int `json:"remaining_terms,omitempty"` + Note *string `json:"note,omitempty"` +} + +type NetWorthSummary struct { + TotalAssets int64 `json:"total_assets"` // assets 表手工录入项汇总 + TotalDebt int64 `json:"total_debt"` // liabilities 表手工录入项汇总 + LiquidAssets int64 `json:"liquid_assets"` // 由活跃账户当前余额派生:非信用卡且 current_balance > 0 + LiquidDebt int64 `json:"liquid_debt"` // 由活跃账户当前余额派生:信用卡且 current_balance < 0 时的欠款绝对值 + NetWorth int64 `json:"net_worth"` // = total_assets + liquid_assets - total_debt - liquid_debt +} + +type AssetSnapshot struct { + ID int64 `json:"id"` + Date string `json:"date"` + TotalAsset int64 `json:"total_asset"` + TotalDebt int64 `json:"total_debt"` + NetWorth int64 `json:"net_worth"` + CreatedAt string `json:"created_at"` +} diff --git a/backend/model/backup.go b/backend/model/backup.go new file mode 100644 index 0000000..3f57b1d --- /dev/null +++ b/backend/model/backup.go @@ -0,0 +1,8 @@ +package model + +type BackupStatus struct { + Directory string `json:"directory"` + LastBackup string `json:"last_backup"` + LastBackupAt string `json:"last_backup_at"` + RetentionDays int `json:"retention_days"` +} diff --git a/backend/model/budget.go b/backend/model/budget.go new file mode 100644 index 0000000..da6cb37 --- /dev/null +++ b/backend/model/budget.go @@ -0,0 +1,41 @@ +package model + +type Budget struct { + ID int64 `json:"id"` + Year int `json:"year"` + Month *int `json:"month"` + CategoryID *int64 `json:"category_id"` + CategoryName string `json:"category_name"` + CategoryType string `json:"category_type"` + Amount int64 `json:"amount"` + Spent int64 `json:"spent"` + Remaining int64 `json:"remaining"` + UsagePercent float64 `json:"usage_percent"` + Note string `json:"note"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type UpsertBudgetRequest struct { + Year int `json:"year"` + Month *int `json:"month"` + CategoryID *int64 `json:"category_id"` + Amount int64 `json:"amount"` + Note string `json:"note"` +} + +type BudgetOverview struct { + Year int `json:"year"` + Month int `json:"month"` + AnnualBudget int64 `json:"annual_budget"` + AnnualSpent int64 `json:"annual_spent"` + AnnualRemaining int64 `json:"annual_remaining"` + AnnualUsagePercent float64 `json:"annual_usage_percent"` + MonthlyBudget int64 `json:"monthly_budget"` + MonthlySpent int64 `json:"monthly_spent"` + MonthlyBudgetedSpent int64 `json:"monthly_budgeted_spent"` + MonthlyUnbudgetedSpent int64 `json:"monthly_unbudgeted_spent"` + MonthlyRemaining int64 `json:"monthly_remaining"` + MonthlyUsagePercent float64 `json:"monthly_usage_percent"` + Items []Budget `json:"items"` +} diff --git a/backend/model/category.go b/backend/model/category.go new file mode 100644 index 0000000..b119606 --- /dev/null +++ b/backend/model/category.go @@ -0,0 +1,29 @@ +package model + +type Category struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + ParentID *int64 `json:"parent_id"` + SortOrder int `json:"sort_order"` + Keywords string `json:"keywords"` + IsActive bool `json:"is_active"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateCategoryRequest struct { + Name string `json:"name"` + Type string `json:"type"` + ParentID *int64 `json:"parent_id,omitempty"` + SortOrder int `json:"sort_order"` + Keywords string `json:"keywords"` +} + +type UpdateCategoryRequest struct { + Name *string `json:"name,omitempty"` + ParentID NullableInt64 `json:"parent_id,omitempty"` + SortOrder *int `json:"sort_order,omitempty"` + Keywords *string `json:"keywords,omitempty"` + IsActive *bool `json:"is_active,omitempty"` +} diff --git a/backend/model/dashboard.go b/backend/model/dashboard.go new file mode 100644 index 0000000..3f197e4 --- /dev/null +++ b/backend/model/dashboard.go @@ -0,0 +1,8 @@ +package model + +type DashboardSummary struct { + Income int64 `json:"income"` + Expense int64 `json:"expense"` + Balance int64 `json:"balance"` + TransactionCount int64 `json:"transaction_count"` +} diff --git a/backend/model/lifecycle.go b/backend/model/lifecycle.go new file mode 100644 index 0000000..a4f7378 --- /dev/null +++ b/backend/model/lifecycle.go @@ -0,0 +1,29 @@ +package model + +type LifecycleEvent struct { + ID int64 `json:"id"` + Year int `json:"year"` + MemberID *int64 `json:"member_id"` + MemberName string `json:"member_name"` + Event string `json:"event"` + EstimatedCost int64 `json:"estimated_cost"` + Note string `json:"note"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateLifecycleEventRequest struct { + Year int `json:"year"` + MemberID *int64 `json:"member_id"` + Event string `json:"event"` + EstimatedCost int64 `json:"estimated_cost"` + Note string `json:"note"` +} + +type UpdateLifecycleEventRequest struct { + Year *int `json:"year,omitempty"` + MemberID NullableInt64 `json:"member_id,omitempty"` + Event *string `json:"event,omitempty"` + EstimatedCost *int64 `json:"estimated_cost,omitempty"` + Note *string `json:"note,omitempty"` +} diff --git a/backend/model/member.go b/backend/model/member.go new file mode 100644 index 0000000..b7c00f2 --- /dev/null +++ b/backend/model/member.go @@ -0,0 +1,25 @@ +package model + +type Member struct { + ID int64 `json:"id"` + Name string `json:"name"` + Relation string `json:"relation"` + Birthday string `json:"birthday"` + Phone string `json:"phone"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateMemberRequest struct { + Name string `json:"name"` + Relation string `json:"relation"` + Birthday string `json:"birthday"` + Phone string `json:"phone"` +} + +type UpdateMemberRequest struct { + Name *string `json:"name,omitempty"` + Relation *string `json:"relation,omitempty"` + Birthday *string `json:"birthday,omitempty"` + Phone *string `json:"phone,omitempty"` +} diff --git a/backend/model/nullable.go b/backend/model/nullable.go new file mode 100644 index 0000000..ce00d2a --- /dev/null +++ b/backend/model/nullable.go @@ -0,0 +1,29 @@ +package model + +import ( + "bytes" + "encoding/json" +) + +type NullableInt64 struct { + Set bool + Valid bool + Value int64 +} + +func (n *NullableInt64) UnmarshalJSON(data []byte) error { + n.Set = true + if bytes.Equal(data, []byte("null")) { + n.Valid = false + n.Value = 0 + return nil + } + + var value int64 + if err := json.Unmarshal(data, &value); err != nil { + return err + } + n.Valid = true + n.Value = value + return nil +} diff --git a/backend/model/policy.go b/backend/model/policy.go new file mode 100644 index 0000000..112c858 --- /dev/null +++ b/backend/model/policy.go @@ -0,0 +1,82 @@ +package model + +type Policy struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + InsuredPerson string `json:"insured_person"` + Premium int64 `json:"premium"` + CoverageAmount int64 `json:"coverage_amount"` + StartDate string `json:"start_date"` + EndDate string `json:"end_date"` + PaymentFrequency string `json:"payment_frequency"` + NextPaymentDate string `json:"next_payment_date"` + PaymentTermEnd string `json:"payment_term_end"` + Beneficiary string `json:"beneficiary"` + Status string `json:"status"` + Note string `json:"note"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreatePolicyRequest struct { + Name string `json:"name"` + Type string `json:"type"` + InsuredPerson string `json:"insured_person"` + Premium int64 `json:"premium"` + CoverageAmount int64 `json:"coverage_amount"` + StartDate string `json:"start_date"` + EndDate string `json:"end_date"` + PaymentFrequency string `json:"payment_frequency"` + NextPaymentDate string `json:"next_payment_date"` + PaymentTermEnd string `json:"payment_term_end"` + Beneficiary string `json:"beneficiary"` + Status string `json:"status"` + Note string `json:"note"` +} + +type UpdatePolicyRequest struct { + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + InsuredPerson *string `json:"insured_person,omitempty"` + Premium *int64 `json:"premium,omitempty"` + CoverageAmount *int64 `json:"coverage_amount,omitempty"` + StartDate *string `json:"start_date,omitempty"` + EndDate *string `json:"end_date,omitempty"` + PaymentFrequency *string `json:"payment_frequency,omitempty"` + NextPaymentDate *string `json:"next_payment_date,omitempty"` + PaymentTermEnd *string `json:"payment_term_end,omitempty"` + Beneficiary *string `json:"beneficiary,omitempty"` + Status *string `json:"status,omitempty"` + Note *string `json:"note,omitempty"` +} + +type PolicyAnnualSummary struct { + Year int `json:"year"` + TotalPremium int64 `json:"total_premium"` + PolicyCount int `json:"policy_count"` +} + +type PolicyPayment struct { + ID int64 `json:"id"` + PolicyID int64 `json:"policy_id"` + PolicyName string `json:"policy_name"` + DueDate string `json:"due_date"` + Amount int64 `json:"amount"` + Status string `json:"status"` + PaidDate string `json:"paid_date"` + Note string `json:"note"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreatePolicyPaymentRequest struct { + DueDate string `json:"due_date"` + Amount int64 `json:"amount"` + Note string `json:"note"` +} +type UpdatePolicyPaymentRequest struct { + Status string `json:"status"` + PaidDate string `json:"paid_date"` + Note *string `json:"note,omitempty"` +} diff --git a/backend/model/report.go b/backend/model/report.go new file mode 100644 index 0000000..e0a3837 --- /dev/null +++ b/backend/model/report.go @@ -0,0 +1,23 @@ +package model + +type CategoryRankingItem struct { + CategoryID int64 `json:"category_id"` + CategoryName string `json:"category_name"` + CategoryIsActive bool `json:"category_is_active"` + Amount int64 `json:"amount"` + Percent float64 `json:"percent"` +} + +type TrendItem struct { + Month string `json:"month"` + Income int64 `json:"income"` + Expense int64 `json:"expense"` + Balance int64 `json:"balance"` +} + +type ReportOverview struct { + Year int `json:"year"` + Month int `json:"month"` + CategoryRanking []CategoryRankingItem `json:"category_ranking"` + Trend []TrendItem `json:"trend"` +} diff --git a/backend/model/transaction.go b/backend/model/transaction.go new file mode 100644 index 0000000..a23e0b1 --- /dev/null +++ b/backend/model/transaction.go @@ -0,0 +1,145 @@ +package model + +type Transaction struct { + ID int64 `json:"id"` + Type string `json:"type"` + Amount int64 `json:"amount"` + CategoryID *int64 `json:"category_id"` + AccountID *int64 `json:"account_id"` + ToAccountID *int64 `json:"to_account_id"` + MemberID *int64 `json:"member_id"` + Date string `json:"date"` + Description string `json:"description"` + Counterparty string `json:"counterparty"` + ImportBatchID *int64 `json:"import_batch_id"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type TransactionListItem struct { + ID int64 `json:"id"` + Type string `json:"type"` + Amount int64 `json:"amount"` + CategoryID *int64 `json:"category_id"` + CategoryName string `json:"category_name"` + CategoryIsActive bool `json:"category_is_active"` + AccountID *int64 `json:"account_id"` + AccountName string `json:"account_name"` + ToAccountID *int64 `json:"to_account_id"` + ToAccountName string `json:"to_account_name"` + MemberID *int64 `json:"member_id"` + MemberName string `json:"member_name"` + Date string `json:"date"` + Description string `json:"description"` + Counterparty string `json:"counterparty"` + ImportBatchID *int64 `json:"import_batch_id"` + ImportFilename string `json:"import_filename"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type CreateTransactionRequest struct { + Type string `json:"type"` + Amount int64 `json:"amount"` + CategoryID *int64 `json:"category_id,omitempty"` + AccountID *int64 `json:"account_id,omitempty"` + ToAccountID *int64 `json:"to_account_id,omitempty"` + MemberID *int64 `json:"member_id,omitempty"` + Date string `json:"date"` + Description string `json:"description"` + Counterparty string `json:"counterparty"` +} + +type UpdateTransactionRequest struct { + Type *string `json:"type,omitempty"` + Amount *int64 `json:"amount,omitempty"` + CategoryID NullableInt64 `json:"category_id,omitempty"` + AccountID NullableInt64 `json:"account_id,omitempty"` + ToAccountID NullableInt64 `json:"to_account_id,omitempty"` + MemberID NullableInt64 `json:"member_id,omitempty"` + Date *string `json:"date,omitempty"` + Description *string `json:"description,omitempty"` + Counterparty *string `json:"counterparty,omitempty"` +} + +type TransactionListRequest struct { + Month string + CategoryID *int64 + Type string + Keyword string + DateFrom string + DateTo string + MemberID *int64 + AccountID *int64 + ImportBatchID *int64 + Page int + PageSize int +} + +type TransactionListResponse struct { + Items []TransactionListItem `json:"items"` + Total int `json:"total"` + Page int `json:"page"` + PageSize int `json:"page_size"` +} + +type ImportTransactionsRequest struct { + Filename string + Content []byte + SourceKind string // cmb_debit / cmb_credit / alipay / wechat + BankName string + CardType string + AccountID *int64 + CategoryOverrides map[string]int64 +} + +type ImportTransactionsResult struct { + ImportedCount int `json:"imported_count"` + SkippedCount int `json:"skipped_count"` + AccountID int64 `json:"account_id"` + ImportBatchID int64 `json:"import_batch_id"` + Items []TransactionListItem `json:"items"` +} + +// ImportPreviewItem 导入预览中的一条解析结果(尚未写入数据库)。 +type ImportPreviewItem struct { + SourceKey string `json:"source_key"` + Type string `json:"type"` + Amount int64 `json:"amount"` + Date string `json:"date"` + Description string `json:"description"` + Counterparty string `json:"counterparty"` + CategoryName string `json:"category_name"` + CategoryID int64 `json:"category_id"` + CategoryReason string `json:"category_reason"` + Status string `json:"status"` // new | duplicate_database | duplicate_file +} + +type ImportPreviewResult struct { + TotalCount int `json:"total_count"` + NewCount int `json:"new_count"` + DuplicateCount int `json:"duplicate_count"` + AccountName string `json:"account_name"` + WillCreateAccount bool `json:"will_create_account"` + Items []ImportPreviewItem `json:"items"` +} + +type DeleteTransactionsRequest struct { + IDs []int64 `json:"ids"` +} + +type DeleteTransactionsResult struct { + DeletedCount int64 `json:"deleted_count"` +} + +type ImportBatch struct { + ID int64 `json:"id"` + Filename string `json:"filename"` + BankName string `json:"bank_name"` + CardType string `json:"card_type"` + AccountID *int64 `json:"account_id"` + AccountName string `json:"account_name"` + ImportedCount int `json:"imported_count"` + SkippedCount int `json:"skipped_count"` + CreatedAt string `json:"created_at"` +} diff --git a/backend/service/account.go b/backend/service/account.go new file mode 100644 index 0000000..11dd05c --- /dev/null +++ b/backend/service/account.go @@ -0,0 +1,254 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "household-book/model" +) + +type AccountService struct { + db *sql.DB +} + +func (s *AccountService) Reconcile(ctx context.Context, id int64, req model.ReconcileAccountRequest) (*model.AccountReconciliation, error) { + account, err := s.GetByID(ctx, id) + if err != nil { + return nil, err + } + diff := req.ActualBalance - account.CurrentBalance + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + var transactionID *int64 + if req.CreateAdjustment && diff != 0 { + typ := "income" + amount := diff + if amount < 0 { + typ = "expense" + amount = -amount + } + var categoryID int64 + err = tx.QueryRowContext(ctx, `SELECT id FROM categories WHERE type=? AND parent_id IS NOT NULL AND is_active=1 ORDER BY CASE WHEN name='其他' THEN 0 ELSE 1 END,sort_order,id LIMIT 1`, typ).Scan(&categoryID) + if err != nil { + return nil, err + } + r, e := tx.ExecContext(ctx, `INSERT INTO transactions(type,amount,category_id,account_id,date,description,counterparty) VALUES(?,?,?,?,?,?,?)`, typ, amount, categoryID, id, time.Now().Format("2006-01-02"), "账户对账余额调整", "系统对账") + if e != nil { + return nil, e + } + tid, _ := r.LastInsertId() + transactionID = &tid + } + r, err := tx.ExecContext(ctx, `INSERT INTO account_reconciliations(account_id,system_balance,actual_balance,difference,transaction_id,note) VALUES(?,?,?,?,?,?)`, id, account.CurrentBalance, req.ActualBalance, diff, transactionID, req.Note) + if err != nil { + return nil, err + } + rid, _ := r.LastInsertId() + if err = tx.Commit(); err != nil { + return nil, err + } + return &model.AccountReconciliation{ID: rid, AccountID: id, SystemBalance: account.CurrentBalance, ActualBalance: req.ActualBalance, Difference: diff, TransactionID: transactionID, Note: req.Note}, nil +} + +func (s *AccountService) ListReconciliations(ctx context.Context, id int64) ([]model.AccountReconciliation, error) { + rows, err := s.db.QueryContext(ctx, `SELECT id,account_id,system_balance,actual_balance,difference,transaction_id,note,created_at FROM account_reconciliations WHERE account_id=? ORDER BY id DESC`, id) + if err != nil { + return nil, err + } + defer rows.Close() + items := []model.AccountReconciliation{} + for rows.Next() { + var v model.AccountReconciliation + if err := rows.Scan(&v.ID, &v.AccountID, &v.SystemBalance, &v.ActualBalance, &v.Difference, &v.TransactionID, &v.Note, &v.CreatedAt); err != nil { + return nil, err + } + items = append(items, v) + } + return items, rows.Err() +} + +func NewAccountService(db *sql.DB) *AccountService { + return &AccountService{db: db} +} + +func (s *AccountService) List(ctx context.Context) ([]model.Account, error) { + rows, err := s.db.QueryContext(ctx, accountSelectSQL()+" ORDER BY a.id") + if err != nil { + return nil, fmt.Errorf("query accounts: %w", err) + } + defer rows.Close() + + var list []model.Account + for rows.Next() { + var a model.Account + var isActive int + if err := rows.Scan( + &a.ID, &a.Name, &a.Type, &a.Balance, &a.CurrentBalance, + &a.BankName, &a.CardNumber, &a.BranchName, &a.Note, + &isActive, &a.CreatedAt, &a.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan account: %w", err) + } + a.IsActive = isActive == 1 + list = append(list, a) + } + if list == nil { + list = []model.Account{} + } + return list, rows.Err() +} + +func (s *AccountService) GetByID(ctx context.Context, id int64) (*model.Account, error) { + var a model.Account + var isActive int + err := s.db.QueryRowContext(ctx, accountSelectSQL()+" WHERE a.id = ?", id).Scan( + &a.ID, &a.Name, &a.Type, &a.Balance, &a.CurrentBalance, + &a.BankName, &a.CardNumber, &a.BranchName, &a.Note, + &isActive, &a.CreatedAt, &a.UpdatedAt, + ) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query account: %w", err) + } + a.IsActive = isActive == 1 + return &a, nil +} + +func (s *AccountService) Create(ctx context.Context, req model.CreateAccountRequest) (*model.Account, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + result, err := tx.ExecContext(ctx, + `INSERT INTO accounts (name, type, balance, bank_name, card_number, branch_name, note) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + req.Name, req.Type, req.Balance, req.BankName, req.CardNumber, req.BranchName, req.Note) + if err != nil { + return nil, fmt.Errorf("insert account: %w", err) + } + id, _ := result.LastInsertId() + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *AccountService) Update(ctx context.Context, id int64, req model.UpdateAccountRequest) (*model.Account, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + var sets []string + var args []any + + if req.Name != nil { + sets = append(sets, "name = ?") + args = append(args, *req.Name) + } + if req.Type != nil { + sets = append(sets, "type = ?") + args = append(args, *req.Type) + } + if req.Balance != nil { + sets = append(sets, "balance = ?") + args = append(args, *req.Balance) + } + if req.BankName != nil { + sets = append(sets, "bank_name = ?") + args = append(args, *req.BankName) + } + if req.CardNumber != nil { + sets = append(sets, "card_number = ?") + args = append(args, *req.CardNumber) + } + if req.BranchName != nil { + sets = append(sets, "branch_name = ?") + args = append(args, *req.BranchName) + } + if req.Note != nil { + sets = append(sets, "note = ?") + args = append(args, *req.Note) + } + if req.IsActive != nil { + isActive := 0 + if *req.IsActive { + isActive = 1 + } + sets = append(sets, "is_active = ?") + args = append(args, isActive) + } + + if len(sets) == 0 { + return s.GetByID(ctx, id) + } + + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + + query := "UPDATE accounts SET " + strings.Join(sets, ", ") + " WHERE id = ?" + result, err := tx.ExecContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("update account: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, fmt.Errorf("check updated account: %w", err) + } else if affected == 0 { + return nil, ErrNotFound + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *AccountService) Delete(ctx context.Context, id int64) error { + count, err := countAccountReferences(ctx, s.db, id) + if err != nil { + return err + } + if count > 0 { + return ErrHasTransactions + } + + result, err := s.db.ExecContext(ctx, "DELETE FROM accounts WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return fmt.Errorf("check deleted account: %w", err) + } else if affected == 0 { + return ErrNotFound + } + return nil +} + +func countAccountReferences(ctx context.Context, q sqlQueryer, accountID int64) (int, error) { + var count int + if err := q.QueryRowContext(ctx, ` + SELECT + (SELECT COUNT(*) FROM transactions WHERE account_id = ? OR to_account_id = ?) + + (SELECT COUNT(*) FROM assets WHERE account_id = ?) + + (SELECT COUNT(*) FROM import_batches WHERE account_id = ?) + + (SELECT COUNT(*) FROM account_reconciliations WHERE account_id = ?)`, + accountID, accountID, accountID, accountID, accountID, + ).Scan(&count); err != nil { + return 0, fmt.Errorf("check account references: %w", err) + } + return count, nil +} diff --git a/backend/service/account_delete_test.go b/backend/service/account_delete_test.go new file mode 100644 index 0000000..a01b284 --- /dev/null +++ b/backend/service/account_delete_test.go @@ -0,0 +1,106 @@ +package service + +import ( + "context" + "database/sql" + "errors" + "path/filepath" + "testing" + + database "household-book/db" +) + +func TestDeleteAccountRejectsReconciliationReference(t *testing.T) { + store := setupAccountReferenceTestDB(t) + if _, err := store.Exec(` + INSERT INTO accounts (id, name, type) VALUES (1, '现金', 'cash'); + INSERT INTO account_reconciliations + (account_id, system_balance, actual_balance, difference) + VALUES (1, 100, 100, 0); + `); err != nil { + t.Fatal(err) + } + + err := NewAccountService(store).Delete(context.Background(), 1) + if !errors.Is(err, ErrHasTransactions) { + t.Fatalf("delete error=%v, want ErrHasTransactions", err) + } +} + +func TestDeleteAccountRejectsTransferTargetReference(t *testing.T) { + store := setupAccountReferenceTestDB(t) + if _, err := store.Exec(` + INSERT INTO accounts (id, name, type) VALUES + (1, '转入账户', 'cash'), + (2, '转出账户', 'cash'); + INSERT INTO transactions (type, amount, account_id, to_account_id, date) + VALUES ('transfer', 100, 2, 1, '2026-08-09'); + `); err != nil { + t.Fatal(err) + } + + err := NewAccountService(store).Delete(context.Background(), 1) + if !errors.Is(err, ErrHasTransactions) { + t.Fatalf("delete error=%v, want ErrHasTransactions", err) + } +} + +func TestDeleteAccountWithoutReferencesSucceeds(t *testing.T) { + store := setupAccountReferenceTestDB(t) + if _, err := store.Exec("INSERT INTO accounts (id, name, type) VALUES (1, '现金', 'cash')"); err != nil { + t.Fatal(err) + } + + if err := NewAccountService(store).Delete(context.Background(), 1); err != nil { + t.Fatalf("delete unreferenced account: %v", err) + } + var count int + if err := store.QueryRow("SELECT COUNT(*) FROM accounts WHERE id = 1").Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("account count=%d, want 0", count) + } +} + +func TestCleanupAutoImportAccountKeepsReferencedAccount(t *testing.T) { + store := setupAccountReferenceTestDB(t) + if _, err := store.Exec(` + INSERT INTO accounts (id, name, type, note) + VALUES (1, '导入账户', 'debit_card', '由收支导入自动创建'); + INSERT INTO account_reconciliations + (account_id, system_balance, actual_balance, difference) + VALUES (1, 100, 100, 0); + `); err != nil { + t.Fatal(err) + } + + tx, err := store.Begin() + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := NewTransactionService(store).cleanupAutoImportAccount(context.Background(), tx, 1); err != nil { + t.Fatal(err) + } + var count int + if err := tx.QueryRow("SELECT COUNT(*) FROM accounts WHERE id = 1").Scan(&count); err != nil { + t.Fatal(err) + } + if count != 1 { + t.Fatalf("account count=%d, want 1", count) + } +} + +func setupAccountReferenceTestDB(t *testing.T) *sql.DB { + t.Helper() + store, err := database.Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + if err := database.RunMigrations(store); err != nil { + t.Fatal(err) + } + return store +} diff --git a/backend/service/asset.go b/backend/service/asset.go new file mode 100644 index 0000000..fcce4a6 --- /dev/null +++ b/backend/service/asset.go @@ -0,0 +1,369 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "log/slog" + "strings" + "time" + + "household-book/model" +) + +type AssetService struct{ db *sql.DB } + +func NewAssetService(db *sql.DB) *AssetService { return &AssetService{db: db} } + +func scanAsset(row interface { + Scan(...any) error +}) (model.Asset, error) { + var a model.Asset + var boundBalance int64 + if err := row.Scan(&a.ID, &a.Name, &a.Type, &a.Value, &a.AccountID, &a.AccountName, &boundBalance, &a.Note, &a.CreatedAt, &a.UpdatedAt); err != nil { + return a, err + } + if a.AccountID != nil { + a.IsDerived = true + a.Value = boundBalance + } + return a, nil +} + +func (s *AssetService) ListAssets(ctx context.Context) ([]model.Asset, error) { + rows, err := s.db.QueryContext(ctx, assetSelectSQL()+" ORDER BY a.type, a.id") + if err != nil { + return nil, fmt.Errorf("query assets: %w", err) + } + defer rows.Close() + var list []model.Asset + for rows.Next() { + a, err := scanAsset(rows) + if err != nil { + return nil, fmt.Errorf("scan asset: %w", err) + } + list = append(list, a) + } + if list == nil { + list = []model.Asset{} + } + return list, rows.Err() +} + +func (s *AssetService) CreateAsset(ctx context.Context, req model.CreateAssetRequest) (*model.Asset, error) { + value := req.Value + if req.AccountID != nil { + if err := s.ensureAccountNotBound(ctx, *req.AccountID, 0); err != nil { + return nil, err + } + value = 0 // 绑定账户时实际值由派生计算,存 0 以避免误用 + } + result, err := s.db.ExecContext(ctx, + "INSERT INTO assets (name, type, value, account_id, note) VALUES (?, ?, ?, ?, ?)", + req.Name, req.Type, value, req.AccountID, req.Note) + if err != nil { + if isUniqueConstraintError(err) { + return nil, ErrAccountAlreadyBound + } + return nil, fmt.Errorf("insert asset: %w", err) + } + id, _ := result.LastInsertId() + return s.GetAsset(ctx, id) +} + +func (s *AssetService) GetAsset(ctx context.Context, id int64) (*model.Asset, error) { + a, err := scanAsset(s.db.QueryRowContext(ctx, assetSelectSQL()+" WHERE a.id = ?", id)) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query asset: %w", err) + } + return &a, nil +} + +func (s *AssetService) UpdateAsset(ctx context.Context, id int64, req model.UpdateAssetRequest) (*model.Asset, error) { + var sets []string + var args []any + if req.Name != nil { + sets = append(sets, "name = ?") + args = append(args, *req.Name) + } + if req.Type != nil { + sets = append(sets, "type = ?") + args = append(args, *req.Type) + } + if req.AccountID.Set { + sets = append(sets, "account_id = ?") + if req.AccountID.Valid { + if err := s.ensureAccountNotBound(ctx, req.AccountID.Value, id); err != nil { + return nil, err + } + args = append(args, req.AccountID.Value) + // 绑定账户时清零 value,避免误展示 + sets = append(sets, "value = 0") + } else { + args = append(args, nil) + } + } + if req.Value != nil { + // 仅在未绑定时才允许更新 value(如果同时传了 AccountID 绑定,上面已经清零) + if !(req.AccountID.Set && req.AccountID.Valid) { + sets = append(sets, "value = ?") + args = append(args, *req.Value) + } + } + if req.Note != nil { + sets = append(sets, "note = ?") + args = append(args, *req.Note) + } + if len(sets) == 0 { + return s.GetAsset(ctx, id) + } + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + result, err := s.db.ExecContext(ctx, "UPDATE assets SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...) + if err != nil { + if isUniqueConstraintError(err) { + return nil, ErrAccountAlreadyBound + } + return nil, fmt.Errorf("update asset: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, err + } else if affected == 0 { + return nil, ErrNotFound + } + return s.GetAsset(ctx, id) +} + +func (s *AssetService) DeleteAsset(ctx context.Context, id int64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM assets WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return err + } else if affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *AssetService) ListLiabilities(ctx context.Context) ([]model.Liability, error) { + rows, err := s.db.QueryContext(ctx, "SELECT id, name, type, principal, interest_rate, monthly_payment, remaining_terms, note, created_at, updated_at FROM liabilities ORDER BY type, id") + if err != nil { + return nil, fmt.Errorf("query liabilities: %w", err) + } + defer rows.Close() + var list []model.Liability + for rows.Next() { + var l model.Liability + if err := rows.Scan(&l.ID, &l.Name, &l.Type, &l.Principal, &l.InterestRate, &l.MonthlyPayment, &l.RemainingTerms, &l.Note, &l.CreatedAt, &l.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan liability: %w", err) + } + list = append(list, l) + } + if list == nil { + list = []model.Liability{} + } + return list, rows.Err() +} + +func (s *AssetService) CreateLiability(ctx context.Context, req model.CreateLiabilityRequest) (*model.Liability, error) { + result, err := s.db.ExecContext(ctx, `INSERT INTO liabilities (name, type, principal, interest_rate, monthly_payment, remaining_terms, note) + VALUES (?, ?, ?, ?, ?, ?, ?)`, req.Name, req.Type, req.Principal, req.InterestRate, req.MonthlyPayment, req.RemainingTerms, req.Note) + if err != nil { + return nil, fmt.Errorf("insert liability: %w", err) + } + id, _ := result.LastInsertId() + return s.GetLiability(ctx, id) +} + +func (s *AssetService) GetLiability(ctx context.Context, id int64) (*model.Liability, error) { + var l model.Liability + err := s.db.QueryRowContext(ctx, "SELECT id, name, type, principal, interest_rate, monthly_payment, remaining_terms, note, created_at, updated_at FROM liabilities WHERE id = ?", id). + Scan(&l.ID, &l.Name, &l.Type, &l.Principal, &l.InterestRate, &l.MonthlyPayment, &l.RemainingTerms, &l.Note, &l.CreatedAt, &l.UpdatedAt) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query liability: %w", err) + } + return &l, nil +} + +func (s *AssetService) UpdateLiability(ctx context.Context, id int64, req model.UpdateLiabilityRequest) (*model.Liability, error) { + var sets []string + var args []any + if req.Name != nil { + sets = append(sets, "name = ?") + args = append(args, *req.Name) + } + if req.Type != nil { + sets = append(sets, "type = ?") + args = append(args, *req.Type) + } + if req.Principal != nil { + sets = append(sets, "principal = ?") + args = append(args, *req.Principal) + } + if req.InterestRate != nil { + sets = append(sets, "interest_rate = ?") + args = append(args, *req.InterestRate) + } + if req.MonthlyPayment != nil { + sets = append(sets, "monthly_payment = ?") + args = append(args, *req.MonthlyPayment) + } + if req.RemainingTerms != nil { + sets = append(sets, "remaining_terms = ?") + args = append(args, *req.RemainingTerms) + } + if req.Note != nil { + sets = append(sets, "note = ?") + args = append(args, *req.Note) + } + if len(sets) == 0 { + return s.GetLiability(ctx, id) + } + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + result, err := s.db.ExecContext(ctx, "UPDATE liabilities SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...) + if err != nil { + return nil, fmt.Errorf("update liability: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, err + } else if affected == 0 { + return nil, ErrNotFound + } + return s.GetLiability(ctx, id) +} + +func (s *AssetService) DeleteLiability(ctx context.Context, id int64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM liabilities WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return err + } else if affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *AssetService) NetWorth(ctx context.Context) (*model.NetWorthSummary, error) { + summary, err := s.computeNetWorth(ctx) + if err != nil { + return nil, err + } + return summary, nil +} + +// ListSnapshots 返回按日期升序的所有净值快照。 +func (s *AssetService) ListSnapshots(ctx context.Context) ([]model.AssetSnapshot, error) { + rows, err := s.db.QueryContext(ctx, + "SELECT id, date, total_asset, total_debt, net_worth, created_at FROM asset_snapshots ORDER BY date ASC, id ASC") + if err != nil { + return nil, fmt.Errorf("query asset snapshots: %w", err) + } + defer rows.Close() + list := []model.AssetSnapshot{} + for rows.Next() { + var snap model.AssetSnapshot + if err := rows.Scan(&snap.ID, &snap.Date, &snap.TotalAsset, &snap.TotalDebt, &snap.NetWorth, &snap.CreatedAt); err != nil { + return nil, fmt.Errorf("scan snapshot: %w", err) + } + list = append(list, snap) + } + return list, rows.Err() +} + +// EnsureMonthlySnapshot 保存当月最新净值。date 是月份键(每月 1 日), +// 当月重复运行会更新数值,进入下月后旧月份自然冻结。 +func (s *AssetService) EnsureMonthlySnapshot(ctx context.Context, now time.Time) error { + monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) + date := monthStart.Format("2006-01-02") + + summary, err := s.computeNetWorth(ctx) + if err != nil { + return err + } + totalAsset := summary.TotalAssets + summary.LiquidAssets + totalDebt := summary.TotalDebt + summary.LiquidDebt + if _, err := s.db.ExecContext(ctx, + `INSERT INTO asset_snapshots (date, total_asset, total_debt, net_worth) + VALUES (?, ?, ?, ?) + ON CONFLICT(date) DO UPDATE SET + total_asset = excluded.total_asset, + total_debt = excluded.total_debt, + net_worth = excluded.net_worth, + created_at = datetime('now')`, + date, totalAsset, totalDebt, summary.NetWorth, + ); err != nil { + return fmt.Errorf("insert snapshot: %w", err) + } + slog.Info("monthly net worth snapshot refreshed", "month", date[:7], "net_worth", summary.NetWorth) + return nil +} + +// RunSnapshotScheduler 启动后台任务:进程启动时立刻补一条当月快照, +// 之后每 6 小时检查一次(覆盖跨月场景)。ctx 取消时退出。 +func (s *AssetService) RunSnapshotScheduler(ctx context.Context) { + if err := s.EnsureMonthlySnapshot(ctx, time.Now()); err != nil { + slog.Error("initial snapshot failed", "error", err) + } + ticker := time.NewTicker(6 * time.Hour) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + if err := s.EnsureMonthlySnapshot(ctx, t); err != nil { + slog.Error("scheduled snapshot failed", "error", err) + } + } + } +} + +// computeNetWorth 共用给 NetWorth 端点和后台快照任务。 +// +// - TotalAssets:assets 表总和。绑定到账户的资产 value 列存 0,但派生值已通过 List 计算; +// 这里要把所有 assets 的派生 value 加起来,所以用一段 CTE 把账户余额映射回 assets。 +// - LiquidAssets:账户当前余额(非信用卡,正向),且 NOT IN (assets.account_id),避免与上面重复。 +// - LiquidDebt:信用卡账户当前余额为负的绝对值。 +func (s *AssetService) computeNetWorth(ctx context.Context) (*model.NetWorthSummary, error) { + var summary model.NetWorthSummary + if err := s.db.QueryRowContext(ctx, netWorthSQL()).Scan( + &summary.TotalAssets, + &summary.TotalDebt, + &summary.LiquidAssets, + &summary.LiquidDebt, + ); err != nil { + return nil, fmt.Errorf("query net worth: %w", err) + } + + summary.NetWorth = summary.TotalAssets + summary.LiquidAssets - summary.TotalDebt - summary.LiquidDebt + return &summary, nil +} + +func (s *AssetService) ensureAccountNotBound(ctx context.Context, accountID, excludeAssetID int64) error { + query := "SELECT id FROM assets WHERE account_id = ?" + args := []any{accountID} + if excludeAssetID > 0 { + query += " AND id != ?" + args = append(args, excludeAssetID) + } + var existing int64 + err := s.db.QueryRowContext(ctx, query, args...).Scan(&existing) + if err == sql.ErrNoRows { + return nil + } + if err != nil { + return fmt.Errorf("check bound account: %w", err) + } + return ErrAccountAlreadyBound +} diff --git a/backend/service/asset_bind_test.go b/backend/service/asset_bind_test.go new file mode 100644 index 0000000..6109b2b --- /dev/null +++ b/backend/service/asset_bind_test.go @@ -0,0 +1,91 @@ +package service + +import ( + "context" + "database/sql" + "errors" + "testing" + + "household-book/model" + + _ "modernc.org/sqlite" +) + +func TestCreateAssetRejectsDuplicateAccountBinding(t *testing.T) { + db := setupAssetBindTestDB(t) + svc := NewAssetService(db) + ctx := context.Background() + accountID := int64(1) + + _, err := svc.CreateAsset(ctx, model.CreateAssetRequest{ + Name: "储蓄", Type: "deposit", AccountID: &accountID, + }) + if err != nil { + t.Fatalf("first create: %v", err) + } + + _, err = svc.CreateAsset(ctx, model.CreateAssetRequest{ + Name: "重复绑定", Type: "deposit", AccountID: &accountID, + }) + if !errors.Is(err, ErrAccountAlreadyBound) { + t.Fatalf("expected ErrAccountAlreadyBound, got %v", err) + } +} + +func setupAssetBindTestDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + + stmts := []string{ + `CREATE TABLE accounts ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'cash', + balance INTEGER NOT NULL DEFAULT 0, + bank_name TEXT NOT NULL DEFAULT '', + card_number TEXT NOT NULL DEFAULT '', + branch_name TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + is_active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`, + `CREATE TABLE assets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'other', + value INTEGER NOT NULL DEFAULT 0, + account_id INTEGER, + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`, + `CREATE UNIQUE INDEX idx_assets_account_id_unique ON assets(account_id) WHERE account_id IS NOT NULL`, + `CREATE TABLE transactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT NOT NULL, + amount INTEGER NOT NULL, + category_id INTEGER, + account_id INTEGER, + to_account_id INTEGER, + member_id INTEGER, + date TEXT NOT NULL DEFAULT '', + description TEXT NOT NULL DEFAULT '', + counterparty TEXT NOT NULL DEFAULT '', + import_batch_id INTEGER, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`, + `INSERT INTO accounts (id, name, type) VALUES (1, '招行', 'debit_card')`, + } + for _, stmt := range stmts { + if _, err := db.Exec(stmt); err != nil { + t.Fatalf("exec: %v", err) + } + } + return db +} diff --git a/backend/service/asset_snapshot_test.go b/backend/service/asset_snapshot_test.go new file mode 100644 index 0000000..de1b786 --- /dev/null +++ b/backend/service/asset_snapshot_test.go @@ -0,0 +1,49 @@ +package service + +import ( + "context" + "database/sql" + "testing" + "time" + + _ "modernc.org/sqlite" +) + +func TestEnsureMonthlySnapshotRefreshesCurrentMonth(t *testing.T) { + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + for _, stmt := range []string{ + `CREATE TABLE accounts (id INTEGER PRIMARY KEY, type TEXT, balance INTEGER, is_active INTEGER)`, + `CREATE TABLE transactions (id INTEGER PRIMARY KEY, type TEXT, amount INTEGER, account_id INTEGER, to_account_id INTEGER)`, + `CREATE TABLE assets (id INTEGER PRIMARY KEY, value INTEGER, account_id INTEGER)`, + `CREATE TABLE liabilities (id INTEGER PRIMARY KEY, principal INTEGER)`, + `CREATE TABLE asset_snapshots (id INTEGER PRIMARY KEY, date TEXT UNIQUE, total_asset INTEGER, total_debt INTEGER, net_worth INTEGER, created_at TEXT DEFAULT (datetime('now')))`, + `INSERT INTO assets VALUES (1, 1000, NULL)`, + } { + if _, err := db.Exec(stmt); err != nil { + t.Fatal(err) + } + } + svc := NewAssetService(db) + now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.Local) + if err := svc.EnsureMonthlySnapshot(context.Background(), now); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`UPDATE assets SET value = 2500 WHERE id = 1`); err != nil { + t.Fatal(err) + } + if err := svc.EnsureMonthlySnapshot(context.Background(), now.AddDate(0, 0, 1)); err != nil { + t.Fatal(err) + } + var count int + var netWorth int64 + if err := db.QueryRow(`SELECT COUNT(*), MAX(net_worth) FROM asset_snapshots`).Scan(&count, &netWorth); err != nil { + t.Fatal(err) + } + if count != 1 || netWorth != 2500 { + t.Fatalf("count=%d netWorth=%d", count, netWorth) + } +} diff --git a/backend/service/backup.go b/backend/service/backup.go new file mode 100644 index 0000000..5812a47 --- /dev/null +++ b/backend/service/backup.go @@ -0,0 +1,141 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "household-book/model" +) + +const backupRetentionDays = 30 +const backupStartupDelay = 30 * time.Second +const backupCheckInterval = 6 * time.Hour + +type BackupService struct { + db *sql.DB + dbPath string + now func() time.Time + startupDelay time.Duration + checkInterval time.Duration + create func(context.Context) (*model.BackupStatus, error) +} + +func NewBackupService(db *sql.DB, dbPath string) *BackupService { + service := &BackupService{ + db: db, + dbPath: dbPath, + now: time.Now, + startupDelay: backupStartupDelay, + checkInterval: backupCheckInterval, + } + service.create = service.Create + return service +} + +func (s *BackupService) directory() string { + return filepath.Join(filepath.Dir(s.dbPath), "backups") +} + +func (s *BackupService) Create(ctx context.Context) (*model.BackupStatus, error) { + dir := s.directory() + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, fmt.Errorf("create backup directory: %w", err) + } + target := filepath.Join(dir, s.now().Format("2006-01-02")+".db") + if _, err := os.Stat(target); err == nil { + if err := s.cleanup(); err != nil { + return nil, err + } + return s.Status() + } else if !os.IsNotExist(err) { + return nil, err + } + quoted := strings.ReplaceAll(target, "'", "''") + if _, err := s.db.ExecContext(ctx, "VACUUM INTO '"+filepath.ToSlash(quoted)+"'"); err != nil { + return nil, fmt.Errorf("backup database: %w", err) + } + if err := s.cleanup(); err != nil { + return nil, err + } + return s.Status() +} + +func (s *BackupService) Status() (*model.BackupStatus, error) { + status := &model.BackupStatus{Directory: s.directory(), RetentionDays: backupRetentionDays} + entries, err := os.ReadDir(s.directory()) + if os.IsNotExist(err) { + return status, nil + } + if err != nil { + return nil, err + } + var names []string + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".db") { + names = append(names, e.Name()) + } + } + if len(names) == 0 { + return status, nil + } + sort.Strings(names) + status.LastBackup = names[len(names)-1] + if info, err := os.Stat(filepath.Join(s.directory(), status.LastBackup)); err == nil { + status.LastBackupAt = info.ModTime().Format(time.RFC3339) + } + return status, nil +} + +func (s *BackupService) cleanup() error { + entries, err := os.ReadDir(s.directory()) + if err != nil { + return err + } + cutoff := s.now().AddDate(0, 0, -backupRetentionDays) + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".db") { + continue + } + date, err := time.Parse("2006-01-02.db", e.Name()) + if err == nil && date.Before(cutoff) { + if err := os.Remove(filepath.Join(s.directory(), e.Name())); err != nil { + return err + } + } + } + return nil +} + +func (s *BackupService) RunScheduler(ctx context.Context) { + timer := time.NewTimer(s.startupDelay) + defer timer.Stop() + select { + case <-ctx.Done(): + return + case <-timer.C: + } + + if _, err := s.create(ctx); err != nil { + slog.Error("scheduled backup failed", "error", err) + } + + ticker := time.NewTicker(s.checkInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if _, err := s.create(ctx); err != nil { + slog.Error("scheduled backup failed", "error", err) + } + } + } +} diff --git a/backend/service/backup_scheduler_test.go b/backend/service/backup_scheduler_test.go new file mode 100644 index 0000000..c4c16ba --- /dev/null +++ b/backend/service/backup_scheduler_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "household-book/model" +) + +func TestNewBackupServiceUsesProductionSchedule(t *testing.T) { + svc := NewBackupService(nil, "book.db") + if svc.startupDelay != 30*time.Second { + t.Fatalf("startup delay=%s, want 30s", svc.startupDelay) + } + if svc.checkInterval != 6*time.Hour { + t.Fatalf("check interval=%s, want 6h", svc.checkInterval) + } + if svc.create == nil { + t.Fatal("scheduled create function is nil") + } +} + +func TestBackupSchedulerCancellationDuringStartupDelay(t *testing.T) { + var calls atomic.Int32 + svc := &BackupService{ + startupDelay: time.Hour, + checkInterval: time.Hour, + create: func(context.Context) (*model.BackupStatus, error) { + calls.Add(1) + return nil, nil + }, + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + svc.RunScheduler(ctx) + close(done) + }() + cancel() + + select { + case <-done: + case <-time.After(200 * time.Millisecond): + t.Fatal("scheduler did not stop after context cancellation") + } + if got := calls.Load(); got != 0 { + t.Fatalf("create called %d times before startup delay elapsed", got) + } +} + +func TestBackupSchedulerRunsAfterStartupDelay(t *testing.T) { + called := make(chan struct{}, 1) + svc := &BackupService{ + startupDelay: time.Millisecond, + checkInterval: time.Hour, + create: func(context.Context) (*model.BackupStatus, error) { + called <- struct{}{} + return nil, nil + }, + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + svc.RunScheduler(ctx) + close(done) + }() + + select { + case <-called: + case <-time.After(200 * time.Millisecond): + t.Fatal("scheduler did not create backup after startup delay") + } + cancel() + select { + case <-done: + case <-time.After(200 * time.Millisecond): + t.Fatal("scheduler did not stop after context cancellation") + } +} diff --git a/backend/service/balance_integration_test.go b/backend/service/balance_integration_test.go new file mode 100644 index 0000000..ed4b494 --- /dev/null +++ b/backend/service/balance_integration_test.go @@ -0,0 +1,179 @@ +package service + +import ( + "context" + "database/sql" + "path/filepath" + "testing" + + database "household-book/db" + + _ "modernc.org/sqlite" +) + +func TestGroupedBalanceAccountsAndBoundAsset(t *testing.T) { + db := setupGroupedBalanceTestDB(t) + ctx := context.Background() + + accounts, err := NewAccountService(db).List(ctx) + if err != nil { + t.Fatalf("list accounts: %v", err) + } + balances := make(map[string]int64, len(accounts)) + for _, account := range accounts { + balances[account.Name] = account.CurrentBalance + } + if got := balances["现金"]; got != 11800 { + t.Fatalf("cash current balance=%d, want 11800", got) + } + if got := balances["信用卡"]; got != 1200 { + t.Fatalf("credit current balance=%d, want 1200", got) + } + if got := balances["无流水账户"]; got != 300 { + t.Fatalf("no-transaction current balance=%d, want 300", got) + } + + assets, err := NewAssetService(db).ListAssets(ctx) + if err != nil { + t.Fatalf("list assets: %v", err) + } + if len(assets) != 1 { + t.Fatalf("assets count=%d, want 1", len(assets)) + } + if !assets[0].IsDerived || assets[0].Value != 11800 { + t.Fatalf("bound asset=%+v, want derived value 11800", assets[0]) + } +} + +func TestGroupedBalanceNetWorth(t *testing.T) { + db := setupGroupedBalanceTestDB(t) + for _, stmt := range []string{ + `INSERT INTO assets (id, name, type, value, account_id) + VALUES (2, '手工资产', 'other', 2500, NULL)`, + `INSERT INTO liabilities (id, principal) VALUES (1, 1700)`, + } { + if _, err := db.Exec(stmt); err != nil { + t.Fatalf("exec net worth fixture: %v", err) + } + } + + summary, err := NewAssetService(db).NetWorth(context.Background()) + if err != nil { + t.Fatalf("net worth: %v", err) + } + if summary.TotalAssets != 14300 { + t.Fatalf("total assets=%d, want 14300", summary.TotalAssets) + } + if summary.TotalDebt != 1700 { + t.Fatalf("total debt=%d, want 1700", summary.TotalDebt) + } + if summary.LiquidAssets != 300 { + t.Fatalf("liquid assets=%d, want 300", summary.LiquidAssets) + } + if summary.LiquidDebt != 900 { + t.Fatalf("liquid debt=%d, want 900", summary.LiquidDebt) + } + if summary.NetWorth != 12000 { + t.Fatalf("net worth=%d, want 12000", summary.NetWorth) + } +} + +func TestBalanceQueriesExecuteAgainstMigratedSchema(t *testing.T) { + store, err := database.Open(filepath.Join(t.TempDir(), "book.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + if err := database.RunMigrations(store); err != nil { + t.Fatal(err) + } + if err := database.Seed(store); err != nil { + t.Fatal(err) + } + + for name, query := range map[string]string{ + "accounts": accountSelectSQL(), + "assets": assetSelectSQL(), + } { + rows, err := store.Query(query) + if err != nil { + t.Fatalf("%s query: %v", name, err) + } + if err := rows.Close(); err != nil { + t.Fatalf("close %s rows: %v", name, err) + } + } + var totalAssets, totalDebt, liquidAssets, liquidDebt int64 + if err := store.QueryRow(netWorthSQL()).Scan( + &totalAssets, &totalDebt, &liquidAssets, &liquidDebt, + ); err != nil { + t.Fatalf("net worth query: %v", err) + } +} + +func setupGroupedBalanceTestDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + db.SetMaxOpenConns(1) + t.Cleanup(func() { _ = db.Close() }) + + for _, stmt := range []string{ + `CREATE TABLE accounts ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + balance INTEGER NOT NULL, + bank_name TEXT NOT NULL DEFAULT '', + card_number TEXT NOT NULL DEFAULT '', + branch_name TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + is_active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT '', + updated_at TEXT NOT NULL DEFAULT '' + )`, + `CREATE TABLE transactions ( + id INTEGER PRIMARY KEY, + type TEXT NOT NULL, + amount INTEGER NOT NULL, + account_id INTEGER, + to_account_id INTEGER + )`, + `CREATE TABLE assets ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + value INTEGER NOT NULL, + account_id INTEGER, + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT '', + updated_at TEXT NOT NULL DEFAULT '' + )`, + `CREATE TABLE liabilities ( + id INTEGER PRIMARY KEY, + principal INTEGER NOT NULL + )`, + `INSERT INTO accounts (id, name, type, balance) VALUES + (1, '现金', 'cash', 10000), + (2, '信用卡', 'credit_card', 0), + (3, '负余额信用卡', 'credit_card', 0), + (4, '无流水账户', 'cash', 300), + (5, '停用账户', 'cash', 400)`, + `UPDATE accounts SET is_active = 0 WHERE id = 5`, + `INSERT INTO transactions (id, type, amount, account_id, to_account_id) VALUES + (1, 'income', 5000, 1, NULL), + (2, 'expense', 1200, 1, NULL), + (3, 'transfer', 2000, 1, 2), + (4, 'expense', 800, 2, NULL), + (5, 'expense', 900, 3, NULL)`, + `INSERT INTO assets (id, name, type, value, account_id) + VALUES (1, '现金资产', 'cash', 0, 1)`, + } { + if _, err := db.Exec(stmt); err != nil { + t.Fatalf("exec fixture: %v", err) + } + } + return db +} diff --git a/backend/service/balance_sql.go b/backend/service/balance_sql.go new file mode 100644 index 0000000..731597c --- /dev/null +++ b/backend/service/balance_sql.go @@ -0,0 +1,88 @@ +package service + +// accountBalancesCTE 供净值汇总等查询复用的 account_balances CTE 片段(不含外层 WITH)。 +func accountBalancesCTE() string { + return `transaction_effects AS ( + SELECT account_id, SUM(CASE + WHEN type = 'income' THEN amount + WHEN type IN ('expense', 'transfer') THEN -amount + ELSE 0 + END) AS delta + FROM transactions + WHERE account_id IS NOT NULL + GROUP BY account_id + + UNION ALL + + SELECT to_account_id AS account_id, SUM(amount) AS delta + FROM transactions + WHERE type = 'transfer' AND to_account_id IS NOT NULL + GROUP BY to_account_id + ), + account_deltas AS ( + SELECT account_id, SUM(delta) AS delta + FROM transaction_effects + GROUP BY account_id + ), + account_balances AS ( + SELECT a.id, a.type, a.balance + COALESCE(d.delta, 0) AS current_balance + FROM accounts a + LEFT JOIN account_deltas d ON d.account_id = a.id + )` +} + +func accountSelectSQL() string { + return `WITH ` + accountBalancesCTE() + ` + SELECT a.id, a.name, a.type, a.balance, + ab.current_balance, + COALESCE(a.bank_name,''), COALESCE(a.card_number,''), COALESCE(a.branch_name,''), COALESCE(a.note,''), + a.is_active, a.created_at, a.updated_at + FROM accounts a + JOIN account_balances ab ON ab.id = a.id` +} + +func assetSelectSQL() string { + return `WITH ` + accountBalancesCTE() + ` + SELECT a.id, a.name, a.type, a.value, a.account_id, COALESCE(ac.name,''), + COALESCE(ab.current_balance, 0) AS bound_balance, + a.note, a.created_at, a.updated_at + FROM assets a + LEFT JOIN accounts ac ON a.account_id = ac.id + LEFT JOIN account_balances ab ON ab.id = ac.id` +} + +func netWorthSQL() string { + return `WITH ` + accountBalancesCTE() + `, + totals AS ( + SELECT + COALESCE(( + SELECT SUM(CASE + WHEN ass.account_id IS NOT NULL THEN COALESCE(ab.current_balance, 0) + ELSE ass.value + END) + FROM assets ass + LEFT JOIN account_balances ab ON ab.id = ass.account_id + ), 0) AS total_assets, + COALESCE((SELECT SUM(principal) FROM liabilities), 0) AS total_debt, + COALESCE(( + SELECT SUM(CASE + WHEN type != 'credit_card' AND current_balance > 0 THEN current_balance + ELSE 0 + END) + FROM account_balances + WHERE id IN (SELECT id FROM accounts WHERE is_active = 1) + AND id NOT IN (SELECT account_id FROM assets WHERE account_id IS NOT NULL) + ), 0) AS liquid_assets, + COALESCE(( + SELECT SUM(CASE + WHEN type = 'credit_card' AND current_balance < 0 THEN -current_balance + ELSE 0 + END) + FROM account_balances + WHERE id IN (SELECT id FROM accounts WHERE is_active = 1) + AND id NOT IN (SELECT account_id FROM assets WHERE account_id IS NOT NULL) + ), 0) AS liquid_debt + ) + SELECT total_assets, total_debt, liquid_assets, liquid_debt + FROM totals` +} diff --git a/backend/service/balance_sql_test.go b/backend/service/balance_sql_test.go new file mode 100644 index 0000000..4f9b31f --- /dev/null +++ b/backend/service/balance_sql_test.go @@ -0,0 +1,47 @@ +package service + +import ( + "strings" + "testing" +) + +func TestAccountBalancesCTEUsesGroupedEffects(t *testing.T) { + sql := accountBalancesCTE() + for _, part := range []string{ + "transaction_effects AS", + "account_deltas AS", + "GROUP BY account_id", + "LEFT JOIN account_deltas", + } { + if !strings.Contains(sql, part) { + t.Fatalf("missing %q: %s", part, sql) + } + } + for _, forbidden := range []string{ + "WHERE account_id = a.id", + "WHERE account_id = ac.id", + } { + if strings.Contains(sql, forbidden) { + t.Fatalf("correlated balance query remains: %q", forbidden) + } + } +} + +func TestNetWorthSQLUsesSingleAccountBalancesCTE(t *testing.T) { + sql := netWorthSQL() + if got := strings.Count(sql, "transaction_effects AS"); got != 1 { + t.Fatalf("account balance CTE count=%d, want 1: %s", got, sql) + } + for _, part := range []string{ + "totals AS", + "total_assets", + "total_debt", + "liquid_assets", + "liquid_debt", + "FROM totals", + } { + if !strings.Contains(sql, part) { + t.Fatalf("missing %q: %s", part, sql) + } + } +} diff --git a/backend/service/budget.go b/backend/service/budget.go new file mode 100644 index 0000000..f9fad5e --- /dev/null +++ b/backend/service/budget.go @@ -0,0 +1,219 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + + "household-book/model" +) + +type BudgetService struct { + db *sql.DB +} + +func NewBudgetService(db *sql.DB) *BudgetService { + return &BudgetService{db: db} +} + +func (s *BudgetService) Overview(ctx context.Context, year, month int) (*model.BudgetOverview, error) { + overview := &model.BudgetOverview{ + Year: year, + Month: month, + Items: []model.Budget{}, + } + + if err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(amount), 0) + FROM budgets WHERE year = ? AND month IS NULL AND category_id IS NULL`, year).Scan(&overview.AnnualBudget); err != nil { + return nil, fmt.Errorf("query annual budget: %w", err) + } + if err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(amount), 0) + FROM transactions WHERE type = 'expense' AND strftime('%Y', date) = printf('%04d', ?)`, year).Scan(&overview.AnnualSpent); err != nil { + return nil, fmt.Errorf("query annual spent: %w", err) + } + overview.AnnualRemaining = overview.AnnualBudget - overview.AnnualSpent + if overview.AnnualBudget > 0 { + overview.AnnualUsagePercent = float64(overview.AnnualSpent) / float64(overview.AnnualBudget) * 100 + } + + rows, err := s.db.QueryContext(ctx, `WITH expense_categories AS ( + SELECT id, name, type, sort_order FROM categories + WHERE type = 'expense' AND parent_id IS NOT NULL AND is_active = 1 + ), + annual AS ( + SELECT * FROM budgets WHERE year = ? AND month IS NULL + ), + monthly AS ( + SELECT * FROM budgets WHERE year = ? AND month = ? + ) + SELECT + COALESCE(monthly.id, annual.id, 0) AS id, + ? AS year, + ? AS month, + c.id AS category_id, + c.name, + c.type, + COALESCE(monthly.amount, annual.amount / 12, 0) AS amount, + COALESCE(( + SELECT SUM(t.amount) + FROM transactions t + WHERE t.type = 'expense' + AND t.category_id = c.id + AND strftime('%Y', t.date) = printf('%04d', ?) + AND strftime('%m', t.date) = printf('%02d', ?) + ), 0) AS spent, + COALESCE(monthly.note, annual.note, '') AS note, + COALESCE(monthly.created_at, annual.created_at, '') AS created_at, + COALESCE(monthly.updated_at, annual.updated_at, '') AS updated_at + FROM expense_categories c + LEFT JOIN annual ON annual.category_id = c.id + LEFT JOIN monthly ON monthly.category_id = c.id + WHERE annual.id IS NOT NULL OR monthly.id IS NOT NULL + ORDER BY c.sort_order, c.name`, year, year, month, year, month, year, month) + if err != nil { + return nil, fmt.Errorf("query budget overview: %w", err) + } + defer rows.Close() + + for rows.Next() { + var item model.Budget + var categoryID int64 + var scannedMonth int + if err := rows.Scan( + &item.ID, &item.Year, &scannedMonth, &categoryID, &item.CategoryName, &item.CategoryType, + &item.Amount, &item.Spent, &item.Note, &item.CreatedAt, &item.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan budget: %w", err) + } + monthValue := scannedMonth + item.Month = &monthValue + item.CategoryID = &categoryID + item.Remaining = item.Amount - item.Spent + if item.Amount > 0 { + item.UsagePercent = float64(item.Spent) / float64(item.Amount) * 100 + } + + overview.MonthlyBudget += item.Amount + overview.MonthlyBudgetedSpent += item.Spent + overview.Items = append(overview.Items, item) + } + if err := rows.Err(); err != nil { + return nil, err + } + + if overview.MonthlyBudget == 0 && overview.AnnualBudget > 0 { + overview.MonthlyBudget = overview.AnnualBudget / 12 + } + // 月度总预算执行始终使用当月全部支出,不能只统计已配置预算的分类。 + if err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(amount), 0) + FROM transactions + WHERE type = 'expense' + AND strftime('%Y', date) = printf('%04d', ?) + AND strftime('%m', date) = printf('%02d', ?)`, year, month).Scan(&overview.MonthlySpent); err != nil { + return nil, fmt.Errorf("query monthly spent: %w", err) + } + overview.MonthlyUnbudgetedSpent = overview.MonthlySpent - overview.MonthlyBudgetedSpent + if overview.MonthlyUnbudgetedSpent < 0 { + overview.MonthlyUnbudgetedSpent = 0 + } + overview.MonthlyRemaining = overview.MonthlyBudget - overview.MonthlySpent + if overview.MonthlyBudget > 0 { + overview.MonthlyUsagePercent = float64(overview.MonthlySpent) / float64(overview.MonthlyBudget) * 100 + } + return overview, nil +} + +func (s *BudgetService) Upsert(ctx context.Context, req model.UpsertBudgetRequest) (*model.Budget, error) { + // SELECT-then-INSERT/UPDATE 的并发安全依赖 db.SetMaxOpenConns(1) 串行写入; + // 唯一索引(迁移 003)作为最后一道保险,会以唯一约束错误形式拒绝重复写入。 + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + var id int64 + err = tx.QueryRowContext(ctx, + `SELECT id FROM budgets + WHERE year = ? AND ((month IS NULL AND ? IS NULL) OR month = ?) AND ((category_id IS NULL AND ? IS NULL) OR category_id = ?)`, + req.Year, req.Month, req.Month, req.CategoryID, req.CategoryID, + ).Scan(&id) + if err != nil && err != sql.ErrNoRows { + return nil, fmt.Errorf("query budget before upsert: %w", err) + } + + if err == sql.ErrNoRows { + result, err := tx.ExecContext(ctx, `INSERT INTO budgets (year, month, category_id, amount, note) + VALUES (?, ?, ?, ?, ?)`, req.Year, req.Month, req.CategoryID, req.Amount, req.Note) + if err != nil { + return nil, fmt.Errorf("insert budget: %w", err) + } + id, err = result.LastInsertId() + if err != nil { + return nil, fmt.Errorf("read inserted budget id: %w", err) + } + } else { + if _, err := tx.ExecContext(ctx, `UPDATE budgets + SET amount = ?, note = ?, updated_at = datetime('now') + WHERE id = ?`, req.Amount, req.Note, id); err != nil { + return nil, fmt.Errorf("update budget: %w", err) + } + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *BudgetService) Delete(ctx context.Context, id int64) error { + result, err := s.db.ExecContext(ctx, `DELETE FROM budgets WHERE id = ?`, id) + if err != nil { + return fmt.Errorf("delete budget: %w", err) + } + rows, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("rows affected: %w", err) + } + if rows == 0 { + return ErrNotFound + } + return nil +} + +func (s *BudgetService) GetByID(ctx context.Context, id int64) (*model.Budget, error) { + var item model.Budget + var monthValue sql.NullInt64 + var categoryID sql.NullInt64 + var categoryName sql.NullString + var categoryType sql.NullString + err := s.db.QueryRowContext(ctx, `SELECT + b.id, b.year, b.month, b.category_id, c.name, c.type, + b.amount, 0, b.note, b.created_at, b.updated_at + FROM budgets b + LEFT JOIN categories c ON c.id = b.category_id + WHERE b.id = ?`, id, + ).Scan( + &item.ID, &item.Year, &monthValue, &categoryID, &categoryName, &categoryType, + &item.Amount, &item.Spent, &item.Note, &item.CreatedAt, &item.UpdatedAt, + ) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query budget: %w", err) + } + if monthValue.Valid { + v := int(monthValue.Int64) + item.Month = &v + } + if categoryID.Valid { + v := categoryID.Int64 + item.CategoryID = &v + } + item.CategoryName = categoryName.String + item.CategoryType = categoryType.String + item.Remaining = item.Amount - item.Spent + return &item, nil +} diff --git a/backend/service/budget_test.go b/backend/service/budget_test.go new file mode 100644 index 0000000..d0b095b --- /dev/null +++ b/backend/service/budget_test.go @@ -0,0 +1,36 @@ +package service + +import ( + "context" + "database/sql" + "testing" + + _ "modernc.org/sqlite" +) + +func TestBudgetOverviewCountsUnbudgetedExpenseInMonthlyTotal(t *testing.T) { + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + for _, stmt := range []string{ + `CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT, type TEXT, parent_id INTEGER, sort_order INTEGER, is_active INTEGER)`, + `CREATE TABLE budgets (id INTEGER PRIMARY KEY, year INTEGER, month INTEGER, category_id INTEGER, amount INTEGER, note TEXT, created_at TEXT, updated_at TEXT)`, + `CREATE TABLE transactions (id INTEGER PRIMARY KEY, type TEXT, amount INTEGER, category_id INTEGER, date TEXT)`, + `INSERT INTO categories VALUES (1, '支出', 'expense', NULL, 1, 1), (2, '餐饮', 'expense', 1, 1, 1), (3, '交通', 'expense', 1, 2, 1)`, + `INSERT INTO budgets VALUES (1, 2026, NULL, NULL, 120000, '', '', ''), (2, 2026, NULL, 2, 60000, '', '', '')`, + `INSERT INTO transactions VALUES (1, 'expense', 1000, 2, '2026-08-01'), (2, 'expense', 2000, 3, '2026-08-02')`, + } { + if _, err := db.Exec(stmt); err != nil { + t.Fatal(err) + } + } + overview, err := NewBudgetService(db).Overview(context.Background(), 2026, 8) + if err != nil { + t.Fatal(err) + } + if overview.MonthlySpent != 3000 || overview.MonthlyBudgetedSpent != 1000 || overview.MonthlyUnbudgetedSpent != 2000 { + t.Fatalf("unexpected monthly amounts: %+v", overview) + } +} diff --git a/backend/service/category.go b/backend/service/category.go new file mode 100644 index 0000000..f9d6211 --- /dev/null +++ b/backend/service/category.go @@ -0,0 +1,205 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "household-book/model" +) + +type CategoryService struct { + db *sql.DB +} + +func NewCategoryService(db *sql.DB) *CategoryService { + return &CategoryService{db: db} +} + +func (s *CategoryService) List(ctx context.Context, typ string) ([]model.Category, error) { + query := "SELECT id, name, type, parent_id, sort_order, COALESCE(keywords,''), is_active, created_at, updated_at FROM categories" + var args []any + + if typ != "" { + query += " WHERE type = ?" + args = append(args, typ) + } + query += " ORDER BY type, sort_order" + + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("query categories: %w", err) + } + defer rows.Close() + + var list []model.Category + for rows.Next() { + var c model.Category + var isActive int + if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.ParentID, &c.SortOrder, &c.Keywords, &isActive, &c.CreatedAt, &c.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan category: %w", err) + } + c.IsActive = isActive == 1 + list = append(list, c) + } + if list == nil { + list = []model.Category{} + } + return list, rows.Err() +} + +func (s *CategoryService) GetByID(ctx context.Context, id int64) (*model.Category, error) { + var c model.Category + var isActive int + err := s.db.QueryRowContext(ctx, + "SELECT id, name, type, parent_id, sort_order, COALESCE(keywords,''), is_active, created_at, updated_at FROM categories WHERE id = ?", id, + ).Scan(&c.ID, &c.Name, &c.Type, &c.ParentID, &c.SortOrder, &c.Keywords, &isActive, &c.CreatedAt, &c.UpdatedAt) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query category: %w", err) + } + c.IsActive = isActive == 1 + return &c, nil +} + +func (s *CategoryService) Create(ctx context.Context, req model.CreateCategoryRequest) (*model.Category, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + sortOrder := req.SortOrder + if sortOrder <= 0 { + sortOrder, err = s.nextSortOrder(ctx, tx, req.Type, req.ParentID) + if err != nil { + return nil, err + } + } + + result, err := tx.ExecContext(ctx, + "INSERT INTO categories (name, type, parent_id, sort_order, keywords) VALUES (?, ?, ?, ?, ?)", + req.Name, req.Type, req.ParentID, sortOrder, req.Keywords) + if err != nil { + return nil, fmt.Errorf("insert category: %w", err) + } + id, _ := result.LastInsertId() + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *CategoryService) nextSortOrder(ctx context.Context, tx *sql.Tx, typ string, parentID *int64) (int, error) { + query := "SELECT COALESCE(MAX(sort_order), 0) + 1 FROM categories WHERE type = ?" + args := []any{typ} + if parentID == nil { + query += " AND parent_id IS NULL" + } else { + query += " AND parent_id = ?" + args = append(args, *parentID) + } + var next int + if err := tx.QueryRowContext(ctx, query, args...).Scan(&next); err != nil { + return 0, fmt.Errorf("query next category sort order: %w", err) + } + return next, nil +} + +func (s *CategoryService) Update(ctx context.Context, id int64, req model.UpdateCategoryRequest) (*model.Category, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + var sets []string + var args []any + + if req.Name != nil { + sets = append(sets, "name = ?") + args = append(args, *req.Name) + } + if req.ParentID.Set { + sets = append(sets, "parent_id = ?") + if req.ParentID.Valid { + args = append(args, req.ParentID.Value) + } else { + args = append(args, nil) + } + } + if req.SortOrder != nil { + sets = append(sets, "sort_order = ?") + args = append(args, *req.SortOrder) + } + if req.Keywords != nil { + sets = append(sets, "keywords = ?") + args = append(args, *req.Keywords) + } + if req.IsActive != nil { + isActive := 0 + if *req.IsActive { + isActive = 1 + } + sets = append(sets, "is_active = ?") + args = append(args, isActive) + } + + if len(sets) == 0 { + return s.GetByID(ctx, id) + } + + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + + query := "UPDATE categories SET " + strings.Join(sets, ", ") + " WHERE id = ?" + result, err := tx.ExecContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("update category: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, fmt.Errorf("check updated category: %w", err) + } else if affected == 0 { + return nil, ErrNotFound + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *CategoryService) Delete(ctx context.Context, id int64) error { + var count int + if err := s.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM transactions WHERE category_id = ?", id).Scan(&count); err != nil { + return fmt.Errorf("check transactions: %w", err) + } + if count > 0 { + return ErrHasTransactions + } + if err := s.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM categories WHERE parent_id = ?", id).Scan(&count); err != nil { + return fmt.Errorf("check children: %w", err) + } + if count > 0 { + return ErrHasChildren + } + + result, err := s.db.ExecContext(ctx, "DELETE FROM categories WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return fmt.Errorf("check deleted category: %w", err) + } else if affected == 0 { + return ErrNotFound + } + return nil +} diff --git a/backend/service/csv_import.go b/backend/service/csv_import.go new file mode 100644 index 0000000..1d347fc --- /dev/null +++ b/backend/service/csv_import.go @@ -0,0 +1,361 @@ +package service + +import ( + "bytes" + "encoding/csv" + "fmt" + "io" + "strings" + + "household-book/model" + + "golang.org/x/text/encoding/simplifiedchinese" + "golang.org/x/text/transform" +) + +// parseAlipayCSV 解析支付宝导出的"交易记录明细"CSV(GBK 编码)。 +// +// 文件结构: +// +// 行 1:标题 +// 行 2:账号 +// 行 3:起止日期 +// 行 4:分隔行 +// 行 5:表头(包含"金额(元)"、"收/支"、"交易状态"等列) +// 行 6+:数据行;尾部还可能有一段统计/分隔行 +func parseAlipayCSV(req model.ImportTransactionsRequest) ([]parsedImportTransaction, error) { + rows, err := readChineseCSV(req.Content, true) + if err != nil { + return nil, fmt.Errorf("alipay csv: %w", err) + } + header, headerRow, ok := findCSVHeader(rows, []string{"收/支", "金额"}) + if !ok { + return nil, fmt.Errorf("alipay csv: header row not found") + } + idxCreate := headerColumn(header, "交易创建时间") + idxPay := headerColumn(header, "付款时间") + idxCounterparty := headerColumn(header, "交易对方") + idxProduct := headerColumn(header, "商品名称") + idxAmount := headerColumn(header, "金额") + idxFlow := headerColumn(header, "收/支") + idxStatus := headerColumn(header, "交易状态") + idxTradeNo := headerColumn(header, "交易号") + + if idxAmount < 0 || idxFlow < 0 { + return nil, fmt.Errorf("alipay csv: missing required columns") + } + + items := make([]parsedImportTransaction, 0, len(rows)-headerRow-1) + for i := headerRow + 1; i < len(rows); i++ { + fields := rows[i] + if len(fields) <= idxAmount || len(fields) <= idxFlow { + continue + } + + flow := strings.TrimSpace(getField(fields, idxFlow)) + typ, ok := alipayFlowToType(flow) + if !ok { + continue + } + + status := strings.TrimSpace(getField(fields, idxStatus)) + if status != "" && !alipayAcceptStatus(status) { + continue + } + + amount, err := yuanToCents(strings.TrimSpace(getField(fields, idxAmount))) + if err != nil || amount <= 0 { + continue + } + + date := pickAlipayDate(getField(fields, idxPay), getField(fields, idxCreate)) + if date == "" { + continue + } + + counterparty := strings.TrimSpace(getField(fields, idxCounterparty)) + product := strings.TrimSpace(getField(fields, idxProduct)) + desc := composeDescription(counterparty, product) + if desc == "" { + desc = "支付宝交易" + } + + identity := strings.TrimSpace(getField(fields, idxTradeNo)) + if identity == "" { + identity = strings.Join([]string{date, fmt.Sprintf("%d", amount), desc, flow}, "|") + } + items = append(items, parsedImportTransaction{ + Type: typ, + Amount: amount, + Date: date, + Description: desc, + Counterparty: counterparty, + SourceKey: sourceKey(req, identity), + }) + } + return items, nil +} + +// parseWechatCSV 解析微信支付导出的账单 CSV(UTF-8 with BOM)。 +// +// 文件结构: +// +// 前 16 行是标题/统计/说明 +// 含 "----------------------微信支付账单明细列表--------------------" 分隔 +// 紧接的下一行是表头(交易时间, 交易类型, 交易对方, 商品, 收/支, 金额(元), 支付方式, 当前状态, 交易单号, 商户单号, 备注) +// 数据行从表头下一行开始 +func parseWechatCSV(req model.ImportTransactionsRequest) ([]parsedImportTransaction, error) { + rows, err := readChineseCSV(req.Content, false) + if err != nil { + return nil, fmt.Errorf("wechat csv: %w", err) + } + header, headerRow, ok := findCSVHeader(rows, []string{"收/支", "金额"}) + if !ok { + return nil, fmt.Errorf("wechat csv: header row not found") + } + idxTime := headerColumn(header, "交易时间") + idxKind := headerColumn(header, "交易类型") + idxCounterparty := headerColumn(header, "交易对方") + idxProduct := headerColumn(header, "商品") + idxFlow := headerColumn(header, "收/支") + idxAmount := headerColumn(header, "金额") + idxStatus := headerColumn(header, "当前状态") + idxTradeNo := headerColumn(header, "交易单号") + + if idxTime < 0 || idxAmount < 0 || idxFlow < 0 { + return nil, fmt.Errorf("wechat csv: missing required columns") + } + + items := make([]parsedImportTransaction, 0, len(rows)-headerRow-1) + for i := headerRow + 1; i < len(rows); i++ { + fields := rows[i] + if len(fields) <= idxAmount || len(fields) <= idxFlow { + continue + } + + flow := strings.TrimSpace(getField(fields, idxFlow)) + typ, ok := wechatFlowToType(flow) + if !ok { + continue + } + + status := strings.TrimSpace(getField(fields, idxStatus)) + if status != "" && !wechatAcceptStatus(status) { + continue + } + + rawAmount := strings.TrimSpace(getField(fields, idxAmount)) + rawAmount = strings.TrimPrefix(rawAmount, "¥") + rawAmount = strings.TrimPrefix(rawAmount, "¥") + amount, err := yuanToCents(rawAmount) + if err != nil || amount <= 0 { + continue + } + + date := wechatDate(getField(fields, idxTime)) + if date == "" { + continue + } + + counterparty := strings.TrimSpace(getField(fields, idxCounterparty)) + product := wechatProduct(getField(fields, idxProduct)) + kind := strings.TrimSpace(getField(fields, idxKind)) + desc := composeDescription(counterparty, product) + if desc == "" { + desc = strings.TrimSpace(kind) + if desc == "" { + desc = "微信交易" + } + } + + identity := strings.TrimSpace(getField(fields, idxTradeNo)) + if identity == "" { + identity = strings.Join([]string{date, fmt.Sprintf("%d", amount), desc, flow}, "|") + } + items = append(items, parsedImportTransaction{ + Type: typ, + Amount: amount, + Date: date, + Description: desc, + Counterparty: counterparty, + SourceKey: sourceKey(req, identity), + }) + } + return items, nil +} + +// readChineseCSV 读取 CSV 字节流。alipay=true 时按 GBK 解码;否则按 UTF-8(去除可能的 BOM)。 +// +// 返回所有行;空行被保留以便上下文判断。 +func readChineseCSV(content []byte, alipay bool) ([][]string, error) { + var reader io.Reader = bytes.NewReader(content) + if alipay { + reader = transform.NewReader(reader, simplifiedchinese.GBK.NewDecoder()) + } else { + // 移除 UTF-8 BOM + if bytes.HasPrefix(content, []byte{0xEF, 0xBB, 0xBF}) { + reader = bytes.NewReader(content[3:]) + } + } + c := csv.NewReader(reader) + c.FieldsPerRecord = -1 + c.LazyQuotes = true + c.TrimLeadingSpace = false + rows, err := c.ReadAll() + if err != nil { + return nil, err + } + return rows, nil +} + +// findCSVHeader 在前 30 行中找包含全部 needles 子串的表头行。 +func findCSVHeader(rows [][]string, needles []string) ([]string, int, bool) { + limit := len(rows) + if limit > 30 { + limit = 30 + } + for i := 0; i < limit; i++ { + row := rows[i] + joined := strings.Join(row, "|") + matched := true + for _, n := range needles { + if !strings.Contains(joined, n) { + matched = false + break + } + } + if matched { + return row, i, true + } + } + return nil, 0, false +} + +func headerColumn(header []string, contains string) int { + for i, name := range header { + if strings.Contains(name, contains) { + return i + } + } + return -1 +} + +func getField(fields []string, idx int) string { + if idx < 0 || idx >= len(fields) { + return "" + } + return fields[idx] +} + +func alipayFlowToType(flow string) (string, bool) { + switch flow { + case "支出": + return "expense", true + case "收入": + return "income", true + default: + // 不计收支、空字符串等 + return "", false + } +} + +// alipayAcceptStatus 过滤掉退款成功、交易关闭等无效或重复状态。 +func alipayAcceptStatus(status string) bool { + switch status { + case "交易成功", "支付成功", "等待确认收货", "代付成功": + return true + } + if strings.Contains(status, "成功") && !strings.Contains(status, "退款") { + return true + } + return false +} + +func wechatFlowToType(flow string) (string, bool) { + switch flow { + case "支出": + return "expense", true + case "收入": + return "income", true + default: + return "", false + } +} + +// wechatAcceptStatus 过滤掉已退款、转账失败等。 +func wechatAcceptStatus(status string) bool { + if strings.Contains(status, "已退款") || strings.Contains(status, "失败") { + return false + } + return true +} + +// pickAlipayDate 优先取付款时间,其次创建时间;返回 YYYY-MM-DD。 +func pickAlipayDate(payTime, createTime string) string { + for _, raw := range []string{payTime, createTime} { + raw = strings.TrimSpace(raw) + if raw == "" { + continue + } + if d := normalizeDateOnly(raw); d != "" { + return d + } + } + return "" +} + +func wechatDate(raw string) string { + return normalizeDateOnly(strings.TrimSpace(raw)) +} + +// normalizeDateOnly 接收 "2025/5/31 20:51" 或 "2024-12-26 11:51:58",返回 YYYY-MM-DD。 +func normalizeDateOnly(raw string) string { + if raw == "" { + return "" + } + if i := strings.IndexAny(raw, " T"); i > 0 { + raw = raw[:i] + } + parts := strings.FieldsFunc(raw, func(r rune) bool { return r == '-' || r == '/' }) + if len(parts) != 3 { + return "" + } + year := parts[0] + if len(year) != 4 { + return "" + } + return fmt.Sprintf("%s-%s-%s", year, padTwo(parts[1]), padTwo(parts[2])) +} + +func padTwo(v string) string { + if len(v) >= 2 { + return v + } + return "0" + v +} + +// composeDescription 优先用商品名,其次用对手方;两者拼接以兼容某些行只有一个有内容的情况。 +func composeDescription(counterparty, product string) string { + counterparty = strings.TrimSpace(counterparty) + product = strings.TrimSpace(product) + if product == "" || product == "/" { + return counterparty + } + if counterparty == "" || counterparty == "/" { + return product + } + if strings.Contains(product, counterparty) { + return product + } + return counterparty + " " + product +} + +// wechatProduct 微信账单的"商品"列经常用 "/" 表示空,且会带前后引号。 +func wechatProduct(raw string) string { + raw = strings.TrimSpace(raw) + raw = strings.Trim(raw, "\"") + if raw == "/" { + return "" + } + return raw +} diff --git a/backend/service/csv_import_test.go b/backend/service/csv_import_test.go new file mode 100644 index 0000000..66a0645 --- /dev/null +++ b/backend/service/csv_import_test.go @@ -0,0 +1,80 @@ +package service + +import ( + "os" + "path/filepath" + "testing" + + "household-book/model" +) + +func TestParseAlipayCSV(t *testing.T) { + content := readExampleFile(t, "alipay_record_20250723_2030_1.csv") + req := model.ImportTransactionsRequest{ + Filename: "alipay_record_20250723_2030_1.csv", + Content: content, + SourceKind: "alipay", + BankName: "支付宝", + CardType: "alipay", + } + items, err := parseAlipayCSV(req) + if err != nil { + t.Fatalf("parse alipay: %v", err) + } + if len(items) < 50 { + t.Fatalf("expected many alipay items, got %d", len(items)) + } + + // 抽样校验:第一行是 2025-05-31 张红旗饸饹面 29.7 支出 + first := items[0] + if first.Date != "2025-05-31" || first.Type != "expense" || first.Amount != 2970 { + t.Fatalf("unexpected first alipay item: %+v", first) + } + if first.Counterparty != "张红旗饸饹面" { + t.Fatalf("unexpected counterparty: %q", first.Counterparty) + } +} + +func TestParseWechatCSV(t *testing.T) { + content := readExampleFile(t, "微信支付账单(20241001-20250101).csv") + req := model.ImportTransactionsRequest{ + Filename: "微信支付账单(20241001-20250101).csv", + Content: content, + SourceKind: "wechat", + BankName: "微信", + CardType: "wechat", + } + items, err := parseWechatCSV(req) + if err != nil { + t.Fatalf("parse wechat: %v", err) + } + if len(items) < 5 { + t.Fatalf("expected wechat items, got %d", len(items)) + } + + var foundExpense, foundIncome bool + for _, item := range items { + if item.Type == "expense" && item.Date == "2024-12-26" && item.Amount == 13700 && item.Counterparty == "我心依然" { + foundExpense = true + } + if item.Type == "income" && item.Date == "2024-12-20" && item.Amount == 1800 && item.Counterparty == "范军" { + foundIncome = true + } + } + if !foundExpense { + t.Fatalf("expected wechat expense 我心依然 137.00 not found") + } + if !foundIncome { + t.Fatalf("expected wechat income 范军 18.00 not found") + } +} + +func readExampleFile(t *testing.T, name string) []byte { + t.Helper() + path := filepath.Join("..", "..", "docs", name) + content, err := os.ReadFile(path) + if err != nil { + t.Skipf("example file not available: %v", err) + } + return content +} diff --git a/backend/service/dashboard.go b/backend/service/dashboard.go new file mode 100644 index 0000000..3e3e55a --- /dev/null +++ b/backend/service/dashboard.go @@ -0,0 +1,107 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "sort" + + "household-book/model" +) + +type DashboardService struct { + db *sql.DB +} + +func NewDashboardService(db *sql.DB) *DashboardService { + return &DashboardService{db: db} +} + +func (s *DashboardService) Summary(ctx context.Context, year, month string) (*model.DashboardSummary, error) { + var result model.DashboardSummary + prefix := "" + if year != "" { + prefix = year + if month != "" { + if len(month) == 1 { + month = "0" + month + } + prefix += "-" + month + } + } + + query := `SELECT + COALESCE(SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END), 0), + COUNT(*) + FROM transactions + WHERE type IN ('income', 'expense')` + + var args []any + if prefix != "" { + query += " AND date LIKE ?" + args = append(args, prefix+"%") + } + + if err := s.db.QueryRowContext(ctx, query, args...).Scan( + &result.Income, &result.Expense, &result.TransactionCount, + ); err != nil { + return nil, fmt.Errorf("query dashboard summary: %w", err) + } + result.Balance = result.Income - result.Expense + return &result, nil +} + +func (s *DashboardService) Recent(ctx context.Context, limit int) ([]model.TransactionListItem, error) { + if limit < 1 { + limit = 5 + } + + rows, err := s.db.QueryContext(ctx, + `SELECT t.id, t.type, t.amount, t.category_id, COALESCE(c.name,''), COALESCE(c.is_active, 1), + t.account_id, COALESCE(a.name,''), t.to_account_id, COALESCE(ta.name,''), + t.member_id, COALESCE(m.name,''), + t.date, t.description, COALESCE(t.counterparty,''), t.import_batch_id, COALESCE(ib.filename,''), + t.created_at, t.updated_at + FROM transactions t + LEFT JOIN categories c ON t.category_id = c.id + LEFT JOIN accounts a ON t.account_id = a.id + LEFT JOIN accounts ta ON t.to_account_id = ta.id + LEFT JOIN members m ON t.member_id = m.id + LEFT JOIN import_batches ib ON t.import_batch_id = ib.id + ORDER BY t.date DESC, t.id DESC LIMIT ?`, limit) + if err != nil { + return nil, fmt.Errorf("query recent transactions: %w", err) + } + defer rows.Close() + + var items []model.TransactionListItem + for rows.Next() { + var item model.TransactionListItem + var categoryIsActive int + if err := rows.Scan( + &item.ID, &item.Type, &item.Amount, + &item.CategoryID, &item.CategoryName, &categoryIsActive, + &item.AccountID, &item.AccountName, + &item.ToAccountID, &item.ToAccountName, + &item.MemberID, &item.MemberName, + &item.Date, &item.Description, &item.Counterparty, + &item.ImportBatchID, &item.ImportFilename, + &item.CreatedAt, &item.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan transaction: %w", err) + } + item.CategoryIsActive = categoryIsActive == 1 + items = append(items, item) + } + if items == nil { + items = []model.TransactionListItem{} + } + sort.SliceStable(items, func(i, j int) bool { + if items[i].Date == items[j].Date { + return items[i].ID < items[j].ID + } + return items[i].Date < items[j].Date + }) + return items, rows.Err() +} diff --git a/backend/service/errors.go b/backend/service/errors.go new file mode 100644 index 0000000..6d314ba --- /dev/null +++ b/backend/service/errors.go @@ -0,0 +1,13 @@ +package service + +import "errors" + +var ( + ErrNotFound = errors.New("record not found") + ErrHasTransactions = errors.New("record has associated transactions") + ErrHasChildren = errors.New("record has children") + ErrNoImportableTransactions = errors.New("no importable transactions") + ErrAccountAlreadyBound = errors.New("account already bound to another asset") + ErrInvalidTransaction = errors.New("invalid transaction field combination") + ErrInvalidPaymentStatus = errors.New("invalid payment status") +) diff --git a/backend/service/high_priority_test.go b/backend/service/high_priority_test.go new file mode 100644 index 0000000..881c70b --- /dev/null +++ b/backend/service/high_priority_test.go @@ -0,0 +1,81 @@ +package service + +import ( + "context" + "database/sql" + "household-book/model" + _ "modernc.org/sqlite" + "os" + "path/filepath" + "testing" + "time" +) + +func TestNextPaymentDate(t *testing.T) { + if got := nextPaymentDate("2026-01-15", "quarterly"); got != "2026-04-15" { + t.Fatalf("got %s", got) + } + if got := nextPaymentDate("2026-01-15", "single"); got != "" { + t.Fatalf("single got %s", got) + } +} + +func TestBackupCreateAndStatus(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "book.db") + db, err := sql.Open("sqlite", dbPath) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err = db.Exec(`CREATE TABLE sample(id INTEGER); INSERT INTO sample VALUES(1)`); err != nil { + t.Fatal(err) + } + svc := NewBackupService(db, dbPath) + svc.now = func() time.Time { return time.Date(2026, 8, 6, 12, 0, 0, 0, time.Local) } + status, err := svc.Create(context.Background()) + if err != nil { + t.Fatal(err) + } + if status.LastBackup != "2026-08-06.db" { + t.Fatalf("status=%+v", status) + } + if _, err := os.Stat(filepath.Join(dir, "backups", status.LastBackup)); err != nil { + t.Fatal(err) + } +} + +func TestReconcileCreatesAdjustment(t *testing.T) { + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + stmts := []string{ + `CREATE TABLE accounts(id INTEGER PRIMARY KEY,name TEXT,type TEXT,balance INTEGER,bank_name TEXT,card_number TEXT,branch_name TEXT,note TEXT,is_active INTEGER,created_at TEXT,updated_at TEXT)`, + `CREATE TABLE categories(id INTEGER PRIMARY KEY,name TEXT,type TEXT,parent_id INTEGER,sort_order INTEGER,is_active INTEGER)`, + `CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT,type TEXT,amount INTEGER,category_id INTEGER,account_id INTEGER,to_account_id INTEGER,member_id INTEGER,date TEXT,description TEXT,counterparty TEXT,import_batch_id INTEGER,created_at TEXT DEFAULT '',updated_at TEXT DEFAULT '')`, + `CREATE TABLE account_reconciliations(id INTEGER PRIMARY KEY AUTOINCREMENT,account_id INTEGER,system_balance INTEGER,actual_balance INTEGER,difference INTEGER,transaction_id INTEGER,note TEXT,created_at TEXT DEFAULT '')`, + `INSERT INTO accounts VALUES(1,'现金','cash',1000,'','','','',1,'','')`, + `INSERT INTO categories VALUES(1,'支出','expense',NULL,1,1),(2,'其他','expense',1,1,1),(3,'收入','income',NULL,1,1),(4,'其他','income',3,1,1)`, + } + for _, s := range stmts { + if _, err = db.Exec(s); err != nil { + t.Fatal(err) + } + } + v, err := NewAccountService(db).Reconcile(context.Background(), 1, model.ReconcileAccountRequest{ActualBalance: 1500, CreateAdjustment: true}) + if err != nil { + t.Fatal(err) + } + if v.Difference != 500 || v.TransactionID == nil { + t.Fatalf("result=%+v", v) + } + a, err := NewAccountService(db).GetByID(context.Background(), 1) + if err != nil { + t.Fatal(err) + } + if a.CurrentBalance != 1500 { + t.Fatalf("balance=%d", a.CurrentBalance) + } +} diff --git a/backend/service/lifecycle.go b/backend/service/lifecycle.go new file mode 100644 index 0000000..465bd84 --- /dev/null +++ b/backend/service/lifecycle.go @@ -0,0 +1,115 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "household-book/model" +) + +type LifecycleService struct{ db *sql.DB } + +func NewLifecycleService(db *sql.DB) *LifecycleService { return &LifecycleService{db: db} } + +func (s *LifecycleService) List(ctx context.Context) ([]model.LifecycleEvent, error) { + rows, err := s.db.QueryContext(ctx, `SELECT e.id, e.year, e.member_id, COALESCE(m.name,''), e.event, e.estimated_cost, e.note, e.created_at, e.updated_at + FROM lifecycle_events e LEFT JOIN members m ON m.id = e.member_id ORDER BY e.year, e.id`) + if err != nil { + return nil, fmt.Errorf("query lifecycle events: %w", err) + } + defer rows.Close() + var list []model.LifecycleEvent + for rows.Next() { + var e model.LifecycleEvent + if err := rows.Scan(&e.ID, &e.Year, &e.MemberID, &e.MemberName, &e.Event, &e.EstimatedCost, &e.Note, &e.CreatedAt, &e.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan lifecycle event: %w", err) + } + list = append(list, e) + } + if list == nil { + list = []model.LifecycleEvent{} + } + return list, rows.Err() +} + +func (s *LifecycleService) Create(ctx context.Context, req model.CreateLifecycleEventRequest) (*model.LifecycleEvent, error) { + result, err := s.db.ExecContext(ctx, "INSERT INTO lifecycle_events (year, member_id, event, estimated_cost, note) VALUES (?, ?, ?, ?, ?)", req.Year, req.MemberID, req.Event, req.EstimatedCost, req.Note) + if err != nil { + return nil, fmt.Errorf("insert lifecycle event: %w", err) + } + id, _ := result.LastInsertId() + return s.GetByID(ctx, id) +} + +func (s *LifecycleService) GetByID(ctx context.Context, id int64) (*model.LifecycleEvent, error) { + var e model.LifecycleEvent + err := s.db.QueryRowContext(ctx, `SELECT e.id, e.year, e.member_id, COALESCE(m.name,''), e.event, e.estimated_cost, e.note, e.created_at, e.updated_at + FROM lifecycle_events e LEFT JOIN members m ON m.id = e.member_id WHERE e.id = ?`, id). + Scan(&e.ID, &e.Year, &e.MemberID, &e.MemberName, &e.Event, &e.EstimatedCost, &e.Note, &e.CreatedAt, &e.UpdatedAt) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query lifecycle event: %w", err) + } + return &e, nil +} + +func (s *LifecycleService) Update(ctx context.Context, id int64, req model.UpdateLifecycleEventRequest) (*model.LifecycleEvent, error) { + var sets []string + var args []any + if req.Year != nil { + sets = append(sets, "year = ?") + args = append(args, *req.Year) + } + if req.MemberID.Set { + sets = append(sets, "member_id = ?") + if req.MemberID.Valid { + args = append(args, req.MemberID.Value) + } else { + args = append(args, nil) + } + } + if req.Event != nil { + sets = append(sets, "event = ?") + args = append(args, *req.Event) + } + if req.EstimatedCost != nil { + sets = append(sets, "estimated_cost = ?") + args = append(args, *req.EstimatedCost) + } + if req.Note != nil { + sets = append(sets, "note = ?") + args = append(args, *req.Note) + } + if len(sets) == 0 { + return s.GetByID(ctx, id) + } + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + result, err := s.db.ExecContext(ctx, "UPDATE lifecycle_events SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...) + if err != nil { + return nil, fmt.Errorf("update lifecycle event: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, err + } else if affected == 0 { + return nil, ErrNotFound + } + return s.GetByID(ctx, id) +} + +func (s *LifecycleService) Delete(ctx context.Context, id int64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM lifecycle_events WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return err + } else if affected == 0 { + return ErrNotFound + } + return nil +} diff --git a/backend/service/member.go b/backend/service/member.go new file mode 100644 index 0000000..ca235ad --- /dev/null +++ b/backend/service/member.go @@ -0,0 +1,157 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "household-book/model" +) + +type MemberService struct { + db *sql.DB +} + +func NewMemberService(db *sql.DB) *MemberService { + return &MemberService{db: db} +} + +func (s *MemberService) List(ctx context.Context) ([]model.Member, error) { + rows, err := s.db.QueryContext(ctx, + "SELECT id, name, relation, COALESCE(birthday,''), COALESCE(phone,''), created_at, updated_at FROM members ORDER BY id") + if err != nil { + return nil, fmt.Errorf("query members: %w", err) + } + defer rows.Close() + + var list []model.Member + for rows.Next() { + var m model.Member + if err := rows.Scan(&m.ID, &m.Name, &m.Relation, &m.Birthday, &m.Phone, &m.CreatedAt, &m.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan member: %w", err) + } + list = append(list, m) + } + if list == nil { + list = []model.Member{} + } + return list, rows.Err() +} + +func (s *MemberService) GetByID(ctx context.Context, id int64) (*model.Member, error) { + var m model.Member + err := s.db.QueryRowContext(ctx, + "SELECT id, name, relation, COALESCE(birthday,''), COALESCE(phone,''), created_at, updated_at FROM members WHERE id = ?", id, + ).Scan(&m.ID, &m.Name, &m.Relation, &m.Birthday, &m.Phone, &m.CreatedAt, &m.UpdatedAt) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query member: %w", err) + } + return &m, nil +} + +func (s *MemberService) Create(ctx context.Context, req model.CreateMemberRequest) (*model.Member, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + result, err := tx.ExecContext(ctx, + "INSERT INTO members (name, relation, birthday, phone) VALUES (?, ?, ?, ?)", + req.Name, req.Relation, req.Birthday, req.Phone) + if err != nil { + return nil, fmt.Errorf("insert member: %w", err) + } + id, _ := result.LastInsertId() + + var m model.Member + err = tx.QueryRowContext(ctx, + "SELECT id, name, relation, COALESCE(birthday,''), COALESCE(phone,''), created_at, updated_at FROM members WHERE id = ?", id, + ).Scan(&m.ID, &m.Name, &m.Relation, &m.Birthday, &m.Phone, &m.CreatedAt, &m.UpdatedAt) + if err != nil { + return nil, fmt.Errorf("read back member: %w", err) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + return &m, nil +} + +func (s *MemberService) Update(ctx context.Context, id int64, req model.UpdateMemberRequest) (*model.Member, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + var sets []string + var args []any + + if req.Name != nil { + sets = append(sets, "name = ?") + args = append(args, *req.Name) + } + if req.Relation != nil { + sets = append(sets, "relation = ?") + args = append(args, *req.Relation) + } + if req.Birthday != nil { + sets = append(sets, "birthday = ?") + args = append(args, *req.Birthday) + } + if req.Phone != nil { + sets = append(sets, "phone = ?") + args = append(args, *req.Phone) + } + + if len(sets) == 0 { + return s.GetByID(ctx, id) + } + + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + + query := "UPDATE members SET " + strings.Join(sets, ", ") + " WHERE id = ?" + result, err := tx.ExecContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("update member: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, fmt.Errorf("check updated member: %w", err) + } else if affected == 0 { + return nil, ErrNotFound + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *MemberService) Delete(ctx context.Context, id int64) error { + var count int + if err := s.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM transactions WHERE member_id = ?", id).Scan(&count); err != nil { + return fmt.Errorf("check transactions: %w", err) + } + if count > 0 { + return ErrHasTransactions + } + + result, err := s.db.ExecContext(ctx, "DELETE FROM members WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return fmt.Errorf("check deleted member: %w", err) + } else if affected == 0 { + return ErrNotFound + } + return nil +} diff --git a/backend/service/pdf_text.go b/backend/service/pdf_text.go new file mode 100644 index 0000000..13470e3 --- /dev/null +++ b/backend/service/pdf_text.go @@ -0,0 +1,289 @@ +package service + +import ( + "bytes" + "compress/zlib" + "encoding/hex" + "io" + "regexp" + "strconv" + "strings" + "unicode/utf16" +) + +type pdfObjectStream struct { + object int + body []byte + data []byte +} + +var ( + pdfObjectRe = regexp.MustCompile(`(?s)(\d+)\s+0\s+obj(.*?)endobj`) + pdfStreamRe = regexp.MustCompile(`(?s)stream\s*(.*?)\s*endstream`) + pdfTextOpRe = regexp.MustCompile(`(?s)\((?:\\.|[^\\()])*\)\s*Tj|<([0-9A-Fa-f\s]+)>\s*Tj|\[(.*?)\]\s*TJ`) + pdfStringRe = regexp.MustCompile(`(?s)\((?:\\.|[^\\()])*\)|<([0-9A-Fa-f\s]+)>`) + pdfBfCharRe = regexp.MustCompile(`(?s)beginbfchar(.*?)endbfchar`) + pdfBfRangeRe = regexp.MustCompile(`(?s)beginbfrange(.*?)endbfrange`) + pdfPairRe = regexp.MustCompile(`<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>`) + pdfRangeRe = regexp.MustCompile(`<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>`) + pdfArrayRe = regexp.MustCompile(`(?s)<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[(.*?)\]`) + pdfHexRe = regexp.MustCompile(`<([0-9A-Fa-f]+)>`) +) + +func extractPDFText(content []byte) string { + streams := pdfStreams(content) + streams = append(streams, pdfObjectStream{object: 0, data: content}) + cmap := map[int]string{} + for _, s := range streams { + if bytes.Contains(s.data, []byte("beginbf")) { + for k, v := range parsePDFCMap(s.data) { + cmap[k] = v + } + } + } + + var b strings.Builder + for _, s := range streams { + if bytes.Contains(s.data, []byte("beginbf")) { + continue + } + for _, op := range pdfTextOpRe.FindAll(s.data, -1) { + for _, match := range pdfStringRe.FindAllSubmatch(op, -1) { + raw := match[0] + if len(raw) == 0 { + continue + } + if raw[0] == '(' { + b.WriteString(mapPDFTextBytes(unescapePDFLiteral(raw[1:len(raw)-1]), cmap)) + continue + } + if len(match) > 1 && len(match[1]) > 0 { + decoded, ok := decodePDFHex(match[1]) + if ok { + b.WriteString(mapPDFTextBytes(decoded, cmap)) + } + } + } + } + } + return b.String() +} + +func extractPDFRawText(content []byte) string { + streams := pdfStreams(content) + streams = append(streams, pdfObjectStream{object: 0, data: content}) + var b strings.Builder + for _, s := range streams { + if bytes.Contains(s.data, []byte("beginbf")) { + continue + } + for _, op := range pdfTextOpRe.FindAll(s.data, -1) { + for _, match := range pdfStringRe.FindAllSubmatch(op, -1) { + raw := match[0] + if len(raw) == 0 { + continue + } + if raw[0] == '(' { + b.WriteString(decodeRawPDFBytes(unescapePDFLiteral(raw[1 : len(raw)-1]))) + continue + } + if len(match) > 1 && len(match[1]) > 0 { + decoded, ok := decodePDFHex(match[1]) + if ok { + b.WriteString(decodeRawPDFBytes(decoded)) + } + } + } + } + } + return b.String() +} + +func decodeRawPDFBytes(value []byte) string { + if len(value) >= 2 && value[0] == 0xfe && value[1] == 0xff { + return decodeUTF16BE(value[2:]) + } + zeros := 0 + for i := 0; i < len(value); i += 2 { + if value[i] == 0 { + zeros++ + } + } + if len(value) > 2 && zeros > len(value)/4 { + return decodeUTF16BE(value) + } + return string(value) +} + +func decodeUTF16BE(value []byte) string { + if len(value)%2 == 1 { + value = append([]byte{0}, value...) + } + u16 := make([]uint16, 0, len(value)/2) + for i := 0; i+1 < len(value); i += 2 { + u16 = append(u16, uint16(value[i])<<8|uint16(value[i+1])) + } + return string(utf16.Decode(u16)) +} + +func pdfStreams(content []byte) []pdfObjectStream { + matches := pdfObjectRe.FindAllSubmatch(content, -1) + out := make([]pdfObjectStream, 0, len(matches)) + for _, m := range matches { + obj, _ := strconv.Atoi(string(m[1])) + body := m[2] + sm := pdfStreamRe.FindSubmatch(body) + if len(sm) == 0 { + continue + } + data := bytes.Trim(sm[1], "\r\n") + if bytes.Contains(body, []byte("/FlateDecode")) { + if inflated, err := inflatePDFStream(data); err == nil { + data = inflated + } + } + out = append(out, pdfObjectStream{object: obj, body: body, data: data}) + } + return out +} + +func inflatePDFStream(data []byte) ([]byte, error) { + r, err := zlib.NewReader(bytes.NewReader(data)) + if err != nil { + return nil, err + } + defer r.Close() + return io.ReadAll(r) +} + +func parsePDFCMap(data []byte) map[int]string { + out := map[int]string{} + for _, block := range pdfBfCharRe.FindAllSubmatch(data, -1) { + for _, pair := range pdfPairRe.FindAllSubmatch(block[1], -1) { + code, err := strconv.ParseInt(string(pair[1]), 16, 32) + if err == nil { + out[int(code)] = decodeUTF16BEHex(pair[2]) + } + } + } + + for _, block := range pdfBfRangeRe.FindAllSubmatch(data, -1) { + for _, arr := range pdfArrayRe.FindAllSubmatch(block[1], -1) { + start, err := strconv.ParseInt(string(arr[1]), 16, 32) + if err != nil { + continue + } + values := pdfHexRe.FindAllSubmatch(arr[3], -1) + for i, value := range values { + out[int(start)+i] = decodeUTF16BEHex(value[1]) + } + } + for _, rng := range pdfRangeRe.FindAllSubmatch(block[1], -1) { + start, err1 := strconv.ParseInt(string(rng[1]), 16, 32) + end, err2 := strconv.ParseInt(string(rng[2]), 16, 32) + base, err3 := strconv.ParseInt(string(rng[3]), 16, 32) + if err1 != nil || err2 != nil || err3 != nil || end < start { + continue + } + width := len(rng[3]) + for code := start; code <= end; code++ { + value := strconv.FormatInt(base+code-start, 16) + if len(value) < width { + value = strings.Repeat("0", width-len(value)) + value + } + out[int(code)] = decodeUTF16BEHex([]byte(value)) + } + } + } + return out +} + +func decodeUTF16BEHex(value []byte) string { + decoded, ok := decodePDFHex(value) + if !ok || len(decoded) == 0 { + return "" + } + if len(decoded)%2 == 1 { + decoded = append([]byte{0}, decoded...) + } + u16 := make([]uint16, 0, len(decoded)/2) + for i := 0; i+1 < len(decoded); i += 2 { + u16 = append(u16, uint16(decoded[i])<<8|uint16(decoded[i+1])) + } + return string(utf16.Decode(u16)) +} + +func decodePDFHex(value []byte) ([]byte, bool) { + clean := strings.Map(func(r rune) rune { + if r == ' ' || r == '\n' || r == '\r' || r == '\t' { + return -1 + } + return r + }, string(value)) + if len(clean)%2 == 1 { + clean += "0" + } + decoded, err := hex.DecodeString(clean) + return decoded, err == nil +} + +func unescapePDFLiteral(value []byte) []byte { + out := make([]byte, 0, len(value)) + for i := 0; i < len(value); i++ { + if value[i] != '\\' || i+1 >= len(value) { + out = append(out, value[i]) + continue + } + i++ + switch value[i] { + case 'n': + out = append(out, '\n') + case 'r': + out = append(out, '\r') + case 't': + out = append(out, '\t') + case 'b': + out = append(out, '\b') + case 'f': + out = append(out, '\f') + case '(', ')', '\\': + out = append(out, value[i]) + default: + if value[i] >= '0' && value[i] <= '7' { + octal := []byte{value[i]} + for j := 0; j < 2 && i+1 < len(value) && value[i+1] >= '0' && value[i+1] <= '7'; j++ { + i++ + octal = append(octal, value[i]) + } + n, err := strconv.ParseInt(string(octal), 8, 16) + if err == nil { + out = append(out, byte(n)) + } + } else { + out = append(out, value[i]) + } + } + } + return out +} + +func mapPDFTextBytes(value []byte, cmap map[int]string) string { + var b strings.Builder + for i := 0; i < len(value); { + if i+1 < len(value) { + code := int(value[i])<<8 | int(value[i+1]) + if mapped, ok := cmap[code]; ok { + b.WriteString(mapped) + i += 2 + continue + } + } + if mapped, ok := cmap[int(value[i])]; ok { + b.WriteString(mapped) + } else { + b.WriteByte(value[i]) + } + i++ + } + return b.String() +} diff --git a/backend/service/policy.go b/backend/service/policy.go new file mode 100644 index 0000000..d7305c9 --- /dev/null +++ b/backend/service/policy.go @@ -0,0 +1,270 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "household-book/model" +) + +type PolicyService struct { + db *sql.DB + now func() time.Time +} + +func NewPolicyService(db *sql.DB) *PolicyService { return &PolicyService{db: db, now: time.Now} } + +func (s *PolicyService) List(ctx context.Context) ([]model.Policy, error) { + rows, err := s.db.QueryContext(ctx, `SELECT id, name, type, insured_person, premium, coverage_amount, start_date, end_date, payment_frequency, next_payment_date, payment_term_end, beneficiary, status, note, created_at, updated_at FROM policies ORDER BY next_payment_date, id`) + if err != nil { + return nil, fmt.Errorf("query policies: %w", err) + } + defer rows.Close() + var list []model.Policy + for rows.Next() { + var p model.Policy + if err := rows.Scan(&p.ID, &p.Name, &p.Type, &p.InsuredPerson, &p.Premium, &p.CoverageAmount, &p.StartDate, &p.EndDate, &p.PaymentFrequency, &p.NextPaymentDate, &p.PaymentTermEnd, &p.Beneficiary, &p.Status, &p.Note, &p.CreatedAt, &p.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan policy: %w", err) + } + list = append(list, p) + } + if list == nil { + list = []model.Policy{} + } + return list, rows.Err() +} + +func (s *PolicyService) Upcoming(ctx context.Context, days int) ([]model.Policy, error) { + if days <= 0 { + days = 30 + } + today := s.now().In(time.Local) + start := today.Format("2006-01-02") + end := today.AddDate(0, 0, days).Format("2006-01-02") + rows, err := s.db.QueryContext(ctx, `SELECT id, name, type, insured_person, premium, coverage_amount, start_date, end_date, payment_frequency, next_payment_date, payment_term_end, beneficiary, status, note, created_at, updated_at + FROM policies + WHERE status = 'active' AND next_payment_date <> '' AND date(next_payment_date) BETWEEN date(?) AND date(?) + ORDER BY next_payment_date`, start, end) + if err != nil { + return nil, fmt.Errorf("query upcoming policies: %w", err) + } + defer rows.Close() + var list []model.Policy + for rows.Next() { + var p model.Policy + if err := rows.Scan(&p.ID, &p.Name, &p.Type, &p.InsuredPerson, &p.Premium, &p.CoverageAmount, &p.StartDate, &p.EndDate, &p.PaymentFrequency, &p.NextPaymentDate, &p.PaymentTermEnd, &p.Beneficiary, &p.Status, &p.Note, &p.CreatedAt, &p.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan policy: %w", err) + } + list = append(list, p) + } + if list == nil { + list = []model.Policy{} + } + return list, rows.Err() +} + +func (s *PolicyService) Create(ctx context.Context, req model.CreatePolicyRequest) (*model.Policy, error) { + result, err := s.db.ExecContext(ctx, `INSERT INTO policies (name, type, insured_person, premium, coverage_amount, start_date, end_date, payment_frequency, next_payment_date, payment_term_end, beneficiary, status, note) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, req.Name, req.Type, req.InsuredPerson, req.Premium, req.CoverageAmount, req.StartDate, req.EndDate, req.PaymentFrequency, req.NextPaymentDate, req.PaymentTermEnd, req.Beneficiary, req.Status, req.Note) + if err != nil { + return nil, fmt.Errorf("insert policy: %w", err) + } + id, _ := result.LastInsertId() + return s.GetByID(ctx, id) +} + +func (s *PolicyService) GetByID(ctx context.Context, id int64) (*model.Policy, error) { + var p model.Policy + err := s.db.QueryRowContext(ctx, `SELECT id, name, type, insured_person, premium, coverage_amount, start_date, end_date, payment_frequency, next_payment_date, payment_term_end, beneficiary, status, note, created_at, updated_at FROM policies WHERE id = ?`, id). + Scan(&p.ID, &p.Name, &p.Type, &p.InsuredPerson, &p.Premium, &p.CoverageAmount, &p.StartDate, &p.EndDate, &p.PaymentFrequency, &p.NextPaymentDate, &p.PaymentTermEnd, &p.Beneficiary, &p.Status, &p.Note, &p.CreatedAt, &p.UpdatedAt) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query policy: %w", err) + } + return &p, nil +} + +func (s *PolicyService) Update(ctx context.Context, id int64, req model.UpdatePolicyRequest) (*model.Policy, error) { + var sets []string + var args []any + if req.Name != nil { + sets = append(sets, "name = ?") + args = append(args, *req.Name) + } + if req.Type != nil { + sets = append(sets, "type = ?") + args = append(args, *req.Type) + } + if req.InsuredPerson != nil { + sets = append(sets, "insured_person = ?") + args = append(args, *req.InsuredPerson) + } + if req.Premium != nil { + sets = append(sets, "premium = ?") + args = append(args, *req.Premium) + } + if req.CoverageAmount != nil { + sets = append(sets, "coverage_amount = ?") + args = append(args, *req.CoverageAmount) + } + if req.StartDate != nil { + sets = append(sets, "start_date = ?") + args = append(args, *req.StartDate) + } + if req.EndDate != nil { + sets = append(sets, "end_date = ?") + args = append(args, *req.EndDate) + } + if req.PaymentFrequency != nil { + sets = append(sets, "payment_frequency = ?") + args = append(args, *req.PaymentFrequency) + } + if req.NextPaymentDate != nil { + sets = append(sets, "next_payment_date = ?") + args = append(args, *req.NextPaymentDate) + } + if req.PaymentTermEnd != nil { + sets = append(sets, "payment_term_end = ?") + args = append(args, *req.PaymentTermEnd) + } + if req.Beneficiary != nil { + sets = append(sets, "beneficiary = ?") + args = append(args, *req.Beneficiary) + } + if req.Status != nil { + sets = append(sets, "status = ?") + args = append(args, *req.Status) + } + if req.Note != nil { + sets = append(sets, "note = ?") + args = append(args, *req.Note) + } + if len(sets) == 0 { + return s.GetByID(ctx, id) + } + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + result, err := s.db.ExecContext(ctx, "UPDATE policies SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...) + if err != nil { + return nil, fmt.Errorf("update policy: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, err + } else if affected == 0 { + return nil, ErrNotFound + } + return s.GetByID(ctx, id) +} + +func (s *PolicyService) Delete(ctx context.Context, id int64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM policies WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return err + } else if affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *PolicyService) ListPayments(ctx context.Context, policyID int64) ([]model.PolicyPayment, error) { + rows, err := s.db.QueryContext(ctx, `SELECT pp.id, pp.policy_id, p.name, pp.due_date, pp.amount, pp.status, pp.paid_date, pp.note, pp.created_at, pp.updated_at FROM policy_payments pp JOIN policies p ON p.id=pp.policy_id WHERE pp.policy_id=? ORDER BY pp.due_date DESC, pp.id DESC`, policyID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []model.PolicyPayment{} + for rows.Next() { + var v model.PolicyPayment + if err := rows.Scan(&v.ID, &v.PolicyID, &v.PolicyName, &v.DueDate, &v.Amount, &v.Status, &v.PaidDate, &v.Note, &v.CreatedAt, &v.UpdatedAt); err != nil { + return nil, err + } + items = append(items, v) + } + return items, rows.Err() +} + +func (s *PolicyService) CreatePayment(ctx context.Context, policyID int64, req model.CreatePolicyPaymentRequest) (*model.PolicyPayment, error) { + r, err := s.db.ExecContext(ctx, `INSERT INTO policy_payments(policy_id,due_date,amount,note) VALUES(?,?,?,?)`, policyID, req.DueDate, req.Amount, req.Note) + if err != nil { + return nil, err + } + id, _ := r.LastInsertId() + return s.getPayment(ctx, id) +} + +func (s *PolicyService) UpdatePayment(ctx context.Context, id int64, req model.UpdatePolicyPaymentRequest) (*model.PolicyPayment, error) { + if req.Status != "pending" && req.Status != "paid" && req.Status != "skipped" { + return nil, ErrInvalidPaymentStatus + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + var policyID int64 + var due string + if err = tx.QueryRowContext(ctx, `SELECT policy_id,due_date FROM policy_payments WHERE id=?`, id).Scan(&policyID, &due); err != nil { + return nil, err + } + paidDate := req.PaidDate + if req.Status == "paid" && paidDate == "" { + paidDate = s.now().Format("2006-01-02") + } + if req.Status != "paid" { + paidDate = "" + } + if _, err = tx.ExecContext(ctx, `UPDATE policy_payments SET status=?,paid_date=?,updated_at=datetime('now') WHERE id=?`, req.Status, paidDate, id); err != nil { + return nil, err + } + if req.Status == "paid" || req.Status == "skipped" { + var frequency string + if err = tx.QueryRowContext(ctx, `SELECT payment_frequency FROM policies WHERE id=?`, policyID).Scan(&frequency); err != nil { + return nil, err + } + next := nextPaymentDate(due, frequency) + if next != "" { + _, err = tx.ExecContext(ctx, `UPDATE policies SET next_payment_date=?,updated_at=datetime('now') WHERE id=?`, next, policyID) + if err != nil { + return nil, err + } + } + } + if err = tx.Commit(); err != nil { + return nil, err + } + return s.getPayment(ctx, id) +} + +func (s *PolicyService) getPayment(ctx context.Context, id int64) (*model.PolicyPayment, error) { + var v model.PolicyPayment + err := s.db.QueryRowContext(ctx, `SELECT pp.id,pp.policy_id,p.name,pp.due_date,pp.amount,pp.status,pp.paid_date,pp.note,pp.created_at,pp.updated_at FROM policy_payments pp JOIN policies p ON p.id=pp.policy_id WHERE pp.id=?`, id).Scan(&v.ID, &v.PolicyID, &v.PolicyName, &v.DueDate, &v.Amount, &v.Status, &v.PaidDate, &v.Note, &v.CreatedAt, &v.UpdatedAt) + return &v, err +} + +func nextPaymentDate(date, frequency string) string { + d, err := time.Parse("2006-01-02", date) + if err != nil { + return "" + } + switch frequency { + case "monthly": + d = d.AddDate(0, 1, 0) + case "quarterly": + d = d.AddDate(0, 3, 0) + case "semiannual": + d = d.AddDate(0, 6, 0) + case "annual": + d = d.AddDate(1, 0, 0) + default: + return "" + } + return d.Format("2006-01-02") +} diff --git a/backend/service/policy_test.go b/backend/service/policy_test.go new file mode 100644 index 0000000..edf07af --- /dev/null +++ b/backend/service/policy_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "context" + "database/sql" + "testing" + "time" + + _ "modernc.org/sqlite" +) + +func TestUpcomingPoliciesUsesInclusiveLocalDateWindow(t *testing.T) { + db := setupPolicyTestDB(t) + svc := NewPolicyService(db) + svc.now = func() time.Time { + return time.Date(2026, 4, 28, 23, 30, 0, 0, time.Local) + } + + insertPolicy(t, db, "expired", "2026-04-27") + insertPolicy(t, db, "today", "2026-04-28") + insertPolicy(t, db, "in 30 days", "2026-05-28") + insertPolicy(t, db, "in 31 days", "2026-05-29") + insertPolicy(t, db, "no end date", "") + + items, err := svc.Upcoming(context.Background(), 30) + if err != nil { + t.Fatalf("Upcoming returned error: %v", err) + } + + got := make([]string, 0, len(items)) + for _, item := range items { + got = append(got, item.Name) + } + want := []string{"today", "in 30 days"} + if len(got) != len(want) { + t.Fatalf("expected %v, got %v", want, got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("expected %v, got %v", want, got) + } + } +} + +func setupPolicyTestDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + + _, err = db.Exec(`CREATE TABLE policies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'other', + insured_person TEXT NOT NULL DEFAULT '', + premium INTEGER NOT NULL DEFAULT 0, + coverage_amount INTEGER NOT NULL DEFAULT 0, + start_date TEXT NOT NULL DEFAULT '', + end_date TEXT NOT NULL DEFAULT '', + payment_frequency TEXT NOT NULL DEFAULT 'annual', + next_payment_date TEXT NOT NULL DEFAULT '', + payment_term_end TEXT NOT NULL DEFAULT '', + beneficiary TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'active', + note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`) + if err != nil { + t.Fatalf("create policies table: %v", err) + } + return db +} + +func insertPolicy(t *testing.T, db *sql.DB, name string, endDate string) { + t.Helper() + _, err := db.Exec(`INSERT INTO policies (name, end_date, next_payment_date) VALUES (?, ?, ?)`, name, endDate, endDate) + if err != nil { + t.Fatalf("insert policy %q: %v", name, err) + } +} diff --git a/backend/service/report.go b/backend/service/report.go new file mode 100644 index 0000000..7445dcc --- /dev/null +++ b/backend/service/report.go @@ -0,0 +1,126 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + + "household-book/model" +) + +type ReportService struct { + db *sql.DB +} + +func NewReportService(db *sql.DB) *ReportService { + return &ReportService{db: db} +} + +func (s *ReportService) CategoryRanking(ctx context.Context, year, month int, typ string, limit int) ([]model.CategoryRankingItem, error) { + if typ == "" { + typ = "expense" + } + if limit <= 0 { + limit = 10 + } + + // 百分比分母用当月该类型的全部金额,与 LIMIT 解耦: + // 否则当分类数 > limit 时,截断后的 top-N 之和会让百分比之和强行凑到 100%,与实际口径不符。 + var monthTotal int64 + if err := s.db.QueryRowContext(ctx, + `SELECT COALESCE(SUM(amount), 0) FROM transactions + WHERE type = ? + AND strftime('%Y', date) = printf('%04d', ?) + AND strftime('%m', date) = printf('%02d', ?)`, + typ, year, month, + ).Scan(&monthTotal); err != nil { + return nil, fmt.Errorf("query month total: %w", err) + } + + // 与预算看板一致:仅统计叶子分类(parent_id IS NOT NULL),避免父类与子类金额并列不可加。 + rows, err := s.db.QueryContext(ctx, `SELECT c.id, c.name, c.is_active, COALESCE(SUM(t.amount), 0) AS amount + FROM transactions t + JOIN categories c ON c.id = t.category_id + WHERE t.type = ? + AND c.parent_id IS NOT NULL + AND strftime('%Y', t.date) = printf('%04d', ?) + AND strftime('%m', t.date) = printf('%02d', ?) + GROUP BY c.id, c.name, c.is_active + ORDER BY amount DESC + LIMIT ?`, typ, year, month, limit) + if err != nil { + return nil, fmt.Errorf("query category ranking: %w", err) + } + defer rows.Close() + + var items []model.CategoryRankingItem + for rows.Next() { + var item model.CategoryRankingItem + var isActive int + if err := rows.Scan(&item.CategoryID, &item.CategoryName, &isActive, &item.Amount); err != nil { + return nil, fmt.Errorf("scan category ranking: %w", err) + } + item.CategoryIsActive = isActive == 1 + items = append(items, item) + } + if err := rows.Err(); err != nil { + return nil, err + } + if items == nil { + items = []model.CategoryRankingItem{} + } + if monthTotal > 0 { + for i := range items { + items[i].Percent = float64(items[i].Amount) / float64(monthTotal) * 100 + } + } + return items, nil +} + +func (s *ReportService) Trend(ctx context.Context, year int) ([]model.TrendItem, error) { + rows, err := s.db.QueryContext(ctx, `WITH months(month) AS ( + VALUES ('01'), ('02'), ('03'), ('04'), ('05'), ('06'), ('07'), ('08'), ('09'), ('10'), ('11'), ('12') + ) + SELECT + printf('%04d-', ?) || months.month AS month, + COALESCE(SUM(CASE WHEN t.type = 'income' THEN t.amount ELSE 0 END), 0) AS income, + COALESCE(SUM(CASE WHEN t.type = 'expense' THEN t.amount ELSE 0 END), 0) AS expense + FROM months + LEFT JOIN transactions t + ON strftime('%Y', t.date) = printf('%04d', ?) + AND strftime('%m', t.date) = months.month + GROUP BY months.month + ORDER BY months.month`, year, year) + if err != nil { + return nil, fmt.Errorf("query trend: %w", err) + } + defer rows.Close() + + items := make([]model.TrendItem, 0, 12) + for rows.Next() { + var item model.TrendItem + if err := rows.Scan(&item.Month, &item.Income, &item.Expense); err != nil { + return nil, fmt.Errorf("scan trend: %w", err) + } + item.Balance = item.Income - item.Expense + items = append(items, item) + } + return items, rows.Err() +} + +func (s *ReportService) Overview(ctx context.Context, year, month int, typ string) (*model.ReportOverview, error) { + ranking, err := s.CategoryRanking(ctx, year, month, typ, 10) + if err != nil { + return nil, err + } + trend, err := s.Trend(ctx, year) + if err != nil { + return nil, err + } + return &model.ReportOverview{ + Year: year, + Month: month, + CategoryRanking: ranking, + Trend: trend, + }, nil +} diff --git a/backend/service/report_test.go b/backend/service/report_test.go new file mode 100644 index 0000000..2c8122e --- /dev/null +++ b/backend/service/report_test.go @@ -0,0 +1,116 @@ +package service + +import ( + "context" + "database/sql" + "testing" + + _ "modernc.org/sqlite" +) + +func TestCategoryRankingOnlyLeafCategories(t *testing.T) { + db := setupReportTestDB(t) + svc := NewReportService(db) + ctx := context.Background() + + insertCategory(t, db, 1, "支出", "expense", nil, 1) + insertCategory(t, db, 2, "餐饮", "expense", int64Ptr(1), 1) + insertTransaction(t, db, "expense", 1000, 1, "2026-05-10") + insertTransaction(t, db, "expense", 2000, 2, "2026-05-11") + + items, err := svc.CategoryRanking(ctx, 2026, 5, "expense", 10) + if err != nil { + t.Fatalf("CategoryRanking: %v", err) + } + if len(items) != 1 { + t.Fatalf("expected only leaf category in ranking, got %d items", len(items)) + } + if items[0].CategoryID != 2 || items[0].Amount != 2000 { + t.Fatalf("unexpected ranking item: %+v", items[0]) + } +} + +func TestCategoryRankingIncludesInactiveFlag(t *testing.T) { + db := setupReportTestDB(t) + svc := NewReportService(db) + ctx := context.Background() + + insertCategory(t, db, 1, "支出", "expense", nil, 1) + insertCategory(t, db, 2, "旧分类", "expense", int64Ptr(1), 0) + insertTransaction(t, db, "expense", 500, 2, "2026-05-12") + + items, err := svc.CategoryRanking(ctx, 2026, 5, "expense", 10) + if err != nil { + t.Fatalf("CategoryRanking: %v", err) + } + if len(items) != 1 { + t.Fatalf("expected 1 item, got %d", len(items)) + } + if items[0].CategoryIsActive { + t.Fatalf("expected inactive category, got %+v", items[0]) + } +} + +func setupReportTestDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + + stmts := []string{ + `CREATE TABLE categories ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + parent_id INTEGER, + is_active INTEGER NOT NULL DEFAULT 1 + )`, + `CREATE TABLE transactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT NOT NULL, + amount INTEGER NOT NULL, + category_id INTEGER, + account_id INTEGER, + to_account_id INTEGER, + member_id INTEGER, + date TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + counterparty TEXT NOT NULL DEFAULT '', + import_batch_id INTEGER, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`, + } + for _, stmt := range stmts { + if _, err := db.Exec(stmt); err != nil { + t.Fatalf("exec schema: %v", err) + } + } + return db +} + +func insertCategory(t *testing.T, db *sql.DB, id int64, name, typ string, parentID *int64, isActive int) { + t.Helper() + _, err := db.Exec( + `INSERT INTO categories (id, name, type, parent_id, is_active) VALUES (?, ?, ?, ?, ?)`, + id, name, typ, parentID, isActive, + ) + if err != nil { + t.Fatalf("insert category: %v", err) + } +} + +func insertTransaction(t *testing.T, db *sql.DB, typ string, amount, categoryID int64, date string) { + t.Helper() + _, err := db.Exec( + `INSERT INTO transactions (type, amount, category_id, date) VALUES (?, ?, ?, ?)`, + typ, amount, categoryID, date, + ) + if err != nil { + t.Fatalf("insert transaction: %v", err) + } +} + +func int64Ptr(v int64) *int64 { return &v } diff --git a/backend/service/source_key_test.go b/backend/service/source_key_test.go new file mode 100644 index 0000000..84c19a3 --- /dev/null +++ b/backend/service/source_key_test.go @@ -0,0 +1,15 @@ +package service + +import ( + "testing" + + "household-book/model" +) + +func TestSourceKeyDoesNotDependOnWholeFile(t *testing.T) { + a := model.ImportTransactionsRequest{Content: []byte("first export"), SourceKind: "wechat", BankName: "微信", CardType: "wechat"} + b := model.ImportTransactionsRequest{Content: []byte("overlapping export"), SourceKind: "wechat", BankName: "微信", CardType: "wechat"} + if sourceKey(a, "stable-trade-id") != sourceKey(b, "stable-trade-id") { + t.Fatal("same transaction identity should deduplicate across different files") + } +} diff --git a/backend/service/transaction.go b/backend/service/transaction.go new file mode 100644 index 0000000..58c90ff --- /dev/null +++ b/backend/service/transaction.go @@ -0,0 +1,432 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "household-book/model" +) + +type TransactionService struct { + db *sql.DB +} + +func NewTransactionService(db *sql.DB) *TransactionService { + return &TransactionService{db: db} +} + +func (s *TransactionService) List(ctx context.Context, req model.TransactionListRequest) (*model.TransactionListResponse, error) { + var conditions []string + var args []any + + if req.Month != "" { + conditions = append(conditions, "t.date LIKE ?") + args = append(args, req.Month+"%") + } + if req.DateFrom != "" { + conditions = append(conditions, "t.date >= ?") + args = append(args, req.DateFrom) + } + if req.DateTo != "" { + conditions = append(conditions, "t.date <= ?") + args = append(args, req.DateTo) + } + if req.CategoryID != nil { + conditions = append(conditions, "t.category_id = ?") + args = append(args, *req.CategoryID) + } + if req.Type != "" { + conditions = append(conditions, "t.type = ?") + args = append(args, req.Type) + } + if req.MemberID != nil { + conditions = append(conditions, "t.member_id = ?") + args = append(args, *req.MemberID) + } + if req.AccountID != nil { + conditions = append(conditions, "(t.account_id = ? OR t.to_account_id = ?)") + args = append(args, *req.AccountID, *req.AccountID) + } + if req.ImportBatchID != nil { + conditions = append(conditions, "t.import_batch_id = ?") + args = append(args, *req.ImportBatchID) + } + if req.Keyword != "" { + conditions = append(conditions, "(t.description LIKE ? OR t.counterparty LIKE ?)") + args = append(args, "%"+req.Keyword+"%", "%"+req.Keyword+"%") + } + + where := "" + if len(conditions) > 0 { + where = " WHERE " + strings.Join(conditions, " AND ") + } + + // Count total + var total int + countQuery := "SELECT COUNT(*) FROM transactions t" + where + if err := s.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil { + return nil, fmt.Errorf("count transactions: %w", err) + } + + // Pagination + if req.Page < 1 { + req.Page = 1 + } + if req.PageSize < 1 { + req.PageSize = 20 + } + offset := (req.Page - 1) * req.PageSize + + query := `SELECT t.id, t.type, t.amount, t.category_id, COALESCE(c.name,''), COALESCE(c.is_active, 1), + t.account_id, COALESCE(a.name,''), t.to_account_id, COALESCE(ta.name,''), + t.member_id, COALESCE(m.name,''), + t.date, t.description, COALESCE(t.counterparty,''), t.import_batch_id, COALESCE(ib.filename,''), + t.created_at, t.updated_at + FROM transactions t + LEFT JOIN categories c ON t.category_id = c.id + LEFT JOIN accounts a ON t.account_id = a.id + LEFT JOIN accounts ta ON t.to_account_id = ta.id + LEFT JOIN members m ON t.member_id = m.id + LEFT JOIN import_batches ib ON t.import_batch_id = ib.id` + where + + " ORDER BY t.date DESC, t.id DESC LIMIT ? OFFSET ?" + fullArgs := append(args, req.PageSize, offset) + + rows, err := s.db.QueryContext(ctx, query, fullArgs...) + if err != nil { + return nil, fmt.Errorf("query transactions: %w", err) + } + defer rows.Close() + + var items []model.TransactionListItem + for rows.Next() { + var item model.TransactionListItem + var categoryIsActive int + if err := rows.Scan( + &item.ID, &item.Type, &item.Amount, + &item.CategoryID, &item.CategoryName, &categoryIsActive, + &item.AccountID, &item.AccountName, + &item.ToAccountID, &item.ToAccountName, + &item.MemberID, &item.MemberName, + &item.Date, &item.Description, &item.Counterparty, + &item.ImportBatchID, &item.ImportFilename, + &item.CreatedAt, &item.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan transaction: %w", err) + } + item.CategoryIsActive = categoryIsActive == 1 + items = append(items, item) + } + if items == nil { + items = []model.TransactionListItem{} + } + + return &model.TransactionListResponse{ + Items: items, + Total: total, + Page: req.Page, + PageSize: req.PageSize, + }, rows.Err() +} + +func (s *TransactionService) GetByID(ctx context.Context, id int64) (*model.Transaction, error) { + var t model.Transaction + err := s.db.QueryRowContext(ctx, + `SELECT id, type, amount, category_id, account_id, to_account_id, member_id, date, description, + COALESCE(counterparty,''), import_batch_id, created_at, updated_at + FROM transactions WHERE id = ?`, id, + ).Scan(&t.ID, &t.Type, &t.Amount, &t.CategoryID, &t.AccountID, &t.ToAccountID, &t.MemberID, + &t.Date, &t.Description, &t.Counterparty, &t.ImportBatchID, &t.CreatedAt, &t.UpdatedAt) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("query transaction: %w", err) + } + return &t, nil +} + +func (s *TransactionService) Create(ctx context.Context, req model.CreateTransactionRequest) (*model.Transaction, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + result, err := tx.ExecContext(ctx, + `INSERT INTO transactions (type, amount, category_id, account_id, to_account_id, member_id, date, description, counterparty) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + req.Type, req.Amount, req.CategoryID, req.AccountID, req.ToAccountID, req.MemberID, req.Date, req.Description, req.Counterparty) + if err != nil { + return nil, fmt.Errorf("insert transaction: %w", err) + } + id, _ := result.LastInsertId() + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func (s *TransactionService) Update(ctx context.Context, id int64, req model.UpdateTransactionRequest) (*model.Transaction, error) { + current, err := s.GetByID(ctx, id) + if err != nil { + return nil, err + } + merged := *current + mergeTransactionUpdate(&merged, req) + if err := validateTransactionFields(merged.Type, merged.CategoryID, merged.AccountID, merged.ToAccountID); err != nil { + return nil, err + } + + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + var sets []string + var args []any + + if req.Type != nil { + sets = append(sets, "type = ?") + args = append(args, *req.Type) + } + if req.Amount != nil { + sets = append(sets, "amount = ?") + args = append(args, *req.Amount) + } + if req.CategoryID.Set { + sets = append(sets, "category_id = ?") + if req.CategoryID.Valid { + args = append(args, req.CategoryID.Value) + } else { + args = append(args, nil) + } + } + if req.AccountID.Set { + sets = append(sets, "account_id = ?") + if req.AccountID.Valid { + args = append(args, req.AccountID.Value) + } else { + args = append(args, nil) + } + } + if req.ToAccountID.Set { + sets = append(sets, "to_account_id = ?") + if req.ToAccountID.Valid { + args = append(args, req.ToAccountID.Value) + } else { + args = append(args, nil) + } + } + if req.MemberID.Set { + sets = append(sets, "member_id = ?") + if req.MemberID.Valid { + args = append(args, req.MemberID.Value) + } else { + args = append(args, nil) + } + } + if req.Date != nil { + sets = append(sets, "date = ?") + args = append(args, *req.Date) + } + if req.Description != nil { + sets = append(sets, "description = ?") + args = append(args, *req.Description) + } + if req.Counterparty != nil { + sets = append(sets, "counterparty = ?") + args = append(args, *req.Counterparty) + } + + if len(sets) == 0 { + return s.GetByID(ctx, id) + } + + sets = append(sets, "updated_at = datetime('now')") + args = append(args, id) + + query := "UPDATE transactions SET " + strings.Join(sets, ", ") + " WHERE id = ?" + result, err := tx.ExecContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("update transaction: %w", err) + } + if affected, err := result.RowsAffected(); err != nil { + return nil, fmt.Errorf("check updated transaction: %w", err) + } else if affected == 0 { + return nil, ErrNotFound + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit: %w", err) + } + + return s.GetByID(ctx, id) +} + +func mergeTransactionUpdate(t *model.Transaction, req model.UpdateTransactionRequest) { + if req.Type != nil { + t.Type = *req.Type + } + if req.CategoryID.Set { + if req.CategoryID.Valid { + v := req.CategoryID.Value + t.CategoryID = &v + } else { + t.CategoryID = nil + } + } + if req.AccountID.Set { + if req.AccountID.Valid { + v := req.AccountID.Value + t.AccountID = &v + } else { + t.AccountID = nil + } + } + if req.ToAccountID.Set { + if req.ToAccountID.Valid { + v := req.ToAccountID.Value + t.ToAccountID = &v + } else { + t.ToAccountID = nil + } + } +} + +func validateTransactionFields(typ string, categoryID, accountID, toAccountID *int64) error { + if typ == "transfer" { + if categoryID != nil || accountID == nil || toAccountID == nil || *accountID == *toAccountID { + return ErrInvalidTransaction + } + return nil + } + if (typ != "income" && typ != "expense") || categoryID == nil || *categoryID <= 0 || toAccountID != nil { + return ErrInvalidTransaction + } + return nil +} + +func (s *TransactionService) Delete(ctx context.Context, id int64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM transactions WHERE id = ?", id) + if err != nil { + return err + } + if affected, err := result.RowsAffected(); err != nil { + return fmt.Errorf("check deleted transaction: %w", err) + } else if affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *TransactionService) DeleteBatch(ctx context.Context, ids []int64) (int64, error) { + if len(ids) == 0 { + return 0, nil + } + placeholders := make([]string, len(ids)) + args := make([]any, len(ids)) + for i, id := range ids { + placeholders[i] = "?" + args[i] = id + } + result, err := s.db.ExecContext(ctx, "DELETE FROM transactions WHERE id IN ("+strings.Join(placeholders, ",")+")", args...) + if err != nil { + return 0, fmt.Errorf("delete transactions: %w", err) + } + return result.RowsAffected() +} + +func (s *TransactionService) ListImportBatches(ctx context.Context) ([]model.ImportBatch, error) { + rows, err := s.db.QueryContext(ctx, + `SELECT ib.id, ib.filename, ib.bank_name, ib.card_type, ib.account_id, COALESCE(a.name,''), + ib.imported_count, ib.skipped_count, ib.created_at + FROM import_batches ib + LEFT JOIN accounts a ON ib.account_id = a.id + ORDER BY ib.created_at DESC, ib.id DESC`) + if err != nil { + return nil, fmt.Errorf("query import batches: %w", err) + } + defer rows.Close() + + var batches []model.ImportBatch + for rows.Next() { + var b model.ImportBatch + if err := rows.Scan(&b.ID, &b.Filename, &b.BankName, &b.CardType, &b.AccountID, &b.AccountName, &b.ImportedCount, &b.SkippedCount, &b.CreatedAt); err != nil { + return nil, fmt.Errorf("scan import batch: %w", err) + } + batches = append(batches, b) + } + if batches == nil { + batches = []model.ImportBatch{} + } + return batches, rows.Err() +} + +func (s *TransactionService) DeleteImportBatch(ctx context.Context, batchID int64) (int64, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + var batchAccountID sql.NullInt64 + if err := tx.QueryRowContext(ctx, "SELECT account_id FROM import_batches WHERE id = ?", batchID).Scan(&batchAccountID); err != nil && err != sql.ErrNoRows { + return 0, fmt.Errorf("load import batch: %w", err) + } + + result, err := tx.ExecContext(ctx, "DELETE FROM transactions WHERE import_batch_id = ?", batchID) + if err != nil { + return 0, fmt.Errorf("delete imported transactions: %w", err) + } + deleted, err := result.RowsAffected() + if err != nil { + return 0, fmt.Errorf("check deleted imported transactions: %w", err) + } + if _, err := tx.ExecContext(ctx, "DELETE FROM import_batches WHERE id = ?", batchID); err != nil { + return 0, fmt.Errorf("delete import batch: %w", err) + } + + if batchAccountID.Valid { + if err := s.cleanupAutoImportAccount(ctx, tx, batchAccountID.Int64); err != nil { + return 0, err + } + } + + if err := tx.Commit(); err != nil { + return 0, fmt.Errorf("commit: %w", err) + } + return deleted, nil +} + +// cleanupAutoImportAccount 删除"由收支导入自动创建"且不再被任何交易、其他导入批次引用的账户。 +// 用 note 字段做标识,避免误删用户手动创建的账户。 +func (s *TransactionService) cleanupAutoImportAccount(ctx context.Context, tx *sql.Tx, accountID int64) error { + const autoCreatedNote = "由收支导入自动创建" + var note string + if err := tx.QueryRowContext(ctx, "SELECT COALESCE(note,'') FROM accounts WHERE id = ?", accountID).Scan(¬e); err != nil { + if err == sql.ErrNoRows { + return nil + } + return fmt.Errorf("load account note: %w", err) + } + if note != autoCreatedNote { + return nil + } + + refs, err := countAccountReferences(ctx, tx, accountID) + if err != nil { + return err + } + if refs > 0 { + return nil + } + if _, err := tx.ExecContext(ctx, "DELETE FROM accounts WHERE id = ?", accountID); err != nil { + return fmt.Errorf("delete orphan account: %w", err) + } + return nil +} diff --git a/backend/service/transaction_import.go b/backend/service/transaction_import.go new file mode 100644 index 0000000..b6cf06d --- /dev/null +++ b/backend/service/transaction_import.go @@ -0,0 +1,789 @@ +package service + +import ( + "context" + "crypto/sha1" + "database/sql" + "errors" + "fmt" + "log/slog" + "math" + "regexp" + "strconv" + "strings" + "time" + + "household-book/model" + + sqlite "modernc.org/sqlite" + sqlite3 "modernc.org/sqlite/lib" +) + +type parsedImportTransaction struct { + Type string + Amount int64 + Date string + Description string + Counterparty string + SourceKey string +} + +var ( + debitLineStartRe = regexp.MustCompile(`20\d{2}-\d{2}-\d{2}CNY-?\d{1,3}(?:,\d{3})*\.\d{2}\d{1,3}(?:,\d{3})*\.\d{2}`) + debitLineRe = regexp.MustCompile(`^(20\d{2}-\d{2}-\d{2})CNY(-?\d{1,3}(?:,\d{3})*\.\d{2})(\d{1,3}(?:,\d{3})*\.\d{2})(.*)$`) + cardSegmentRe = regexp.MustCompile(`支付宝|财付通|京东支付|美团支付|CURSOR`) + cardTailRe = regexp.MustCompile(`MVSN([A-Z0-9聚]{1,8}(?:\.[A-Z0-9聚]{2,3})?|[A-Z0-9聚]{3,10})(?:ECN|Erp)\)`) + cardRawAmountRe = regexp.MustCompile(`(-?\d{1,3}(?:,\d{3})*\.\d{2})0961`) + pageMarkerRe = regexp.MustCompile(`\d{1,2}/\d{1,2}`) + creditMonthRe = regexp.MustCompile(`(20\d{2})年(\d{1,2})月`) + digitRunRe = regexp.MustCompile(`\d+`) + accountNumberRes = []*regexp.Regexp{ + regexp.MustCompile(`账号[::]\s*([0-9*]{8,})`), + regexp.MustCompile(`Account No\s*([0-9*]{8,})`), + regexp.MustCompile(`卡号末四位[^0-9A-Za-z]*([0-9]{4})`), + } +) + +const importPreviewSampleLimit = 1000 + +func (s *TransactionService) Import(ctx context.Context, req model.ImportTransactionsRequest) (*model.ImportTransactionsResult, error) { + items, hintKey, err := parseImportItems(req) + if err != nil { + return nil, err + } + + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + accountID, err := s.ensureImportAccount(ctx, tx, req, hintKey) + if err != nil { + return nil, err + } + batchID, err := s.createImportBatch(ctx, tx, req, accountID) + if err != nil { + return nil, err + } + + importedIDs := make([]int64, 0, len(items)) + skipped := 0 + for _, item := range items { + categoryID, ok := req.CategoryOverrides[item.SourceKey] + var err error + if !ok { + categoryID, err = s.findCategoryID(ctx, tx, item.Type, item.Description) + } + if err != nil { + return nil, err + } + result, err := tx.ExecContext(ctx, + `INSERT INTO transactions (type, amount, category_id, account_id, date, description, counterparty, source_key, import_batch_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + item.Type, item.Amount, categoryID, accountID, item.Date, item.Description, item.Counterparty, item.SourceKey, batchID, + ) + if err != nil { + if isUniqueConstraintError(err) { + skipped++ + continue + } + return nil, fmt.Errorf("insert imported transaction: %w", err) + } + id, _ := result.LastInsertId() + importedIDs = append(importedIDs, id) + } + + if err := s.updateImportBatchStats(ctx, tx, batchID, len(importedIDs), skipped); err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit import: %w", err) + } + + importedItems, err := s.listByIDs(ctx, importedIDs) + if err != nil { + return nil, err + } + return &model.ImportTransactionsResult{ + ImportedCount: len(importedIDs), + SkippedCount: skipped, + AccountID: accountID, + ImportBatchID: batchID, + Items: importedItems, + }, nil +} + +// PreviewImport 解析账单并返回预览统计,不写入数据库。 +func (s *TransactionService) PreviewImport(ctx context.Context, req model.ImportTransactionsRequest) (*model.ImportPreviewResult, error) { + items, hintKey, err := parseImportItems(req) + if err != nil { + return nil, err + } + + accountName, willCreate, err := s.resolveImportAccountPreview(ctx, req, hintKey) + if err != nil { + return nil, err + } + + preview := &model.ImportPreviewResult{ + TotalCount: len(items), + AccountName: accountName, + WillCreateAccount: willCreate, + Items: make([]model.ImportPreviewItem, 0, min(len(items), importPreviewSampleLimit)), + } + seen := make(map[string]bool, len(items)) + for i, item := range items { + status := "new" + if seen[item.SourceKey] { + status = "duplicate_file" + preview.DuplicateCount++ + } else { + seen[item.SourceKey] = true + } + var exists int + if status == "new" { + if err := s.db.QueryRowContext(ctx, + "SELECT 1 FROM transactions WHERE source_key = ? LIMIT 1", item.SourceKey, + ).Scan(&exists); err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("check duplicate source_key: %w", err) + } else if err == nil { + status = "duplicate_database" + preview.DuplicateCount++ + } else { + preview.NewCount++ + } + } + + categoryName := "" + categoryReason := "" + var categoryID int64 + if status == "new" { + var catErr error + categoryID, categoryReason, catErr = s.findCategoryWithReason(ctx, s.db, item.Type, item.Description) + if catErr != nil { + return nil, catErr + } + if err := s.db.QueryRowContext(ctx, "SELECT name FROM categories WHERE id = ?", categoryID).Scan(&categoryName); err != nil { + return nil, fmt.Errorf("query category name: %w", err) + } + } + + if i < importPreviewSampleLimit { + preview.Items = append(preview.Items, model.ImportPreviewItem{ + SourceKey: item.SourceKey, + Type: item.Type, + Amount: item.Amount, + Date: item.Date, + Description: item.Description, + Counterparty: item.Counterparty, + CategoryName: categoryName, + CategoryID: categoryID, + CategoryReason: categoryReason, + Status: status, + }) + } + } + return preview, nil +} + +func parseImportItems(req model.ImportTransactionsRequest) ([]parsedImportTransaction, string, error) { + req.SourceKind = resolveSourceKind(req) + switch req.SourceKind { + case "cmb_debit": + req.BankName = "招商银行" + req.CardType = "debit_card" + case "cmb_credit": + req.BankName = "招商银行" + req.CardType = "credit_card" + case "alipay": + req.BankName = "支付宝" + req.CardType = "alipay" + case "wechat": + req.BankName = "微信" + req.CardType = "wechat" + default: + return nil, "", fmt.Errorf("unsupported import source %q", req.SourceKind) + } + + var ( + items []parsedImportTransaction + hintKey string + ) + switch req.SourceKind { + case "cmb_debit": + text := extractPDFText(req.Content) + hintKey = text + items = parseDebitStatement(text, req) + case "cmb_credit": + text := extractPDFText(req.Content) + hintKey = text + items = parseCreditCardStatement(text, req) + items = mergeCreditRawAmounts(items, parseCreditRawAmounts(extractPDFRawText(req.Content), req, text)) + case "alipay": + parsed, err := parseAlipayCSV(req) + if err != nil { + return nil, "", err + } + items = parsed + case "wechat": + parsed, err := parseWechatCSV(req) + if err != nil { + return nil, "", err + } + items = parsed + } + if len(items) == 0 { + return nil, "", ErrNoImportableTransactions + } + return items, hintKey, nil +} + +func (s *TransactionService) resolveImportAccountPreview(ctx context.Context, req model.ImportTransactionsRequest, text string) (name string, willCreate bool, err error) { + if req.AccountID != nil && *req.AccountID > 0 { + err = s.db.QueryRowContext(ctx, "SELECT name FROM accounts WHERE id = ?", *req.AccountID).Scan(&name) + if errors.Is(err, sql.ErrNoRows) { + return "", false, fmt.Errorf("account %d not found", *req.AccountID) + } + if err != nil { + return "", false, err + } + return name, false, nil + } + + cardNumber := "" + if req.CardType == "debit_card" || req.CardType == "credit_card" { + cardNumber = extractAccountNumber(text) + } + var id int64 + err = s.db.QueryRowContext(ctx, + `SELECT id, name FROM accounts + WHERE type = ? AND COALESCE(bank_name,'') = ? AND (? = '' OR card_number = ?) + ORDER BY id LIMIT 1`, + req.CardType, req.BankName, cardNumber, cardNumber, + ).Scan(&id, &name) + if err == nil { + return name, false, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return "", false, fmt.Errorf("find import account: %w", err) + } + return importAccountName(req, cardNumber), true, nil +} + +// resolveSourceKind 解析新 SourceKind 字段;为兼容旧调用,仍接受 BankName + CardType。 +func resolveSourceKind(req model.ImportTransactionsRequest) string { + switch req.SourceKind { + case "cmb_debit", "cmb_credit", "alipay", "wechat": + return req.SourceKind + case "": + // fallthrough + default: + return req.SourceKind + } + switch normalizeCardType(req.CardType) { + case "debit_card": + return "cmb_debit" + case "credit_card": + return "cmb_credit" + } + return "" +} + +// parseImportTransactions 兼容现有测试,按 CardType 分发到 PDF 解析器。 +func parseImportTransactions(text string, req model.ImportTransactionsRequest) []parsedImportTransaction { + switch normalizeCardType(req.CardType) { + case "debit_card": + return parseDebitStatement(text, req) + case "credit_card": + return parseCreditCardStatement(text, req) + default: + return nil + } +} + +func parseDebitStatement(text string, req model.ImportTransactionsRequest) []parsedImportTransaction { + indexes := debitLineStartRe.FindAllStringIndex(text, -1) + items := make([]parsedImportTransaction, 0, len(indexes)) + for i, idx := range indexes { + end := len(text) + if i+1 < len(indexes) { + end = indexes[i+1][0] + } + match := debitLineRe.FindStringSubmatch(text[idx[0]:end]) + if len(match) != 5 { + continue + } + amount, err := yuanToCents(match[2]) + if err != nil || amount == 0 { + continue + } + typ := "income" + if amount < 0 { + typ = "expense" + amount = -amount + } + desc := cleanDebitDescription(match[4]) + if desc == "" { + desc = "招商银行交易流水" + } + counterparty := extractCounterparty(desc) + sourceKey := sourceKey(req, match[1], match[2], desc) + items = append(items, parsedImportTransaction{ + Type: typ, + Amount: amount, + Date: match[1], + Description: desc, + Counterparty: counterparty, + SourceKey: sourceKey, + }) + } + return items +} + +func parseCreditCardStatement(text string, req model.ImportTransactionsRequest) []parsedImportTransaction { + year, month := inferCreditCardMonth(text, req.Filename) + date := fmt.Sprintf("%04d-%02d-01", year, month) + matches := cardTailRe.FindAllStringSubmatchIndex(text, -1) + items := make([]parsedImportTransaction, 0, len(matches)) + for _, match := range matches { + token := text[match[2]:match[3]] + amount, err := encodedCreditAmountToCents(token) + if err != nil || amount <= 0 { + continue + } + desc := creditDescriptionBefore(text, match[0]) + if desc == "" { + desc = "招商银行信用卡消费" + } + if strings.Contains(desc, "还款") || strings.Contains(desc, "退款") { + continue + } + typ := "expense" + items = append(items, parsedImportTransaction{ + Type: typ, + Amount: amount, + Date: date, + Description: desc, + Counterparty: extractCounterparty(desc), + SourceKey: sourceKey(req, date, fmt.Sprintf("%d", amount), desc), + }) + } + return items +} + +func parseCreditRawAmounts(rawText string, req model.ImportTransactionsRequest, mappedText string) []parsedImportTransaction { + year, month := inferCreditCardMonth(mappedText, req.Filename) + date := fmt.Sprintf("%04d-%02d-01", year, month) + matches := cardRawAmountRe.FindAllStringSubmatch(rawText, -1) + items := make([]parsedImportTransaction, 0, len(matches)) + for i, match := range matches { + amount, err := yuanToCents(match[1]) + if err != nil || amount <= 0 { + continue + } + desc := fmt.Sprintf("招商银行信用卡账单消费 #%02d", i+1) + items = append(items, parsedImportTransaction{ + Type: "expense", + Amount: amount, + Date: date, + Description: desc, + Counterparty: "", + SourceKey: sourceKey(req, date, fmt.Sprintf("%d", amount), desc), + }) + } + return items +} + +// mergeCreditRawAmounts 是信用卡解析的 fallback 策略: +// 当带描述的解析(cardTailRe)漏掉条目时,用纯金额解析(cardRawAmountRe)的结果替补。 +// 代价是 raw 分支只有 "招商银行信用卡账单消费 #N" 这种占位描述,准确度较低。 +func mergeCreditRawAmounts(parsed, raw []parsedImportTransaction) []parsedImportTransaction { + if len(raw) > len(parsed) { + slog.Warn("credit card parse fallback to raw amounts", + "parsed_count", len(parsed), "raw_count", len(raw)) + return raw + } + return parsed +} + +func inferCreditCardMonth(text, filename string) (int, int) { + combined := text + filename + if m := creditMonthRe.FindStringSubmatch(combined); len(m) == 3 { + year, _ := strconv.Atoi(m[1]) + month, _ := strconv.Atoi(m[2]) + if month >= 1 && month <= 12 { + return year, month + } + } + now := time.Now() + return now.Year(), int(now.Month()) +} + +func encodedCreditAmountToCents(token string) (int64, error) { + token = strings.TrimPrefix(token, "-") + if strings.Contains(token, ".") { + parts := strings.SplitN(token, ".", 2) + intText := decodeCreditDigits(parts[0]) + decText := decodeCreditDigits(parts[1]) + if len(decText) > 2 { + decText = decText[:2] + } + if intText == "" || len(decText) != 2 { + return 0, fmt.Errorf("invalid encoded amount") + } + yuan, err := strconv.ParseInt(intText, 10, 64) + if err != nil { + return 0, err + } + cents, err := strconv.ParseInt(decText, 10, 64) + if err != nil { + return 0, err + } + return yuan*100 + cents, nil + } + text := decodeCreditDigits(token) + if len(text) < 3 { + return 0, fmt.Errorf("invalid encoded amount") + } + if strings.HasSuffix(text, "0") { + text = strings.TrimSuffix(text, "0") + } + value, err := strconv.ParseInt(text, 10, 64) + if err != nil { + return 0, err + } + return value, nil +} + +func decodeCreditDigits(value string) string { + var b strings.Builder + for _, r := range value { + switch { + case r >= '0' && r <= '9': + b.WriteRune(r) + case r >= 'M' && r <= 'V': + b.WriteRune('0' + (r - 'M')) + case r == '聚': + b.WriteByte('6') + } + } + return b.String() +} + +func creditDescriptionBefore(text string, offset int) string { + start := offset - 80 + if start < 0 { + start = 0 + } + window := text[start:offset] + for _, sep := range []string{"ECN)", "\u00a0", "\n", "Transaction Details"} { + if idx := strings.LastIndex(window, sep); idx >= 0 { + window = window[idx+len(sep):] + } + } + if loc := cardSegmentRe.FindStringIndex(window); loc != nil { + window = window[loc[0]:] + } + window = strings.TrimSpace(window) + window = strings.Trim(window, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .-()()") + return window +} + +func extractCounterparty(desc string) string { + desc = strings.TrimSpace(desc) + if desc == "" { + return "" + } + for _, sep := range []string{"-", "-", "—"} { + if idx := strings.LastIndex(desc, sep); idx >= 0 && idx+len(sep) < len(desc) { + return strings.TrimSpace(desc[idx+len(sep):]) + } + } + for _, prefix := range []string{"快捷支付", "银联快捷支付", "行内转账转入", "转账汇款", "汇入汇款", "代发工资", "代发奖金", "信用卡自动还款"} { + if strings.HasPrefix(desc, prefix) { + return strings.TrimSpace(strings.TrimPrefix(desc, prefix)) + } + } + return "" +} + +func cleanDebitDescription(desc string) string { + desc = strings.TrimSpace(desc) + for _, marker := range []string{ + "————————————————", + "温馨提示", + "记账日期货币交易金额", + "DateCurrencyTransactionAmount", + "招商银行交易流水", + } { + if idx := strings.Index(desc, marker); idx >= 0 { + desc = desc[:idx] + } + } + if loc := pageMarkerRe.FindStringIndex(desc); loc != nil { + desc = desc[:loc[0]] + } + return strings.TrimSpace(desc) +} + +func (s *TransactionService) createImportBatch(ctx context.Context, tx *sql.Tx, req model.ImportTransactionsRequest, accountID int64) (int64, error) { + result, err := tx.ExecContext(ctx, + `INSERT INTO import_batches (filename, bank_name, card_type, account_id) + VALUES (?, ?, ?, ?)`, + req.Filename, req.BankName, req.CardType, accountID, + ) + if err != nil { + return 0, fmt.Errorf("create import batch: %w", err) + } + return result.LastInsertId() +} + +func (s *TransactionService) updateImportBatchStats(ctx context.Context, tx *sql.Tx, batchID int64, imported, skipped int) error { + _, err := tx.ExecContext(ctx, + `UPDATE import_batches SET imported_count = ?, skipped_count = ? WHERE id = ?`, + imported, skipped, batchID, + ) + if err != nil { + return fmt.Errorf("update import batch stats: %w", err) + } + return nil +} + +func (s *TransactionService) ensureImportAccount(ctx context.Context, tx *sql.Tx, req model.ImportTransactionsRequest, text string) (int64, error) { + if req.AccountID != nil && *req.AccountID > 0 { + return *req.AccountID, nil + } + + // 银行类来源用 PDF 中的卡号末四位辅助匹配;第三方支付不需要卡号。 + cardNumber := "" + if req.CardType == "debit_card" || req.CardType == "credit_card" { + cardNumber = extractAccountNumber(text) + } + + var id int64 + err := tx.QueryRowContext(ctx, + `SELECT id FROM accounts + WHERE type = ? AND COALESCE(bank_name,'') = ? AND (? = '' OR card_number = ?) + ORDER BY id LIMIT 1`, + req.CardType, req.BankName, cardNumber, cardNumber, + ).Scan(&id) + if err == nil { + return id, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return 0, fmt.Errorf("find import account: %w", err) + } + + name := importAccountName(req, cardNumber) + result, err := tx.ExecContext(ctx, + `INSERT INTO accounts (name, type, bank_name, card_number, note) + VALUES (?, ?, ?, ?, ?)`, + name, req.CardType, req.BankName, cardNumber, "由收支导入自动创建", + ) + if err != nil { + return 0, fmt.Errorf("create import account: %w", err) + } + return result.LastInsertId() +} + +func importAccountName(req model.ImportTransactionsRequest, cardNumber string) string { + switch req.CardType { + case "credit_card": + name := req.BankName + "信用卡" + if cardNumber != "" { + name += "(" + lastCardDigits(cardNumber) + ")" + } + return name + case "debit_card": + name := req.BankName + "储蓄卡" + if cardNumber != "" { + name += "(" + lastCardDigits(cardNumber) + ")" + } + return name + case "alipay": + return "支付宝" + case "wechat": + return "微信" + default: + return req.BankName + "账户" + } +} + +type sqlQueryer interface { + QueryRowContext(context.Context, string, ...any) *sql.Row + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +} + +func (s *TransactionService) findCategoryID(ctx context.Context, q sqlQueryer, typ, desc string) (int64, error) { + id, _, err := s.findCategoryWithReason(ctx, q, typ, desc) + return id, err +} + +func (s *TransactionService) findCategoryWithReason(ctx context.Context, q sqlQueryer, typ, desc string) (int64, string, error) { + if id, ok, err := s.findCategoryByConfiguredKeywords(ctx, q, typ, desc); err != nil { + return 0, "", err + } else if ok { + return id, "关键词匹配", nil + } + + var id int64 + err := q.QueryRowContext(ctx, + `SELECT id FROM categories + WHERE type = ? AND parent_id IS NOT NULL AND is_active = 1 + ORDER BY CASE WHEN name = '其他' THEN 0 ELSE 1 END, sort_order, id LIMIT 1`, + typ, + ).Scan(&id) + if err != nil { + return 0, "", fmt.Errorf("find fallback category: %w", err) + } + return id, "未命中关键词,归入其他", nil +} + +// findCategoryByConfiguredKeywords 用 categories.keywords 字段(逗号分隔)匹配交易描述。 +// 命中后返回 sort_order 最小的那个分类。 +func (s *TransactionService) findCategoryByConfiguredKeywords(ctx context.Context, q sqlQueryer, typ, desc string) (int64, bool, error) { + rows, err := q.QueryContext(ctx, + `SELECT id, COALESCE(keywords,'') FROM categories + WHERE type = ? AND parent_id IS NOT NULL AND is_active = 1 AND keywords <> '' + ORDER BY sort_order, id`, + typ, + ) + if err != nil { + return 0, false, fmt.Errorf("query keyword categories: %w", err) + } + defer rows.Close() + for rows.Next() { + var id int64 + var keywords string + if err := rows.Scan(&id, &keywords); err != nil { + return 0, false, fmt.Errorf("scan keyword category: %w", err) + } + for _, kw := range strings.Split(keywords, ",") { + kw = strings.TrimSpace(kw) + if kw == "" { + continue + } + if strings.Contains(desc, kw) { + return id, true, nil + } + } + } + return 0, false, rows.Err() +} + +func (s *TransactionService) listByIDs(ctx context.Context, ids []int64) ([]model.TransactionListItem, error) { + if len(ids) == 0 { + return []model.TransactionListItem{}, nil + } + placeholders := make([]string, len(ids)) + args := make([]any, len(ids)) + for i, id := range ids { + placeholders[i] = "?" + args[i] = id + } + query := `SELECT t.id, t.type, t.amount, t.category_id, COALESCE(c.name,''), COALESCE(c.is_active, 1), + t.account_id, COALESCE(a.name,''), t.to_account_id, COALESCE(ta.name,''), + t.member_id, COALESCE(m.name,''), + t.date, t.description, COALESCE(t.counterparty,''), t.import_batch_id, COALESCE(ib.filename,''), + t.created_at, t.updated_at + FROM transactions t + LEFT JOIN categories c ON t.category_id = c.id + LEFT JOIN accounts a ON t.account_id = a.id + LEFT JOIN accounts ta ON t.to_account_id = ta.id + LEFT JOIN members m ON t.member_id = m.id + LEFT JOIN import_batches ib ON t.import_batch_id = ib.id + WHERE t.id IN (` + strings.Join(placeholders, ",") + `) + ORDER BY t.date DESC, t.id DESC` + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("query imported transactions: %w", err) + } + defer rows.Close() + + items := []model.TransactionListItem{} + for rows.Next() { + var item model.TransactionListItem + var categoryIsActive int + if err := rows.Scan( + &item.ID, &item.Type, &item.Amount, + &item.CategoryID, &item.CategoryName, &categoryIsActive, + &item.AccountID, &item.AccountName, + &item.ToAccountID, &item.ToAccountName, + &item.MemberID, &item.MemberName, + &item.Date, &item.Description, &item.Counterparty, + &item.ImportBatchID, &item.ImportFilename, + &item.CreatedAt, &item.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan imported transaction: %w", err) + } + item.CategoryIsActive = categoryIsActive == 1 + items = append(items, item) + } + return items, rows.Err() +} + +func yuanToCents(text string) (int64, error) { + clean := strings.ReplaceAll(text, ",", "") + value, err := strconv.ParseFloat(clean, 64) + if err != nil { + return 0, err + } + return int64(math.Round(value * 100)), nil +} + +func sourceKey(req model.ImportTransactionsRequest, parts ...string) string { + h := sha1.New() + // 交易身份不得依赖整个文件内容,否则同一交易出现在不同日期范围的账单中会失去防重能力。 + h.Write([]byte(resolveSourceKind(req) + "|" + req.BankName + "|" + req.CardType + "|")) + for _, part := range parts { + h.Write([]byte(part)) + h.Write([]byte("|")) + } + return fmt.Sprintf("import:%x", h.Sum(nil)) +} + +func guessBankName(filename string) string { + if strings.Contains(filename, "招商") || strings.Contains(strings.ToLower(filename), "cmb") { + return "招商银行" + } + return "银行" +} + +func normalizeCardType(value string) string { + switch value { + case "bank_card", "debit", "debit_card": + return "debit_card" + case "credit", "credit_card": + return "credit_card" + default: + return value + } +} + +func extractAccountNumber(text string) string { + for _, re := range accountNumberRes { + if match := re.FindStringSubmatch(text); len(match) == 2 { + return strings.TrimSpace(match[1]) + } + } + return "" +} + +func lastCardDigits(value string) string { + digits := digitRunRe.FindAllString(value, -1) + joined := strings.Join(digits, "") + if len(joined) <= 4 { + return joined + } + return joined[len(joined)-4:] +} + +func isUniqueConstraintError(err error) bool { + var serr *sqlite.Error + if errors.As(err, &serr) { + return serr.Code() == sqlite3.SQLITE_CONSTRAINT_UNIQUE || + serr.Code() == sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY + } + return false +} diff --git a/backend/service/transaction_import_preview_test.go b/backend/service/transaction_import_preview_test.go new file mode 100644 index 0000000..645391a --- /dev/null +++ b/backend/service/transaction_import_preview_test.go @@ -0,0 +1,109 @@ +package service + +import ( + "context" + "database/sql" + "testing" + + "household-book/model" + + _ "modernc.org/sqlite" +) + +func TestPreviewImportCountsDuplicates(t *testing.T) { + content := readExampleFile(t, "alipay_record_20250723_2030_1.csv") + db := setupImportPreviewDB(t) + svc := NewTransactionService(db) + ctx := context.Background() + + req := model.ImportTransactionsRequest{ + Filename: "alipay_record_20250723_2030_1.csv", + Content: content, + SourceKind: "alipay", + } + items, _, err := parseImportItems(req) + if err != nil { + t.Fatalf("parse: %v", err) + } + if len(items) == 0 { + t.Fatal("expected parsed items") + } + _, err = db.Exec( + `INSERT INTO transactions (type, amount, category_id, account_id, date, description, source_key) + VALUES ('expense', ?, 2, 1, '2025-05-31', 'dup', ?)`, + items[0].Amount, items[0].SourceKey, + ) + if err != nil { + t.Fatalf("insert existing: %v", err) + } + + preview, err := svc.PreviewImport(ctx, req) + if err != nil { + t.Fatalf("PreviewImport: %v", err) + } + if preview.TotalCount < len(items) { + t.Fatalf("total=%d want>=%d", preview.TotalCount, len(items)) + } + if preview.DuplicateCount < 1 { + t.Fatalf("expected at least 1 duplicate, got %d", preview.DuplicateCount) + } +} + +func setupImportPreviewDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("open: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + + stmts := []string{ + `CREATE TABLE accounts ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'alipay', + balance INTEGER NOT NULL DEFAULT 0, + bank_name TEXT NOT NULL DEFAULT '', + card_number TEXT NOT NULL DEFAULT '', + branch_name TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + is_active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`, + `INSERT INTO accounts (id, name, type, bank_name) VALUES (1, '支付宝', 'alipay', '支付宝')`, + `CREATE TABLE categories ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + parent_id INTEGER, + keywords TEXT NOT NULL DEFAULT '', + sort_order INTEGER NOT NULL DEFAULT 0, + is_active INTEGER NOT NULL DEFAULT 1 + )`, + `INSERT INTO categories (id, name, type, parent_id) VALUES (1, '支出', 'expense', NULL)`, + `INSERT INTO categories (id, name, type, parent_id) VALUES (2, '其他', 'expense', 1)`, + `CREATE TABLE transactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT NOT NULL, + amount INTEGER NOT NULL, + category_id INTEGER, + account_id INTEGER, + to_account_id INTEGER, + member_id INTEGER, + date TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + counterparty TEXT NOT NULL DEFAULT '', + source_key TEXT, + import_batch_id INTEGER, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + )`, + } + for _, s := range stmts { + if _, err := db.Exec(s); err != nil { + t.Fatalf("schema: %v", err) + } + } + return db +} diff --git a/backend/service/transaction_import_test.go b/backend/service/transaction_import_test.go new file mode 100644 index 0000000..55fe4af --- /dev/null +++ b/backend/service/transaction_import_test.go @@ -0,0 +1,78 @@ +package service + +import ( + "os" + "path/filepath" + "testing" + + "household-book/model" +) + +func TestParseDebitStatementPDF(t *testing.T) { + content := readExamplePDF(t, "招商银行交易流水(申请时间2026年04月12日16时46分05秒).pdf") + req := model.ImportTransactionsRequest{ + Filename: "招商银行交易流水(申请时间2026年04月12日16时46分05秒).pdf", + Content: content, + BankName: "招商银行", + CardType: "debit_card", + } + + text := extractPDFText(content) + items := parseImportTransactions(text, req) + items = mergeCreditRawAmounts(items, parseCreditRawAmounts(extractPDFRawText(content), req, text)) + if len(items) < 100 { + t.Fatalf("expected many debit statement items, got %d", len(items)) + } + if items[0].Date != "2025-04-10" || items[0].Type != "income" || items[0].Amount != 2016372 { + t.Fatalf("unexpected first debit item: %+v", items[0]) + } + foundFeb20 := false + foundApr10 := false + for _, item := range items { + if item.Date == "2026-04-10" && item.Amount == 1230000 { + foundApr10 = true + if item.Description != "转账汇款张聚锁" || item.Counterparty != "张聚锁" { + t.Fatalf("unexpected 2026-04-10 item: %+v", item) + } + } + if item.Date == "2026-02-20" && item.Amount == 150000 { + foundFeb20 = true + if item.Description != "银联快捷支付微信转账" || item.Counterparty != "微信转账" { + t.Fatalf("unexpected 2026-02-20 item: %+v", item) + } + } + } + if !foundApr10 || !foundFeb20 { + t.Fatalf("expected target debit items, foundApr10=%v foundFeb20=%v", foundApr10, foundFeb20) + } +} + +func TestParseCreditCardStatementPDF(t *testing.T) { + content := readExamplePDF(t, "2025年10月信用卡账单.pdf") + req := model.ImportTransactionsRequest{ + Filename: "2025年10月信用卡账单.pdf", + Content: content, + BankName: "招商银行", + CardType: "credit_card", + } + + items := parseImportTransactions(extractPDFText(content), req) + if len(items) < 10 { + t.Fatalf("expected credit card bill items, got %d", len(items)) + } + for _, item := range items { + if item.Type != "expense" || item.Date != "2025-10-01" || item.Amount <= 0 { + t.Fatalf("unexpected credit card item: %+v", item) + } + } +} + +func readExamplePDF(t *testing.T, name string) []byte { + t.Helper() + path := filepath.Join("..", "..", "docs", name) + content, err := os.ReadFile(path) + if err != nil { + t.Skipf("example PDF not available: %v", err) + } + return content +} diff --git a/backend/service/transaction_validation_test.go b/backend/service/transaction_validation_test.go new file mode 100644 index 0000000..d99a297 --- /dev/null +++ b/backend/service/transaction_validation_test.go @@ -0,0 +1,27 @@ +package service + +import "testing" + +func TestValidateTransactionFields(t *testing.T) { + one, two := int64(1), int64(2) + cases := []struct { + name, typ string + category, from, to *int64 + wantErr bool + }{ + {"expense", "expense", &one, &one, nil, false}, + {"transfer", "transfer", nil, &one, &two, false}, + {"transfer category", "transfer", &one, &one, &two, true}, + {"transfer same account", "transfer", nil, &one, &one, true}, + {"expense without category", "expense", nil, &one, nil, true}, + {"expense with target", "expense", &one, &one, &two, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateTransactionFields(tc.typ, tc.category, tc.from, tc.to) + if (err != nil) != tc.wantErr { + t.Fatalf("error=%v wantErr=%v", err, tc.wantErr) + } + }) + } +} diff --git a/desktop/README.md b/desktop/README.md new file mode 100644 index 0000000..3ebd53e --- /dev/null +++ b/desktop/README.md @@ -0,0 +1,12 @@ +# Desktop Shell + +This directory is reserved for the Wails desktop shell described in the product roadmap. + +Current Phase 1 scope keeps the Web build as the primary runnable target and adds the Wails project configuration at the repository root (`wails.json`) so desktop packaging can be completed in Phase 4 without reshaping the existing Go + React + SQLite structure. + +Expected commands once Wails is installed and the desktop binding is wired: + +```bash +wails dev +wails build +``` diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/frontend/.gitignore @@ -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? diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..7dbf7eb --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,73 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/frontend/components.json b/frontend/components.json new file mode 100644 index 0000000..277af4c --- /dev/null +++ b/frontend/components.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.ts", + "css": "src/index.css", + "baseColor": "zinc", + "cssVariables": true + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + } +} diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js new file mode 100644 index 0000000..ef614d2 --- /dev/null +++ b/frontend/eslint.config.js @@ -0,0 +1,22 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + globals: globals.browser, + }, + }, +]) diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..8af500d --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,16 @@ + + + + + + + + + + 家庭记账本 + + +
+ + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..e739d68 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,53 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build && node scripts/precompress.mjs", + "lint": "eslint .", + "test": "vitest run", + "preview": "vite preview" + }, + "dependencies": { + "@fortawesome/fontawesome-svg-core": "^7.2.0", + "@fortawesome/free-solid-svg-icons": "^7.2.0", + "@fortawesome/react-fontawesome": "^3.3.1", + "@hookform/resolvers": "^5.2.2", + "@radix-ui/react-dialog": "^1.1.15", + "@radix-ui/react-label": "^2.1.8", + "@radix-ui/react-slot": "^1.2.4", + "@radix-ui/react-tabs": "^1.1.13", + "@tanstack/react-query": "^5.100.11", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "react": "^19.2.5", + "react-dom": "^19.2.5", + "react-hook-form": "^7.74.0", + "react-router-dom": "^7.14.2", + "recharts": "^3.8.1", + "tailwind-merge": "^3.5.0", + "zod": "^4.3.6" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@testing-library/react": "^16.3.2", + "@types/node": "^24.12.2", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^4.7.0", + "autoprefixer": "^10.5.0", + "eslint": "^10.2.1", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.5.0", + "jsdom": "^26.0.0", + "postcss": "^8.5.10", + "tailwindcss": "^3.4.19", + "typescript": "~6.0.2", + "typescript-eslint": "^8.58.2", + "vite": "^5.4.21", + "vitest": "^3.2.7" + } +} diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml new file mode 100644 index 0000000..4777466 --- /dev/null +++ b/frontend/pnpm-lock.yaml @@ -0,0 +1,5184 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@fortawesome/fontawesome-svg-core': + specifier: ^7.2.0 + version: 7.2.0 + '@fortawesome/free-solid-svg-icons': + specifier: ^7.2.0 + version: 7.2.0 + '@fortawesome/react-fontawesome': + specifier: ^3.3.1 + version: 3.3.1(@fortawesome/fontawesome-svg-core@7.2.0)(react@19.2.5) + '@hookform/resolvers': + specifier: ^5.2.2 + version: 5.7.1(@standard-schema/spec@1.1.0)(react-hook-form@7.74.0(react@19.2.5))(zod@4.3.6) + '@radix-ui/react-dialog': + specifier: ^1.1.15 + version: 1.1.23(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-label': + specifier: ^2.1.8 + version: 2.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': + specifier: ^1.2.4 + version: 1.3.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-tabs': + specifier: ^1.1.13 + version: 1.1.21(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@tanstack/react-query': + specifier: ^5.100.11 + version: 5.100.11(react@19.2.5) + class-variance-authority: + specifier: ^0.7.1 + version: 0.7.1 + clsx: + specifier: ^2.1.1 + version: 2.1.1 + react: + specifier: ^19.2.5 + version: 19.2.5 + react-dom: + specifier: ^19.2.5 + version: 19.2.5(react@19.2.5) + react-hook-form: + specifier: ^7.74.0 + version: 7.74.0(react@19.2.5) + react-router-dom: + specifier: ^7.14.2 + version: 7.14.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + recharts: + specifier: ^3.8.1 + version: 3.8.1(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react-is@19.2.5)(react@19.2.5)(redux@5.0.1) + tailwind-merge: + specifier: ^3.5.0 + version: 3.5.0 + zod: + specifier: ^4.3.6 + version: 4.3.6 + devDependencies: + '@eslint/js': + specifier: ^10.0.1 + version: 10.0.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0)) + '@testing-library/react': + specifier: ^16.3.2 + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + '@types/react': + specifier: ^19.2.14 + version: 19.2.14 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.4(@types/react@19.2.14) + '@vitejs/plugin-react': + specifier: ^4.7.0 + version: 4.7.0(supports-color@7.1.0)(vite@5.4.21(@types/node@24.12.2)(lightningcss@1.32.0)) + autoprefixer: + specifier: ^10.5.0 + version: 10.5.0(postcss@8.5.10) + eslint: + specifier: ^10.2.1 + version: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + eslint-plugin-react-hooks: + specifier: ^7.1.1 + version: 7.1.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0) + eslint-plugin-react-refresh: + specifier: ^0.5.2 + version: 0.5.2(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0)) + globals: + specifier: ^17.5.0 + version: 17.5.0 + jsdom: + specifier: ^26.0.0 + version: 26.0.0(supports-color@7.1.0) + postcss: + specifier: ^8.5.10 + version: 8.5.10 + tailwindcss: + specifier: ^3.4.19 + version: 3.4.19 + typescript: + specifier: ~6.0.2 + version: 6.0.3 + typescript-eslint: + specifier: ^8.58.2 + version: 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + vite: + specifier: ^5.4.21 + version: 5.4.21(@types/node@24.12.2)(lightningcss@1.32.0) + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@24.12.2)(jiti@1.21.7)(jsdom@26.0.0(supports-color@7.1.0))(lightningcss@1.32.0)(supports-color@7.1.0) + +packages: + + '@alloc/quick-lru@5.2.0': + resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==} + engines: {node: '>=10'} + + '@asamuzakjp/css-color@2.8.2': + resolution: {integrity: sha512-RtWv9jFN2/bLExuZgFFZ0I3pWWeezAHGgrmjqGGWclATl1aDe3yhCUaI0Ilkp6OCk9zX7+FjvDasEX8Q9Rxc5w==} + + '@babel/code-frame@7.29.0': + resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@7.29.0': + resolution: {integrity: sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.29.0': + resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==} + engines: {node: '>=6.9.0'} + + '@babel/generator@7.29.1': + resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@7.28.6': + resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-imports@7.28.6': + resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.28.6': + resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-plugin-utils@7.28.6': + resolution: {integrity: sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.29.2': + resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.2': + resolution: {integrity: sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/plugin-transform-react-jsx-self@7.27.1': + resolution: {integrity: sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/plugin-transform-react-jsx-source@7.27.1': + resolution: {integrity: sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/runtime@7.29.7': + resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} + engines: {node: '>=6.9.0'} + + '@babel/template@7.28.6': + resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.29.0': + resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.29.0': + resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} + engines: {node: '>=6.9.0'} + + '@csstools/color-helpers@5.0.1': + resolution: {integrity: sha512-MKtmkA0BX87PKaO1NFRTFH+UnkgnmySQOvNxJubsadusqPEC2aJ9MOQiMceZJJ6oitUl/i0L6u0M1IrmAOmgBA==} + engines: {node: '>=18'} + + '@csstools/css-calc@2.1.1': + resolution: {integrity: sha512-rL7kaUnTkL9K+Cvo2pnCieqNpTKgQzy5f+N+5Iuko9HAoasP+xgprVh7KN/MaJVvVL1l0EzQq2MoqBHKSrDrag==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.4 + '@csstools/css-tokenizer': ^3.0.3 + + '@csstools/css-color-parser@3.0.7': + resolution: {integrity: sha512-nkMp2mTICw32uE5NN+EsJ4f5N+IGFeCFu4bGpiKgb2Pq/7J/MpyLBeQ5ry4KKtRFZaYs6sTmcMYrSRIyj5DFKA==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.4 + '@csstools/css-tokenizer': ^3.0.3 + + '@csstools/css-parser-algorithms@3.0.4': + resolution: {integrity: sha512-Up7rBoV77rv29d3uKHUIVubz1BTcgyUK72IvCQAbfbMv584xHcGKCKbWh7i8hPrRJ7qU4Y8IO3IY9m+iTB7P3A==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-tokenizer': ^3.0.3 + + '@csstools/css-tokenizer@3.0.3': + resolution: {integrity: sha512-UJnjoFsmxfKUdNYdWgOB0mWUypuLvAfQPH1+pyvRJs6euowbFkFC6P13w1l8mJyi3vxYMxc9kld5jZEGRQs6bw==} + engines: {node: '>=18'} + + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.1': + resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.1': + resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.1': + resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.1': + resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.1': + resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.1': + resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.1': + resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.1': + resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.1': + resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.1': + resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.1': + resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.1': + resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.1': + resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.1': + resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.1': + resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.1': + resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.1': + resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.1': + resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.1': + resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.1': + resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.1': + resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.1': + resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.1': + resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.1': + resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.1': + resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.1': + resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.9.1': + resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.23.5': + resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/config-helpers@0.5.5': + resolution: {integrity: sha512-eIJYKTCECbP/nsKaaruF6LW967mtbQbsw4JTtSVkUQc9MneSkbrgPJAbKl9nWr0ZeowV8BfsarBmPpBzGelA2w==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/core@1.2.1': + resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/js@10.0.1': + resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^10.0.0 + peerDependenciesMeta: + eslint: + optional: true + + '@eslint/object-schema@3.0.5': + resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/plugin-kit@0.7.1': + resolution: {integrity: sha512-rZAP3aVgB9ds9KOeUSL+zZ21hPmo8dh6fnIFwRQj5EAZl9gzR7wxYbYXYysAM8CTqGmUGyp2S4kUdV17MnGuWQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@floating-ui/core@1.7.5': + resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==} + + '@floating-ui/dom@1.7.6': + resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==} + + '@floating-ui/react-dom@2.1.8': + resolution: {integrity: sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==} + peerDependencies: + react: '>=16.8.0' + react-dom: '>=16.8.0' + + '@floating-ui/utils@0.2.11': + resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} + + '@fortawesome/fontawesome-common-types@7.2.0': + resolution: {integrity: sha512-IpR0bER9FY25p+e7BmFH25MZKEwFHTfRAfhOyJubgiDnoJNsSvJ7nigLraHtp4VOG/cy8D7uiV0dLkHOne5Fhw==} + engines: {node: '>=6'} + + '@fortawesome/fontawesome-svg-core@7.2.0': + resolution: {integrity: sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q==} + engines: {node: '>=6'} + + '@fortawesome/free-solid-svg-icons@7.2.0': + resolution: {integrity: sha512-YTVITFGN0/24PxzXrwqCgnyd7njDuzp5ZvaCx5nq/jg55kUYd94Nj8UTchBdBofi/L0nwRfjGOg0E41d2u9T1w==} + engines: {node: '>=6'} + + '@fortawesome/react-fontawesome@3.3.1': + resolution: {integrity: sha512-wGnAPhfzivDwBWYmEG8MSrEXPruoiMMo48NnsRkj1NZkoaawgOijPNAiSHKMYEoCsqTBSgLTzL6EqTTWGaUR4w==} + engines: {node: '>=20'} + peerDependencies: + '@fortawesome/fontawesome-svg-core': ~6 || ~7 + react: ^18.0.0 || ^19.0.0 + + '@hookform/resolvers@5.7.1': + resolution: {integrity: sha512-8wS/P4UDr5sQDe4nFaV51TVyfDPrWgNIXweqG0Bs9Z5LSuzKLb+RQNPvkN2oHM5SRrJyWrVH/F+LOUcFjUyvwQ==} + peerDependencies: + '@sinclair/typebox': '>=0.25.24' + '@standard-schema/spec': ^1.0.0 + '@typeschema/main': '>=0.13.7' + '@vinejs/vine': ^2.0.0 || ^3.0.0 || ^4.0.0 + ajv: ^8.12.0 + ajv-errors: ^3.0.0 + ajv-formats: ^2.1.1 + arktype: ^2.0.0 + ata-validator: ^1.2.0 + class-transformer: '>=0.4.0' + class-validator: '>=0.12.0' + computed-types: ^1.0.0 + effect: ^3.10.3 + fluentvalidation-ts: ^3.0.0 + fp-ts: ^2.7.0 + io-ts: ^2.0.0 + joi: ^17.0.0 + nope-validator: '>=0.12.0' + react-hook-form: ^7.55.0 + superstruct: '>=0.12.0' + typanion: ^3.3.2 + valibot: '>=0.31.0 || ^1.0.0-beta.4 || ^1.0.0-rc' + vest: '>=3.0.0' + yup: ^1.0.0 + zod: ^3.25.0 || ^4.0.0 + peerDependenciesMeta: + '@sinclair/typebox': + optional: true + '@standard-schema/spec': + optional: true + '@typeschema/main': + optional: true + '@vinejs/vine': + optional: true + ajv: + optional: true + ajv-errors: + optional: true + ajv-formats: + optional: true + arktype: + optional: true + ata-validator: + optional: true + class-transformer: + optional: true + class-validator: + optional: true + computed-types: + optional: true + effect: + optional: true + fluentvalidation-ts: + optional: true + fp-ts: + optional: true + io-ts: + optional: true + joi: + optional: true + nope-validator: + optional: true + superstruct: + optional: true + typanion: + optional: true + valibot: + optional: true + vest: + optional: true + yup: + optional: true + zod: + optional: true + + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + + '@jest/types@27.0.2': + resolution: {integrity: sha512-XpjCtJ/99HB4PmyJ2vgmN7vT+JLP7RW1FBT9RgnMFS4Dt7cvIyBee8O3/j98aUZ34ZpenPZFqmaaObWSeL65dg==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + + '@radix-ui/number@1.1.3': + resolution: {integrity: sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==} + + '@radix-ui/primitive@1.1.7': + resolution: {integrity: sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q==} + + '@radix-ui/react-arrow@1.1.15': + resolution: {integrity: sha512-v4zggRcjadnI+ClKDuijlQEW4tw3NoaeHc/PwpKnLoLLKNUG4InLegkstooLcRIUWCs+8L22dGURCVuFfOKfnA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-collection@1.1.15': + resolution: {integrity: sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-compose-refs@1.1.5': + resolution: {integrity: sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-context@1.2.2': + resolution: {integrity: sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-dialog@1.1.23': + resolution: {integrity: sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-direction@1.1.4': + resolution: {integrity: sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-dismissable-layer@1.1.19': + resolution: {integrity: sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-focus-guards@1.1.6': + resolution: {integrity: sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-focus-scope@1.1.16': + resolution: {integrity: sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-id@1.1.4': + resolution: {integrity: sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-label@2.1.15': + resolution: {integrity: sha512-o/rdYEwZTTo5tjknnPeyQFU45kUC4i/XyeDPP+HGyi6XqpOP6Zf5Ya5vh/Yfe9Id5JiuWnnAx2XqIeD3UYZt0g==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-popper@1.3.7': + resolution: {integrity: sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-portal@1.1.17': + resolution: {integrity: sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-presence@1.1.10': + resolution: {integrity: sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-primitive@2.1.10': + resolution: {integrity: sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-roving-focus@1.1.19': + resolution: {integrity: sha512-V9jI6hDjT7l3jsCQD9bLNvDLM3tH/gdbOTp7Tefp3hbbgCGQoK7tUvrWiRlcoBHIZ809ElXwNQwVo0B98LuTXQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-select@2.3.7': + resolution: {integrity: sha512-WFGImkmbzcfxeIwq/+4HvRN0pizBwbwQUED4I13ezQsDdfl38ZntN6TmR8XaSzPBqoCToe8rF75j6NPNDSzhbg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-slot@1.3.3': + resolution: {integrity: sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-tabs@1.1.21': + resolution: {integrity: sha512-UKxJlZid7FVtsk/WTxj4i4uSEgj2Au+KBbS7SQyTlzMhhn+86Cz3tISZdTa87bfEfcuvZezf2ZsxD4xuEKtkog==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-use-callback-ref@1.1.4': + resolution: {integrity: sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-controllable-state@1.2.6': + resolution: {integrity: sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-effect-event@0.0.5': + resolution: {integrity: sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-is-hydrated@0.1.3': + resolution: {integrity: sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-layout-effect@1.1.4': + resolution: {integrity: sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-previous@1.1.4': + resolution: {integrity: sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-rect@1.1.4': + resolution: {integrity: sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-size@1.1.4': + resolution: {integrity: sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-visually-hidden@1.2.11': + resolution: {integrity: sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/rect@1.1.3': + resolution: {integrity: sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==} + + '@reduxjs/toolkit@2.11.2': + resolution: {integrity: sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ==} + peerDependencies: + react: ^16.9.0 || ^17.0.0 || ^18 || ^19 + react-redux: ^7.2.1 || ^8.1.3 || ^9.0.0 + peerDependenciesMeta: + react: + optional: true + react-redux: + optional: true + + '@rolldown/pluginutils@1.0.0-beta.27': + resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} + + '@rollup/rollup-android-arm-eabi@4.60.2': + resolution: {integrity: sha512-dnlp69efPPg6Uaw2dVqzWRfAWRnYVb1XJ8CyyhIbZeaq4CA5/mLeZ1IEt9QqQxmbdvagjLIm2ZL8BxXv5lH4Yw==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.60.2': + resolution: {integrity: sha512-OqZTwDRDchGRHHm/hwLOL7uVPB9aUvI0am/eQuWMNyFHf5PSEQmyEeYYheA0EPPKUO/l0uigCp+iaTjoLjVoHg==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.60.2': + resolution: {integrity: sha512-UwRE7CGpvSVEQS8gUMBe1uADWjNnVgP3Iusyda1nSRwNDCsRjnGc7w6El6WLQsXmZTbLZx9cecegumcitNfpmA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.60.2': + resolution: {integrity: sha512-gjEtURKLCC5VXm1I+2i1u9OhxFsKAQJKTVB8WvDAHF+oZlq0GTVFOlTlO1q3AlCTE/DF32c16ESvfgqR7343/g==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.60.2': + resolution: {integrity: sha512-Bcl6CYDeAgE70cqZaMojOi/eK63h5Me97ZqAQoh77VPjMysA/4ORQBRGo3rRy45x4MzVlU9uZxs8Uwy7ZaKnBw==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.60.2': + resolution: {integrity: sha512-LU+TPda3mAE2QB0/Hp5VyeKJivpC6+tlOXd1VMoXV/YFMvk/MNk5iXeBfB4MQGRWyOYVJ01625vjkr0Az98OJQ==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.60.2': + resolution: {integrity: sha512-2QxQrM+KQ7DAW4o22j+XZ6RKdxjLD7BOWTP0Bv0tmjdyhXSsr2Ul1oJDQqh9Zf5qOwTuTc7Ek83mOFaKnodPjg==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.60.2': + resolution: {integrity: sha512-TbziEu2DVsTEOPif2mKWkMeDMLoYjx95oESa9fkQQK7r/Orta0gnkcDpzwufEcAO2BLBsD7mZkXGFqEdMRRwfw==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.60.2': + resolution: {integrity: sha512-bO/rVDiDUuM2YfuCUwZ1t1cP+/yqjqz+Xf2VtkdppefuOFS2OSeAfgafaHNkFn0t02hEyXngZkxtGqXcXwO8Rg==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.60.2': + resolution: {integrity: sha512-hr26p7e93Rl0Za+JwW7EAnwAvKkehh12BU1Llm9Ykiibg4uIr2rbpxG9WCf56GuvidlTG9KiiQT/TXT1yAWxTA==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.60.2': + resolution: {integrity: sha512-pOjB/uSIyDt+ow3k/RcLvUAOGpysT2phDn7TTUB3n75SlIgZzM6NKAqlErPhoFU+npgY3/n+2HYIQVbF70P9/A==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.60.2': + resolution: {integrity: sha512-2/w+q8jszv9Ww1c+6uJT3OwqhdmGP2/4T17cu8WuwyUuuaCDDJ2ojdyYwZzCxx0GcsZBhzi3HmH+J5pZNXnd+Q==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.60.2': + resolution: {integrity: sha512-11+aL5vKheYgczxtPVVRhdptAM2H7fcDR5Gw4/bTcteuZBlH4oP9f5s9zYO9aGZvoGeBpqXI/9TZZihZ609wKw==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.60.2': + resolution: {integrity: sha512-i16fokAGK46IVZuV8LIIwMdtqhin9hfYkCh8pf8iC3QU3LpwL+1FSFGej+O7l3E/AoknL6Dclh2oTdnRMpTzFQ==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.60.2': + resolution: {integrity: sha512-49FkKS6RGQoriDSK/6E2GkAsAuU5kETFCh7pG4yD/ylj9rKhTmO3elsnmBvRD4PgJPds5W2PkhC82aVwmUcJ7A==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.60.2': + resolution: {integrity: sha512-mjYNkHPfGpUR00DuM1ZZIgs64Hpf4bWcz9Z41+4Q+pgDx73UwWdAYyf6EG/lRFldmdHHzgrYyge5akFUW0D3mQ==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.60.2': + resolution: {integrity: sha512-ALyvJz965BQk8E9Al/JDKKDLH2kfKFLTGMlgkAbbYtZuJt9LU8DW3ZoDMCtQpXAltZxwBHevXz5u+gf0yA0YoA==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.60.2': + resolution: {integrity: sha512-UQjrkIdWrKI626Du8lCQ6MJp/6V1LAo2bOK9OTu4mSn8GGXIkPXk/Vsp4bLHCd9Z9Iz2OTEaokUE90VweJgIYQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.60.2': + resolution: {integrity: sha512-bTsRGj6VlSdn/XD4CGyzMnzaBs9bsRxy79eTqTCBsA8TMIEky7qg48aPkvJvFe1HyzQ5oMZdg7AnVlWQSKLTnw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.60.2': + resolution: {integrity: sha512-6d4Z3534xitaA1FcMWP7mQPq5zGwBmGbhphh2DwaA1aNIXUu3KTOfwrWpbwI4/Gr0uANo7NTtaykFyO2hPuFLg==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.60.2': + resolution: {integrity: sha512-NetAg5iO2uN7eB8zE5qrZ3CSil+7IJt4WDFLcC75Ymywq1VZVD6qJ6EvNLjZ3rEm6gB7XW5JdT60c6MN35Z85Q==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.60.2': + resolution: {integrity: sha512-NCYhOotpgWZ5kdxCZsv6Iudx0wX8980Q/oW4pNFNihpBKsDbEA1zpkfxJGC0yugsUuyDZ7gL37dbzwhR0VI7pQ==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.60.2': + resolution: {integrity: sha512-RXsaOqXxfoUBQoOgvmmijVxJnW2IGB0eoMO7F8FAjaj0UTywUO/luSqimWBJn04WNgUkeNhh7fs7pESXajWmkg==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.60.2': + resolution: {integrity: sha512-qdAzEULD+/hzObedtmV6iBpdL5TIbKVztGiK7O3/KYSf+HIzU257+MX1EXJcyIiDbMAqmbwaufcYPvyRryeZtA==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.60.2': + resolution: {integrity: sha512-Nd/SgG27WoA9e+/TdK74KnHz852TLa94ovOYySo/yMPuTmpckK/jIF2jSwS3g7ELSKXK13/cVdmg1Z/DaCWKxA==} + cpu: [x64] + os: [win32] + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@standard-schema/utils@0.3.0': + resolution: {integrity: sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==} + + '@tanstack/query-core@5.100.11': + resolution: {integrity: sha512-lmE0994apShXPj8CUxgx4ch5yUJhE9k/+tVwihBvPOyerACWdBocfFg24t8+0RhtlTd7tEgchDkhlCxNssvDxw==} + + '@tanstack/react-query@5.100.11': + resolution: {integrity: sha512-J0f9s5x3LE1450nNNfYx+e/n0DMa0uOBdFJUy5r0RvmsXd4nB/n0rbHtHI1vYXhikNFan+wf51p6Tmp4c8ucrg==} + peerDependencies: + react: ^18 || ^19 + + '@testing-library/dom@10.4.1': + resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} + engines: {node: '>=18'} + + '@testing-library/react@16.3.2': + resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==} + engines: {node: '>=18'} + peerDependencies: + '@testing-library/dom': ^10.0.0 + '@types/react': ^18.0.0 || ^19.0.0 + '@types/react-dom': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + + '@types/babel__core@7.20.5': + resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} + + '@types/babel__generator@7.27.0': + resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==} + + '@types/babel__template@7.4.4': + resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==} + + '@types/babel__traverse@7.28.0': + resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/d3-array@3.2.2': + resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} + + '@types/d3-color@3.1.3': + resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==} + + '@types/d3-ease@3.0.2': + resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==} + + '@types/d3-interpolate@3.0.4': + resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==} + + '@types/d3-path@3.1.1': + resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} + + '@types/d3-scale@4.0.9': + resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} + + '@types/d3-shape@3.1.8': + resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==} + + '@types/d3-time@3.0.4': + resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} + + '@types/d3-timer@3.0.2': + resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/esrecurse@4.3.1': + resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} + + '@types/estree@1.0.8': + resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/istanbul-lib-coverage@2.0.6': + resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==} + + '@types/istanbul-lib-report@3.0.3': + resolution: {integrity: sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==} + + '@types/istanbul-reports@3.0.4': + resolution: {integrity: sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/node@24.12.2': + resolution: {integrity: sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==} + + '@types/react-dom@19.2.4': + resolution: {integrity: sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==} + peerDependencies: + '@types/react': ^19.2.0 + + '@types/react@19.2.14': + resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + + '@types/use-sync-external-store@0.0.6': + resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + + '@types/yargs-parser@21.0.3': + resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} + + '@types/yargs@16.0.11': + resolution: {integrity: sha512-sbtvk8wDN+JvEdabmZExoW/HNr1cB7D/j4LT08rMiuikfA7m/JNJg7ATQcgzs34zHnoScDkY0ZRSl29Fkmk36g==} + + '@typescript-eslint/eslint-plugin@8.59.0': + resolution: {integrity: sha512-HyAZtpdkgZwpq8Sz3FSUvCR4c+ScbuWa9AksK2Jweub7w4M3yTz4O11AqVJzLYjy/B9ZWPyc81I+mOdJU/bDQw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.59.0 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.59.0': + resolution: {integrity: sha512-TI1XGwKbDpo9tRW8UDIXCOeLk55qe9ZFGs8MTKU6/M08HWTw52DD/IYhfQtOEhEdPhLMT26Ka/x7p70nd3dzDg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/project-service@8.59.0': + resolution: {integrity: sha512-Lw5ITrR5s5TbC19YSvlr63ZfLaJoU6vtKTHyB0GQOpX0W7d5/Ir6vUahWi/8Sps/nOukZQ0IB3SmlxZnjaKVnw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/scope-manager@8.59.0': + resolution: {integrity: sha512-UzR16Ut8IpA3Mc4DbgAShlPPkVm8xXMWafXxB0BocaVRHs8ZGakAxGRskF7FId3sdk9lgGD73GSFaWmWFDE4dg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/tsconfig-utils@8.59.0': + resolution: {integrity: sha512-91Sbl3s4Kb3SybliIY6muFBmHVv+pYXfybC4Oolp3dvk8BvIE3wOPc+403CWIT7mJNkfQRGtdqghzs2+Z91Tqg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/type-utils@8.59.0': + resolution: {integrity: sha512-3TRiZaQSltGqGeNrJzzr1+8YcEobKH9rHnqIp/1psfKFmhRQDNMGP5hBufanYTGznwShzVLs3Mz+gDN7HkWfXg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/types@8.59.0': + resolution: {integrity: sha512-nLzdsT1gdOgFxxxwrlNVUBzSNBEEHJ86bblmk4QAS6stfig7rcJzWKqCyxFy3YRRHXDWEkb2NralA1nOYkkm/A==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.59.0': + resolution: {integrity: sha512-O9Re9P1BmBLFJyikRbQpLku/QA3/AueZNO9WePLBwQrvkixTmDe8u76B6CYUAITRl/rHawggEqUGn5QIkVRLMw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/utils@8.59.0': + resolution: {integrity: sha512-I1R/K7V07XsMJ12Oaxg/O9GfrysGTmCRhvZJBv0RE0NcULMzjqVpR5kRRQjHsz3J/bElU7HwCO7zkqL+MSUz+g==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/visitor-keys@8.59.0': + resolution: {integrity: sha512-/uejZt4dSere1bx12WLlPfv8GktzcaDtuJ7s42/HEZ5zGj9oxRaD4bj7qwSunXkf+pbAhFt2zjpHYUiT5lHf0Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@vitejs/plugin-react@4.7.0': + resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 + + '@vitest/expect@3.2.7': + resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==} + + '@vitest/mocker@3.2.7': + resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@3.2.7': + resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==} + + '@vitest/runner@3.2.7': + resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==} + + '@vitest/snapshot@3.2.7': + resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==} + + '@vitest/spy@3.2.7': + resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==} + + '@vitest/utils@3.2.7': + resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.16.0: + resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} + engines: {node: '>=0.4.0'} + hasBin: true + + agent-base@7.1.0: + resolution: {integrity: sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==} + engines: {node: '>= 14'} + + agent-base@7.1.2: + resolution: {integrity: sha512-JVzqkCNRT+VfqzzgPWDPnwvDheSAUdiMUn3NoLXpDJF5lRqeJqyC9iGsAxIOAW+mzIdq+uP1TvcX6bMtrH0agg==} + engines: {node: '>= 14'} + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.1.0: + resolution: {integrity: sha512-Qts4KCLKG+waHc9C4m07weIY8qyeixoS0h6RnbsNVD6Fw+pEZGW3vTyObL3WXpE09Mq4Oi7/lBEyLmOiLtlYWQ==} + engines: {node: '>=8'} + + ansi-styles@5.0.0: + resolution: {integrity: sha512-6564t0m0fuQMnockqBv7wJxo9T5C2V9JpYXyNScfRDPVLusOQQhkpMGrFC17QbiolraQ1sMXX+Y5nJpjqozL4g==} + engines: {node: '>=10'} + + any-promise@1.3.0: + resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} + + anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + + arg@5.0.2: + resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==} + + aria-hidden@1.2.6: + resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} + engines: {node: '>=10'} + + aria-query@5.3.0: + resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + autoprefixer@10.5.0: + resolution: {integrity: sha512-FMhOoZV4+qR6aTUALKX2rEqGG+oyATvwBt9IIzVR5rMa2HRWPkxf+P+PAJLD1I/H5/II+HuZcBJYEFBpq39ong==} + engines: {node: ^10 || ^12 || >=14} + hasBin: true + peerDependencies: + postcss: ^8.1.0 + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + baseline-browser-mapping@2.10.22: + resolution: {integrity: sha512-6qruVrb5rse6WylFkU0FhBKKGuecWseqdpQfhkawn6ztyk2QlfwSRjsDxMCLJrkfmfN21qvhl9ABgaMeRkuwww==} + engines: {node: '>=6.0.0'} + hasBin: true + + binary-extensions@2.3.0: + resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} + engines: {node: '>=8'} + + brace-expansion@5.0.5: + resolution: {integrity: sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==} + engines: {node: 18 || 20 || >=22} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browserslist@4.28.2: + resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + camelcase-css@2.0.1: + resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==} + engines: {node: '>= 6'} + + caniuse-lite@1.0.30001791: + resolution: {integrity: sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==} + + chai@5.2.0: + resolution: {integrity: sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==} + engines: {node: '>=12'} + + chalk@4.0.0: + resolution: {integrity: sha512-N9oWFcegS0sFr9oh1oz2d7Npos6vNoWW9HvtCg5N1KRFpUhaAhvTv5Y58g880fZaEYSNm3qDz8SU1UrGvp+n7A==} + engines: {node: '>=10'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + chokidar@3.6.0: + resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} + engines: {node: '>= 8.10.0'} + + class-variance-authority@0.7.1: + resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + + commander@4.1.1: + resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} + engines: {node: '>= 6'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + cssesc@3.0.0: + resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} + engines: {node: '>=4'} + hasBin: true + + cssstyle@4.2.1: + resolution: {integrity: sha512-9+vem03dMXG7gDmZ62uqmRiMRNtinIZ9ZyuF6BdxzfOD+FdN5hretzynkn0ReS2DO2GSw76RWHs0UmJPI2zUjw==} + engines: {node: '>=18'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + d3-array@3.2.4: + resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} + engines: {node: '>=12'} + + d3-color@3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + + d3-ease@3.0.1: + resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==} + engines: {node: '>=12'} + + d3-format@3.1.2: + resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==} + engines: {node: '>=12'} + + d3-interpolate@3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + + d3-path@3.1.0: + resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==} + engines: {node: '>=12'} + + d3-scale@4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + + d3-shape@3.2.0: + resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + engines: {node: '>=12'} + + d3-time-format@4.1.0: + resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} + engines: {node: '>=12'} + + d3-time@3.1.0: + resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==} + engines: {node: '>=12'} + + d3-timer@3.0.1: + resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==} + engines: {node: '>=12'} + + data-urls@5.0.0: + resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==} + engines: {node: '>=18'} + + date-fns@4.1.0: + resolution: {integrity: sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decimal.js-light@2.5.1: + resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==} + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + detect-node-es@1.1.0: + resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + + didyoumean@1.2.2: + resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==} + + dlv@1.1.3: + resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==} + + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + electron-to-chromium@1.5.344: + resolution: {integrity: sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg==} + + entities@4.5.0: + resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} + engines: {node: '>=0.12'} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + es-toolkit@1.46.0: + resolution: {integrity: sha512-IToJ6ct9OLl5zz6WsC/1vZEwfSZ7Myil+ygl5Tf30Xjn9AEkzNB4kqp2G7VUJKF1DtTx/ra5M5KLlXvzOg51BA==} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.28.1: + resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} + engines: {node: '>=18'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-plugin-react-hooks@7.1.1: + resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==} + engines: {node: '>=18'} + peerDependencies: + eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0 + + eslint-plugin-react-refresh@0.5.2: + resolution: {integrity: sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==} + peerDependencies: + eslint: ^9 || ^10 + + eslint-scope@9.1.2: + resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@10.2.1: + resolution: {integrity: sha512-wiyGaKsDgqXvF40P8mDwiUp/KQjE1FdrIEJsM8PZ3XCiniTMXS3OHWWUe5FI5agoCnr8x4xPrTDZuxsBlNHl+Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@11.2.0: + resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + eventemitter3@5.0.4: + resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-glob@3.3.3: + resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} + engines: {node: '>=8.6.0'} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fastq@1.20.1: + resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-entry-cache@8.0.0: + resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} + engines: {node: '>=16.0.0'} + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@4.0.1: + resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} + engines: {node: '>=16'} + + flatted@3.4.2: + resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + + form-data@4.0.6: + resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} + engines: {node: '>= 6'} + + fraction.js@5.3.4: + resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-nonce@1.0.1: + resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} + engines: {node: '>=6'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + globals@17.5.0: + resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==} + engines: {node: '>=18'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + hasown@2.0.3: + resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==} + engines: {node: '>= 0.4'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + hermes-estree@0.25.1: + resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==} + + hermes-parser@0.25.1: + resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==} + + html-encoding-sniffer@4.0.0: + resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==} + engines: {node: '>=18'} + + http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} + engines: {node: '>= 14'} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.5: + resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==} + engines: {node: '>= 4'} + + immer@10.2.0: + resolution: {integrity: sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==} + + immer@11.1.4: + resolution: {integrity: sha512-XREFCPo6ksxVzP4E0ekD5aMdf8WMwmdNaz6vuvxgI40UaEiu6q3p8X52aU6GdyvLY3XXX/8R7JOTXStz/nBbRw==} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + + is-binary-path@2.1.0: + resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} + engines: {node: '>=8'} + + is-core-module@2.16.1: + resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jiti@1.21.7: + resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==} + hasBin: true + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + js-tokens@9.0.1: + resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} + + jsdom@26.0.0: + resolution: {integrity: sha512-BZYDGVAIriBWTpIxYzrXjv3E/4u8+/pSG5bQdIYCbNCGOvsPkDQfTVLAIXAf9ETdCpduCVTkDe2NNZ8NIwUVzw==} + engines: {node: '>=18'} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lightningcss-android-arm64@1.32.0: + resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.32.0: + resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.32.0: + resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.32.0: + resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.32.0: + resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.32.0: + resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.32.0: + resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.32.0: + resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.32.0: + resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.32.0: + resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.32.0: + resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.32.0: + resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} + engines: {node: '>= 12.0.0'} + + lilconfig@3.1.3: + resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} + engines: {node: '>=14'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + lru-cache@11.5.2: + resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} + engines: {node: 20 || >=22} + + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + mz@2.7.0: + resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} + + nanoid@3.3.11: + resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + node-releases@2.0.38: + resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==} + + normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + + nwsapi@2.2.24: + resolution: {integrity: sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==} + + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + object-hash@3.0.0: + resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==} + engines: {node: '>= 6'} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + parse5@7.2.1: + resolution: {integrity: sha512-BuBYQYlv1ckiPdQi/ohiivi9Sagc9JG+Ozs0r7b/0iK3sKmrb0b9FdWdBbOdx6hBCM/F9Ir82ofnBhtZOjCRPQ==} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + picomatch@4.0.4: + resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} + engines: {node: '>=12'} + + pify@2.3.0: + resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==} + engines: {node: '>=0.10.0'} + + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + + postcss-import@15.1.0: + resolution: {integrity: sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==} + engines: {node: '>=14.0.0'} + peerDependencies: + postcss: ^8.0.0 + + postcss-js@4.1.0: + resolution: {integrity: sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==} + engines: {node: ^12 || ^14 || >= 16} + peerDependencies: + postcss: ^8.4.21 + + postcss-load-config@6.0.1: + resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} + engines: {node: '>= 18'} + peerDependencies: + jiti: '>=1.21.0' + postcss: '>=8.0.9' + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + jiti: + optional: true + postcss: + optional: true + tsx: + optional: true + yaml: + optional: true + + postcss-nested@6.2.0: + resolution: {integrity: sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==} + engines: {node: '>=12.0'} + peerDependencies: + postcss: ^8.2.14 + + postcss-selector-parser@6.1.2: + resolution: {integrity: sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==} + engines: {node: '>=4'} + + postcss-value-parser@4.2.0: + resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} + + postcss@8.5.10: + resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==} + engines: {node: ^10 || ^12 || >=14} + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + pretty-format@27.0.2: + resolution: {integrity: sha512-mXKbbBPnYTG7Yra9qFBtqj+IXcsvxsvOBco3QHxtxTl+hHKq6QdzMZ+q0CtL4ORHZgwGImRr2XZUX2EWzORxig==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + react-dom@19.2.5: + resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==} + peerDependencies: + react: ^19.2.5 + + react-hook-form@7.74.0: + resolution: {integrity: sha512-yR6wHr99p9wFv686jhRWVSFhUvDvNbdUf2dKlbno8/VKOCuoNobDGC6S+M2dua9A9Yo8vpcrp8assIYbsZCQ9g==} + engines: {node: '>=18.0.0'} + peerDependencies: + react: ^16.8.0 || ^17 || ^18 || ^19 + + react-is@17.0.1: + resolution: {integrity: sha512-NAnt2iGDXohE5LI7uBnLnqvLQMtzhkiAOLXTmv+qnF9Ky7xAPcX8Up/xWIhxvLVGJvuLiNc4xQLtuqDRzb4fSA==} + + react-is@19.2.5: + resolution: {integrity: sha512-Dn0t8IQhCmeIT3wu+Apm1/YVsJXsGWi6k4sPdnBIdqMVtHtv0IGi6dcpNpNkNac0zB2uUAqNX3MHzN8c+z2rwQ==} + + react-redux@9.2.0: + resolution: {integrity: sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==} + peerDependencies: + '@types/react': ^18.2.25 || ^19 + react: ^18.0 || ^19 + redux: ^5.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + redux: + optional: true + + react-refresh@0.17.0: + resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==} + engines: {node: '>=0.10.0'} + + react-remove-scroll-bar@2.3.8: + resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + + react-remove-scroll@2.7.2: + resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + react-router-dom@7.14.2: + resolution: {integrity: sha512-YZcM5ES8jJSM+KrJ9BdvHHqlnGTg5tH3sC5ChFRj4inosKctdyzBDhOyyHdGk597q2OT6NTrCA1OvB/YDwfekQ==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + + react-router@7.14.2: + resolution: {integrity: sha512-yCqNne6I8IB6rVCH7XUvlBK7/QKyqypBFGv+8dj4QBFJiiRX+FG7/nkdAvGElyvVZ/HQP5N19wzteuTARXi5Gw==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + peerDependenciesMeta: + react-dom: + optional: true + + react-style-singleton@2.2.3: + resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + react@19.2.5: + resolution: {integrity: sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==} + engines: {node: '>=0.10.0'} + + read-cache@1.0.0: + resolution: {integrity: sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==} + + readdirp@3.6.0: + resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} + engines: {node: '>=8.10.0'} + + recharts@3.8.1: + resolution: {integrity: sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg==} + engines: {node: '>=18'} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-is: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + redux-thunk@3.1.0: + resolution: {integrity: sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==} + peerDependencies: + redux: ^5.0.0 + + redux@5.0.1: + resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==} + + reselect@5.1.1: + resolution: {integrity: sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==} + + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rollup@4.60.2: + resolution: {integrity: sha512-J9qZyW++QK/09NyN/zeO0dG/1GdGfyp9lV8ajHnRVLfo/uFsbji5mHnDgn/qYdUHyCkM2N+8VyspgZclfAh0eQ==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + rrweb-cssom@0.8.0: + resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==} + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + + scheduler@0.27.0: + resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.7.4: + resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==} + engines: {node: '>=10'} + hasBin: true + + set-cookie-parser@2.7.2: + resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.9.0: + resolution: {integrity: sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==} + + strip-literal@3.0.0: + resolution: {integrity: sha512-TcccoMhJOM3OebGhSBEmp3UZ2SfDMZUEBdRA/9ynfLi8yYajyWX3JiXArcJt4Umh4vISpspkQIY8ZZoCqjbviA==} + + sucrase@3.35.1: + resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} + engines: {node: '>=16 || 14 >=14.17'} + hasBin: true + + supports-color@7.1.0: + resolution: {integrity: sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==} + engines: {node: '>=8'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + + tailwind-merge@3.5.0: + resolution: {integrity: sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==} + + tailwindcss@3.4.19: + resolution: {integrity: sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==} + engines: {node: '>=14.0.0'} + hasBin: true + + thenify-all@1.6.0: + resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} + engines: {node: '>=0.8'} + + thenify@3.3.1: + resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + + tiny-invariant@1.3.3: + resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyglobby@0.2.16: + resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} + engines: {node: '>=12.0.0'} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@2.0.0: + resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==} + engines: {node: '>=14.0.0'} + + tinyspy@4.0.4: + resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==} + engines: {node: '>=14.0.0'} + + tldts-core@6.1.32: + resolution: {integrity: sha512-XfnnY74YWMBfE6BNpi33GCpjzw0lJUUmUW+bKukARTD4IChV9plBnu4wRvl/rN8mnoXA+xAEpVN8XfmtKvQWlA==} + + tldts@6.1.32: + resolution: {integrity: sha512-M5zZuEGvVz6YAwt3w93zhtBXbW0K4KF4ejzuBULyVp40u/FTQVpLj01zwYTlUkgYqYprTqxCfQFfZSWgz5fJnw==} + hasBin: true + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tough-cookie@5.0.0: + resolution: {integrity: sha512-FRKsF7cz96xIIeMZ82ehjC3xW2E+O2+v11udrDYewUbszngYhsGa8z6YUMMzO9QJZzzyd0nGGXnML/TReX6W8Q==} + engines: {node: '>=16'} + + tr46@5.1.1: + resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==} + engines: {node: '>=18'} + + ts-api-utils@2.5.0: + resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} + engines: {node: '>=18.12'} + peerDependencies: + typescript: '>=4.8.4' + + ts-interface-checker@0.1.13: + resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + typescript-eslint@8.59.0: + resolution: {integrity: sha512-BU3ONW9X+v90EcCH9ZS6LMackcVtxRLlI3XrYyqZIwVSHIk7Qf7bFw1z0M9Q0IUxhTMZCf8piY9hTYaNEIASrw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + + update-browserslist-db@1.2.3: + resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + use-callback-ref@1.3.3: + resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + use-sidecar@1.1.3: + resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + use-sync-external-store@1.6.0: + resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + victory-vendor@37.3.6: + resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==} + + vite-node@3.2.4: + resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + + vite@5.4.21: + resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vite@7.3.6: + resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + jiti: '>=1.21.0' + less: ^4.0.0 + lightningcss: ^1.21.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@3.2.7: + resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/debug': ^4.1.12 + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@vitest/browser': 3.2.7 + '@vitest/ui': 3.2.7 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/debug': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + whatwg-url@14.1.0: + resolution: {integrity: sha512-jlf/foYIKywAt3x/XWKZ/3rz8OSJPiWktjmk891alJUEjiVxKX9LEO92qH3hv4aJ0mN3MWPvGMCy8jQi95xK4w==} + engines: {node: '>=18'} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + ws@8.21.3: + resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + + zod-validation-error@4.0.2: + resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} + engines: {node: '>=18.0.0'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 + + zod@4.3.6: + resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==} + +snapshots: + + '@alloc/quick-lru@5.2.0': {} + + '@asamuzakjp/css-color@2.8.2': + dependencies: + '@csstools/css-calc': 2.1.1(@csstools/css-parser-algorithms@3.0.4(@csstools/css-tokenizer@3.0.3))(@csstools/css-tokenizer@3.0.3) + '@csstools/css-color-parser': 3.0.7(@csstools/css-parser-algorithms@3.0.4(@csstools/css-tokenizer@3.0.3))(@csstools/css-tokenizer@3.0.3) + '@csstools/css-parser-algorithms': 3.0.4(@csstools/css-tokenizer@3.0.3) + '@csstools/css-tokenizer': 3.0.3 + lru-cache: 11.5.2 + + '@babel/code-frame@7.29.0': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.29.0': {} + + '@babel/core@7.29.0(supports-color@7.1.0)': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/generator': 7.29.1 + '@babel/helper-compilation-targets': 7.28.6 + '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.0(supports-color@7.1.0))(supports-color@7.1.0) + '@babel/helpers': 7.29.2 + '@babel/parser': 7.29.2 + '@babel/template': 7.28.6 + '@babel/traverse': 7.29.0(supports-color@7.1.0) + '@babel/types': 7.29.0 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3(supports-color@7.1.0) + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/generator@7.29.1': + dependencies: + '@babel/parser': 7.29.2 + '@babel/types': 7.29.0 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.28.6': + dependencies: + '@babel/compat-data': 7.29.0 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.28.2 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-globals@7.29.7': {} + + '@babel/helper-module-imports@7.28.6(supports-color@7.1.0)': + dependencies: + '@babel/traverse': 7.29.0(supports-color@7.1.0) + '@babel/types': 7.29.0 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.28.6(@babel/core@7.29.0(supports-color@7.1.0))(supports-color@7.1.0)': + dependencies: + '@babel/core': 7.29.0(supports-color@7.1.0) + '@babel/helper-module-imports': 7.28.6(supports-color@7.1.0) + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.0(supports-color@7.1.0) + transitivePeerDependencies: + - supports-color + + '@babel/helper-plugin-utils@7.28.6': {} + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/helper-validator-option@7.29.7': {} + + '@babel/helpers@7.29.2': + dependencies: + '@babel/template': 7.28.6 + '@babel/types': 7.29.0 + + '@babel/parser@7.29.2': + dependencies: + '@babel/types': 7.29.0 + + '@babel/plugin-transform-react-jsx-self@7.27.1(@babel/core@7.29.0(supports-color@7.1.0))': + dependencies: + '@babel/core': 7.29.0(supports-color@7.1.0) + '@babel/helper-plugin-utils': 7.28.6 + + '@babel/plugin-transform-react-jsx-source@7.27.1(@babel/core@7.29.0(supports-color@7.1.0))': + dependencies: + '@babel/core': 7.29.0(supports-color@7.1.0) + '@babel/helper-plugin-utils': 7.28.6 + + '@babel/runtime@7.29.7': {} + + '@babel/template@7.28.6': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/parser': 7.29.2 + '@babel/types': 7.29.0 + + '@babel/traverse@7.29.0(supports-color@7.1.0)': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/generator': 7.29.1 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.2 + '@babel/template': 7.28.6 + '@babel/types': 7.29.0 + debug: 4.4.3(supports-color@7.1.0) + transitivePeerDependencies: + - supports-color + + '@babel/types@7.29.0': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@csstools/color-helpers@5.0.1': {} + + '@csstools/css-calc@2.1.1(@csstools/css-parser-algorithms@3.0.4(@csstools/css-tokenizer@3.0.3))(@csstools/css-tokenizer@3.0.3)': + dependencies: + '@csstools/css-parser-algorithms': 3.0.4(@csstools/css-tokenizer@3.0.3) + '@csstools/css-tokenizer': 3.0.3 + + '@csstools/css-color-parser@3.0.7(@csstools/css-parser-algorithms@3.0.4(@csstools/css-tokenizer@3.0.3))(@csstools/css-tokenizer@3.0.3)': + dependencies: + '@csstools/color-helpers': 5.0.1 + '@csstools/css-calc': 2.1.1(@csstools/css-parser-algorithms@3.0.4(@csstools/css-tokenizer@3.0.3))(@csstools/css-tokenizer@3.0.3) + '@csstools/css-parser-algorithms': 3.0.4(@csstools/css-tokenizer@3.0.3) + '@csstools/css-tokenizer': 3.0.3 + + '@csstools/css-parser-algorithms@3.0.4(@csstools/css-tokenizer@3.0.3)': + dependencies: + '@csstools/css-tokenizer': 3.0.3 + + '@csstools/css-tokenizer@3.0.3': {} + + '@esbuild/aix-ppc64@0.21.5': + optional: true + + '@esbuild/aix-ppc64@0.28.1': + optional: true + + '@esbuild/android-arm64@0.21.5': + optional: true + + '@esbuild/android-arm64@0.28.1': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-arm@0.28.1': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/android-x64@0.28.1': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.28.1': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.28.1': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.28.1': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.28.1': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.28.1': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-arm@0.28.1': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.28.1': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.28.1': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.28.1': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.28.1': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.28.1': + optional: true + + '@esbuild/linux-s390x@0.21.5': + optional: true + + '@esbuild/linux-s390x@0.28.1': + optional: true + + '@esbuild/linux-x64@0.21.5': + optional: true + + '@esbuild/linux-x64@0.28.1': + optional: true + + '@esbuild/netbsd-arm64@0.28.1': + optional: true + + '@esbuild/netbsd-x64@0.21.5': + optional: true + + '@esbuild/netbsd-x64@0.28.1': + optional: true + + '@esbuild/openbsd-arm64@0.28.1': + optional: true + + '@esbuild/openbsd-x64@0.21.5': + optional: true + + '@esbuild/openbsd-x64@0.28.1': + optional: true + + '@esbuild/openharmony-arm64@0.28.1': + optional: true + + '@esbuild/sunos-x64@0.21.5': + optional: true + + '@esbuild/sunos-x64@0.28.1': + optional: true + + '@esbuild/win32-arm64@0.21.5': + optional: true + + '@esbuild/win32-arm64@0.28.1': + optional: true + + '@esbuild/win32-ia32@0.21.5': + optional: true + + '@esbuild/win32-ia32@0.28.1': + optional: true + + '@esbuild/win32-x64@0.21.5': + optional: true + + '@esbuild/win32-x64@0.28.1': + optional: true + + '@eslint-community/eslint-utils@4.9.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))': + dependencies: + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/config-array@0.23.5(supports-color@7.1.0)': + dependencies: + '@eslint/object-schema': 3.0.5 + debug: 4.4.3(supports-color@7.1.0) + minimatch: 10.2.5 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.5.5': + dependencies: + '@eslint/core': 1.2.1 + + '@eslint/core@1.2.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/js@10.0.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))': + optionalDependencies: + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + + '@eslint/object-schema@3.0.5': {} + + '@eslint/plugin-kit@0.7.1': + dependencies: + '@eslint/core': 1.2.1 + levn: 0.4.1 + + '@floating-ui/core@1.7.5': + dependencies: + '@floating-ui/utils': 0.2.11 + + '@floating-ui/dom@1.7.6': + dependencies: + '@floating-ui/core': 1.7.5 + '@floating-ui/utils': 0.2.11 + + '@floating-ui/react-dom@2.1.8(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@floating-ui/dom': 1.7.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@floating-ui/utils@0.2.11': {} + + '@fortawesome/fontawesome-common-types@7.2.0': {} + + '@fortawesome/fontawesome-svg-core@7.2.0': + dependencies: + '@fortawesome/fontawesome-common-types': 7.2.0 + + '@fortawesome/free-solid-svg-icons@7.2.0': + dependencies: + '@fortawesome/fontawesome-common-types': 7.2.0 + + '@fortawesome/react-fontawesome@3.3.1(@fortawesome/fontawesome-svg-core@7.2.0)(react@19.2.5)': + dependencies: + '@fortawesome/fontawesome-svg-core': 7.2.0 + react: 19.2.5 + + '@hookform/resolvers@5.7.1(@standard-schema/spec@1.1.0)(react-hook-form@7.74.0(react@19.2.5))(zod@4.3.6)': + dependencies: + '@standard-schema/utils': 0.3.0 + react-hook-form: 7.74.0(react@19.2.5) + optionalDependencies: + '@standard-schema/spec': 1.1.0 + zod: 4.3.6 + + '@humanfs/core@0.19.2': + dependencies: + '@humanfs/types': 0.15.0 + + '@humanfs/node@0.16.8': + dependencies: + '@humanfs/core': 0.19.2 + '@humanfs/types': 0.15.0 + '@humanwhocodes/retry': 0.4.3 + + '@humanfs/types@0.15.0': {} + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + + '@jest/types@27.0.2': + dependencies: + '@types/istanbul-lib-coverage': 2.0.6 + '@types/istanbul-reports': 3.0.4 + '@types/node': 24.12.2 + '@types/yargs': 16.0.11 + chalk: 4.0.0 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.20.1 + + '@radix-ui/number@1.1.3': {} + + '@radix-ui/primitive@1.1.7': {} + + '@radix-ui/react-arrow@1.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-collection@1.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.3.3(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-compose-refs@1.1.5(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-context@1.2.2(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-dialog@1.1.23(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.7 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-dismissable-layer': 1.1.19(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-focus-guards': 1.1.6(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-focus-scope': 1.1.16(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-id': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-portal': 1.1.17(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-presence': 1.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.3.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.6(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + aria-hidden: 1.2.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-direction@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-dismissable-layer@1.1.19(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.7 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-effect-event': 0.0.5(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-focus-guards@1.1.6(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-focus-scope@1.1.16(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-id@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-label@2.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-popper@1.3.7(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@floating-ui/react-dom': 2.1.8(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-arrow': 1.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-rect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-size': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/rect': 1.1.3 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-portal@1.1.17(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-presence@1.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-primitive@2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-slot': 1.3.3(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-roving-focus@1.1.19(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.7 + '@radix-ui/react-collection': 1.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-id': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.6(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-is-hydrated': 0.1.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-select@2.3.7(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/number': 1.1.3 + '@radix-ui/primitive': 1.1.7 + '@radix-ui/react-collection': 1.1.15(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-dismissable-layer': 1.1.19(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-focus-guards': 1.1.6(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-focus-scope': 1.1.16(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-id': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-popper': 1.3.7(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-portal': 1.1.17(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-presence': 1.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.3.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.6(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-visually-hidden': 1.2.11(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + aria-hidden: 1.2.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-slot@1.3.3(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-tabs@1.1.21(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.7 + '@radix-ui/react-context': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-id': 1.1.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-presence': 1.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-roving-focus': 1.1.19(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.6(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/react-use-callback-ref@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-controllable-state@1.2.6(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.7 + '@radix-ui/react-use-effect-event': 0.0.5(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-effect-event@0.0.5(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-is-hydrated@0.1.3(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-layout-effect@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-previous@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-rect@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/rect': 1.1.3 + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-size@1.1.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-visually-hidden@1.2.11(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@radix-ui/rect@1.1.3': {} + + '@reduxjs/toolkit@2.11.2(react-redux@9.2.0(@types/react@19.2.14)(react@19.2.5)(redux@5.0.1))(react@19.2.5)': + dependencies: + '@standard-schema/spec': 1.1.0 + '@standard-schema/utils': 0.3.0 + immer: 11.1.4 + redux: 5.0.1 + redux-thunk: 3.1.0(redux@5.0.1) + reselect: 5.1.1 + optionalDependencies: + react: 19.2.5 + react-redux: 9.2.0(@types/react@19.2.14)(react@19.2.5)(redux@5.0.1) + + '@rolldown/pluginutils@1.0.0-beta.27': {} + + '@rollup/rollup-android-arm-eabi@4.60.2': + optional: true + + '@rollup/rollup-android-arm64@4.60.2': + optional: true + + '@rollup/rollup-darwin-arm64@4.60.2': + optional: true + + '@rollup/rollup-darwin-x64@4.60.2': + optional: true + + '@rollup/rollup-freebsd-arm64@4.60.2': + optional: true + + '@rollup/rollup-freebsd-x64@4.60.2': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.60.2': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.60.2': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.60.2': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.60.2': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.60.2': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.60.2': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.60.2': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.60.2': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.60.2': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.60.2': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.60.2': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.60.2': + optional: true + + '@rollup/rollup-linux-x64-musl@4.60.2': + optional: true + + '@rollup/rollup-openbsd-x64@4.60.2': + optional: true + + '@rollup/rollup-openharmony-arm64@4.60.2': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.60.2': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.60.2': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.60.2': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.60.2': + optional: true + + '@standard-schema/spec@1.1.0': {} + + '@standard-schema/utils@0.3.0': {} + + '@tanstack/query-core@5.100.11': {} + + '@tanstack/react-query@5.100.11(react@19.2.5)': + dependencies: + '@tanstack/query-core': 5.100.11 + react: 19.2.5 + + '@testing-library/dom@10.4.1': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/runtime': 7.29.7 + '@types/aria-query': 5.0.4 + aria-query: 5.3.0 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + picocolors: 1.1.1 + pretty-format: 27.0.2 + + '@testing-library/react@16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.4(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@babel/runtime': 7.29.7 + '@testing-library/dom': 10.4.1 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.4(@types/react@19.2.14) + + '@types/aria-query@5.0.4': {} + + '@types/babel__core@7.20.5': + dependencies: + '@babel/parser': 7.29.2 + '@babel/types': 7.29.0 + '@types/babel__generator': 7.27.0 + '@types/babel__template': 7.4.4 + '@types/babel__traverse': 7.28.0 + + '@types/babel__generator@7.27.0': + dependencies: + '@babel/types': 7.29.0 + + '@types/babel__template@7.4.4': + dependencies: + '@babel/parser': 7.29.2 + '@babel/types': 7.29.0 + + '@types/babel__traverse@7.28.0': + dependencies: + '@babel/types': 7.29.0 + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/d3-array@3.2.2': {} + + '@types/d3-color@3.1.3': {} + + '@types/d3-ease@3.0.2': {} + + '@types/d3-interpolate@3.0.4': + dependencies: + '@types/d3-color': 3.1.3 + + '@types/d3-path@3.1.1': {} + + '@types/d3-scale@4.0.9': + dependencies: + '@types/d3-time': 3.0.4 + + '@types/d3-shape@3.1.8': + dependencies: + '@types/d3-path': 3.1.1 + + '@types/d3-time@3.0.4': {} + + '@types/d3-timer@3.0.2': {} + + '@types/deep-eql@4.0.2': {} + + '@types/esrecurse@4.3.1': {} + + '@types/estree@1.0.8': {} + + '@types/estree@1.0.9': {} + + '@types/istanbul-lib-coverage@2.0.6': {} + + '@types/istanbul-lib-report@3.0.3': + dependencies: + '@types/istanbul-lib-coverage': 2.0.6 + + '@types/istanbul-reports@3.0.4': + dependencies: + '@types/istanbul-lib-report': 3.0.3 + + '@types/json-schema@7.0.15': {} + + '@types/node@24.12.2': + dependencies: + undici-types: 7.16.0 + + '@types/react-dom@19.2.4(@types/react@19.2.14)': + dependencies: + '@types/react': 19.2.14 + + '@types/react@19.2.14': + dependencies: + csstype: 3.2.3 + + '@types/use-sync-external-store@0.0.6': {} + + '@types/yargs-parser@21.0.3': {} + + '@types/yargs@16.0.11': + dependencies: + '@types/yargs-parser': 21.0.3 + + '@typescript-eslint/eslint-plugin@8.59.0(@typescript-eslint/parser@8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3))(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3)': + dependencies: + '@eslint-community/regexpp': 4.12.2 + '@typescript-eslint/parser': 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/scope-manager': 8.59.0 + '@typescript-eslint/type-utils': 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/utils': 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.59.0 + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + ignore: 7.0.5 + natural-compare: 1.4.0 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/scope-manager': 8.59.0 + '@typescript-eslint/types': 8.59.0 + '@typescript-eslint/typescript-estree': 8.59.0(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.59.0 + debug: 4.4.3(supports-color@7.1.0) + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/project-service@8.59.0(supports-color@7.1.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.59.0(typescript@6.0.3) + '@typescript-eslint/types': 8.59.0 + debug: 4.4.3(supports-color@7.1.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@8.59.0': + dependencies: + '@typescript-eslint/types': 8.59.0 + '@typescript-eslint/visitor-keys': 8.59.0 + + '@typescript-eslint/tsconfig-utils@8.59.0(typescript@6.0.3)': + dependencies: + typescript: 6.0.3 + + '@typescript-eslint/type-utils@8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/types': 8.59.0 + '@typescript-eslint/typescript-estree': 8.59.0(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/utils': 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + debug: 4.4.3(supports-color@7.1.0) + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@8.59.0': {} + + '@typescript-eslint/typescript-estree@8.59.0(supports-color@7.1.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/project-service': 8.59.0(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/tsconfig-utils': 8.59.0(typescript@6.0.3) + '@typescript-eslint/types': 8.59.0 + '@typescript-eslint/visitor-keys': 8.59.0 + debug: 4.4.3(supports-color@7.1.0) + minimatch: 10.2.5 + semver: 7.7.4 + tinyglobby: 0.2.16 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3)': + dependencies: + '@eslint-community/eslint-utils': 4.9.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0)) + '@typescript-eslint/scope-manager': 8.59.0 + '@typescript-eslint/types': 8.59.0 + '@typescript-eslint/typescript-estree': 8.59.0(supports-color@7.1.0)(typescript@6.0.3) + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/visitor-keys@8.59.0': + dependencies: + '@typescript-eslint/types': 8.59.0 + eslint-visitor-keys: 5.0.1 + + '@vitejs/plugin-react@4.7.0(supports-color@7.1.0)(vite@5.4.21(@types/node@24.12.2)(lightningcss@1.32.0))': + dependencies: + '@babel/core': 7.29.0(supports-color@7.1.0) + '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.0(supports-color@7.1.0)) + '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.29.0(supports-color@7.1.0)) + '@rolldown/pluginutils': 1.0.0-beta.27 + '@types/babel__core': 7.20.5 + react-refresh: 0.17.0 + vite: 5.4.21(@types/node@24.12.2)(lightningcss@1.32.0) + transitivePeerDependencies: + - supports-color + + '@vitest/expect@3.2.7': + dependencies: + '@types/chai': 5.2.3 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.2.0 + tinyrainbow: 2.0.0 + + '@vitest/mocker@3.2.7(vite@7.3.6(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0))': + dependencies: + '@vitest/spy': 3.2.7 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.6(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0) + + '@vitest/pretty-format@3.2.7': + dependencies: + tinyrainbow: 2.0.0 + + '@vitest/runner@3.2.7': + dependencies: + '@vitest/utils': 3.2.7 + pathe: 2.0.3 + strip-literal: 3.0.0 + + '@vitest/snapshot@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@3.2.7': + dependencies: + tinyspy: 4.0.4 + + '@vitest/utils@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + loupe: 3.2.1 + tinyrainbow: 2.0.0 + + acorn-jsx@5.3.2(acorn@8.16.0): + dependencies: + acorn: 8.16.0 + + acorn@8.16.0: {} + + agent-base@7.1.0(supports-color@7.1.0): + dependencies: + debug: 4.4.3(supports-color@7.1.0) + transitivePeerDependencies: + - supports-color + + agent-base@7.1.2(supports-color@7.1.0): + dependencies: + debug: 4.4.3(supports-color@7.1.0) + transitivePeerDependencies: + - supports-color + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ansi-regex@5.0.1: {} + + ansi-styles@4.1.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@5.0.0: {} + + any-promise@1.3.0: {} + + anymatch@3.1.3: + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.2 + + arg@5.0.2: {} + + aria-hidden@1.2.6: + dependencies: + tslib: 2.8.1 + + aria-query@5.3.0: + dependencies: + dequal: 2.0.3 + + assertion-error@2.0.1: {} + + asynckit@0.4.0: {} + + autoprefixer@10.5.0(postcss@8.5.10): + dependencies: + browserslist: 4.28.2 + caniuse-lite: 1.0.30001791 + fraction.js: 5.3.4 + picocolors: 1.1.1 + postcss: 8.5.10 + postcss-value-parser: 4.2.0 + + balanced-match@4.0.4: {} + + baseline-browser-mapping@2.10.22: {} + + binary-extensions@2.3.0: {} + + brace-expansion@5.0.5: + dependencies: + balanced-match: 4.0.4 + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browserslist@4.28.2: + dependencies: + baseline-browser-mapping: 2.10.22 + caniuse-lite: 1.0.30001791 + electron-to-chromium: 1.5.344 + node-releases: 2.0.38 + update-browserslist-db: 1.2.3(browserslist@4.28.2) + + cac@6.7.14: {} + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + camelcase-css@2.0.1: {} + + caniuse-lite@1.0.30001791: {} + + chai@5.2.0: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + chalk@4.0.0: + dependencies: + ansi-styles: 4.1.0 + supports-color: 7.1.0 + + check-error@2.1.3: {} + + chokidar@3.6.0: + dependencies: + anymatch: 3.1.3 + braces: 3.0.3 + glob-parent: 5.1.2 + is-binary-path: 2.1.0 + is-glob: 4.0.3 + normalize-path: 3.0.0 + readdirp: 3.6.0 + optionalDependencies: + fsevents: 2.3.3 + + class-variance-authority@0.7.1: + dependencies: + clsx: 2.1.1 + + clsx@2.1.1: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + + commander@4.1.1: {} + + convert-source-map@2.0.0: {} + + cookie@1.1.1: {} + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + cssesc@3.0.0: {} + + cssstyle@4.2.1: + dependencies: + '@asamuzakjp/css-color': 2.8.2 + rrweb-cssom: 0.8.0 + + csstype@3.2.3: {} + + d3-array@3.2.4: + dependencies: + internmap: 2.0.3 + + d3-color@3.1.0: {} + + d3-ease@3.0.1: {} + + d3-format@3.1.2: {} + + d3-interpolate@3.0.1: + dependencies: + d3-color: 3.1.0 + + d3-path@3.1.0: {} + + d3-scale@4.0.2: + dependencies: + d3-array: 3.2.4 + d3-format: 3.1.2 + d3-interpolate: 3.0.1 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + + d3-shape@3.2.0: + dependencies: + d3-path: 3.1.0 + + d3-time-format@4.1.0: + dependencies: + d3-time: 3.1.0 + + d3-time@3.1.0: + dependencies: + d3-array: 3.2.4 + + d3-timer@3.0.1: {} + + data-urls@5.0.0: + dependencies: + whatwg-mimetype: 4.0.0 + whatwg-url: 14.1.0 + + date-fns@4.1.0: {} + + debug@4.4.3(supports-color@7.1.0): + dependencies: + ms: 2.1.3 + optionalDependencies: + supports-color: 7.1.0 + + decimal.js-light@2.5.1: {} + + decimal.js@10.6.0: {} + + deep-eql@5.0.2: {} + + deep-is@0.1.4: {} + + delayed-stream@1.0.0: {} + + dequal@2.0.3: {} + + detect-libc@2.1.2: + optional: true + + detect-node-es@1.1.0: {} + + didyoumean@1.2.2: {} + + dlv@1.1.3: {} + + dom-accessibility-api@0.5.16: {} + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + electron-to-chromium@1.5.344: {} + + entities@4.5.0: {} + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-module-lexer@1.7.0: {} + + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.3 + + es-toolkit@1.46.0: {} + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + esbuild@0.28.1: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.1 + '@esbuild/android-arm': 0.28.1 + '@esbuild/android-arm64': 0.28.1 + '@esbuild/android-x64': 0.28.1 + '@esbuild/darwin-arm64': 0.28.1 + '@esbuild/darwin-x64': 0.28.1 + '@esbuild/freebsd-arm64': 0.28.1 + '@esbuild/freebsd-x64': 0.28.1 + '@esbuild/linux-arm': 0.28.1 + '@esbuild/linux-arm64': 0.28.1 + '@esbuild/linux-ia32': 0.28.1 + '@esbuild/linux-loong64': 0.28.1 + '@esbuild/linux-mips64el': 0.28.1 + '@esbuild/linux-ppc64': 0.28.1 + '@esbuild/linux-riscv64': 0.28.1 + '@esbuild/linux-s390x': 0.28.1 + '@esbuild/linux-x64': 0.28.1 + '@esbuild/netbsd-arm64': 0.28.1 + '@esbuild/netbsd-x64': 0.28.1 + '@esbuild/openbsd-arm64': 0.28.1 + '@esbuild/openbsd-x64': 0.28.1 + '@esbuild/openharmony-arm64': 0.28.1 + '@esbuild/sunos-x64': 0.28.1 + '@esbuild/win32-arm64': 0.28.1 + '@esbuild/win32-ia32': 0.28.1 + '@esbuild/win32-x64': 0.28.1 + + escalade@3.2.0: {} + + escape-string-regexp@4.0.0: {} + + eslint-plugin-react-hooks@7.1.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0): + dependencies: + '@babel/core': 7.29.0(supports-color@7.1.0) + '@babel/parser': 7.29.2 + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + hermes-parser: 0.25.1 + zod: 4.3.6 + zod-validation-error: 4.0.2(zod@4.3.6) + transitivePeerDependencies: + - supports-color + + eslint-plugin-react-refresh@0.5.2(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0)): + dependencies: + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + + eslint-scope@9.1.2: + dependencies: + '@types/esrecurse': 4.3.1 + '@types/estree': 1.0.8 + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0): + dependencies: + '@eslint-community/eslint-utils': 4.9.1(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0)) + '@eslint-community/regexpp': 4.12.2 + '@eslint/config-array': 0.23.5(supports-color@7.1.0) + '@eslint/config-helpers': 0.5.5 + '@eslint/core': 1.2.1 + '@eslint/plugin-kit': 0.7.1 + '@humanfs/node': 0.16.8 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.8 + ajv: 6.15.0 + cross-spawn: 7.0.6 + debug: 4.4.3(supports-color@7.1.0) + escape-string-regexp: 4.0.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + espree: 11.2.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 8.0.0 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + minimatch: 10.2.5 + natural-compare: 1.4.0 + optionator: 0.9.4 + optionalDependencies: + jiti: 1.21.7 + transitivePeerDependencies: + - supports-color + + espree@11.2.0: + dependencies: + acorn: 8.16.0 + acorn-jsx: 5.3.2(acorn@8.16.0) + eslint-visitor-keys: 5.0.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + esutils@2.0.3: {} + + eventemitter3@5.0.4: {} + + expect-type@1.4.0: {} + + fast-deep-equal@3.1.3: {} + + fast-glob@3.3.3: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.8 + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fastq@1.20.1: + dependencies: + reusify: 1.1.0 + + fdir@6.5.0(picomatch@4.0.4): + optionalDependencies: + picomatch: 4.0.4 + + file-entry-cache@8.0.0: + dependencies: + flat-cache: 4.0.1 + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@4.0.1: + dependencies: + flatted: 3.4.2 + keyv: 4.5.4 + + flatted@3.4.2: {} + + form-data@4.0.6: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.4 + mime-types: 2.1.35 + + fraction.js@5.3.4: {} + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + gensync@1.0.0-beta.2: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.3 + math-intrinsics: 1.1.0 + + get-nonce@1.0.1: {} + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + globals@17.5.0: {} + + gopd@1.2.0: {} + + has-flag@4.0.0: {} + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + hasown@2.0.3: + dependencies: + function-bind: 1.1.2 + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + hermes-estree@0.25.1: {} + + hermes-parser@0.25.1: + dependencies: + hermes-estree: 0.25.1 + + html-encoding-sniffer@4.0.0: + dependencies: + whatwg-encoding: 3.1.1 + + http-proxy-agent@7.0.2(supports-color@7.1.0): + dependencies: + agent-base: 7.1.0(supports-color@7.1.0) + debug: 4.4.3(supports-color@7.1.0) + transitivePeerDependencies: + - supports-color + + https-proxy-agent@7.0.6(supports-color@7.1.0): + dependencies: + agent-base: 7.1.2(supports-color@7.1.0) + debug: 4.4.3(supports-color@7.1.0) + transitivePeerDependencies: + - supports-color + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + ignore@5.3.2: {} + + ignore@7.0.5: {} + + immer@10.2.0: {} + + immer@11.1.4: {} + + imurmurhash@0.1.4: {} + + internmap@2.0.3: {} + + is-binary-path@2.1.0: + dependencies: + binary-extensions: 2.3.0 + + is-core-module@2.16.1: + dependencies: + hasown: 2.0.3 + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-number@7.0.0: {} + + is-potential-custom-element-name@1.0.1: {} + + isexe@2.0.0: {} + + jiti@1.21.7: {} + + js-tokens@4.0.0: {} + + js-tokens@9.0.1: {} + + jsdom@26.0.0(supports-color@7.1.0): + dependencies: + cssstyle: 4.2.1 + data-urls: 5.0.0 + decimal.js: 10.6.0 + form-data: 4.0.6 + html-encoding-sniffer: 4.0.0 + http-proxy-agent: 7.0.2(supports-color@7.1.0) + https-proxy-agent: 7.0.6(supports-color@7.1.0) + is-potential-custom-element-name: 1.0.1 + nwsapi: 2.2.24 + parse5: 7.2.1 + rrweb-cssom: 0.8.0 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 5.0.0 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 7.0.0 + whatwg-encoding: 3.1.1 + whatwg-mimetype: 4.0.0 + whatwg-url: 14.1.0 + ws: 8.21.3 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + jsesc@3.1.0: {} + + json-buffer@3.0.1: {} + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + json5@2.2.3: {} + + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + lightningcss-android-arm64@1.32.0: + optional: true + + lightningcss-darwin-arm64@1.32.0: + optional: true + + lightningcss-darwin-x64@1.32.0: + optional: true + + lightningcss-freebsd-x64@1.32.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.32.0: + optional: true + + lightningcss-linux-arm64-gnu@1.32.0: + optional: true + + lightningcss-linux-arm64-musl@1.32.0: + optional: true + + lightningcss-linux-x64-gnu@1.32.0: + optional: true + + lightningcss-linux-x64-musl@1.32.0: + optional: true + + lightningcss-win32-arm64-msvc@1.32.0: + optional: true + + lightningcss-win32-x64-msvc@1.32.0: + optional: true + + lightningcss@1.32.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.32.0 + lightningcss-darwin-arm64: 1.32.0 + lightningcss-darwin-x64: 1.32.0 + lightningcss-freebsd-x64: 1.32.0 + lightningcss-linux-arm-gnueabihf: 1.32.0 + lightningcss-linux-arm64-gnu: 1.32.0 + lightningcss-linux-arm64-musl: 1.32.0 + lightningcss-linux-x64-gnu: 1.32.0 + lightningcss-linux-x64-musl: 1.32.0 + lightningcss-win32-arm64-msvc: 1.32.0 + lightningcss-win32-x64-msvc: 1.32.0 + optional: true + + lilconfig@3.1.3: {} + + lines-and-columns@1.2.4: {} + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + loupe@3.2.1: {} + + lru-cache@11.5.2: {} + + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + + lz-string@1.5.0: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + math-intrinsics@1.1.0: {} + + merge2@1.4.1: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + mime-db@1.52.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + minimatch@10.2.5: + dependencies: + brace-expansion: 5.0.5 + + ms@2.1.3: {} + + mz@2.7.0: + dependencies: + any-promise: 1.3.0 + object-assign: 4.1.1 + thenify-all: 1.6.0 + + nanoid@3.3.11: {} + + natural-compare@1.4.0: {} + + node-releases@2.0.38: {} + + normalize-path@3.0.0: {} + + nwsapi@2.2.24: {} + + object-assign@4.1.1: {} + + object-hash@3.0.0: {} + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + parse5@7.2.1: + dependencies: + entities: 4.5.0 + + path-exists@4.0.0: {} + + path-key@3.1.1: {} + + path-parse@1.0.7: {} + + pathe@2.0.3: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + picomatch@4.0.4: {} + + pify@2.3.0: {} + + pirates@4.0.7: {} + + postcss-import@15.1.0(postcss@8.5.10): + dependencies: + postcss: 8.5.10 + postcss-value-parser: 4.2.0 + read-cache: 1.0.0 + resolve: 1.22.12 + + postcss-js@4.1.0(postcss@8.5.10): + dependencies: + camelcase-css: 2.0.1 + postcss: 8.5.10 + + postcss-load-config@6.0.1(jiti@1.21.7)(postcss@8.5.10): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + jiti: 1.21.7 + postcss: 8.5.10 + + postcss-nested@6.2.0(postcss@8.5.10): + dependencies: + postcss: 8.5.10 + postcss-selector-parser: 6.1.2 + + postcss-selector-parser@6.1.2: + dependencies: + cssesc: 3.0.0 + util-deprecate: 1.0.2 + + postcss-value-parser@4.2.0: {} + + postcss@8.5.10: + dependencies: + nanoid: 3.3.11 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prelude-ls@1.2.1: {} + + pretty-format@27.0.2: + dependencies: + '@jest/types': 27.0.2 + ansi-regex: 5.0.1 + ansi-styles: 5.0.0 + react-is: 17.0.1 + + punycode@2.3.1: {} + + queue-microtask@1.2.3: {} + + react-dom@19.2.5(react@19.2.5): + dependencies: + react: 19.2.5 + scheduler: 0.27.0 + + react-hook-form@7.74.0(react@19.2.5): + dependencies: + react: 19.2.5 + + react-is@17.0.1: {} + + react-is@19.2.5: {} + + react-redux@9.2.0(@types/react@19.2.14)(react@19.2.5)(redux@5.0.1): + dependencies: + '@types/use-sync-external-store': 0.0.6 + react: 19.2.5 + use-sync-external-store: 1.6.0(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + redux: 5.0.1 + + react-refresh@0.17.0: {} + + react-remove-scroll-bar@2.3.8(@types/react@19.2.14)(react@19.2.5): + dependencies: + react: 19.2.5 + react-style-singleton: 2.2.3(@types/react@19.2.14)(react@19.2.5) + tslib: 2.8.1 + optionalDependencies: + '@types/react': 19.2.14 + + react-remove-scroll@2.7.2(@types/react@19.2.14)(react@19.2.5): + dependencies: + react: 19.2.5 + react-remove-scroll-bar: 2.3.8(@types/react@19.2.14)(react@19.2.5) + react-style-singleton: 2.2.3(@types/react@19.2.14)(react@19.2.5) + tslib: 2.8.1 + use-callback-ref: 1.3.3(@types/react@19.2.14)(react@19.2.5) + use-sidecar: 1.1.3(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + + react-router-dom@7.14.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-router: 7.14.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + + react-router@7.14.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + cookie: 1.1.1 + react: 19.2.5 + set-cookie-parser: 2.7.2 + optionalDependencies: + react-dom: 19.2.5(react@19.2.5) + + react-style-singleton@2.2.3(@types/react@19.2.14)(react@19.2.5): + dependencies: + get-nonce: 1.0.1 + react: 19.2.5 + tslib: 2.8.1 + optionalDependencies: + '@types/react': 19.2.14 + + react@19.2.5: {} + + read-cache@1.0.0: + dependencies: + pify: 2.3.0 + + readdirp@3.6.0: + dependencies: + picomatch: 2.3.2 + + recharts@3.8.1(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react-is@19.2.5)(react@19.2.5)(redux@5.0.1): + dependencies: + '@reduxjs/toolkit': 2.11.2(react-redux@9.2.0(@types/react@19.2.14)(react@19.2.5)(redux@5.0.1))(react@19.2.5) + clsx: 2.1.1 + decimal.js-light: 2.5.1 + es-toolkit: 1.46.0 + eventemitter3: 5.0.4 + immer: 10.2.0 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-is: 19.2.5 + react-redux: 9.2.0(@types/react@19.2.14)(react@19.2.5)(redux@5.0.1) + reselect: 5.1.1 + tiny-invariant: 1.3.3 + use-sync-external-store: 1.6.0(react@19.2.5) + victory-vendor: 37.3.6 + transitivePeerDependencies: + - '@types/react' + - redux + + redux-thunk@3.1.0(redux@5.0.1): + dependencies: + redux: 5.0.1 + + redux@5.0.1: {} + + reselect@5.1.1: {} + + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.16.1 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + reusify@1.1.0: {} + + rollup@4.60.2: + dependencies: + '@types/estree': 1.0.8 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.60.2 + '@rollup/rollup-android-arm64': 4.60.2 + '@rollup/rollup-darwin-arm64': 4.60.2 + '@rollup/rollup-darwin-x64': 4.60.2 + '@rollup/rollup-freebsd-arm64': 4.60.2 + '@rollup/rollup-freebsd-x64': 4.60.2 + '@rollup/rollup-linux-arm-gnueabihf': 4.60.2 + '@rollup/rollup-linux-arm-musleabihf': 4.60.2 + '@rollup/rollup-linux-arm64-gnu': 4.60.2 + '@rollup/rollup-linux-arm64-musl': 4.60.2 + '@rollup/rollup-linux-loong64-gnu': 4.60.2 + '@rollup/rollup-linux-loong64-musl': 4.60.2 + '@rollup/rollup-linux-ppc64-gnu': 4.60.2 + '@rollup/rollup-linux-ppc64-musl': 4.60.2 + '@rollup/rollup-linux-riscv64-gnu': 4.60.2 + '@rollup/rollup-linux-riscv64-musl': 4.60.2 + '@rollup/rollup-linux-s390x-gnu': 4.60.2 + '@rollup/rollup-linux-x64-gnu': 4.60.2 + '@rollup/rollup-linux-x64-musl': 4.60.2 + '@rollup/rollup-openbsd-x64': 4.60.2 + '@rollup/rollup-openharmony-arm64': 4.60.2 + '@rollup/rollup-win32-arm64-msvc': 4.60.2 + '@rollup/rollup-win32-ia32-msvc': 4.60.2 + '@rollup/rollup-win32-x64-gnu': 4.60.2 + '@rollup/rollup-win32-x64-msvc': 4.60.2 + fsevents: 2.3.3 + + rrweb-cssom@0.8.0: {} + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + + safer-buffer@2.1.2: {} + + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + + scheduler@0.27.0: {} + + semver@6.3.1: {} + + semver@7.7.4: {} + + set-cookie-parser@2.7.2: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + siginfo@2.0.0: {} + + source-map-js@1.2.1: {} + + stackback@0.0.2: {} + + std-env@3.9.0: {} + + strip-literal@3.0.0: + dependencies: + js-tokens: 9.0.1 + + sucrase@3.35.1: + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + commander: 4.1.1 + lines-and-columns: 1.2.4 + mz: 2.7.0 + pirates: 4.0.7 + tinyglobby: 0.2.16 + ts-interface-checker: 0.1.13 + + supports-color@7.1.0: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + symbol-tree@3.2.4: {} + + tailwind-merge@3.5.0: {} + + tailwindcss@3.4.19: + dependencies: + '@alloc/quick-lru': 5.2.0 + arg: 5.0.2 + chokidar: 3.6.0 + didyoumean: 1.2.2 + dlv: 1.1.3 + fast-glob: 3.3.3 + glob-parent: 6.0.2 + is-glob: 4.0.3 + jiti: 1.21.7 + lilconfig: 3.1.3 + micromatch: 4.0.8 + normalize-path: 3.0.0 + object-hash: 3.0.0 + picocolors: 1.1.1 + postcss: 8.5.10 + postcss-import: 15.1.0(postcss@8.5.10) + postcss-js: 4.1.0(postcss@8.5.10) + postcss-load-config: 6.0.1(jiti@1.21.7)(postcss@8.5.10) + postcss-nested: 6.2.0(postcss@8.5.10) + postcss-selector-parser: 6.1.2 + resolve: 1.22.12 + sucrase: 3.35.1 + transitivePeerDependencies: + - tsx + - yaml + + thenify-all@1.6.0: + dependencies: + thenify: 3.3.1 + + thenify@3.3.1: + dependencies: + any-promise: 1.3.0 + + tiny-invariant@1.3.3: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinyglobby@0.2.16: + dependencies: + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + + tinypool@1.1.1: {} + + tinyrainbow@2.0.0: {} + + tinyspy@4.0.4: {} + + tldts-core@6.1.32: {} + + tldts@6.1.32: + dependencies: + tldts-core: 6.1.32 + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tough-cookie@5.0.0: + dependencies: + tldts: 6.1.32 + + tr46@5.1.1: + dependencies: + punycode: 2.3.1 + + ts-api-utils@2.5.0(typescript@6.0.3): + dependencies: + typescript: 6.0.3 + + ts-interface-checker@0.1.13: {} + + tslib@2.8.1: {} + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + typescript-eslint@8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3): + dependencies: + '@typescript-eslint/eslint-plugin': 8.59.0(@typescript-eslint/parser@8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3))(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/parser': 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/typescript-estree': 8.59.0(supports-color@7.1.0)(typescript@6.0.3) + '@typescript-eslint/utils': 8.59.0(eslint@10.2.1(jiti@1.21.7)(supports-color@7.1.0))(supports-color@7.1.0)(typescript@6.0.3) + eslint: 10.2.1(jiti@1.21.7)(supports-color@7.1.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + typescript@6.0.3: {} + + undici-types@7.16.0: {} + + update-browserslist-db@1.2.3(browserslist@4.28.2): + dependencies: + browserslist: 4.28.2 + escalade: 3.2.0 + picocolors: 1.1.1 + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + use-callback-ref@1.3.3(@types/react@19.2.14)(react@19.2.5): + dependencies: + react: 19.2.5 + tslib: 2.8.1 + optionalDependencies: + '@types/react': 19.2.14 + + use-sidecar@1.1.3(@types/react@19.2.14)(react@19.2.5): + dependencies: + detect-node-es: 1.1.0 + react: 19.2.5 + tslib: 2.8.1 + optionalDependencies: + '@types/react': 19.2.14 + + use-sync-external-store@1.6.0(react@19.2.5): + dependencies: + react: 19.2.5 + + util-deprecate@1.0.2: {} + + victory-vendor@37.3.6: + dependencies: + '@types/d3-array': 3.2.2 + '@types/d3-ease': 3.0.2 + '@types/d3-interpolate': 3.0.4 + '@types/d3-scale': 4.0.9 + '@types/d3-shape': 3.1.8 + '@types/d3-time': 3.0.4 + '@types/d3-timer': 3.0.2 + d3-array: 3.2.4 + d3-ease: 3.0.1 + d3-interpolate: 3.0.1 + d3-scale: 4.0.2 + d3-shape: 3.2.0 + d3-time: 3.1.0 + d3-timer: 3.0.1 + + vite-node@3.2.4(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0)(supports-color@7.1.0): + dependencies: + cac: 6.7.14 + debug: 4.4.3(supports-color@7.1.0) + es-module-lexer: 1.7.0 + pathe: 2.0.3 + vite: 7.3.6(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0) + transitivePeerDependencies: + - '@types/node' + - jiti + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + vite@5.4.21(@types/node@24.12.2)(lightningcss@1.32.0): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.10 + rollup: 4.60.2 + optionalDependencies: + '@types/node': 24.12.2 + fsevents: 2.3.3 + lightningcss: 1.32.0 + + vite@7.3.6(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0): + dependencies: + esbuild: 0.28.1 + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + postcss: 8.5.10 + rollup: 4.60.2 + tinyglobby: 0.2.16 + optionalDependencies: + '@types/node': 24.12.2 + fsevents: 2.3.3 + jiti: 1.21.7 + lightningcss: 1.32.0 + + vitest@3.2.7(@types/node@24.12.2)(jiti@1.21.7)(jsdom@26.0.0(supports-color@7.1.0))(lightningcss@1.32.0)(supports-color@7.1.0): + dependencies: + '@types/chai': 5.2.3 + '@vitest/expect': 3.2.7 + '@vitest/mocker': 3.2.7(vite@7.3.6(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0)) + '@vitest/pretty-format': 3.2.7 + '@vitest/runner': 3.2.7 + '@vitest/snapshot': 3.2.7 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.2.0 + debug: 4.4.3(supports-color@7.1.0) + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 3.9.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.16 + tinypool: 1.1.1 + tinyrainbow: 2.0.0 + vite: 7.3.6(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0) + vite-node: 3.2.4(@types/node@24.12.2)(jiti@1.21.7)(lightningcss@1.32.0)(supports-color@7.1.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.12.2 + jsdom: 26.0.0(supports-color@7.1.0) + transitivePeerDependencies: + - jiti + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@7.0.0: {} + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + whatwg-url@14.1.0: + dependencies: + tr46: 5.1.1 + webidl-conversions: 7.0.0 + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + word-wrap@1.2.5: {} + + ws@8.21.3: {} + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + + yallist@3.1.1: {} + + yocto-queue@0.1.0: {} + + zod-validation-error@4.0.2(zod@4.3.6): + dependencies: + zod: 4.3.6 + + zod@4.3.6: {} diff --git a/frontend/pnpm-workspace.yaml b/frontend/pnpm-workspace.yaml new file mode 100644 index 0000000..5ed0b5a --- /dev/null +++ b/frontend/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +allowBuilds: + esbuild: true diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 0000000..2e7af2b --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg new file mode 100644 index 0000000..a275d87 --- /dev/null +++ b/frontend/public/favicon.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/frontend/scripts/precompress.mjs b/frontend/scripts/precompress.mjs new file mode 100644 index 0000000..6f71bc2 --- /dev/null +++ b/frontend/scripts/precompress.mjs @@ -0,0 +1,58 @@ +/** + * 构建后预压缩:为 dist 下的文本资源生成 .br / .gz 副本。 + * + * 后端静态服务(backend/api/router.go)会按 Accept-Encoding 直接返回预压缩文件, + * 省掉每个请求的实时压缩开销,也避免引入压缩中间件依赖。 + */ +import { createReadStream, createWriteStream, readdirSync, statSync } from 'node:fs' +import { extname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { pipeline } from 'node:stream/promises' +import { createGzip, createBrotliCompress, constants as zlibConstants } from 'node:zlib' + +const distDir = fileURLToPath(new URL('../dist/', import.meta.url)) +const COMPRESSIBLE = new Set(['.html', '.js', '.css', '.svg', '.json', '.txt', '.webmanifest']) +const MIN_BYTES = 1024 + +/** @param {string} dir @returns {string[]} */ +function walk(dir) { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = join(dir, entry.name) + return entry.isDirectory() ? walk(full) : [full] + }) +} + +/** + * @param {string} file + * @param {'br' | 'gz'} suffix + * @param {() => import('node:stream').Transform} factory + */ +async function writeCompressed(file, suffix, factory) { + await pipeline(createReadStream(file), factory(), createWriteStream(`${file}.${suffix}`)) +} + +let fileCount = 0 +let sourceBytes = 0 + +for (const file of walk(distDir)) { + if (!COMPRESSIBLE.has(extname(file).toLowerCase())) continue + const size = statSync(file).size + if (size < MIN_BYTES) continue + + await writeCompressed(file, 'gz', () => createGzip({ level: 9 })) + await writeCompressed(file, 'br', () => + createBrotliCompress({ + params: { + [zlibConstants.BROTLI_PARAM_QUALITY]: 11, + [zlibConstants.BROTLI_PARAM_SIZE_HINT]: size, + }, + }), + ) + + fileCount += 1 + sourceBytes += size +} + +console.log( + `precompress: ${fileCount} 个文件生成 .br/.gz 预压缩副本(源文件共 ${(sourceBytes / 1024).toFixed(1)} KB)`, +) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..1f4e5f4 --- /dev/null +++ b/frontend/src/App.tsx @@ -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 ( + + +
页面加载中…
+ + } + > + {children} +
+
+ ) +} + +function App() { + return ( + + + + }> + } /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + + ) +} + +export default App diff --git a/frontend/src/components/AmountDisplay.tsx b/frontend/src/components/AmountDisplay.tsx new file mode 100644 index 0000000..b3cdf73 --- /dev/null +++ b/frontend/src/components/AmountDisplay.tsx @@ -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 ( + + {sign}{formatCents(cents)} + + ) +} diff --git a/frontend/src/components/BrandLogo.tsx b/frontend/src/components/BrandLogo.tsx new file mode 100644 index 0000000..4d7f0b2 --- /dev/null +++ b/frontend/src/components/BrandLogo.tsx @@ -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 ( +
+
+
+ + +
+ {!compact && ( +
+
+ 家庭记账本 + +
+

Household Budget

+
+ )} +
+ ) +} diff --git a/frontend/src/components/CategoryLabel.tsx b/frontend/src/components/CategoryLabel.tsx new file mode 100644 index 0000000..a3a34f3 --- /dev/null +++ b/frontend/src/components/CategoryLabel.tsx @@ -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 ( + + {name} + {!isActive && ( + + 已停用 + + )} + + ) +} diff --git a/frontend/src/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx new file mode 100644 index 0000000..e4bdd6b --- /dev/null +++ b/frontend/src/components/ConfirmDialog.tsx @@ -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 ( + + + + {title} + {description} + + + + + + + + ) +} diff --git a/frontend/src/components/EmptyState.tsx b/frontend/src/components/EmptyState.tsx new file mode 100644 index 0000000..0920322 --- /dev/null +++ b/frontend/src/components/EmptyState.tsx @@ -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 ( +
+
+ +
+

{message}

+ {action &&
{action}
} +
+ ) +} diff --git a/frontend/src/components/ErrorBoundary.tsx b/frontend/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..82c2238 --- /dev/null +++ b/frontend/src/components/ErrorBoundary.tsx @@ -0,0 +1,37 @@ +import { Component, type ReactNode } from 'react' + +interface Props { + children: ReactNode +} + +interface State { + hasError: boolean +} + +export class ErrorBoundary extends Component { + constructor(props: Props) { + super(props) + this.state = { hasError: false } + } + + static getDerivedStateFromError(): State { + return { hasError: true } + } + + render() { + if (this.state.hasError) { + return ( +
+

页面加载出现错误

+ +
+ ) + } + return this.props.children + } +} diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsx new file mode 100644 index 0000000..24be548 --- /dev/null +++ b/frontend/src/components/ImportDialog.tsx @@ -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(null) + const [importSourceKind, setImportSourceKind] = useState('cmb_debit') + const [importAccountID, setImportAccountID] = useState('') + const [preview, setPreview] = useState(null) + const [importError, setImportError] = useState(null) + const [importMessage, setImportMessage] = useState(null) + const [categoryOverrides, setCategoryOverrides] = useState>({}) + + 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 ( + + + + 导入账单 + +
+
+ + +
+
+ + handleFileChange(e.target.files?.[0] ?? null)} + /> +
+
+ + +
+ + {preview && ( +
+

+ 解析 {preview.total_count} 条 · 预计新增 {preview.new_count} 条 · 重复跳过 {preview.duplicate_count} 条 +

+

+ 目标账户:{preview.account_name} + {preview.will_create_account && ( + (将自动创建) + )} +

+ {preview.items.length > 0 && ( +
    + {preview.items.map((item, i) => ( +
  • +
    +

    {item.description || item.counterparty || '—'}

    +

    + {formatDate(item.date)} + {item.status === 'duplicate_database' ? ' · 数据库已有' : item.status === 'duplicate_file' ? ' · 文件内重复' : ''} +

    + {item.status === 'new' && ( +
    + + {item.category_reason} +
    + )} +
    + +
  • + ))} +
+ )} + {preview.total_count > preview.items.length && ( +

+ 仅展示前 {preview.items.length} 条样本,确认后将处理全部 {preview.total_count} 条。 +

+ )} +
+ )} + + {importError &&

{importError}

} + {importMessage &&

{importMessage}

} + +
+ + +
+
+
+
+ ) +} diff --git a/frontend/src/components/LoadingSkeleton.tsx b/frontend/src/components/LoadingSkeleton.tsx new file mode 100644 index 0000000..48bf058 --- /dev/null +++ b/frontend/src/components/LoadingSkeleton.tsx @@ -0,0 +1,21 @@ +import { Skeleton } from '@/components/ui/skeleton' + +export function TableSkeleton({ rows = 5 }: { rows?: number }) { + return ( +
+ {Array.from({ length: rows }).map((_, i) => ( + + ))} +
+ ) +} + +export function CardSkeleton({ count = 3 }: { count?: number }) { + return ( +
+ {Array.from({ length: count }).map((_, i) => ( + + ))} +
+ ) +} diff --git a/frontend/src/components/MonthPicker.tsx b/frontend/src/components/MonthPicker.tsx new file mode 100644 index 0000000..b222cc5 --- /dev/null +++ b/frontend/src/components/MonthPicker.tsx @@ -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 ( +
+ + + + {year}年{month}月 + + +
+ ) +} diff --git a/frontend/src/components/NetWorthTrendChart.tsx b/frontend/src/components/NetWorthTrendChart.tsx new file mode 100644 index 0000000..f627e00 --- /dev/null +++ b/frontend/src/components/NetWorthTrendChart.tsx @@ -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 ( +

+ 系统会持续刷新当月最新净值,进入下月后冻结上月快照;需累积至少两个月才能绘制趋势曲线。当前已有 {snapshots.length} 条快照。 +

+ ) + } + + const data = snapshots.map((snapshot) => ({ + date: snapshot.date.slice(0, 7), + 资产: snapshot.total_asset / 100, + 负债: snapshot.total_debt / 100, + 净值: snapshot.net_worth / 100, + })) + + return ( +
+ + + + + `${(value / 10000).toFixed(0)}万`} + /> + formatCents(Math.round(value * 100))} + /> + + + + + + +
+ ) +} diff --git a/frontend/src/components/QuickAdd.tsx b/frontend/src/components/QuickAdd.tsx new file mode 100644 index 0000000..817964b --- /dev/null +++ b/frontend/src/components/QuickAdd.tsx @@ -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 + +interface Props { + onSubmit: (req: CreateTransactionRequest) => Promise + 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({ + 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 ( +
+
+ + 快速记账 +
+
+ {/* Type toggle */} +
+ + +
+ + + {/* Amount */} +
+ + {errors.amountYuan &&

{errors.amountYuan.message}

} +
+ + {/* Category */} +
+ ( + + )} + /> + {errors.category_id &&

{errors.category_id.message}

} +
+ + {/* Account */} +
+ +
+ + {/* Description */} +
+ +
+ + +
+
+ ) +} + +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 })), + } + }) +} diff --git a/frontend/src/components/SummaryCards.tsx b/frontend/src/components/SummaryCards.tsx new file mode 100644 index 0000000..e942b74 --- /dev/null +++ b/frontend/src/components/SummaryCards.tsx @@ -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 ( +
+ {cards.map(card => ( + +
+
+

{card.label}

+ + + +
+ {loading ? ( +
+ ) : ( +

+ {formatCents(card.amount)} +

+ )} + + ))} +
+ ) +} diff --git a/frontend/src/components/TransactionForm.tsx b/frontend/src/components/TransactionForm.tsx new file mode 100644 index 0000000..2320fac --- /dev/null +++ b/frontend/src/components/TransactionForm.tsx @@ -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 + submitting?: boolean + onSubmit: (data: TransactionFormData) => void | Promise +} + +export function TransactionForm({ + categories, + accounts, + defaultValues, + submitting = false, + onSubmit, +}: Props) { + const { + register, + control, + handleSubmit, + setValue, + watch, + formState: { errors }, + } = useForm({ + 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 ( +
+
+ + + +
+ +
+ + + {errors.amountYuan &&

{errors.amountYuan.message}

} +
+ {!isTransfer && ( +
+ +
+ ( + + )} + /> +
+ {errors.category_id &&

{errors.category_id.message}

} +
+ )} +
+ + + {errors.account_id &&

{errors.account_id.message}

} +
+ {isTransfer && ( +
+ + + {errors.to_account_id &&

{errors.to_account_id.message}

} +
+ )} +
+ +
+ ( + + )} + /> +
+ {errors.date &&

{errors.date.message}

} +
+ {!isTransfer && ( +
+ + +
+ )} +
+ + +
+ +
+ ) +} diff --git a/frontend/src/components/TransactionTable.tsx b/frontend/src/components/TransactionTable.tsx new file mode 100644 index 0000000..f017174 --- /dev/null +++ b/frontend/src/components/TransactionTable.tsx @@ -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 ( + + + + {selectable && ( + + + + )} + 日期 + 分类 + 描述 + {!compact && 对手方} + {!compact && 账户} + 金额 + {(onEdit || onDelete) && } + + + + {items.map(item => ( + + {selectable && ( + + onToggleSelect?.(item.id)} /> + + )} + + {formatDate(item.date)} + + + {item.type === 'transfer' ? ( + 转账 + ) : ( + + )} + + + {item.description} + + {!compact && ( + {item.counterparty || '-'} + )} + {!compact && ( + + {item.type === 'transfer' + ? `${item.account_name || '-'} → ${item.to_account_name || '-'}` + : item.account_name} + + )} + + + + {(onEdit || onDelete) && ( + +
+ {onEdit && ( + + )} + {onDelete && ( + + )} +
+
+ )} +
+ ))} +
+
+ ) +} diff --git a/frontend/src/components/layout/Header.tsx b/frontend/src/components/layout/Header.tsx new file mode 100644 index 0000000..f50583e --- /dev/null +++ b/frontend/src/components/layout/Header.tsx @@ -0,0 +1,28 @@ +import { useLocation } from 'react-router-dom' +import { MonthPicker } from '@/components/MonthPicker' + +const pageTitles: Record = { + '/': '首页', + '/transactions': '收支记录', + '/budget': '预算看板', + '/assets': '资产总览', + '/policies': '保单管理', + '/lifecycle': '人生周期', + '/reports': '报表分析', + '/settings': '设置', +} + +export function Header() { + const location = useLocation() + const title = pageTitles[location.pathname] || '' + + return ( +
+
+

Household Budget Book

+

{title}

+
+ +
+ ) +} diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsx new file mode 100644 index 0000000..91e4f57 --- /dev/null +++ b/frontend/src/components/layout/Layout.tsx @@ -0,0 +1,17 @@ +import { Outlet } from 'react-router-dom' +import { Sidebar } from './Sidebar' +import { Header } from './Header' + +export function Layout() { + return ( +
+ +
+
+
+ +
+
+
+ ) +} diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx new file mode 100644 index 0000000..8da409b --- /dev/null +++ b/frontend/src/components/layout/Sidebar.tsx @@ -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 ( + + ) +} diff --git a/frontend/src/components/ui/badge.tsx b/frontend/src/components/ui/badge.tsx new file mode 100644 index 0000000..6ac2efd --- /dev/null +++ b/frontend/src/components/ui/badge.tsx @@ -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, + VariantProps {} + +function Badge({ className, variant, ...props }: BadgeProps) { + return ( +
+ ) +} + +export { Badge } diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx new file mode 100644 index 0000000..b45ff55 --- /dev/null +++ b/frontend/src/components/ui/button.tsx @@ -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, + VariantProps { + asChild?: boolean +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + return ( + + ) + } +) +Button.displayName = "Button" + +export { Button } diff --git a/frontend/src/components/ui/card.tsx b/frontend/src/components/ui/card.tsx new file mode 100644 index 0000000..81f696b --- /dev/null +++ b/frontend/src/components/ui/card.tsx @@ -0,0 +1,76 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardFooter.displayName = "CardFooter" + +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } diff --git a/frontend/src/components/ui/date-picker.tsx b/frontend/src/components/ui/date-picker.tsx new file mode 100644 index 0000000..ae58ea1 --- /dev/null +++ b/frontend/src/components/ui/date-picker.tsx @@ -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('day') + const selected = React.useMemo(() => parseDateString(value), [value]) + const today = React.useMemo(() => new Date(), []) + const [cursor, setCursor] = React.useState(() => selected || new Date()) + + const triggerRef = React.useRef(null) + const popupRef = React.useRef(null) + const [popupStyle, setPopupStyle] = React.useState({}) + + 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 ( + + ) + } + + 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 ( + <> +
+
+ + +
+
+ + +
+
+ + +
+
+
+ {WEEKDAYS.map(w => ( +
{w}
+ ))} + {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 ( + + ) + })} +
+
+ + {clearable && ( + + )} +
+ + ) + } + + const renderMonthView = () => ( + <> +
+ + + +
+
+ {MONTHS.map((m, idx) => { + const isActive = selected && selected.getFullYear() === cursor.getFullYear() && selected.getMonth() === idx + return ( + + ) + })} +
+ + ) + + const renderYearView = () => { + const start = Math.floor(cursor.getFullYear() / 12) * 12 + const years = Array.from({ length: 12 }, (_, i) => start + i) + return ( + <> +
+ + {start} - {start + 11} + +
+
+ {years.map(y => { + const isActive = selected && selected.getFullYear() === y + return ( + + ) + })} +
+ + ) + } + + return ( + <> + {renderTrigger()} + {open && + createPortal( +
e.stopPropagation()} + onMouseDown={e => e.stopPropagation()} + onClick={e => e.stopPropagation()} + > + {view === 'day' && renderDayView()} + {view === 'month' && renderMonthView()} + {view === 'year' && renderYearView()} +
, + document.body, + )} + + ) +} diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx new file mode 100644 index 0000000..1da70ca --- /dev/null +++ b/frontend/src/components/ui/dialog.tsx @@ -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, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + {children} + + + Close + + + +)) +DialogContent.displayName = DialogPrimitive.Content.displayName + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +DialogHeader.displayName = "DialogHeader" + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +DialogFooter.displayName = "DialogFooter" + +const DialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogTitle.displayName = DialogPrimitive.Title.displayName + +const DialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogDescription.displayName = DialogPrimitive.Description.displayName + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +} diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsx new file mode 100644 index 0000000..4a5d1ad --- /dev/null +++ b/frontend/src/components/ui/input.tsx @@ -0,0 +1,23 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Input = React.forwardRef>( + ({ className, type, ...props }, ref) => { + return ( + + ) + } +) +Input.displayName = "Input" + +export { Input } diff --git a/frontend/src/components/ui/label.tsx b/frontend/src/components/ui/label.tsx new file mode 100644 index 0000000..5341821 --- /dev/null +++ b/frontend/src/components/ui/label.tsx @@ -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, + React.ComponentPropsWithoutRef & + VariantProps +>(({ className, ...props }, ref) => ( + +)) +Label.displayName = LabelPrimitive.Root.displayName + +export { Label } diff --git a/frontend/src/components/ui/skeleton.tsx b/frontend/src/components/ui/skeleton.tsx new file mode 100644 index 0000000..d7e45f7 --- /dev/null +++ b/frontend/src/components/ui/skeleton.tsx @@ -0,0 +1,15 @@ +import { cn } from "@/lib/utils" + +function Skeleton({ + className, + ...props +}: React.HTMLAttributes) { + return ( +
+ ) +} + +export { Skeleton } diff --git a/frontend/src/components/ui/table.tsx b/frontend/src/components/ui/table.tsx new file mode 100644 index 0000000..49c09ce --- /dev/null +++ b/frontend/src/components/ui/table.tsx @@ -0,0 +1,120 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Table = React.forwardRef< + HTMLTableElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+ + +)) +Table.displayName = "Table" + +const TableHeader = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableHeader.displayName = "TableHeader" + +const TableBody = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableBody.displayName = "TableBody" + +const TableFooter = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + tr]:last:border-b-0", + className + )} + {...props} + /> +)) +TableFooter.displayName = "TableFooter" + +const TableRow = React.forwardRef< + HTMLTableRowElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableRow.displayName = "TableRow" + +const TableHead = React.forwardRef< + HTMLTableCellElement, + React.ThHTMLAttributes +>(({ className, ...props }, ref) => ( +
[role=checkbox]]:translate-y-[2px]", + className + )} + {...props} + /> +)) +TableHead.displayName = "TableHead" + +const TableCell = React.forwardRef< + HTMLTableCellElement, + React.TdHTMLAttributes +>(({ className, ...props }, ref) => ( + [role=checkbox]]:translate-y-[2px]", + className + )} + {...props} + /> +)) +TableCell.displayName = "TableCell" + +const TableCaption = React.forwardRef< + HTMLTableCaptionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +TableCaption.displayName = "TableCaption" + +export { + Table, + TableHeader, + TableBody, + TableFooter, + TableHead, + TableRow, + TableCell, + TableCaption, +} diff --git a/frontend/src/components/ui/tabs.tsx b/frontend/src/components/ui/tabs.tsx new file mode 100644 index 0000000..7ecd67d --- /dev/null +++ b/frontend/src/components/ui/tabs.tsx @@ -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, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +TabsList.displayName = TabsPrimitive.List.displayName + +const TabsTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +TabsTrigger.displayName = TabsPrimitive.Trigger.displayName + +const TabsContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +TabsContent.displayName = TabsPrimitive.Content.displayName + +export { Tabs, TabsList, TabsTrigger, TabsContent } diff --git a/frontend/src/components/ui/tree-select.tsx b/frontend/src/components/ui/tree-select.tsx new file mode 100644 index 0000000..a5be65b --- /dev/null +++ b/frontend/src/components/ui/tree-select.tsx @@ -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>(() => new Set()) + const triggerRef = React.useRef(null) + const popupRef = React.useRef(null) + const [popupStyle, setPopupStyle] = React.useState({}) + + 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() + 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( + , + ) + } + return rows + } + + const rows = renderRows() + const triggerLabel = selectedNode?.label + + return ( + <> + + {open && + createPortal( +
e.stopPropagation()} + onMouseDown={e => e.stopPropagation()} + onClick={e => e.stopPropagation()} + > + {searchable && ( +
+ + setKeyword(e.target.value)} + placeholder="搜索分类..." + className="tree-select-search-input" + /> + {keyword && ( + + )} +
+ )} +
+ {rows.length > 0 ? rows :
{emptyText}
} +
+
, + document.body, + )} + + ) +} diff --git a/frontend/src/context/AppContext.tsx b/frontend/src/context/AppContext.tsx new file mode 100644 index 0000000..1bfea0d --- /dev/null +++ b/frontend/src/context/AppContext.tsx @@ -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 ( + + {children} + + ) +} diff --git a/frontend/src/context/contextState.ts b/frontend/src/context/contextState.ts new file mode 100644 index 0000000..e04239b --- /dev/null +++ b/frontend/src/context/contextState.ts @@ -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 +}>({ state: initialState, dispatch: () => {} }) diff --git a/frontend/src/context/useAppContext.ts b/frontend/src/context/useAppContext.ts new file mode 100644 index 0000000..2f620d1 --- /dev/null +++ b/frontend/src/context/useAppContext.ts @@ -0,0 +1,6 @@ +import { useContext } from 'react' +import { AppCtx } from '@/context/contextState' + +export function useAppContext() { + return useContext(AppCtx) +} diff --git a/frontend/src/hooks/useAccounts.ts b/frontend/src/hooks/useAccounts.ts new file mode 100644 index 0000000..63f376f --- /dev/null +++ b/frontend/src/hooks/useAccounts.ts @@ -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 }), + } +} diff --git a/frontend/src/hooks/useAssetMutations.ts b/frontend/src/hooks/useAssetMutations.ts new file mode 100644 index 0000000..67f3b90 --- /dev/null +++ b/frontend/src/hooks/useAssetMutations.ts @@ -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 +} + +interface SaveLiabilityInput { + id?: number + payload: Partial +} + +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, + } +} diff --git a/frontend/src/hooks/useBudgets.ts b/frontend/src/hooks/useBudgets.ts new file mode 100644 index 0000000..32a4819 --- /dev/null +++ b/frontend/src/hooks/useBudgets.ts @@ -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) }), + } +} diff --git a/frontend/src/hooks/useCategories.ts b/frontend/src/hooks/useCategories.ts new file mode 100644 index 0000000..d544311 --- /dev/null +++ b/frontend/src/hooks/useCategories.ts @@ -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 }), + } +} diff --git a/frontend/src/hooks/useDashboard.ts b/frontend/src/hooks/useDashboard.ts new file mode 100644 index 0000000..71ca40a --- /dev/null +++ b/frontend/src/hooks/useDashboard.ts @@ -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, + } +} diff --git a/frontend/src/hooks/useDebouncedValue.test.tsx b/frontend/src/hooks/useDebouncedValue.test.tsx new file mode 100644 index 0000000..a08fa71 --- /dev/null +++ b/frontend/src/hooks/useDebouncedValue.test.tsx @@ -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('餐饮') + }) +}) diff --git a/frontend/src/hooks/useDebouncedValue.ts b/frontend/src/hooks/useDebouncedValue.ts new file mode 100644 index 0000000..6901251 --- /dev/null +++ b/frontend/src/hooks/useDebouncedValue.ts @@ -0,0 +1,12 @@ +import { useEffect, useState } from 'react' + +export function useDebouncedValue(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 +} diff --git a/frontend/src/hooks/useMembers.ts b/frontend/src/hooks/useMembers.ts new file mode 100644 index 0000000..8dbf941 --- /dev/null +++ b/frontend/src/hooks/useMembers.ts @@ -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 }), + } +} diff --git a/frontend/src/hooks/usePhase3.test.tsx b/frontend/src/hooks/usePhase3.test.tsx new file mode 100644 index 0000000..6c2cabd --- /dev/null +++ b/frontend/src/hooks/usePhase3.test.tsx @@ -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 }) => ( + {children} + ) + + 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) + }) +}) diff --git a/frontend/src/hooks/usePhase3.ts b/frontend/src/hooks/usePhase3.ts new file mode 100644 index 0000000..2b87ec0 --- /dev/null +++ b/frontend/src/hooks/usePhase3.ts @@ -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'] }), + } +} diff --git a/frontend/src/hooks/useReports.ts b/frontend/src/hooks/useReports.ts new file mode 100644 index 0000000..bb017a8 --- /dev/null +++ b/frontend/src/hooks/useReports.ts @@ -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, + } +} diff --git a/frontend/src/index.css b/frontend/src/index.css new file mode 100644 index 0000000..244b53d --- /dev/null +++ b/frontend/src/index.css @@ -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); + } +} diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts new file mode 100644 index 0000000..0c12408 --- /dev/null +++ b/frontend/src/lib/api.test.ts @@ -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) + }) +}) diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts new file mode 100644 index 0000000..b4f03e6 --- /dev/null +++ b/frontend/src/lib/api.ts @@ -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(path: string, options?: RequestInit): Promise { + 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(path: string, formData: FormData): Promise { + 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('/api/members'), + createMember: (req: CreateMemberRequest) => + apiFetch('/api/members', { method: 'POST', body: JSON.stringify(req) }), + updateMember: (id: number, req: UpdateMemberRequest) => + apiFetch(`/api/members/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteMember: (id: number) => + apiFetch(`/api/members/${id}`, { method: 'DELETE' }), + + // Categories + getCategories: (type?: string) => + apiFetch(`/api/categories${type ? `?type=${type}` : ''}`), + createCategory: (req: CreateCategoryRequest) => + apiFetch('/api/categories', { method: 'POST', body: JSON.stringify(req) }), + updateCategory: (id: number, req: UpdateCategoryRequest) => + apiFetch(`/api/categories/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteCategory: (id: number) => + apiFetch(`/api/categories/${id}`, { method: 'DELETE' }), + + // Accounts + getAccounts: () => apiFetch('/api/accounts'), + createAccount: (req: CreateAccountRequest) => + apiFetch('/api/accounts', { method: 'POST', body: JSON.stringify(req) }), + updateAccount: (id: number, req: UpdateAccountRequest) => + apiFetch(`/api/accounts/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteAccount: (id: number) => + apiFetch(`/api/accounts/${id}`, { method: 'DELETE' }), + reconcileAccount: (id: number, actual_balance: number, note = '', create_adjustment = true) => + apiFetch(`/api/accounts/${id}/reconcile`, { method: 'POST', body: JSON.stringify({ actual_balance, note, create_adjustment }) }), + getAccountReconciliations: (id: number) => apiFetch(`/api/accounts/${id}/reconciliations`), + + // Transactions + getTransactions: (params: Record, signal?: AbortSignal) => { + const qs = new URLSearchParams(params).toString() + return apiFetch( + `/api/transactions${qs ? `?${qs}` : ''}`, + { signal }, + ) + }, + createTransaction: (req: CreateTransactionRequest) => + apiFetch('/api/transactions', { method: 'POST', body: JSON.stringify(req) }), + previewImportTransactions: (formData: FormData) => + apiUpload('/api/transactions/import/preview', formData), + importTransactions: (formData: FormData) => + apiUpload('/api/transactions/import', formData), + getImportBatches: () => + apiFetch('/api/transactions/import-batches'), + deleteTransactionsBatch: (ids: number[]) => + apiFetch('/api/transactions/batch-delete', { method: 'POST', body: JSON.stringify({ ids }) }), + deleteImportBatch: (id: number) => + apiFetch(`/api/transactions/import-batches/${id}`, { method: 'DELETE' }), + updateTransaction: (id: number, req: UpdateTransactionRequest) => + apiFetch(`/api/transactions/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteTransaction: (id: number) => + apiFetch(`/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(`/api/dashboard/summary${qs ? `?${qs}` : ''}`) + }, + getDashboardRecent: (limit = 5) => + apiFetch(`/api/dashboard/recent?limit=${limit}`), + + // Budgets + getBudgetOverview: (year: number, month: number) => + apiFetch(`/api/budgets/${year}/${month}`), + upsertBudget: (req: UpsertBudgetRequest) => + apiFetch('/api/budgets', { method: 'PUT', body: JSON.stringify(req) }), + deleteBudget: (id: number) => apiFetch(`/api/budgets/${id}`, { method: 'DELETE' }), + + // Reports + getReportOverview: (year: number, month: number, type: 'income' | 'expense' = 'expense') => + apiFetch(`/api/reports/overview?year=${year}&month=${month}&type=${type}`), + getCategoryRanking: (year: number, month: number, type = 'expense') => + apiFetch(`/api/reports/category-ranking?year=${year}&month=${month}&type=${type}`), + getTrend: (year: number) => + apiFetch(`/api/reports/trend?year=${year}`), + + // Assets & liabilities + getAssets: () => apiFetch('/api/assets'), + createAsset: (req: Partial) => + apiFetch('/api/assets', { method: 'POST', body: JSON.stringify(req) }), + updateAsset: (id: number, req: Partial) => + apiFetch(`/api/assets/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteAsset: (id: number) => apiFetch(`/api/assets/${id}`, { method: 'DELETE' }), + getLiabilities: () => apiFetch('/api/liabilities'), + createLiability: (req: Partial) => + apiFetch('/api/liabilities', { method: 'POST', body: JSON.stringify(req) }), + updateLiability: (id: number, req: Partial) => + apiFetch(`/api/liabilities/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteLiability: (id: number) => apiFetch(`/api/liabilities/${id}`, { method: 'DELETE' }), + getNetWorth: () => apiFetch('/api/assets/net-worth'), + getAssetSnapshots: () => apiFetch('/api/assets/snapshots'), + + // Policies + getPolicies: () => apiFetch('/api/policies'), + getUpcomingPolicies: (days = 30) => apiFetch(`/api/policies/upcoming?days=${days}`), + createPolicy: (req: Partial) => + apiFetch('/api/policies', { method: 'POST', body: JSON.stringify(req) }), + updatePolicy: (id: number, req: Partial) => + apiFetch(`/api/policies/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deletePolicy: (id: number) => apiFetch(`/api/policies/${id}`, { method: 'DELETE' }), + getPolicyPayments: (id: number) => apiFetch(`/api/policies/${id}/payments`), + createPolicyPayment: (id: number, req: Partial) => apiFetch(`/api/policies/${id}/payments`, { method: 'POST', body: JSON.stringify(req) }), + updatePolicyPayment: (id: number, req: Partial) => apiFetch(`/api/policy-payments/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + + getBackupStatus: () => apiFetch('/api/backups/status'), + createBackup: () => apiFetch('/api/backups', { method: 'POST' }), + + // Lifecycle + getLifecycleEvents: () => apiFetch('/api/lifecycle'), + createLifecycleEvent: (req: Partial) => + apiFetch('/api/lifecycle/events', { method: 'POST', body: JSON.stringify(req) }), + updateLifecycleEvent: (id: number, req: Partial) => + apiFetch(`/api/lifecycle/events/${id}`, { method: 'PUT', body: JSON.stringify(req) }), + deleteLifecycleEvent: (id: number) => apiFetch(`/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 } diff --git a/frontend/src/lib/categoryTree.ts b/frontend/src/lib/categoryTree.ts new file mode 100644 index 0000000..04ef4a5 --- /dev/null +++ b/frontend/src/lib/categoryTree.ts @@ -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 +} diff --git a/frontend/src/lib/importUtils.ts b/frontend/src/lib/importUtils.ts new file mode 100644 index 0000000..186b211 --- /dev/null +++ b/frontend/src/lib/importUtils.ts @@ -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 + } +} diff --git a/frontend/src/lib/queryClient.ts b/frontend/src/lib/queryClient.ts new file mode 100644 index 0000000..acf2023 --- /dev/null +++ b/frontend/src/lib/queryClient.ts @@ -0,0 +1,11 @@ +import { QueryClient } from '@tanstack/react-query' + +export const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 30_000, + retry: 1, + refetchOnWindowFocus: false, + }, + }, +}) diff --git a/frontend/src/lib/queryInvalidation.test.ts b/frontend/src/lib/queryInvalidation.test.ts new file mode 100644 index 0000000..b94eb04 --- /dev/null +++ b/frontend/src/lib/queryInvalidation.test.ts @@ -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) + }) + }) +}) diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts new file mode 100644 index 0000000..b5c0e0f --- /dev/null +++ b/frontend/src/lib/queryInvalidation.ts @@ -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 { + await Promise.all( + keys.map((queryKey) => queryClient.invalidateQueries({ queryKey })), + ) +} diff --git a/frontend/src/lib/queryKeys.ts b/frontend/src/lib/queryKeys.ts new file mode 100644 index 0000000..32e790c --- /dev/null +++ b/frontend/src/lib/queryKeys.ts @@ -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) => ['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, + }, +} diff --git a/frontend/src/lib/transactionForm.ts b/frontend/src/lib/transactionForm.ts new file mode 100644 index 0000000..1f77301 --- /dev/null +++ b/frontend/src/lib/transactionForm.ts @@ -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 + +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: '', +} diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts new file mode 100644 index 0000000..72a0a09 --- /dev/null +++ b/frontend/src/lib/utils.ts @@ -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}` +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx new file mode 100644 index 0000000..cd306e8 --- /dev/null +++ b/frontend/src/main.tsx @@ -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( + + + + + , +) diff --git a/frontend/src/pages/AssetOverview.test.tsx b/frontend/src/pages/AssetOverview.test.tsx new file mode 100644 index 0000000..63e07f0 --- /dev/null +++ b/frontend/src/pages/AssetOverview.test.tsx @@ -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: () =>
趋势图
, +})) + +import AssetOverview from './AssetOverview' + +describe('AssetOverview', () => { + it('guards an in-flight asset save from rapid duplicate submission', () => { + mutationMocks.saveAsset.mockReturnValue(new Promise(() => {})) + + render() + + 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) + }) +}) diff --git a/frontend/src/pages/AssetOverview.tsx b/frontend/src/pages/AssetOverview.tsx new file mode 100644 index 0000000..d85eab2 --- /dev/null +++ b/frontend/src/pages/AssetOverview.tsx @@ -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(null) + const [debtName, setDebtName] = useState('') + const [debtValue, setDebtValue] = useState('') + const [debtType, setDebtType] = useState('mortgage') + const [editingDebt, setEditingDebt] = useState(null) + const [deleteAssetTarget, setDeleteAssetTarget] = useState(null) + const [deleteDebtTarget, setDeleteDebtTarget] = useState(null) + const [mutationError, setMutationError] = useState(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 = { + 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 ( +
+
+ + 0 ? `其中信用卡欠款 ${formatCents(netWorth.liquid_debt)}` : undefined} + /> + = 0 ? 'text-income' : 'text-expense'} + /> +
+ +
+ + 0 ? 'text-expense' : 'text-muted'} + hint="信用卡账户当前余额为负时的欠款绝对值。" + /> +
+ + {(error || mutationError) &&

{error || mutationError}

} + {!loading && refreshing &&

资产数据更新中…

} + +
+ + {editingAsset ? '修改资产' : '登记资产'} + +
+ + setAssetName(e.target.value)} placeholder="资产名称" className="h-9 text-sm" /> + + {!assetAccountID && ( + setAssetValue(e.target.value)} placeholder="当前估值" inputMode="decimal" className="h-9 text-sm" /> + )} + + {editingAsset && } +
+
+
+ + + {editingDebt ? '修改负债' : '登记负债'} + +
+ + setDebtName(e.target.value)} placeholder="负债名称" className="h-9 text-sm" /> + setDebtValue(e.target.value)} placeholder="剩余本金" inputMode="decimal" className="h-9 text-sm" /> + + {editingDebt && } +
+
+
+
+ +
+ + 资产列表 + + {assetsLoading ?
: assets.length > 0 ? ( +
{assets.map(a => ( + : undefined} + value={formatCents(a.value)} + onEdit={() => editAsset(a)} + onDelete={() => setDeleteAssetTarget(a)} + disabled={assetPending} + /> + ))}
+ ) : } + + + + 负债列表 + + {liabilitiesLoading ?
: liabilities.length > 0 ? ( +
{liabilities.map(d => editDebt(d)} onDelete={() => setDeleteDebtTarget(d)} disabled={liabilityPending} />)}
+ ) : } + + +
+ + + 净值趋势 + + {snapshotsLoading + ?
+ : ( + }> + + + )} + + + + setDeleteAssetTarget(null)} + title="删除资产" + description={`确认删除资产「${deleteAssetTarget?.name ?? ''}」(${formatCents(deleteAssetTarget?.value ?? 0)})吗?`} + onConfirm={handleDeleteAsset} + loading={assetPending} + /> + setDeleteDebtTarget(null)} + title="删除负债" + description={`确认删除负债「${deleteDebtTarget?.name ?? ''}」(${formatCents(deleteDebtTarget?.principal ?? 0)})吗?`} + onConfirm={handleDeleteDebt} + loading={liabilityPending} + /> +
+ ) +} + +function Metric({ title, value, icon, tone = 'text-primary', hint, loading = false }: { title: string; value: string | null; icon: Parameters[0]['icon']; tone?: string; hint?: string; loading?: boolean }) { + return ( + +
+

{title}

+ +
+ {loading || value === null + ?
+ :

{value}

} + {hint &&

{hint}

} + + ) +} + +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 ( +
+
+

{title}{badge}

+

{sub}

+
+
+

{value}

+ + {onDelete && ( + + )} +
+
+ ) +} diff --git a/frontend/src/pages/BudgetBoard.tsx b/frontend/src/pages/BudgetBoard.tsx new file mode 100644 index 0000000..9edb8ee --- /dev/null +++ b/frontend/src/pages/BudgetBoard.tsx @@ -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(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 ( +
+
+ + + +
+ + + + + + 年度设定 + + + +
+
+ + + +
+ {scope !== 'annual_total' && ( + + )} + setAmountYuan(e.target.value)} placeholder="预算金额" inputMode="decimal" className="h-9 w-36 text-sm" /> + setNote(e.target.value)} placeholder="备注" className="h-9 min-w-[180px] flex-1 text-sm" /> + +
+

+ 年度分类预算会按 12 个月折算为月度目标;“本月覆盖”用于临时调整单月分类额度。 +

+ {error &&

{error}

} +
+
+ + + + + + 月度看板与超支预警 + + + +
+
+ 本月总执行率 + + {(overview?.monthly_usage_percent ?? 0).toFixed(0)}% + +
+ +

+ 已用 {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))}`} +

+ {(overview?.monthly_unbudgeted_spent ?? 0) > 0 && ( +

+ 其中预算外支出 {formatCents(overview?.monthly_unbudgeted_spent ?? 0)} +

+ )} +
+ + {loading ? ( +
+ {Array.from({ length: 4 }).map((_, index) => ( +
+ ))} +
+ ) : budgetItems.length > 0 ? ( +
+ {budgetItems.map(item => ( +
+
+
+

{item.category_name}

+

+ 已用 {formatCents(item.spent)} / 月目标 {formatCents(item.amount)} +

+
+ + {item.usage_percent.toFixed(0)}% + +
+ +
+

+ {item.remaining >= 0 ? `剩余 ${formatCents(item.remaining)}` : `超支 ${formatCents(Math.abs(item.remaining))}`} + {item.note ? ` · ${item.note}` : ''} +

+
+ + +
+
+
+ ))} +
+ ) : ( + + )} + + + + setDeleteTarget(null)} + title="删除预算" + description={`确认删除 ${deleteTarget?.category_name ?? ''} ${deleteTarget?.month ? '本月' : '年度'} 预算 ${formatCents(deleteTarget?.amount ?? 0)} 吗?`} + onConfirm={handleDelete} + loading={deleting} + /> +
+ ) +} + +function MetricCard({ title, value, icon, tone = 'text-primary' }: { + title: string + value: string + icon: Parameters[0]['icon'] + tone?: string +}) { + return ( + +
+

{title}

+ + + +
+

{value}

+
+ ) +} + +function ProgressBar({ value }: { value: number }) { + return ( +
+
= 100 ? 'bg-expense' : value >= 80 ? 'bg-warning' : 'bg-income'}`} style={{ width: `${Math.min(value, 100)}%` }} /> +
+ ) +} + +function toneByUsage(value: number) { + if (value >= 100) return 'text-expense' + if (value >= 80) return 'text-warning' + return 'text-income' +} diff --git a/frontend/src/pages/Dashboard.tsx b/frontend/src/pages/Dashboard.tsx new file mode 100644 index 0000000..969ea05 --- /dev/null +++ b/frontend/src/pages/Dashboard.tsx @@ -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 ( +
+ + + createMutation.mutateAsync(req)} + submitting={createMutation.isPending} + /> + + + + + + 最近记录 + + + + {recentItems.length > 0 ? ( + + ) : ( + + )} + + +
+ ) +} diff --git a/frontend/src/pages/Lifecycle.tsx b/frontend/src/pages/Lifecycle.tsx new file mode 100644 index 0000000..e87e1e7 --- /dev/null +++ b/frontend/src/pages/Lifecycle.tsx @@ -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(null) + const [deleteTarget, setDeleteTarget] = useState(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 ( +
+ {error &&

{error}

} + + {editingEvent ? '修改人生事件' : '添加人生事件'} + +
+ setYear(e.target.value)} placeholder="年份" className="h-9 w-24 text-sm" /> + + setEvent(e.target.value)} placeholder="事件描述" className="h-9 min-w-[220px] flex-1 text-sm" /> + setCost(e.target.value)} placeholder="预估费用" inputMode="decimal" className="h-9 w-32 text-sm" /> + + {editingEvent && } +
+
+
+ + + 家庭时间线 + + {loading ?
: events.length > 0 ? ( +
+ {events.map(item => ( +
+

{item.year}

+

{item.event}

{item.member_name || '家庭整体'}{item.note ? ` · ${item.note}` : ''}

+
+

{formatCents(item.estimated_cost)}

+ + +
+
+ ))} +
+ ) : } + + + + setDeleteTarget(null)} + title="删除人生事件" + description={`确认删除 ${deleteTarget?.year ?? ''} 年「${deleteTarget?.event ?? ''}」吗?`} + onConfirm={handleDelete} + loading={deleting} + /> +
+ ) +} diff --git a/frontend/src/pages/PolicyList.tsx b/frontend/src/pages/PolicyList.tsx new file mode 100644 index 0000000..ca48d47 --- /dev/null +++ b/frontend/src/pages/PolicyList.tsx @@ -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(null) + const [deleteTarget, setDeleteTarget] = useState(null) + const [deleting, setDeleting] = useState(false) + const [paymentPolicy, setPaymentPolicy] = useState(null) + const [payments, setPayments] = useState([]) + + 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 ( +
+ {error &&

{error}

} + + 未来 30 天续费提醒 + + {upcoming.length > 0 ?
{upcoming.map(p => { setPaymentPolicy(p); setPayments(await api.getPolicyPayments(p.id)) }} />)}
: } +
+
+ + + {editingPolicy ? '修改保单' : '登记保单'} + +
+ + setName(e.target.value)} placeholder="保单名称" className="h-9 text-sm" /> + setInsured(e.target.value)} placeholder="被保险人" className="h-9 text-sm" /> + setPremium(e.target.value)} placeholder="年保费" inputMode="decimal" className="h-9 text-sm" /> + +
+
+ + {editingPolicy && } +
+
+
+ + + 保单列表 + + {loading ?
: policies.length > 0 ?
{policies.map(p => editPolicy(p)} onDelete={() => setDeleteTarget(p)} onPayment={async () => { setPaymentPolicy(p); setPayments(await api.getPolicyPayments(p.id)) }} />)}
: } + + + + setDeleteTarget(null)} + title="删除保单" + description={`确认删除保单「${deleteTarget?.name ?? ''}」吗?年保费 ${formatCents(deleteTarget?.premium ?? 0)}`} + onConfirm={handleDelete} + loading={deleting} + /> + setPaymentPolicy(null)}> + 缴费记录 · {paymentPolicy?.name}
+ + {payments.map(v =>

{v.due_date} · {formatCents(v.amount)}

{v.status === 'pending' ? '待处理' : v.status === 'paid' ? '已缴' : '已跳过'}

{v.status === 'pending' &&
}
)} +
+
+
+ ) +} + +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 ( +
+
+

{policy.name}

+
+ 分类:{policyTypeLabel(policy.type)} + 下次缴费:{policy.next_payment_date || '未设置'} + 保障截止:{policy.end_date || '长期'} + 被保险人:{policy.insured_person || '未填'} +
+
+
+

{formatCents(policy.premium)}

+ {onPayment && } + {onEdit && } + {onDelete && } +
+
+ ) +} diff --git a/frontend/src/pages/Report.tsx b/frontend/src/pages/Report.tsx new file mode 100644 index 0000000..2b8699d --- /dev/null +++ b/frontend/src/pages/Report.tsx @@ -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('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 ( +
+ {error &&

{error}

} + +
+ 分类统计 +
+ + +
+

仅统计叶子分类,与预算看板口径一致。

+
+ +
+ + + + + {typeLabel}分类饼图 + + + + {loading ? ( +
+ ) : rankingData.length > 0 ? ( + <> + + + + {rankingData.map((_, index) => ( + + ))} + + { + const pct = (entry?.payload as { percent?: number } | undefined)?.percent ?? 0 + return [`${formatCents(Math.round(value * 100))}(${pct.toFixed(1)}%)`, '金额'] + }} + contentStyle={tooltipStyle} + /> + + + + {rankingCovered < 99.5 && ( +

+ Top {rankingData.length} 占 {rankingCovered.toFixed(1)}%,其余{typeLabel}合计 {(100 - rankingCovered).toFixed(1)}% 未在图中显示(含未列入 Top 的叶子分类及挂在父分类上的金额)。 +

+ )} + + ) : ( + + )} + + + + + + + + {typeLabel}分类排行 + + + + {rankingData.length > 0 ? ( + + + + + + { + const pct = (entry?.payload as { percent?: number } | undefined)?.percent ?? 0 + return [`${formatCents(Math.round(value * 100))}(${pct.toFixed(1)}%)`, '金额'] + }} + contentStyle={tooltipStyle} + /> + + {rankingData.map((_, index) => ( + + ))} + + + + + ) : ( + + )} + {rankingTotal > 0 && ( +

+ 合计 {formatCents(rankingTotal)}({rankingCovered.toFixed(1)}%),分母为当月全部{typeLabel}金额。 +

+ )} +
+
+
+ + + + + + 月度趋势折线图 + + + + {trendData.length > 0 ? ( + + + + + `${value}`} /> + formatCents(Math.round(value * 100))} contentStyle={tooltipStyle} /> + + + + + + ) : ( + + )} + + +
+ ) +} + +const tooltipStyle = { + backgroundColor: '#11151c', + border: '1px solid #28303a', + borderRadius: '6px', + color: '#f8f3e8', +} diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsx new file mode 100644 index 0000000..6f1de32 --- /dev/null +++ b/frontend/src/pages/Settings.tsx @@ -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(null) + const [delItem, setDelItem] = useState(null) + const [name, setName] = useState('') + const [relation, setRelation] = useState('') + const [birthday, setBirthday] = useState('') + const [phone, setPhone] = useState('') + const [success, setSuccess] = useState(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 ( +
+
+ +
+ {success &&

{success}

} + {members.length === 0 ? ( + + ) : ( + + + + 姓名 + 关系 + 出生日期 + 电话 + + + + + {members.map(m => ( + + {m.name} + {m.relation || '-'} + {m.birthday || '-'} + {m.phone || '-'} + +
+ + +
+
+
+ ))} +
+
+ )} + + + {editItem ? '编辑成员' : '添加成员'} +
+
setName(e.target.value)} className="h-9 mt-1" />
+
setRelation(e.target.value)} placeholder="如:配偶、子女" className="h-9 mt-1" />
+
+
setPhone(e.target.value)} placeholder="可选" className="h-9 mt-1" />
+ +
+
+
+ setDelItem(null)} + title="确认删除" description={`确定删除成员「${delItem?.name}」吗?`} + onConfirm={async () => { if (delItem) { await deleteMember(delItem.id); setDelItem(null) } }} /> +
+ ) +} + +function CategorySettings() { + const { categories, createCategory, updateCategory, deleteCategory } = useCategories() + const [open, setOpen] = useState(false) + const [editItem, setEditItem] = useState(null) + const [delItem, setDelItem] = useState(null) + const [name, setName] = useState('') + const [catType, setCatType] = useState<'expense' | 'income'>('expense') + const [parentId, setParentId] = useState('') + const [keywords, setKeywords] = useState('') + const [isActive, setIsActive] = useState(true) + const [error, setError] = useState(null) + const [success, setSuccess] = useState(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 ( +
+
+ +
+ {error &&

{error}

} + {success &&

{success}

} +
+ {(['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 ( + + + + + {type === 'expense' ? '支出分类' : '收入分类'} + + + + {topItems.map(top => ( +
+
+ {top.name} + toggleActive(top)}> + {top.is_active ? '启用' : '禁用'} + + +
+
+ {children.filter(c => c.parent_id === top.id).map(child => ( +
+
+ {child.name} + {child.keywords && ( + + · {child.keywords} + + )} +
+
+ + +
+
+ ))} +
+
+ ))} +
+
+ ) + })} +
+ + + {editItem ? '编辑分类' : '添加分类'} +
+
+ + +
+
setName(e.target.value)} className="h-9 mt-1" />
+
+ +
+
+ + setKeywords(e.target.value)} placeholder="多个关键字以英文逗号分隔,如:餐,美团,饿了么" className="h-9 mt-1" /> +

PDF 导入时按描述匹配;命中后自动归入该分类。

+
+ + +
+
+
+ setDelItem(null)} + title="确认删除" description={`确定删除分类「${delItem?.name}」吗?`} + onConfirm={confirmDelete} /> +
+ ) +} + +function AccountSettings() { + const { accounts, createAccount, updateAccount, deleteAccount } = useAccounts() + const [open, setOpen] = useState(false) + const [editItem, setEditItem] = useState(null) + const [delItem, setDelItem] = useState(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(null) + const [success, setSuccess] = useState(null) + const [reconcileAccount, setReconcileAccount] = useState(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 ( +
+
+ +
+ {error &&

{error}

} + {success &&

{success}

} +
+ {accounts.map(a => ( + +
+
+
+

{a.name}

+ + {a.is_active ? '启用' : '禁用'} + +
+

{accountTypeLabel(a.type)}

+
+

+ 当前余额: + {formatCents(a.current_balance)} +

+ {a.balance !== a.current_balance && ( +

开账:{formatCents(a.balance)}

+ )} +
+ {isBankCardType(a.type) && ( +
+

+ + {a.bank_name || '未填写银行'} +

+

{maskCardNumber(a.card_number)}

+
+ )} + {a.note &&

{a.note}

} +
+
+ + + +
+
+
+ ))} +
+ + + {editItem ? '编辑账户' : '添加账户'} +
+
setName(e.target.value)} className="h-9 mt-1" />
+
+ +
+ {isBankCardType(acctType) && ( + <> +
setBankName(e.target.value)} placeholder="如:中国工商银行" className="h-9 mt-1" />
+
setCardNumber(e.target.value)} placeholder="可输入完整卡号或尾号" className="h-9 mt-1" />
+
setBranchName(e.target.value)} placeholder="可选" className="h-9 mt-1" />
+ + )} +
+ + setOpeningBalanceYuan(e.target.value)} placeholder="0.00" className="h-9 mt-1" inputMode="decimal" /> +

账户在录入到本系统前的初始余额;当前余额会按流水自动更新。

+
+
setNote(e.target.value)} placeholder="可选" className="h-9 mt-1" />
+ + +
+
+
+ setReconcileAccount(null)}> + + 账户对账 · {reconcileAccount?.name} +
+

系统余额:{formatCents(reconcileAccount?.current_balance ?? 0)}

+
setActualBalance(e.target.value)} inputMode="decimal" className="mt-1" />
+

确认后保存对账记录,并自动生成余额调整交易。

+ +
+
+
+ setDelItem(null)} + title="确认删除" description={`确定删除账户「${delItem?.name}」吗?`} + onConfirm={confirmDelete} /> +
+ ) +} + +function DataSettings() { + const query = useQuery({ queryKey: ['backup-status'], queryFn: api.getBackupStatus }) + const backup = useMutation({ mutationFn: api.createBackup, onSuccess: () => query.refetch() }) + return 数据备份 +

最近备份:{query.data?.last_backup || '尚未备份'}

+

目录:{query.data?.directory || '加载中…'} · 保留 {query.data?.retention_days ?? 30} 天

+ +
+} + +export default function Settings() { + return ( +
+ + + + + 家庭成员 + + + + 收支分类 + + + + 支付账户 + + 数据安全 + + + + + + +
+ ) +} diff --git a/frontend/src/pages/TransactionList.test.tsx b/frontend/src/pages/TransactionList.test.tsx new file mode 100644 index 0000000..40e1a82 --- /dev/null +++ b/frontend/src/pages/TransactionList.test.tsx @@ -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 + }) => ( +
+ {items.map((item) => item.description).join(',')} + 已选择:{selectedIds.length} + {items[0] && } +
+ ), +})) +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 { + 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 }) => ( + {children} + ) + return render(, { wrapper }) +} + +describe('TransactionList', () => { + beforeEach(() => { + apiMocks.getTransactions.mockReset() + apiMocks.getImportBatches.mockReset() + apiMocks.getImportBatches.mockResolvedValue([]) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('翻页请求期间保留旧表格、显示刷新状态并传递 signal', async () => { + apiMocks.getTransactions.mockImplementation( + (params: Record, 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) => + 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, 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, 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, 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() + }) +}) diff --git a/frontend/src/pages/TransactionList.tsx b/frontend/src/pages/TransactionList.tsx new file mode 100644 index 0000000..125d190 --- /dev/null +++ b/frontend/src/pages/TransactionList.tsx @@ -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(null) + const [editingItem, setEditingItem] = useState(null) + const [selectedIds, setSelectedIds] = useState([]) + const [batchDeleteOpen, setBatchDeleteOpen] = useState(false) + const [deleteImportBatchTarget, setDeleteImportBatchTarget] = useState(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 = { + 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 }) => + 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 ( +
+
+
+ {(['', 'expense', 'income', 'transfer'] as const).map((t) => ( + + ))} +
+
+ { + setFilters((p) => ({ ...p, category_id: v })) + resetListState() + }} + nodes={filterCategoryNodes} + placeholder="全部分类" + variant="muted" + clearable + /> +
+
+ { + setFilters((p) => ({ ...p, date_from: v })) + resetListState() + }} + placeholder="开始日期" + clearable + /> +
+
+ { + setFilters((p) => ({ ...p, date_to: v })) + resetListState() + }} + placeholder="结束日期" + clearable + /> +
+ + + +
+ + setKeywordInput(e.target.value)} + className="h-9 w-44 pl-9 text-sm" + /> +
+
+ {selectedIds.length > 0 && ( + + )} + {filters.import_batch_id && ( + + )} + + + +
+ + {isLoading ? ( + + ) : ( + <> + {(isFetching || isPlaceholderData) && ( +
更新中…
+ )} + {transactions.length > 0 ? ( + <> + + 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 && ( +
+ + {page} / {totalPages} + +
+ )} + + ) : ( + setAddOpen(true)}>记一笔} + /> + )} + + )} + + + + + 记一笔 + + createMutation.mutate(buildTransactionPayload(data))} + /> + + + + + + + 编辑记录 + + {editDefaults && ( + { + if (!editingItem) return + updateMutation.mutate({ id: editingItem.id, req: buildTransactionPayload(data) }) + }} + /> + )} + + + + + + setDeleteTarget(null)} + title="确认删除" + description={`确定要删除这条${deleteTarget?.type === 'income' ? '收入' : deleteTarget?.type === 'transfer' ? '转账' : '支出'}记录吗?金额:${formatCents(deleteTarget?.amount ?? 0)}`} + onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)} + loading={deleteLoading} + /> + batchDeleteMutation.mutate(selectedIds)} + loading={deleteLoading} + /> + setDeleteImportBatchTarget(null)} + title="按导入文件删除" + description={`确定删除「${deleteImportBatchTarget?.filename}」导入的全部收支记录吗?`} + onConfirm={() => + deleteImportBatchTarget && deleteBatchMutation.mutate(deleteImportBatchTarget.id) + } + loading={deleteLoading} + /> +
+ ) +} diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts new file mode 100644 index 0000000..384ea29 --- /dev/null +++ b/frontend/src/test/setup.ts @@ -0,0 +1,4 @@ +import { cleanup } from '@testing-library/react' +import { afterEach } from 'vitest' + +afterEach(cleanup) diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts new file mode 100644 index 0000000..2386d4b --- /dev/null +++ b/frontend/src/types/index.ts @@ -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 +} diff --git a/frontend/tailwind.config.ts b/frontend/tailwind.config.ts new file mode 100644 index 0000000..888036f --- /dev/null +++ b/frontend/tailwind.config.ts @@ -0,0 +1,53 @@ +import type { Config } from 'tailwindcss' + +export default { + content: [ + './index.html', + './src/**/*.{js,ts,jsx,tsx}', + ], + darkMode: 'class', + theme: { + extend: { + colors: { + background: '#090b0f', + foreground: '#f8f3e8', + card: '#11151c', + 'card-foreground': '#f8f3e8', + popover: '#121720', + 'popover-foreground': '#f8f3e8', + border: '#28303a', + input: '#303946', + ring: '#d9b86f', + accent: '#202834', + 'accent-foreground': '#fff7e8', + muted: '#87909d', + 'muted-foreground': '#aab2bd', + primary: { + DEFAULT: '#d9b86f', + foreground: '#14110a', + }, + secondary: { + DEFAULT: '#1b222d', + foreground: '#e9eef5', + }, + destructive: { + DEFAULT: '#e05252', + foreground: '#ffffff', + }, + income: '#38d39f', + expense: '#ff6b6b', + warning: '#f2b84b', + }, + fontFamily: { + sans: ['"PingFang SC"', '"Microsoft YaHei"', 'system-ui', 'sans-serif'], + mono: ['"JetBrains Mono"', 'monospace'], + }, + borderRadius: { + lg: '0.5rem', + md: '0.375rem', + sm: '0.25rem', + }, + }, + }, + plugins: [], +} satisfies Config diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json new file mode 100644 index 0000000..c43ac95 --- /dev/null +++ b/frontend/tsconfig.app.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023", "DOM"], + "module": "esnext", + "types": ["vite/client"], + "skipLibCheck": true, + "ignoreDeprecations": "6.0", + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + }, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json new file mode 100644 index 0000000..d3c52ea --- /dev/null +++ b/frontend/tsconfig.node.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023"], + "module": "esnext", + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["vite.config.ts"] +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts new file mode 100644 index 0000000..1c34ebd --- /dev/null +++ b/frontend/vite.config.ts @@ -0,0 +1,38 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import path from 'node:path' + +/** + * 第三方依赖按稳定性分组,避免业务代码改动时把整个 vendor 也打成新 hash, + * 让浏览器能长期复用 vendor 缓存。 + */ +function vendorChunks(id: string): string | undefined { + if (!id.includes('node_modules')) return undefined + if (/[\\/]node_modules[\\/]@tanstack[\\/]/.test(id)) return 'vendor-query' + if (/[\\/]node_modules[\\/](react-router|react-router-dom|@remix-run)[\\/]/.test(id)) { + return 'vendor-router' + } + if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) return 'vendor-react' + return undefined +} + +export default defineConfig({ + plugins: [react()], + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + }, + }, + server: { + proxy: { + '/api': 'http://localhost:8080', + }, + }, + build: { + rollupOptions: { + output: { + manualChunks: vendorChunks, + }, + }, + }, +}) diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts new file mode 100644 index 0000000..bccbdfa --- /dev/null +++ b/frontend/vitest.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import path from 'node:path' + +export default defineConfig({ + plugins: [react()], + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + }, + }, + test: { + environment: 'jsdom', + setupFiles: ['./src/test/setup.ts'], + }, +}) diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 0000000..8e96cb1 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FRONTEND_DIR="$ROOT/frontend" +BACKEND_DIR="$ROOT/backend" +STATIC_DIR="$BACKEND_DIR/static" +OUTPUT="$ROOT/household-book" + +echo "=== 1/3 Building frontend ===" +cd "$FRONTEND_DIR" +pnpm install --frozen-lockfile +pnpm run build + +echo "=== 2/3 Copying static files ===" +rm -rf "$STATIC_DIR" +mkdir -p "$STATIC_DIR" +cp -r "$FRONTEND_DIR/dist/"* "$STATIC_DIR/" + +echo "=== 3/3 Building Go backend ===" +cd "$BACKEND_DIR" +go build -o "$OUTPUT" . + +echo "=== Done ===" +echo "Binary: $OUTPUT" +echo "Run: $OUTPUT -mode=prod -static=$STATIC_DIR" diff --git a/wails.json b/wails.json new file mode 100644 index 0000000..bdc6a07 --- /dev/null +++ b/wails.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://wails.io/schemas/config.v3.json", + "name": "HouseholdBudgetBook", + "outputfilename": "household-book", + "frontend:dir": "frontend", + "frontend:install": "pnpm install", + "frontend:build": "pnpm run build", + "frontend:dev": "pnpm run dev", + "frontend:dev:serverUrl": "http://localhost:5173", + "author": { + "name": "Household Budget Book", + "email": "" + } +}