chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)
This commit is contained in:
commit
4a5db3f1f9
167 files changed
+21732
No files matched your search
+43
@@ -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
|
||||||
@@ -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` 的 "待办事项" 段
|
||||||
@@ -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` 的 "待办事项" 段
|
||||||
@@ -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 导出、保单缴费记录和账户对账基础流程。
|
||||||
|
- 完成报表类型切换、叶子分类口径、停用分类标识和分类排行自适应布局。
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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})
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
@@ -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"), "<!doctype html><div id=\"root\"></div>")
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -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 '';
|
||||||
@@ -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;
|
||||||
@@ -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);
|
||||||
@@ -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 <> '';
|
||||||
@@ -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);
|
||||||
@@ -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';
|
||||||
@@ -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 <> '';
|
||||||
@@ -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);
|
||||||
@@ -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;
|
||||||
@@ -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);
|
||||||
@@ -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);
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
)
|
||||||
+133
@@ -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=
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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`
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
)
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
```
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,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...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta name="color-scheme" content="dark" />
|
||||||
|
<meta name="theme-color" content="#090b0f" />
|
||||||
|
<meta name="description" content="家庭记账本 - 本地优先的家庭财务管理系统" />
|
||||||
|
<title>家庭记账本</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+5184
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
|||||||
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" fill="none">
|
||||||
|
<rect width="64" height="64" rx="14" fill="#090B0F"/>
|
||||||
|
<rect x="5" y="5" width="54" height="54" rx="11" fill="url(#bg)" stroke="#D9B86F" stroke-opacity=".42" stroke-width="1.4"/>
|
||||||
|
<path d="M18 25.5c0-3.3 2.7-6 6-6h20c1.1 0 2 .9 2 2v25.5c0 1.1-.9 2-2 2H23c-2.8 0-5-2.2-5-5V25.5Z" fill="#131922" stroke="#D9B86F" stroke-width="2"/>
|
||||||
|
<path d="M23 19.5v23.8c0 1.1.9 2 2 2h21" stroke="#D9B86F" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path d="M29 28h11M29 34h8" stroke="#F8F3E8" stroke-opacity=".76" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<path d="M20 24.5 32 14l12 10.5" stroke="#38D39F" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
<path d="M36.5 38.5h7.8c2 0 3.7 1.7 3.7 3.7v0c0 2-1.7 3.7-3.7 3.7h-7.8c-2 0-3.7-1.7-3.7-3.7v0c0-2 1.7-3.7 3.7-3.7Z" fill="#D9B86F"/>
|
||||||
|
<circle cx="37.3" cy="42.2" r="1.7" fill="#14110A"/>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="bg" x1="9" y1="8" x2="57" y2="58" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop stop-color="#25221A"/>
|
||||||
|
<stop offset=".52" stop-color="#11151C"/>
|
||||||
|
<stop offset="1" stop-color="#0A0D12"/>
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -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)`,
|
||||||
|
)
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { lazy, Suspense } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { BrowserRouter, Routes, Route } from 'react-router-dom'
|
||||||
|
import { AppProvider } from '@/context/AppContext'
|
||||||
|
import { Layout } from '@/components/layout/Layout'
|
||||||
|
import { ErrorBoundary } from '@/components/ErrorBoundary'
|
||||||
|
import Dashboard from '@/pages/Dashboard'
|
||||||
|
|
||||||
|
const TransactionList = lazy(() => import('@/pages/TransactionList'))
|
||||||
|
const BudgetBoard = lazy(() => import('@/pages/BudgetBoard'))
|
||||||
|
const Report = lazy(() => import('@/pages/Report'))
|
||||||
|
const AssetOverview = lazy(() => import('@/pages/AssetOverview'))
|
||||||
|
const PolicyList = lazy(() => import('@/pages/PolicyList'))
|
||||||
|
const Lifecycle = lazy(() => import('@/pages/Lifecycle'))
|
||||||
|
const Settings = lazy(() => import('@/pages/Settings'))
|
||||||
|
|
||||||
|
function PageBoundary({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ErrorBoundary>
|
||||||
|
<Suspense
|
||||||
|
fallback={
|
||||||
|
<div className="app-page">
|
||||||
|
<div className="premium-panel p-8 text-sm text-ink-300">页面加载中…</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</Suspense>
|
||||||
|
</ErrorBoundary>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<BrowserRouter>
|
||||||
|
<AppProvider>
|
||||||
|
<Routes>
|
||||||
|
<Route element={<Layout />}>
|
||||||
|
<Route index element={<Dashboard />} />
|
||||||
|
<Route
|
||||||
|
path="transactions"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<TransactionList />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="budget"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<BudgetBoard />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="reports"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<Report />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="assets"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<AssetOverview />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="policies"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<PolicyList />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="lifecycle"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<Lifecycle />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="settings"
|
||||||
|
element={
|
||||||
|
<PageBoundary>
|
||||||
|
<Settings />
|
||||||
|
</PageBoundary>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
</AppProvider>
|
||||||
|
</BrowserRouter>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { formatCents } from '@/lib/utils'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
cents: number
|
||||||
|
type?: 'income' | 'expense' | 'transfer'
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AmountDisplay({ cents, type, className = '' }: Props) {
|
||||||
|
const sign = type === 'income' ? '+' : type === 'expense' ? '-' : ''
|
||||||
|
const color = type === 'income' ? 'text-income' : type === 'expense' ? 'text-expense' : 'text-muted'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className={`tabular-nums font-medium ${color} ${className}`}>
|
||||||
|
{sign}{formatCents(cents)}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||||
|
import { faBookOpen, faHouseChimney, faWallet } from '@fortawesome/free-solid-svg-icons'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
compact?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BrandLogo({ compact = false }: Props) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="relative grid h-10 w-10 place-items-center rounded-lg border border-primary/30 bg-[linear-gradient(145deg,#25221a,#111317_52%,#0b0d10)] shadow-[0_18px_45px_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.08)]">
|
||||||
|
<div className="absolute inset-1 rounded-md border border-white/5 bg-primary/5" />
|
||||||
|
<FontAwesomeIcon icon={faBookOpen} className="relative h-5 w-5 text-primary" />
|
||||||
|
<FontAwesomeIcon icon={faHouseChimney} className="absolute -right-1 -top-1 h-4 w-4 rounded-full border border-primary/30 bg-background p-1 text-income shadow-lg" />
|
||||||
|
</div>
|
||||||
|
{!compact && (
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="truncate text-sm font-semibold tracking-wide text-foreground">家庭记账本</span>
|
||||||
|
<FontAwesomeIcon icon={faWallet} className="h-3 w-3 text-primary/80" />
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 text-[10px] uppercase tracking-[0.22em] text-muted">Household Budget</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
name: string
|
||||||
|
isActive?: boolean
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 分类名称;已停用分类显示角标。 */
|
||||||
|
export function CategoryLabel({ name, isActive = true, className }: Props) {
|
||||||
|
return (
|
||||||
|
<span className={`inline-flex items-center gap-1.5 ${className ?? ''}`}>
|
||||||
|
<span>{name}</span>
|
||||||
|
{!isActive && (
|
||||||
|
<Badge variant="outline" className="border-muted/50 px-1.5 py-0 text-[10px] font-normal text-muted">
|
||||||
|
已停用
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
title: string
|
||||||
|
description: string
|
||||||
|
onConfirm: () => void
|
||||||
|
loading?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConfirmDialog({ open, onOpenChange, title, description, onConfirm, loading }: Props) {
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-[400px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{title}</DialogTitle>
|
||||||
|
<DialogDescription>{description}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={onConfirm} disabled={loading}>
|
||||||
|
{loading ? '删除中…' : '确认删除'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||||
|
import { faInbox } from '@fortawesome/free-solid-svg-icons'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
message?: string
|
||||||
|
action?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EmptyState({ message = '暂无数据', action }: Props) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center py-16 text-muted">
|
||||||
|
<div className="mb-3 grid h-12 w-12 place-items-center rounded-lg border border-border bg-white/[0.03]">
|
||||||
|
<FontAwesomeIcon icon={faInbox} className="h-5 w-5 text-primary/70" />
|
||||||
|
</div>
|
||||||
|
<p className="text-sm">{message}</p>
|
||||||
|
{action && <div className="mt-4">{action}</div>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { Component, type ReactNode } from 'react'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
hasError: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ErrorBoundary extends Component<Props, State> {
|
||||||
|
constructor(props: Props) {
|
||||||
|
super(props)
|
||||||
|
this.state = { hasError: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDerivedStateFromError(): State {
|
||||||
|
return { hasError: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center py-24">
|
||||||
|
<p className="text-muted text-sm">页面加载出现错误</p>
|
||||||
|
<button
|
||||||
|
className="mt-4 text-sm text-primary hover:underline"
|
||||||
|
onClick={() => this.setState({ hasError: false })}
|
||||||
|
>
|
||||||
|
重试
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return this.props.children
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useMutation } from '@tanstack/react-query'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { api, ApiError, type Account, type ImportPreviewResult } from '@/lib/api'
|
||||||
|
import { formatDate } from '@/lib/utils'
|
||||||
|
import { importIsCSV, sourceKindMatchesAccount, type ImportSourceKind } from '@/lib/importUtils'
|
||||||
|
import { AmountDisplay } from '@/components/AmountDisplay'
|
||||||
|
import { useCategories } from '@/hooks/useCategories'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
accounts: Account[]
|
||||||
|
onImported: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ImportDialog({ open, onOpenChange, accounts, onImported }: Props) {
|
||||||
|
const { categories } = useCategories()
|
||||||
|
const [importFile, setImportFile] = useState<File | null>(null)
|
||||||
|
const [importSourceKind, setImportSourceKind] = useState<ImportSourceKind>('cmb_debit')
|
||||||
|
const [importAccountID, setImportAccountID] = useState('')
|
||||||
|
const [preview, setPreview] = useState<ImportPreviewResult | null>(null)
|
||||||
|
const [importError, setImportError] = useState<string | null>(null)
|
||||||
|
const [importMessage, setImportMessage] = useState<string | null>(null)
|
||||||
|
const [categoryOverrides, setCategoryOverrides] = useState<Record<string, number>>({})
|
||||||
|
|
||||||
|
const resetState = () => {
|
||||||
|
setImportFile(null)
|
||||||
|
setPreview(null)
|
||||||
|
setImportError(null)
|
||||||
|
setImportMessage(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildFormData = () => {
|
||||||
|
const formData = new FormData()
|
||||||
|
if (!importFile) throw new Error('请选择文件')
|
||||||
|
formData.append('file', importFile)
|
||||||
|
formData.append('source_kind', importSourceKind)
|
||||||
|
if (importAccountID) formData.append('account_id', importAccountID)
|
||||||
|
if (Object.keys(categoryOverrides).length) formData.append('category_overrides', JSON.stringify(categoryOverrides))
|
||||||
|
return formData
|
||||||
|
}
|
||||||
|
|
||||||
|
const previewMutation = useMutation({
|
||||||
|
mutationFn: () => api.previewImportTransactions(buildFormData()),
|
||||||
|
onMutate: () => setImportError(null),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
setPreview(data)
|
||||||
|
setImportMessage(null)
|
||||||
|
},
|
||||||
|
onError: (e) => {
|
||||||
|
setPreview(null)
|
||||||
|
setImportError(e instanceof ApiError ? e.message : '预览失败')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const importMutation = useMutation({
|
||||||
|
mutationFn: () => api.importTransactions(buildFormData()),
|
||||||
|
onMutate: () => {
|
||||||
|
setImportError(null)
|
||||||
|
setImportMessage(null)
|
||||||
|
},
|
||||||
|
onSuccess: (result) => {
|
||||||
|
setImportMessage(`导入成功:新增 ${result.imported_count} 条,跳过重复 ${result.skipped_count} 条`)
|
||||||
|
setPreview(null)
|
||||||
|
onImported()
|
||||||
|
},
|
||||||
|
onError: (e) => {
|
||||||
|
setImportError(e instanceof ApiError ? e.message : '导入失败')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next) resetState()
|
||||||
|
onOpenChange(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFileChange = (file: File | null) => {
|
||||||
|
setImportFile(file)
|
||||||
|
setPreview(null)
|
||||||
|
setImportMessage(null)
|
||||||
|
setCategoryOverrides({})
|
||||||
|
setImportError(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>导入账单</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="app-form">
|
||||||
|
<div>
|
||||||
|
<label className="app-form-label">导入来源</label>
|
||||||
|
<select
|
||||||
|
value={importSourceKind}
|
||||||
|
onChange={(e) => {
|
||||||
|
setImportSourceKind(e.target.value as ImportSourceKind)
|
||||||
|
handleFileChange(null)
|
||||||
|
}}
|
||||||
|
className="app-select mt-1 w-full"
|
||||||
|
>
|
||||||
|
<option value="cmb_debit">招商银行储蓄卡(PDF 流水)</option>
|
||||||
|
<option value="cmb_credit">招商银行信用卡(PDF 账单)</option>
|
||||||
|
<option value="alipay">支付宝(CSV 账单)</option>
|
||||||
|
<option value="wechat">微信支付(CSV 账单)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="app-form-label">
|
||||||
|
{importIsCSV(importSourceKind) ? '账单 CSV' : '账单 PDF'}
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
key={importSourceKind}
|
||||||
|
type="file"
|
||||||
|
accept={importIsCSV(importSourceKind) ? '.csv,text/csv' : 'application/pdf,.pdf'}
|
||||||
|
className="h-9 text-sm mt-1"
|
||||||
|
onChange={(e) => handleFileChange(e.target.files?.[0] ?? null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="app-form-label">导入账户</label>
|
||||||
|
<select
|
||||||
|
value={importAccountID}
|
||||||
|
onChange={(e) => setImportAccountID(e.target.value)}
|
||||||
|
className="app-select-muted mt-1 w-full"
|
||||||
|
>
|
||||||
|
<option value="">自动匹配或创建账户</option>
|
||||||
|
{accounts
|
||||||
|
.filter((a) => sourceKindMatchesAccount(importSourceKind, a.type))
|
||||||
|
.map((a) => (
|
||||||
|
<option key={a.id} value={a.id}>{a.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{preview && (
|
||||||
|
<div className="rounded-md border border-border/80 bg-[#0c1016]/60 p-3 space-y-2">
|
||||||
|
<p className="text-xs text-muted">
|
||||||
|
解析 {preview.total_count} 条 · 预计新增 {preview.new_count} 条 · 重复跳过 {preview.duplicate_count} 条
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-foreground">
|
||||||
|
目标账户:{preview.account_name}
|
||||||
|
{preview.will_create_account && (
|
||||||
|
<span className="ml-1 text-primary">(将自动创建)</span>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
{preview.items.length > 0 && (
|
||||||
|
<ul className="max-h-80 space-y-1.5 overflow-y-auto text-xs">
|
||||||
|
{preview.items.map((item, i) => (
|
||||||
|
<li key={i} className="flex items-start justify-between gap-2 border-b border-border/40 pb-1.5 last:border-0">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-foreground">{item.description || item.counterparty || '—'}</p>
|
||||||
|
<p className="text-muted">
|
||||||
|
{formatDate(item.date)}
|
||||||
|
{item.status === 'duplicate_database' ? ' · 数据库已有' : item.status === 'duplicate_file' ? ' · 文件内重复' : ''}
|
||||||
|
</p>
|
||||||
|
{item.status === 'new' && (
|
||||||
|
<div className="mt-1 flex items-center gap-2">
|
||||||
|
<select
|
||||||
|
value={categoryOverrides[item.source_key] ?? item.category_id}
|
||||||
|
onChange={(e) => setCategoryOverrides(p => ({ ...p, [item.source_key]: Number(e.target.value) }))}
|
||||||
|
className="app-select-muted h-7 max-w-40 text-xs"
|
||||||
|
>
|
||||||
|
{categories.filter(c => c.type === item.type && c.parent_id !== null && c.is_active).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||||
|
</select>
|
||||||
|
<span className="text-[11px] text-muted">{item.category_reason}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<AmountDisplay cents={item.amount} type={item.type} />
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{preview.total_count > preview.items.length && (
|
||||||
|
<p className="text-[11px] text-muted">
|
||||||
|
仅展示前 {preview.items.length} 条样本,确认后将处理全部 {preview.total_count} 条。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{importError && <p className="app-error">{importError}</p>}
|
||||||
|
{importMessage && <p className="app-success">{importMessage}</p>}
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="flex-1"
|
||||||
|
disabled={!importFile || previewMutation.isPending || importMutation.isPending}
|
||||||
|
onClick={() => previewMutation.mutate()}
|
||||||
|
>
|
||||||
|
{previewMutation.isPending ? '解析中...' : '预览'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="flex-1"
|
||||||
|
disabled={!importFile || !preview || preview.new_count === 0 || importMutation.isPending}
|
||||||
|
onClick={() => importMutation.mutate()}
|
||||||
|
>
|
||||||
|
{importMutation.isPending ? '导入中...' : `确认导入${preview ? ` (${preview.new_count})` : ''}`}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user