Family bookkeeping PWA modelled on 木木记账
Hono + SQLite server and a React/shadcn PWA with two-level categories, who-spent/who-paid splits, settlement, one-line and voice entry, budget alerts (Web Push and Bark), monthly/annual reports, and 木木 import tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,5 @@
|
|||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
server/data
|
||||||
|
*.xlsx
|
||||||
|
.git
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
data
|
||||||
|
*.db
|
||||||
|
*.db-*
|
||||||
|
.env
|
||||||
|
mumu*.xlsx
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
FROM node:24-bookworm-slim AS build
|
||||||
|
WORKDIR /app
|
||||||
|
# Toolchain for compiling better-sqlite3 when no prebuilt binary matches.
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ && rm -rf /var/lib/apt/lists/* && corepack enable
|
||||||
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
|
COPY server/package.json server/
|
||||||
|
COPY web/package.json web/
|
||||||
|
RUN pnpm install --frozen-lockfile
|
||||||
|
COPY . .
|
||||||
|
RUN pnpm --filter web build && pnpm --filter server build \
|
||||||
|
&& pnpm --filter server deploy --prod /out/server \
|
||||||
|
&& cp -r server/dist /out/server/dist && cp -r web/dist /out/web
|
||||||
|
|
||||||
|
FROM node:24-bookworm-slim
|
||||||
|
ENV NODE_ENV=production TZ=Asia/Shanghai PORT=3000 DB_PATH=/data/billing.db WEB_DIR=/app/web
|
||||||
|
WORKDIR /app/server
|
||||||
|
COPY --from=build /out/server /app/server
|
||||||
|
COPY --from=build /out/web /app/web
|
||||||
|
VOLUME /data
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD ["node", "dist/index.js"]
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# 家庭记账
|
||||||
|
|
||||||
|
A bookkeeping PWA for two people, modelled on 木木记账: two-level categories, "who spent / who paid", splitting and settling shared expenses, one-line and voice entry, budget alerts, and a yearly report.
|
||||||
|
|
||||||
|
- `server/` — Node + Hono + SQLite (better-sqlite3). Amounts are stored in cents and times in ms; calendar math is in China Standard Time.
|
||||||
|
- `web/` — React + Vite + shadcn/ui, installable as a PWA.
|
||||||
|
- `deploy/` — Docker image, compose file, nginx site, and deploy scripts.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
pnpm dev:server # http://localhost:3000
|
||||||
|
pnpm dev:web # http://localhost:5173, proxies /api to the server
|
||||||
|
pnpm test
|
||||||
|
```
|
||||||
|
|
||||||
|
Data scripts (run in `server/`, or in the container as `node dist/scripts/<name>.js`):
|
||||||
|
|
||||||
|
| Command | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `pnpm import:mumu <export.xlsx>` | Import a 木木记账 Excel export (re-runnable) |
|
||||||
|
| `pnpm tsx src/scripts/sync-mumu-db.ts <.mutongji.db> [--apply]` | Fill in payers and split amounts from 木木's own database |
|
||||||
|
| `pnpm user <username> <member> [password]` | Create an account or reset its password |
|
||||||
|
| `pnpm icons:mumu` | Switch categories to 木木 icons (after `deploy/extract-mumu-icons.sh`) |
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
```bash
|
||||||
|
deploy/deploy.sh # build linux/amd64, upload over ssh, restart
|
||||||
|
HOST=root@<server> deploy/extract-mumu-icons.sh # copy 木木 icons into the server's data dir
|
||||||
|
```
|
||||||
|
|
||||||
|
The image is built locally and loaded over ssh, because Docker Hub is unreliable from mainland China. The container listens on 127.0.0.1:3100 behind the host's nginx + certbot (`deploy/nginx-bill.conf`). Configuration goes in `/opt/billing/.env` (see `deploy/env.example`). Data lives in `/opt/billing/data`.
|
||||||
|
|
||||||
|
木木记账's icons are copyrighted by its developer. They are never committed or baked into the image, and the server only serves them to signed-in users.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds the image locally and ships it to the server (Docker Hub is unreliable
|
||||||
|
# from mainland China, so the server never pulls images itself).
|
||||||
|
#
|
||||||
|
# deploy/deploy.sh build, upload, restart
|
||||||
|
# HOST=root@1.2.3.4 deploy/deploy.sh
|
||||||
|
set -euo pipefail
|
||||||
|
HOST=${HOST:-root@8.133.23.131}
|
||||||
|
DIR=/opt/billing
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
docker buildx build --platform linux/amd64 -t billing:latest --load .
|
||||||
|
echo "uploading image…"
|
||||||
|
docker save billing:latest | gzip -1 | ssh "$HOST" 'gunzip | docker load'
|
||||||
|
ssh "$HOST" "mkdir -p $DIR/data"
|
||||||
|
scp deploy/docker-compose.yml "$HOST:$DIR/docker-compose.yml"
|
||||||
|
ssh "$HOST" "test -f $DIR/.env" || scp deploy/env.example "$HOST:$DIR/.env"
|
||||||
|
# docker-compose 1.29 cannot recreate containers on Docker 25+ (KeyError: 'ContainerConfig'),
|
||||||
|
# so remove the old container first; data lives in the mounted ./data directory.
|
||||||
|
ssh "$HOST" "cd $DIR && docker rm -f billing >/dev/null 2>&1; docker-compose up -d && docker image prune -f >/dev/null"
|
||||||
|
echo "deployed"
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
version: "3"
|
||||||
|
services:
|
||||||
|
billing:
|
||||||
|
image: billing:latest
|
||||||
|
container_name: billing
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3100:3000"
|
||||||
|
volumes:
|
||||||
|
- ./data:/data
|
||||||
|
env_file: .env
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
PUBLIC_URL=https://bill.michaelandmeryl.xyz
|
||||||
|
VAPID_SUBJECT=mailto:michael@dynarobotics.ai
|
||||||
|
# Optional: Bark device URLs for budget alerts, comma separated
|
||||||
|
# BARK_URLS=https://bark.michaelandmeryl.xyz/<key1>,https://bark.michaelandmeryl.xyz/<key2>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Copies the category icons from the locally installed 木木记账 into a data
|
||||||
|
# directory (default: server/data/mumu-icons), or to the server with HOST set.
|
||||||
|
# The icons stay private: they are never committed or baked into the image.
|
||||||
|
#
|
||||||
|
# deploy/extract-mumu-icons.sh # local dev
|
||||||
|
# HOST=root@8.133.23.131 deploy/extract-mumu-icons.sh # server
|
||||||
|
set -euo pipefail
|
||||||
|
APP=${APP:-"/Applications/木木记账.app"}
|
||||||
|
SRC="$APP/Contents/Frameworks/App.framework/Versions/A/Resources/flutter_assets/assets"
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
for s in 3d flat filled lineal outline; do test -d "$SRC/$s" || { echo "missing $SRC/$s"; exit 1; }; done
|
||||||
|
|
||||||
|
if [ -n "${HOST:-}" ]; then
|
||||||
|
tar -C "$SRC" -czf - 3d flat filled lineal outline | ssh "$HOST" 'mkdir -p /opt/billing/data/mumu-icons && tar -C /opt/billing/data/mumu-icons -xzf -'
|
||||||
|
else
|
||||||
|
mkdir -p server/data/mumu-icons
|
||||||
|
tar -C "$SRC" -cf - 3d flat filled lineal outline | tar -C server/data/mumu-icons -xf -
|
||||||
|
fi
|
||||||
|
echo "icons copied"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name bill.michaelandmeryl.xyz;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:3100;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "billing",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev:server": "pnpm --filter server dev",
|
||||||
|
"dev:web": "pnpm --filter web dev",
|
||||||
|
"build": "pnpm --filter web build && pnpm --filter server build",
|
||||||
|
"test": "pnpm --filter server test"
|
||||||
|
},
|
||||||
|
"packageManager": "pnpm@9.15.9"
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
packages:
|
||||||
|
- server
|
||||||
|
- web
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// Downloads the Fluent Emoji 3D icons referenced in server/src/icons.ts
|
||||||
|
// into web/public/icons/<slug>.png. Run once; the PNGs are committed.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const root = path.dirname(path.dirname(new URL(import.meta.url).pathname));
|
||||||
|
const src = fs.readFileSync(path.join(root, 'server/src/icons.ts'), 'utf8');
|
||||||
|
const names = [...new Set([...src.matchAll(/'([A-Z][^']*)'/g)].map((m) => m[1]))];
|
||||||
|
const out = path.join(root, 'web/public/icons');
|
||||||
|
fs.mkdirSync(out, { recursive: true });
|
||||||
|
|
||||||
|
const base = 'https://cdn.jsdelivr.net/gh/microsoft/fluentui-emoji@main/assets';
|
||||||
|
for (const name of names) {
|
||||||
|
const slug = name.toLowerCase().replace(/\s+/g, '-');
|
||||||
|
const file = path.join(out, `${slug}.png`);
|
||||||
|
if (fs.existsSync(file)) continue;
|
||||||
|
const snake = name.toLowerCase().replace(/\s+/g, '_');
|
||||||
|
const candidates = [`${name}/3D/${snake}_3d.png`, `${name}/Default/3D/${snake}_3d_default.png`];
|
||||||
|
let ok = false;
|
||||||
|
for (const c of candidates) {
|
||||||
|
const res = await fetch(`${base}/${c.split('/').map(encodeURIComponent).join('/')}`);
|
||||||
|
if (!res.ok) continue;
|
||||||
|
if (res.headers.get('content-type') !== 'image/png') continue;
|
||||||
|
fs.writeFileSync(file, Buffer.from(await res.arrayBuffer()));
|
||||||
|
ok = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
console.log(ok ? 'ok ' : 'MISSING', name);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/index.ts",
|
||||||
|
"build": "tsc -p .",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"test": "vitest run",
|
||||||
|
"import:mumu": "tsx src/scripts/import-mumu.ts",
|
||||||
|
"user": "tsx src/scripts/user.ts",
|
||||||
|
"icons:mumu": "tsx src/scripts/apply-mumu-icons.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@hono/node-server": "^2.1.5",
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
|
"better-sqlite3": "^13.0.3",
|
||||||
|
"hono": "^4.13.14",
|
||||||
|
"web-push": "^3.6.7",
|
||||||
|
"xlsx": "^0.18.5",
|
||||||
|
"zod": "^4.6.7"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bcryptjs": "^3.0.0",
|
||||||
|
"@types/better-sqlite3": "^9.6.0",
|
||||||
|
"@types/node": "^26.6.5",
|
||||||
|
"@types/web-push": "^3.6.4",
|
||||||
|
"tsx": "^4.23.15",
|
||||||
|
"typescript": "^7.0.2",
|
||||||
|
"vitest": "^5.0.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { DB } from './db.js';
|
||||||
|
import { login, logout, requireAuth, type Env } from './auth.js';
|
||||||
|
import { billInput, createBill, deleteBill, getBill, listBills, updateBill } from './bills.js';
|
||||||
|
import { annualReport, byCategory, memberBreakdown, memberMonthly, monthlyTrend, totals } from './stats.js';
|
||||||
|
import { balances, suggestTransfers } from './settle.js';
|
||||||
|
import { budgetStatus, newBudgetAlerts, type BudgetAlert } from './budget.js';
|
||||||
|
import { loadParseContext, parseQuick } from './parse.js';
|
||||||
|
import { pushToAll, removeSubscription, saveSubscription, vapidKeys } from './push.js';
|
||||||
|
import { monthOf, monthRange } from './time.js';
|
||||||
|
import { listMumuIcons, mumuDir, MUMU_STYLES } from './mumu-icons.js';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const yuan = (cents: number) => (cents / 100).toLocaleString('zh-CN', { maximumFractionDigits: 2 });
|
||||||
|
|
||||||
|
export function createApp(db: DB) {
|
||||||
|
const app = new Hono<Env>();
|
||||||
|
|
||||||
|
app.onError((err, c) => {
|
||||||
|
if (err instanceof z.ZodError) return c.json({ error: '参数错误', details: err.issues }, 400);
|
||||||
|
console.error(err);
|
||||||
|
return c.json({ error: err.message || '服务器错误' }, 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/login', async (c) => {
|
||||||
|
const body = z.object({ username: z.string(), password: z.string() }).parse(await c.req.json());
|
||||||
|
const r = await login(c, db, body.username.trim(), body.password);
|
||||||
|
return r.ok ? c.json({ ok: true }) : c.json({ error: r.error }, 401);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/logout', (c) => {
|
||||||
|
logout(c, db);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const api = new Hono<Env>();
|
||||||
|
api.use('*', requireAuth(db));
|
||||||
|
|
||||||
|
const range = (c: { req: { query: (k: string) => string | undefined } }) => {
|
||||||
|
const q = (k: string) => c.req.query(k);
|
||||||
|
const bookId = q('bookId') ? Number(q('bookId')) : undefined;
|
||||||
|
if (q('month')) {
|
||||||
|
const [from, to] = monthRange(q('month')!);
|
||||||
|
return { from, to, bookId };
|
||||||
|
}
|
||||||
|
return { from: Number(q('from') ?? 0), to: Number(q('to') ?? Date.now() + 86400000 * 365), bookId };
|
||||||
|
};
|
||||||
|
|
||||||
|
api.get('/me', (c) => c.json(c.get('user')));
|
||||||
|
|
||||||
|
api.get('/meta', (c) => {
|
||||||
|
const members = db.prepare('SELECT id, name, color FROM members ORDER BY sort, id').all();
|
||||||
|
const books = db.prepare('SELECT id, name FROM books ORDER BY sort, id').all();
|
||||||
|
const categories = db
|
||||||
|
.prepare('SELECT id, parent_id AS parentId, type, name, icon, sort, hidden FROM categories ORDER BY sort, id')
|
||||||
|
.all();
|
||||||
|
return c.json({ me: c.get('user'), members, books, categories, vapidPublicKey: vapidKeys(db).publicKey });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Bills
|
||||||
|
api.get('/bills', (c) => {
|
||||||
|
const r = range(c);
|
||||||
|
const q = c.req.query();
|
||||||
|
return c.json(
|
||||||
|
listBills(db, {
|
||||||
|
...r,
|
||||||
|
categoryId: q.categoryId ? Number(q.categoryId) : undefined,
|
||||||
|
memberId: q.memberId ? Number(q.memberId) : undefined,
|
||||||
|
q: q.q || undefined,
|
||||||
|
limit: q.limit ? Number(q.limit) : undefined,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function afterWrite(bookId: number, time: number): Promise<BudgetAlert[]> {
|
||||||
|
const alerts = newBudgetAlerts(db, bookId, monthOf(time));
|
||||||
|
if (alerts.length) {
|
||||||
|
const names = new Map(
|
||||||
|
(db.prepare('SELECT id, name FROM categories').all() as { id: number; name: string }[]).map((r) => [r.id, r.name]),
|
||||||
|
);
|
||||||
|
for (const a of alerts) {
|
||||||
|
const what = a.budget.categoryId ? `「${names.get(a.budget.categoryId)}」预算` : '本月总预算';
|
||||||
|
const body =
|
||||||
|
a.level >= 100
|
||||||
|
? `${what}已超支:已花 ¥${yuan(a.budget.spent)},预算 ¥${yuan(a.budget.amount)}`
|
||||||
|
: `${what}已用 ${a.budget.percent}%:已花 ¥${yuan(a.budget.spent)},预算 ¥${yuan(a.budget.amount)}`;
|
||||||
|
pushToAll(db, { title: '预算提醒', body, url: '/stats' }).catch((e) => console.error(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return alerts;
|
||||||
|
}
|
||||||
|
|
||||||
|
api.post('/bills', async (c) => {
|
||||||
|
const input = billInput.parse(await c.req.json());
|
||||||
|
const id = createBill(db, input, c.get('user').id);
|
||||||
|
return c.json({ id, alerts: await afterWrite(input.bookId, input.time) });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.get('/bills/:id', (c) => {
|
||||||
|
const bill = getBill(db, Number(c.req.param('id')));
|
||||||
|
return bill ? c.json(bill) : c.json({ error: '账单不存在' }, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
api.put('/bills/:id', async (c) => {
|
||||||
|
const input = billInput.parse(await c.req.json());
|
||||||
|
updateBill(db, Number(c.req.param('id')), input);
|
||||||
|
return c.json({ ok: true, alerts: await afterWrite(input.bookId, input.time) });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.delete('/bills/:id', (c) => {
|
||||||
|
deleteBill(db, Number(c.req.param('id')));
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post('/quick', async (c) => {
|
||||||
|
const { text } = z.object({ text: z.string().min(1).max(200) }).parse(await c.req.json());
|
||||||
|
return c.json(parseQuick(text, loadParseContext(db, c.get('user').memberId)));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Statistics
|
||||||
|
api.get('/stats/overview', (c) => {
|
||||||
|
const r = range(c);
|
||||||
|
const month = c.req.query('month') ?? monthOf(Date.now());
|
||||||
|
return c.json({
|
||||||
|
totals: totals(db, r),
|
||||||
|
budgets: r.bookId ? budgetStatus(db, r.bookId, month) : [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
api.get('/stats/categories', (c) => {
|
||||||
|
const r = range(c);
|
||||||
|
const q = c.req.query();
|
||||||
|
const type = q.type === 'income' ? 'income' : 'expense';
|
||||||
|
return c.json(
|
||||||
|
byCategory(db, r, type, {
|
||||||
|
parentId: q.parentId ? Number(q.parentId) : undefined,
|
||||||
|
memberId: q.memberId ? Number(q.memberId) : undefined,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
api.get('/stats/members', (c) => {
|
||||||
|
const r = range(c);
|
||||||
|
return c.json({ monthly: memberMonthly(db, r), breakdown: memberBreakdown(db, r) });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.get('/stats/trend', (c) => c.json(monthlyTrend(db, range(c))));
|
||||||
|
|
||||||
|
api.get('/report/:year', (c) => {
|
||||||
|
const bookId = c.req.query('bookId') ? Number(c.req.query('bookId')) : undefined;
|
||||||
|
return c.json(annualReport(db, Number(c.req.param('year')), bookId));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Settlement
|
||||||
|
api.get('/settle', (c) => {
|
||||||
|
const list = balances(db);
|
||||||
|
const history = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, from_member AS fromId, to_member AS toId, amount, time, note FROM settlements
|
||||||
|
WHERE deleted_at IS NULL ORDER BY time DESC LIMIT 50`,
|
||||||
|
)
|
||||||
|
.all();
|
||||||
|
return c.json({ balances: list, transfers: suggestTransfers(list), history });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post('/settle', async (c) => {
|
||||||
|
const body = z
|
||||||
|
.object({ fromId: z.number().int(), toId: z.number().int(), amount: z.number().int().positive(), note: z.string().default('') })
|
||||||
|
.parse(await c.req.json());
|
||||||
|
if (body.fromId === body.toId) throw new Error('付款人和收款人不能相同');
|
||||||
|
const r = db
|
||||||
|
.prepare('INSERT INTO settlements (from_member, to_member, amount, time, note, created_by) VALUES (?, ?, ?, ?, ?, ?)')
|
||||||
|
.run(body.fromId, body.toId, body.amount, Date.now(), body.note, c.get('user').id);
|
||||||
|
return c.json({ id: Number(r.lastInsertRowid) });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.delete('/settle/:id', (c) => {
|
||||||
|
db.prepare('UPDATE settlements SET deleted_at = ? WHERE id = ?').run(Date.now(), Number(c.req.param('id')));
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Budgets
|
||||||
|
api.get('/budgets', (c) => {
|
||||||
|
const bookId = Number(c.req.query('bookId'));
|
||||||
|
return c.json(budgetStatus(db, bookId, c.req.query('month') ?? monthOf(Date.now())));
|
||||||
|
});
|
||||||
|
|
||||||
|
api.put('/budgets', async (c) => {
|
||||||
|
const body = z
|
||||||
|
.object({ bookId: z.number().int(), categoryId: z.number().int().nullable(), amount: z.number().int().positive() })
|
||||||
|
.parse(await c.req.json());
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO budgets (book_id, category_id, amount) VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT(book_id, IFNULL(category_id, 0)) DO UPDATE SET amount = excluded.amount`,
|
||||||
|
).run(body.bookId, body.categoryId, body.amount);
|
||||||
|
// Thresholds may be crossed again under the new amount.
|
||||||
|
db.prepare(
|
||||||
|
`DELETE FROM budget_alerts WHERE budget_id IN (SELECT id FROM budgets WHERE book_id = ? AND IFNULL(category_id, 0) = ?)`,
|
||||||
|
).run(body.bookId, body.categoryId ?? 0);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.delete('/budgets/:id', (c) => {
|
||||||
|
db.prepare('DELETE FROM budgets WHERE id = ?').run(Number(c.req.param('id')));
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Categories and books
|
||||||
|
const categoryInput = z.object({
|
||||||
|
parentId: z.number().int().nullable().default(null),
|
||||||
|
type: z.enum(['expense', 'income']),
|
||||||
|
name: z.string().min(1).max(20),
|
||||||
|
icon: z.string().max(80).nullable().default(null),
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post('/categories', async (c) => {
|
||||||
|
const body = categoryInput.parse(await c.req.json());
|
||||||
|
const r = db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO categories (parent_id, type, name, icon, sort)
|
||||||
|
VALUES (?, ?, ?, ?, (SELECT COALESCE(MAX(sort), 0) + 1 FROM categories WHERE IFNULL(parent_id, 0) = ?))`,
|
||||||
|
)
|
||||||
|
.run(body.parentId, body.type, body.name, body.icon, body.parentId ?? 0);
|
||||||
|
return c.json({ id: Number(r.lastInsertRowid) });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.put('/categories/:id', async (c) => {
|
||||||
|
const body = z
|
||||||
|
.object({ name: z.string().min(1).max(20).optional(), icon: z.string().max(80).nullable().optional(), hidden: z.boolean().optional(), sort: z.number().int().optional() })
|
||||||
|
.parse(await c.req.json());
|
||||||
|
const id = Number(c.req.param('id'));
|
||||||
|
if (body.name !== undefined) db.prepare('UPDATE categories SET name = ? WHERE id = ?').run(body.name, id);
|
||||||
|
if (body.icon !== undefined) db.prepare('UPDATE categories SET icon = ? WHERE id = ?').run(body.icon, id);
|
||||||
|
if (body.hidden !== undefined) db.prepare('UPDATE categories SET hidden = ? WHERE id = ?').run(body.hidden ? 1 : 0, id);
|
||||||
|
if (body.sort !== undefined) db.prepare('UPDATE categories SET sort = ? WHERE id = ?').run(body.sort, id);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post('/books', async (c) => {
|
||||||
|
const { name } = z.object({ name: z.string().min(1).max(20) }).parse(await c.req.json());
|
||||||
|
const r = db.prepare('INSERT INTO books (name, sort) VALUES (?, (SELECT COALESCE(MAX(sort), 0) + 1 FROM books))').run(name);
|
||||||
|
return c.json({ id: Number(r.lastInsertRowid) });
|
||||||
|
});
|
||||||
|
|
||||||
|
// 木木记账 icons: only for signed-in users, never public.
|
||||||
|
api.get('/icons', (c) => c.json({ styles: MUMU_STYLES, names: listMumuIcons() }));
|
||||||
|
|
||||||
|
api.get('/icons/:style/:file', (c) => {
|
||||||
|
const style = c.req.param('style');
|
||||||
|
const m = /^([A-Za-z0-9_-]+)\.webp$/.exec(c.req.param('file'));
|
||||||
|
if (!(MUMU_STYLES as readonly string[]).includes(style) || !m) return c.notFound();
|
||||||
|
try {
|
||||||
|
const data = fs.readFileSync(path.join(mumuDir(), style, `${m[1]}.webp`));
|
||||||
|
return c.body(data, 200, { 'Content-Type': 'image/webp', 'Cache-Control': 'private, max-age=2592000' });
|
||||||
|
} catch {
|
||||||
|
return c.notFound();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Push notifications
|
||||||
|
api.post('/push/subscribe', async (c) => {
|
||||||
|
const sub = z.object({ endpoint: z.string().url() }).passthrough().parse(await c.req.json());
|
||||||
|
saveSubscription(db, c.get('user').id, sub);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post('/push/unsubscribe', async (c) => {
|
||||||
|
const { endpoint } = z.object({ endpoint: z.string() }).parse(await c.req.json());
|
||||||
|
removeSubscription(db, endpoint);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post('/push/test', async (c) => {
|
||||||
|
await pushToAll(db, { title: '测试通知', body: '通知已开启,预算提醒会推送到这里' });
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.route('/api', api);
|
||||||
|
return app;
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import type { Context, Next } from 'hono';
|
||||||
|
import { getCookie, setCookie, deleteCookie } from 'hono/cookie';
|
||||||
|
import type { DB } from './db.js';
|
||||||
|
|
||||||
|
export const COOKIE = 'billing_session';
|
||||||
|
const SESSION_DAYS = 180;
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
memberId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Env = { Variables: { user: AuthUser } };
|
||||||
|
|
||||||
|
export async function hashPassword(password: string) {
|
||||||
|
return bcrypt.hash(password, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function upsertUser(db: DB, username: string, passwordHash: string, memberId: number) {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO users (username, password_hash, member_id) VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT(username) DO UPDATE SET password_hash = excluded.password_hash, member_id = excluded.member_id`,
|
||||||
|
).run(username, passwordHash, memberId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Small in-memory brake on password guessing: 10 failures per IP per 15 minutes.
|
||||||
|
const failures = new Map<string, { count: number; until: number }>();
|
||||||
|
|
||||||
|
export async function login(c: Context, db: DB, username: string, password: string) {
|
||||||
|
// nginx sets X-Real-IP from the connecting address; clients cannot forge it.
|
||||||
|
const ip = c.req.header('x-real-ip') ?? 'local';
|
||||||
|
const f = failures.get(ip);
|
||||||
|
if (f && f.until > Date.now() && f.count >= 10) return { ok: false as const, error: '尝试次数过多,请稍后再试' };
|
||||||
|
|
||||||
|
const row = db.prepare('SELECT id, password_hash FROM users WHERE username = ?').get(username) as
|
||||||
|
| { id: number; password_hash: string }
|
||||||
|
| undefined;
|
||||||
|
if (!row || !(await bcrypt.compare(password, row.password_hash))) {
|
||||||
|
const next = f && f.until > Date.now() ? f.count + 1 : 1;
|
||||||
|
failures.set(ip, { count: next, until: Date.now() + 15 * 60 * 1000 });
|
||||||
|
return { ok: false as const, error: '用户名或密码错误' };
|
||||||
|
}
|
||||||
|
failures.delete(ip);
|
||||||
|
|
||||||
|
const token = crypto.randomBytes(32).toString('base64url');
|
||||||
|
const expires = Date.now() + SESSION_DAYS * 86400000;
|
||||||
|
db.prepare('INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)').run(token, row.id, expires);
|
||||||
|
db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(Date.now());
|
||||||
|
setCookie(c, COOKIE, token, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === 'production',
|
||||||
|
sameSite: 'Lax',
|
||||||
|
path: '/',
|
||||||
|
maxAge: SESSION_DAYS * 86400,
|
||||||
|
});
|
||||||
|
return { ok: true as const };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function logout(c: Context, db: DB) {
|
||||||
|
const token = getCookie(c, COOKIE);
|
||||||
|
if (token) db.prepare('DELETE FROM sessions WHERE token = ?').run(token);
|
||||||
|
deleteCookie(c, COOKIE, { path: '/' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireAuth(db: DB) {
|
||||||
|
return async (c: Context<Env>, next: Next) => {
|
||||||
|
const token = getCookie(c, COOKIE);
|
||||||
|
const user = token
|
||||||
|
? (db
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.id, u.username, u.member_id AS memberId FROM sessions s JOIN users u ON u.id = s.user_id
|
||||||
|
WHERE s.token = ? AND s.expires_at > ?`,
|
||||||
|
)
|
||||||
|
.get(token, Date.now()) as AuthUser | undefined)
|
||||||
|
: undefined;
|
||||||
|
if (!user) return c.json({ error: '请先登录' }, 401);
|
||||||
|
c.set('user', user);
|
||||||
|
await next();
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import type { DB } from './db.js';
|
||||||
|
|
||||||
|
export const billInput = z.object({
|
||||||
|
bookId: z.number().int(),
|
||||||
|
type: z.enum(['expense', 'income']),
|
||||||
|
categoryId: z.number().int(),
|
||||||
|
amount: z.number().int().positive(),
|
||||||
|
time: z.number().int(),
|
||||||
|
note: z.string().max(200).default(''),
|
||||||
|
payerId: z.number().int().nullable().default(null),
|
||||||
|
// Members the bill is for. Shares are optional; omitted shares split evenly.
|
||||||
|
members: z
|
||||||
|
.array(z.object({ memberId: z.number().int(), share: z.number().int().nonnegative().optional() }))
|
||||||
|
.min(1),
|
||||||
|
excludeBudget: z.boolean().default(false),
|
||||||
|
});
|
||||||
|
export type BillInput = z.infer<typeof billInput>;
|
||||||
|
|
||||||
|
export interface Bill {
|
||||||
|
id: number;
|
||||||
|
bookId: number;
|
||||||
|
type: 'expense' | 'income';
|
||||||
|
categoryId: number;
|
||||||
|
amount: number;
|
||||||
|
time: number;
|
||||||
|
note: string;
|
||||||
|
payerId: number | null;
|
||||||
|
excludeBudget: boolean;
|
||||||
|
createdBy: number | null;
|
||||||
|
members: { memberId: number; share: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Splits amount across members. Explicit shares must add up to the amount;
|
||||||
|
// otherwise the amount is split evenly and leftover cents go to the first members.
|
||||||
|
export function resolveShares(amount: number, members: BillInput['members']) {
|
||||||
|
const ids = [...new Set(members.map((m) => m.memberId))];
|
||||||
|
if (ids.length !== members.length) throw new Error('成员重复');
|
||||||
|
if (members.every((m) => m.share !== undefined)) {
|
||||||
|
const sum = members.reduce((s, m) => s + m.share!, 0);
|
||||||
|
if (sum !== amount) throw new Error('分摊金额之和必须等于账单金额');
|
||||||
|
return members.map((m) => ({ memberId: m.memberId, share: m.share! }));
|
||||||
|
}
|
||||||
|
const base = Math.floor(amount / ids.length);
|
||||||
|
const rest = amount - base * ids.length;
|
||||||
|
return ids.map((memberId, i) => ({ memberId, share: base + (i < rest ? 1 : 0) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkCategory(db: DB, input: BillInput) {
|
||||||
|
const cat = db.prepare('SELECT type FROM categories WHERE id = ?').get(input.categoryId) as { type: string } | undefined;
|
||||||
|
if (!cat) throw new Error('分类不存在');
|
||||||
|
if (cat.type !== input.type) throw new Error('分类与收支类型不符');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createBill(db: DB, input: BillInput, userId: number | null, importKey?: string): number {
|
||||||
|
checkCategory(db, input);
|
||||||
|
const shares = resolveShares(input.amount, input.members);
|
||||||
|
const now = Date.now();
|
||||||
|
return db.transaction(() => {
|
||||||
|
const { lastInsertRowid } = db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO bills (book_id, type, category_id, amount, time, note, payer_id, exclude_budget,
|
||||||
|
created_by, created_at, updated_at, import_key)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
)
|
||||||
|
.run(input.bookId, input.type, input.categoryId, input.amount, input.time, input.note,
|
||||||
|
input.payerId, input.excludeBudget ? 1 : 0, userId, now, now, importKey ?? null);
|
||||||
|
const id = Number(lastInsertRowid);
|
||||||
|
const ins = db.prepare('INSERT INTO bill_members (bill_id, member_id, share) VALUES (?, ?, ?)');
|
||||||
|
for (const s of shares) ins.run(id, s.memberId, s.share);
|
||||||
|
return id;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateBill(db: DB, id: number, input: BillInput) {
|
||||||
|
checkCategory(db, input);
|
||||||
|
const shares = resolveShares(input.amount, input.members);
|
||||||
|
db.transaction(() => {
|
||||||
|
const r = db
|
||||||
|
.prepare(
|
||||||
|
`UPDATE bills SET book_id = ?, type = ?, category_id = ?, amount = ?, time = ?, note = ?,
|
||||||
|
payer_id = ?, exclude_budget = ?, updated_at = ?
|
||||||
|
WHERE id = ? AND deleted_at IS NULL`,
|
||||||
|
)
|
||||||
|
.run(input.bookId, input.type, input.categoryId, input.amount, input.time, input.note,
|
||||||
|
input.payerId, input.excludeBudget ? 1 : 0, Date.now(), id);
|
||||||
|
if (r.changes === 0) throw new Error('账单不存在');
|
||||||
|
db.prepare('DELETE FROM bill_members WHERE bill_id = ?').run(id);
|
||||||
|
const ins = db.prepare('INSERT INTO bill_members (bill_id, member_id, share) VALUES (?, ?, ?)');
|
||||||
|
for (const s of shares) ins.run(id, s.memberId, s.share);
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteBill(db: DB, id: number) {
|
||||||
|
db.prepare('UPDATE bills SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL').run(Date.now(), id);
|
||||||
|
}
|
||||||
|
|
||||||
|
type BillRow = {
|
||||||
|
id: number; book_id: number; type: 'expense' | 'income'; category_id: number; amount: number;
|
||||||
|
time: number; note: string; payer_id: number | null; exclude_budget: number; created_by: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function attachMembers(db: DB, rows: BillRow[]): Bill[] {
|
||||||
|
if (rows.length === 0) return [];
|
||||||
|
const map = new Map<number, Bill['members']>();
|
||||||
|
const placeholders = rows.map(() => '?').join(',');
|
||||||
|
const members = db
|
||||||
|
.prepare(`SELECT bill_id, member_id, share FROM bill_members WHERE bill_id IN (${placeholders}) ORDER BY member_id`)
|
||||||
|
.all(...rows.map((r) => r.id)) as { bill_id: number; member_id: number; share: number }[];
|
||||||
|
for (const m of members) {
|
||||||
|
if (!map.has(m.bill_id)) map.set(m.bill_id, []);
|
||||||
|
map.get(m.bill_id)!.push({ memberId: m.member_id, share: m.share });
|
||||||
|
}
|
||||||
|
return rows.map((r) => ({
|
||||||
|
id: r.id, bookId: r.book_id, type: r.type, categoryId: r.category_id, amount: r.amount,
|
||||||
|
time: r.time, note: r.note, payerId: r.payer_id, excludeBudget: !!r.exclude_budget,
|
||||||
|
createdBy: r.created_by, members: map.get(r.id) ?? [],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BillQuery {
|
||||||
|
bookId?: number;
|
||||||
|
from?: number;
|
||||||
|
to?: number;
|
||||||
|
categoryId?: number; // matches the category or any of its children
|
||||||
|
memberId?: number;
|
||||||
|
q?: string;
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listBills(db: DB, query: BillQuery): Bill[] {
|
||||||
|
const where = ['b.deleted_at IS NULL'];
|
||||||
|
const args: unknown[] = [];
|
||||||
|
if (query.bookId) { where.push('b.book_id = ?'); args.push(query.bookId); }
|
||||||
|
if (query.from !== undefined) { where.push('b.time >= ?'); args.push(query.from); }
|
||||||
|
if (query.to !== undefined) { where.push('b.time < ?'); args.push(query.to); }
|
||||||
|
if (query.categoryId) {
|
||||||
|
where.push('(b.category_id = ? OR b.category_id IN (SELECT id FROM categories WHERE parent_id = ?))');
|
||||||
|
args.push(query.categoryId, query.categoryId);
|
||||||
|
}
|
||||||
|
if (query.memberId) {
|
||||||
|
where.push('EXISTS (SELECT 1 FROM bill_members bm WHERE bm.bill_id = b.id AND bm.member_id = ?)');
|
||||||
|
args.push(query.memberId);
|
||||||
|
}
|
||||||
|
if (query.q) {
|
||||||
|
where.push(`(b.note LIKE ? OR b.category_id IN (SELECT id FROM categories WHERE name LIKE ?))`);
|
||||||
|
args.push(`%${query.q}%`, `%${query.q}%`);
|
||||||
|
}
|
||||||
|
const rows = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT * FROM bills b WHERE ${where.join(' AND ')} ORDER BY b.time DESC, b.id DESC LIMIT ?`,
|
||||||
|
)
|
||||||
|
.all(...args, query.limit ?? 2000) as BillRow[];
|
||||||
|
return attachMembers(db, rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBill(db: DB, id: number): Bill | undefined {
|
||||||
|
const row = db.prepare('SELECT * FROM bills WHERE id = ? AND deleted_at IS NULL').get(id) as BillRow | undefined;
|
||||||
|
return row ? attachMembers(db, [row])[0] : undefined;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type { DB } from './db.js';
|
||||||
|
import { monthRange } from './time.js';
|
||||||
|
|
||||||
|
export const ALERT_LEVELS = [80, 100];
|
||||||
|
|
||||||
|
export interface BudgetStatus {
|
||||||
|
id: number;
|
||||||
|
bookId: number;
|
||||||
|
categoryId: number | null;
|
||||||
|
amount: number;
|
||||||
|
spent: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function budgetStatus(db: DB, bookId: number, month: string): BudgetStatus[] {
|
||||||
|
const [from, to] = monthRange(month);
|
||||||
|
const budgets = db
|
||||||
|
.prepare('SELECT id, book_id, category_id, amount FROM budgets WHERE book_id = ? ORDER BY category_id IS NOT NULL, id')
|
||||||
|
.all(bookId) as { id: number; book_id: number; category_id: number | null; amount: number }[];
|
||||||
|
const spentStmt = db.prepare(
|
||||||
|
`SELECT COALESCE(SUM(b.amount), 0) AS spent FROM bills b JOIN categories c ON c.id = b.category_id
|
||||||
|
WHERE b.deleted_at IS NULL AND b.type = 'expense' AND b.exclude_budget = 0
|
||||||
|
AND b.book_id = ? AND b.time >= ? AND b.time < ?
|
||||||
|
AND (? IS NULL OR c.id = ? OR c.parent_id = ?)`,
|
||||||
|
);
|
||||||
|
return budgets.map((b) => {
|
||||||
|
const { spent } = spentStmt.get(bookId, from, to, b.category_id, b.category_id, b.category_id) as { spent: number };
|
||||||
|
return {
|
||||||
|
id: b.id, bookId: b.book_id, categoryId: b.category_id, amount: b.amount, spent,
|
||||||
|
percent: Math.round((spent / b.amount) * 100),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BudgetAlert {
|
||||||
|
budget: BudgetStatus;
|
||||||
|
level: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns thresholds newly crossed this month and marks them as sent, so each
|
||||||
|
// alert fires at most once per budget per month.
|
||||||
|
export function newBudgetAlerts(db: DB, bookId: number, month: string): BudgetAlert[] {
|
||||||
|
const out: BudgetAlert[] = [];
|
||||||
|
const mark = db.prepare('INSERT OR IGNORE INTO budget_alerts (budget_id, month, level) VALUES (?, ?, ?)');
|
||||||
|
for (const budget of budgetStatus(db, bookId, month)) {
|
||||||
|
const reached = ALERT_LEVELS.filter((l) => budget.percent >= l);
|
||||||
|
const top = reached.at(-1);
|
||||||
|
if (top === undefined) continue;
|
||||||
|
let fresh = false;
|
||||||
|
for (const level of reached) fresh = mark.run(budget.id, month, level).changes > 0 || fresh;
|
||||||
|
if (fresh) out.push({ budget, level: top });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { createBill, resolveShares } from './bills.js';
|
||||||
|
import { newBudgetAlerts } from './budget.js';
|
||||||
|
import { openDb } from './db.js';
|
||||||
|
import { chineseToNumber, parseQuick, type ParseContext } from './parse.js';
|
||||||
|
import { balances, suggestTransfers } from './settle.js';
|
||||||
|
import { monthOf, parseCst } from './time.js';
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
db.exec(`
|
||||||
|
INSERT INTO members (id, name) VALUES (1, 'dyc'), (2, '猪猪');
|
||||||
|
INSERT INTO books (id, name) VALUES (1, '猪猪家');
|
||||||
|
INSERT INTO categories (id, parent_id, type, name) VALUES
|
||||||
|
(1, NULL, 'expense', '餐饮'), (2, 1, 'expense', '午餐'), (3, 1, 'expense', '晚餐'),
|
||||||
|
(4, NULL, 'expense', '交通'), (5, 4, 'expense', '出租车'),
|
||||||
|
(6, NULL, 'income', '工资'), (7, 6, 'income', '工资');
|
||||||
|
`);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bill = (amount: number, payerId: number, memberIds: number[], categoryId = 2) => ({
|
||||||
|
bookId: 1, type: 'expense' as const, categoryId, amount, time: parseCst('2026-10-05 12:00'),
|
||||||
|
note: '', payerId, members: memberIds.map((memberId) => ({ memberId })), excludeBudget: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('shares', () => {
|
||||||
|
it('splits evenly and gives leftover cents to the first members', () => {
|
||||||
|
expect(resolveShares(1001, [{ memberId: 1 }, { memberId: 2 }])).toEqual([
|
||||||
|
{ memberId: 1, share: 501 }, { memberId: 2, share: 500 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
it('rejects explicit shares that do not add up', () => {
|
||||||
|
expect(() => resolveShares(1000, [{ memberId: 1, share: 300 }, { memberId: 2, share: 600 }])).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('settlement', () => {
|
||||||
|
it('computes who owes whom and clears after a settlement', () => {
|
||||||
|
const db = setup();
|
||||||
|
createBill(db, bill(10000, 1, [1, 2]), null); // dyc paid 100 for both
|
||||||
|
createBill(db, bill(3000, 2, [1, 2]), null); // 猪猪 paid 30 for both
|
||||||
|
createBill(db, bill(5000, 2, [2]), null); // 猪猪's own, no effect
|
||||||
|
let t = suggestTransfers(balances(db));
|
||||||
|
expect(t).toEqual([{ from: 2, to: 1, amount: 3500 }]);
|
||||||
|
db.prepare('INSERT INTO settlements (from_member, to_member, amount, time) VALUES (2, 1, 3500, 0)').run();
|
||||||
|
t = suggestTransfers(balances(db));
|
||||||
|
expect(t).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('budget alerts', () => {
|
||||||
|
it('fires each threshold once per month', () => {
|
||||||
|
const db = setup();
|
||||||
|
db.prepare('INSERT INTO budgets (book_id, category_id, amount) VALUES (1, 1, 10000)').run();
|
||||||
|
const month = monthOf(parseCst('2026-10-05 12:00'));
|
||||||
|
createBill(db, bill(8500, 1, [1]), null);
|
||||||
|
expect(newBudgetAlerts(db, 1, month).map((a) => a.level)).toEqual([80]);
|
||||||
|
expect(newBudgetAlerts(db, 1, month)).toEqual([]);
|
||||||
|
createBill(db, bill(2000, 1, [1], 3), null); // child of 餐饮 counts too
|
||||||
|
expect(newBudgetAlerts(db, 1, month).map((a) => a.level)).toEqual([100]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('quick entry', () => {
|
||||||
|
const ctx: ParseContext = {
|
||||||
|
now: parseCst('2026-10-28 15:00'),
|
||||||
|
meId: 1,
|
||||||
|
members: [{ id: 1, name: 'dyc' }, { id: 2, name: '猪猪' }],
|
||||||
|
categories: [
|
||||||
|
{ id: 1, parentId: null, type: 'expense', name: '餐饮' },
|
||||||
|
{ id: 2, parentId: 1, type: 'expense', name: '午餐' },
|
||||||
|
{ id: 3, parentId: 1, type: 'expense', name: '晚餐' },
|
||||||
|
{ id: 4, parentId: null, type: 'expense', name: '交通' },
|
||||||
|
{ id: 5, parentId: 4, type: 'expense', name: '出租车' },
|
||||||
|
{ id: 6, parentId: null, type: 'income', name: '工资' },
|
||||||
|
{ id: 7, parentId: 6, type: 'income', name: '工资' },
|
||||||
|
{ id: 8, parentId: null, type: 'expense', name: '娱乐' },
|
||||||
|
{ id: 9, parentId: 8, type: 'expense', name: '打赏' },
|
||||||
|
],
|
||||||
|
history: [{ note: '墨衣', categoryId: 9 }],
|
||||||
|
};
|
||||||
|
|
||||||
|
it('reads chinese numbers', () => {
|
||||||
|
expect(chineseToNumber('三十五')).toBe(35);
|
||||||
|
expect(chineseToNumber('一百二')).toBe(120);
|
||||||
|
expect(chineseToNumber('两千五百')).toBe(2500);
|
||||||
|
expect(chineseToNumber('一万二千')).toBe(12000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses amount, category and default member', () => {
|
||||||
|
const r = parseQuick('午餐24', ctx);
|
||||||
|
expect(r).toMatchObject({ type: 'expense', amount: 2400, categoryId: 2, memberIds: [1], payerId: 1, note: '' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('understands aliases, dates and shared spending', () => {
|
||||||
|
const r = parseQuick('昨天和猪猪打车三十五块五', ctx);
|
||||||
|
expect(r.amount).toBe(3550);
|
||||||
|
expect(r.categoryId).toBe(5);
|
||||||
|
expect(r.memberIds.sort()).toEqual([1, 2]);
|
||||||
|
expect(r.time).toBe(parseCst('2026-10-27 12:00'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the remaining words as the note and learns from history', () => {
|
||||||
|
const r = parseQuick('墨衣 135元', ctx);
|
||||||
|
expect(r).toMatchObject({ categoryId: 9, amount: 13500, note: '墨衣' });
|
||||||
|
const s = parseQuick('一起吃晚餐 海底捞 128.5', ctx);
|
||||||
|
expect(s).toMatchObject({ categoryId: 3, amount: 12850, note: '海底捞', memberIds: [1, 2] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects income', () => {
|
||||||
|
const r = parseQuick('发工资 15000', ctx);
|
||||||
|
expect(r).toMatchObject({ type: 'income', categoryId: 7, amount: 1500000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not treat dates as amounts', () => {
|
||||||
|
const r = parseQuick('10月3日 晚餐 88', ctx);
|
||||||
|
expect(r.amount).toBe(8800);
|
||||||
|
expect(r.time).toBe(parseCst('2026-10-03 12:00'));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
export type DB = Database.Database;
|
||||||
|
|
||||||
|
// Amounts are stored as integer cents (分) to avoid floating point drift.
|
||||||
|
// Times are stored as epoch milliseconds.
|
||||||
|
const SCHEMA = `
|
||||||
|
CREATE TABLE IF NOT EXISTS members (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
color TEXT NOT NULL DEFAULT '#3b82f6',
|
||||||
|
sort INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
member_id INTEGER NOT NULL REFERENCES members(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token TEXT PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS books (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
sort INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS categories (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
parent_id INTEGER REFERENCES categories(id),
|
||||||
|
type TEXT NOT NULL CHECK (type IN ('expense', 'income')),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
icon TEXT,
|
||||||
|
sort INTEGER NOT NULL DEFAULT 0,
|
||||||
|
hidden INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS categories_unique
|
||||||
|
ON categories(type, IFNULL(parent_id, 0), name);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS bills (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
book_id INTEGER NOT NULL REFERENCES books(id),
|
||||||
|
type TEXT NOT NULL CHECK (type IN ('expense', 'income')),
|
||||||
|
category_id INTEGER NOT NULL REFERENCES categories(id),
|
||||||
|
amount INTEGER NOT NULL CHECK (amount >= 0),
|
||||||
|
time INTEGER NOT NULL,
|
||||||
|
note TEXT NOT NULL DEFAULT '',
|
||||||
|
payer_id INTEGER REFERENCES members(id),
|
||||||
|
exclude_budget INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_by INTEGER REFERENCES users(id),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
deleted_at INTEGER,
|
||||||
|
import_key TEXT UNIQUE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS bills_time ON bills(book_id, time);
|
||||||
|
|
||||||
|
-- Who the bill is for, and each member's share of it.
|
||||||
|
CREATE TABLE IF NOT EXISTS bill_members (
|
||||||
|
bill_id INTEGER NOT NULL REFERENCES bills(id) ON DELETE CASCADE,
|
||||||
|
member_id INTEGER NOT NULL REFERENCES members(id),
|
||||||
|
share INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (bill_id, member_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- A money transfer between members that settles shared expenses.
|
||||||
|
CREATE TABLE IF NOT EXISTS settlements (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
from_member INTEGER NOT NULL REFERENCES members(id),
|
||||||
|
to_member INTEGER NOT NULL REFERENCES members(id),
|
||||||
|
amount INTEGER NOT NULL CHECK (amount > 0),
|
||||||
|
time INTEGER NOT NULL,
|
||||||
|
note TEXT NOT NULL DEFAULT '',
|
||||||
|
created_by INTEGER REFERENCES users(id),
|
||||||
|
deleted_at INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
-- category_id NULL means the whole book's monthly budget.
|
||||||
|
CREATE TABLE IF NOT EXISTS budgets (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
book_id INTEGER NOT NULL REFERENCES books(id),
|
||||||
|
category_id INTEGER REFERENCES categories(id),
|
||||||
|
amount INTEGER NOT NULL CHECK (amount > 0)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS budgets_unique
|
||||||
|
ON budgets(book_id, IFNULL(category_id, 0));
|
||||||
|
|
||||||
|
-- Records which budget thresholds were already notified for a month.
|
||||||
|
CREATE TABLE IF NOT EXISTS budget_alerts (
|
||||||
|
budget_id INTEGER NOT NULL REFERENCES budgets(id) ON DELETE CASCADE,
|
||||||
|
month TEXT NOT NULL,
|
||||||
|
level INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (budget_id, month, level)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||||
|
endpoint TEXT PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
data TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS kv (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
`;
|
||||||
|
|
||||||
|
export function openDb(file: string): DB {
|
||||||
|
if (file !== ':memory:') fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
const db = new Database(file);
|
||||||
|
db.pragma('journal_mode = WAL');
|
||||||
|
db.pragma('foreign_keys = ON');
|
||||||
|
db.exec(SCHEMA);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function kvGet(db: DB, key: string): string | undefined {
|
||||||
|
const row = db.prepare('SELECT value FROM kv WHERE key = ?').get(key) as { value: string } | undefined;
|
||||||
|
return row?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function kvSet(db: DB, key: string, value: string) {
|
||||||
|
db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
// Default category icons from Microsoft Fluent Emoji 3D (MIT license).
|
||||||
|
// Values are the emoji's asset folder name; the web app serves them as
|
||||||
|
// /icons/<slug>.png where slug is the name lowercased with spaces as dashes.
|
||||||
|
export const ICONS: Record<string, string> = {
|
||||||
|
// expense parents
|
||||||
|
餐饮: 'Fork and knife with plate',
|
||||||
|
交通: 'Automobile',
|
||||||
|
小孩: 'Baby bottle',
|
||||||
|
孩子: 'Baby bottle',
|
||||||
|
日常: 'House',
|
||||||
|
其他: 'Package',
|
||||||
|
购物: 'Shopping bags',
|
||||||
|
娱乐: 'Video game',
|
||||||
|
装修: 'Hammer and wrench',
|
||||||
|
医疗: 'Pill',
|
||||||
|
工作: 'Briefcase',
|
||||||
|
学习: 'Books',
|
||||||
|
社交: 'People hugging',
|
||||||
|
美妆: 'Lipstick',
|
||||||
|
通讯: 'Mobile phone',
|
||||||
|
景区门票: 'Ticket',
|
||||||
|
酒店住宿: 'Hotel',
|
||||||
|
// expense children
|
||||||
|
三餐: 'Pot of food',
|
||||||
|
午餐: 'Bento box',
|
||||||
|
晚餐: 'Steaming bowl',
|
||||||
|
早餐: 'Croissant',
|
||||||
|
咖啡: 'Hot beverage',
|
||||||
|
'咖啡/饮料': 'Hot beverage',
|
||||||
|
'奶茶/饮料': 'Bubble tea',
|
||||||
|
'山姆-食物': 'Shopping cart',
|
||||||
|
水果: 'Red apple',
|
||||||
|
甜品: 'Shortcake',
|
||||||
|
蔬菜: 'Leafy green',
|
||||||
|
停车: 'P button',
|
||||||
|
充电: 'High voltage',
|
||||||
|
公交车: 'Bus',
|
||||||
|
共享单车: 'Bicycle',
|
||||||
|
出租车: 'Taxi',
|
||||||
|
地铁: 'Metro',
|
||||||
|
汽车: 'Oncoming automobile',
|
||||||
|
火车: 'High-speed train',
|
||||||
|
飞机: 'Airplane',
|
||||||
|
保险: 'Shield',
|
||||||
|
礼物: 'Wrapped gift',
|
||||||
|
红包: 'Red envelope',
|
||||||
|
就诊: 'Stethoscope',
|
||||||
|
药品: 'Pill',
|
||||||
|
付费会员: 'Crown',
|
||||||
|
打赏: 'Money with wings',
|
||||||
|
旅行: 'Luggage',
|
||||||
|
游戏: 'Video game',
|
||||||
|
演唱会: 'Microphone',
|
||||||
|
瑜伽: 'Person in lotus position',
|
||||||
|
电影: 'Clapper board',
|
||||||
|
聚会: 'Clinking glasses',
|
||||||
|
运动: 'Running shoe',
|
||||||
|
书籍: 'Books',
|
||||||
|
医疗_小孩: 'Adhesive bandage',
|
||||||
|
'大件/装备': 'Baby',
|
||||||
|
奶粉: 'Baby bottle',
|
||||||
|
尿不湿: 'Roll of paper',
|
||||||
|
打疫苗: 'Syringe',
|
||||||
|
'月嫂/育儿嫂': 'Woman feeding baby',
|
||||||
|
母婴护理用品: 'Lotion bottle',
|
||||||
|
清洁: 'Sponge',
|
||||||
|
玩具: 'Teddy bear',
|
||||||
|
'穿着/浴巾方巾': 'T-shirt',
|
||||||
|
纸巾: 'Roll of paper',
|
||||||
|
'辅具/日用品': 'Basket',
|
||||||
|
'辅食/食物': 'Baby bottle',
|
||||||
|
首饰: 'Gem stone',
|
||||||
|
宠物: 'Cat face',
|
||||||
|
宽带: 'Globe with meridians',
|
||||||
|
居家: 'Couch and lamp',
|
||||||
|
'山姆-非食物': 'Shopping cart',
|
||||||
|
搬家: 'Delivery truck',
|
||||||
|
收纳保洁清洁: 'Broom',
|
||||||
|
日用品: 'Soap',
|
||||||
|
水费: 'Droplet',
|
||||||
|
燃气: 'Fire',
|
||||||
|
物业费: 'Office building',
|
||||||
|
理发: 'Barber pole',
|
||||||
|
电费: 'Light bulb',
|
||||||
|
亲友: 'Red heart',
|
||||||
|
老人: 'Old woman',
|
||||||
|
医美: 'Sparkles',
|
||||||
|
彩妆产品: 'Lipstick',
|
||||||
|
护肤品: 'Lotion bottle',
|
||||||
|
人工费: 'Construction worker',
|
||||||
|
卫浴: 'Bathtub',
|
||||||
|
家具: 'Chair',
|
||||||
|
灯具: 'Light bulb',
|
||||||
|
电器: 'Television',
|
||||||
|
装修材料: 'Brick',
|
||||||
|
软装: 'Framed picture',
|
||||||
|
门窗: 'Door',
|
||||||
|
包包: 'Handbag',
|
||||||
|
彩票: 'Game die',
|
||||||
|
快递: 'Package',
|
||||||
|
数码: 'Laptop',
|
||||||
|
服饰: 'Dress',
|
||||||
|
淘宝: 'Shopping bags',
|
||||||
|
// income
|
||||||
|
工资: 'Money bag',
|
||||||
|
奖金: 'Trophy',
|
||||||
|
报销: 'Receipt',
|
||||||
|
鸡蛋: 'Egg',
|
||||||
|
其他收入: 'Coin',
|
||||||
|
手续费: 'Bank',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fallbacks so new categories still get a sensible icon.
|
||||||
|
export const DEFAULT_ICON = { expense: 'Package', income: 'Coin' };
|
||||||
|
|
||||||
|
export function iconSlug(name: string) {
|
||||||
|
return name.toLowerCase().replace(/\s+/g, '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function iconFor(name: string, type: 'expense' | 'income', parentName?: string): string {
|
||||||
|
const key = parentName === '小孩' && name === '医疗' ? '医疗_小孩' : name;
|
||||||
|
return iconSlug(ICONS[key] ?? DEFAULT_ICON[type]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { serve } from '@hono/node-server';
|
||||||
|
import { serveStatic } from '@hono/node-server/serve-static';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { createApp } from './app.js';
|
||||||
|
import { openDb } from './db.js';
|
||||||
|
|
||||||
|
const db = openDb(process.env.DB_PATH ?? 'data/billing.db');
|
||||||
|
const app = createApp(db);
|
||||||
|
|
||||||
|
// In production the built web app is served from the same origin.
|
||||||
|
const webDir = process.env.WEB_DIR;
|
||||||
|
if (webDir) {
|
||||||
|
const index = fs.readFileSync(path.join(webDir, 'index.html'), 'utf8');
|
||||||
|
app.use('/*', serveStatic({ root: path.relative(process.cwd(), webDir) }));
|
||||||
|
app.get('*', (c) => (c.req.path.startsWith('/api/') ? c.notFound() : c.html(index)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = Number(process.env.PORT ?? 3000);
|
||||||
|
serve({ fetch: app.fetch, port }, () => console.log(`billing server on :${port}`));
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
// Category icons extracted from the family's own copy of 木木记账. They are not
|
||||||
|
// part of the repository or image: deploy/extract-mumu-icons.sh copies them into
|
||||||
|
// the data directory, and the server only serves them to signed-in users.
|
||||||
|
// A category's icon is stored as "mumu:<name>"; other values are Fluent icons.
|
||||||
|
|
||||||
|
export const MUMU_STYLES = ['3d', 'flat', 'filled', 'lineal', 'outline'] as const;
|
||||||
|
|
||||||
|
export function mumuDir() {
|
||||||
|
return process.env.MUMU_ICON_DIR ?? path.join(path.dirname(process.env.DB_PATH ?? 'data/billing.db'), 'mumu-icons');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listMumuIcons(): string[] {
|
||||||
|
try {
|
||||||
|
return fs.readdirSync(path.join(mumuDir(), '3d'))
|
||||||
|
.filter((f) => f.endsWith('.webp'))
|
||||||
|
.map((f) => f.slice(0, -5))
|
||||||
|
.filter((n) => !['add', 'more', 'recent', 'settle', 'transfer', 'shezhi'].includes(n))
|
||||||
|
.sort();
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Category name → icon file name, chosen by looking at each picture.
|
||||||
|
export const MUMU_MAP: Record<string, string> = {
|
||||||
|
餐饮: 'canyin', 三餐: 'sancan', 午餐: 'wucan', 晚餐: 'wancan', 早餐: 'zaocan', 咖啡: 'kafei',
|
||||||
|
'咖啡/饮料': 'kafei', '奶茶/饮料': 'naicha', '山姆-食物': 'lingshi', 水果: 'shuiguo', 甜品: 'tianpin', 蔬菜: 'shucai',
|
||||||
|
交通: 'jiaotong', 停车: 'tingche', 充电: 'chongdian', 公交车: 'gongjiaoche', 共享单车: 'gongxiangdanche',
|
||||||
|
出租车: 'chuzuche', 地铁: 'ditie', 汽车: 'qiche', 火车: 'huoche', 飞机: 'feiji',
|
||||||
|
其他: 'qita', 保险: 'baoxian', 礼物: 'shejiao', 红包: 'lijin',
|
||||||
|
医疗: 'yiliao', 就诊: 'jiuzhen', 药品: 'yaopin',
|
||||||
|
娱乐: 'yule', 付费会员: 'fufeihuiyuan', 打赏: 'KTV', 旅行: 'lvxing', 游戏: 'youxi', 演唱会: 'KTV',
|
||||||
|
瑜伽: 'yujia', 电影: 'dianying', 聚会: 'juhui', 运动: 'yundong',
|
||||||
|
学习: 'xuexi', 书籍: 'shuji',
|
||||||
|
孩子: 'haizi', 小孩: 'haizi', '大件/装备': 'jiaju', 奶粉: 'haizi', 尿不湿: 'riyongpin', 打疫苗: 'yibao',
|
||||||
|
'月嫂/育儿嫂': 'service', 母婴护理用品: 'hufupin', 清洁: 'ximiannai', 玩具: 'wanju', '穿着/浴巾方巾': 'fushi',
|
||||||
|
纸巾: 'riyongpin', '辅具/日用品': 'riyongpin', '辅食/食物': 'lingshi', 首饰: 'zhuangshipin',
|
||||||
|
工作: 'bangong',
|
||||||
|
日常: 'shenghuofei', 宠物: 'chongwu', 宽带: 'wangluo', 居家: 'jujia', '山姆-非食物': 'riyongpin', 搬家: 'kuaidi',
|
||||||
|
收纳保洁清洁: 'ximiannai', 日用品: 'riyongpin', 水费: 'shuifei', 燃气: 'ranqi', 物业费: 'wuyefei', 理发: 'lifa',
|
||||||
|
电费: 'dianfei', 通讯: 'tongxun',
|
||||||
|
景区门票: 'jingqumenpiao', 社交: 'shejiao', 亲友: 'qinyou', 老人: 'laoren',
|
||||||
|
美妆: 'kouhong', 医美: 'meirong', 彩妆产品: 'fendi', 护肤品: 'hufupin',
|
||||||
|
装修: 'zhuangxiu', 人工费: 'rengong', 卫浴: 'weiyu', 家具: 'jiaju', 灯具: 'deng', 电器: 'dianqi',
|
||||||
|
装修材料: 'zhuangxiucailiao', 软装: 'zhuangshipin', 门窗: 'menchuang',
|
||||||
|
购物: 'gouwu', 包包: 'gouwu', 彩票: 'caipiao', 快递: 'kuaidi', 数码: 'shuma', 服饰: 'fushi', 淘宝: 'taobao',
|
||||||
|
酒店住宿: 'jiudianzhusu',
|
||||||
|
// income
|
||||||
|
报销: 'baoxiao', 鸡蛋: 'qita', 其他收入: 'qita', 工资: 'gongzi', 奖金: 'jiangjin', 手续费: 'refund',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function mumuIconFor(name: string, parentName?: string): string | null {
|
||||||
|
if (parentName === '小孩' && name === '医疗') return 'mumu:yiliao';
|
||||||
|
if (parentName === '小孩' && name === '书籍') return 'mumu:shuji';
|
||||||
|
const n = MUMU_MAP[name];
|
||||||
|
return n ? `mumu:${n}` : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
import type { DB } from './db.js';
|
||||||
|
import { dayStart } from './time.js';
|
||||||
|
|
||||||
|
// Turns a short phrase such as "昨天和猪猪吃晚餐 128" or "打车三十五块" (typed or
|
||||||
|
// dictated) into a draft bill. Everything is a best guess the user can still edit.
|
||||||
|
|
||||||
|
export interface ParseContext {
|
||||||
|
now: number;
|
||||||
|
meId: number;
|
||||||
|
members: { id: number; name: string }[];
|
||||||
|
categories: { id: number; parentId: number | null; type: 'expense' | 'income'; name: string }[];
|
||||||
|
// Past notes and the category they were most often filed under.
|
||||||
|
history: { note: string; categoryId: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ParsedBill {
|
||||||
|
type: 'expense' | 'income';
|
||||||
|
amount: number | null;
|
||||||
|
categoryId: number | null;
|
||||||
|
time: number;
|
||||||
|
memberIds: number[];
|
||||||
|
payerId: number;
|
||||||
|
note: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALIASES: Record<string, string[]> = {
|
||||||
|
出租车: ['打车', '滴滴', '的士', '出租'],
|
||||||
|
午餐: ['午饭', '中饭', '中午饭'],
|
||||||
|
晚餐: ['晚饭'],
|
||||||
|
早餐: ['早饭', '早点'],
|
||||||
|
咖啡: ['星巴克', '瑞幸', 'manner', 'costa'],
|
||||||
|
'奶茶/饮料': ['奶茶', '饮料', '喜茶', '蜜雪'],
|
||||||
|
地铁: ['坐地铁'],
|
||||||
|
停车: ['停车费'],
|
||||||
|
充电: ['充电桩'],
|
||||||
|
日用品: ['超市'],
|
||||||
|
工资: ['发工资', '薪水'],
|
||||||
|
};
|
||||||
|
|
||||||
|
const SHARED_WORDS = ['一起', '我们', '共同', '两个人', '大家', 'AA', 'aa', '家里'];
|
||||||
|
const SPOUSE_WORDS = ['老婆', '老公', '妻子', '丈夫', '媳妇', '她', '他'];
|
||||||
|
const INCOME_WORDS = ['收入', '收到', '进账', '入账', '工资', '奖金', '报销'];
|
||||||
|
|
||||||
|
const DIGITS: Record<string, number> = { 零: 0, 〇: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };
|
||||||
|
const UNITS: Record<string, number> = { 十: 10, 百: 100, 千: 1000, 万: 10000 };
|
||||||
|
|
||||||
|
// "三十五" -> 35, "一百二" -> 120, "两千五百" -> 2500
|
||||||
|
export function chineseToNumber(s: string): number | null {
|
||||||
|
if (!s) return null;
|
||||||
|
let total = 0, section = 0, num = 0, lastUnit = 1;
|
||||||
|
for (const ch of s) {
|
||||||
|
if (ch in DIGITS) num = DIGITS[ch];
|
||||||
|
else if (ch in UNITS) {
|
||||||
|
const u = UNITS[ch];
|
||||||
|
if (u === 10000) { total += (section + num) * u; section = 0; }
|
||||||
|
else section += (num || (u === 10 ? 1 : 0)) * u;
|
||||||
|
num = 0;
|
||||||
|
lastUnit = u;
|
||||||
|
} else return null;
|
||||||
|
}
|
||||||
|
// A trailing digit after a unit is shorthand: 一百二 = 120, 两千五 = 2500.
|
||||||
|
if (num && lastUnit >= 100 && !s.endsWith('零' + Object.keys(DIGITS).find((k) => DIGITS[k] === num))) {
|
||||||
|
num *= lastUnit / 10;
|
||||||
|
}
|
||||||
|
return total + section + num;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CN = '[零〇一二两三四五六七八九十百千万]';
|
||||||
|
const AMOUNT_RE = new RegExp(
|
||||||
|
`(\\d+(?:\\.\\d{1,2})?|${CN}+)\\s*(?:元|块钱|块|rmb|RMB)?(?:\\s*(${CN}|\\d)(?:毛|角)?)?`, 'g',
|
||||||
|
);
|
||||||
|
|
||||||
|
function extractAmount(text: string): { cents: number; match: string } | null {
|
||||||
|
let best: { cents: number; match: string } | null = null;
|
||||||
|
for (const m of text.matchAll(AMOUNT_RE)) {
|
||||||
|
const [whole, main, jiao] = m;
|
||||||
|
const isDigits = /^\d/.test(main);
|
||||||
|
// Skip dates like "3月" / "5号" and lone Chinese digits that are part of words.
|
||||||
|
const after = text.slice(m.index! + whole.length, m.index! + whole.length + 1);
|
||||||
|
if (/[月日号点]/.test(after)) continue;
|
||||||
|
if (!isDigits && main.length === 1 && !/[元块]/.test(whole) && !/[十百千万]/.test(main)) continue;
|
||||||
|
const value = isDigits ? Number(main) : chineseToNumber(main);
|
||||||
|
if (value === null || Number.isNaN(value)) continue;
|
||||||
|
let cents = Math.round(value * 100);
|
||||||
|
if (jiao) cents += (/\d/.test(jiao) ? Number(jiao) : DIGITS[jiao] ?? 0) * 10;
|
||||||
|
// Prefer the last number mentioned; people usually say the amount last.
|
||||||
|
best = { cents, match: whole };
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractDate(text: string, now: number): { time: number; match: string } | null {
|
||||||
|
const today = dayStart(now);
|
||||||
|
const offsets: [string, number][] = [['大前天', 3], ['前天', 2], ['昨天', 1], ['昨晚', 1], ['今天', 0]];
|
||||||
|
for (const [word, days] of offsets) {
|
||||||
|
if (text.includes(word)) {
|
||||||
|
// Keep the current time of day for today; use noon for earlier days.
|
||||||
|
const time = days === 0 ? now : today - days * 86400000 + 12 * 3600000;
|
||||||
|
return { time, match: word };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const md = /(\d{1,2})月(\d{1,2})[日号]?/.exec(text);
|
||||||
|
if (md) {
|
||||||
|
const cur = new Date(now + 8 * 3600000);
|
||||||
|
let year = cur.getUTCFullYear();
|
||||||
|
let t = Date.UTC(year, +md[1] - 1, +md[2], 12) - 8 * 3600000;
|
||||||
|
if (t > now) t = Date.UTC(--year, +md[1] - 1, +md[2], 12) - 8 * 3600000;
|
||||||
|
return { time: t, match: md[0] };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseQuick(input: string, ctx: ParseContext): ParsedBill {
|
||||||
|
let rest = input.trim();
|
||||||
|
const strip = (s: string) => { rest = rest.replace(s, ' '); };
|
||||||
|
|
||||||
|
const date = extractDate(rest, ctx.now);
|
||||||
|
if (date) strip(date.match);
|
||||||
|
|
||||||
|
// Members: "一起" means everyone, names pick specific people, default is me.
|
||||||
|
const memberIds = new Set<number>();
|
||||||
|
if (SHARED_WORDS.some((w) => rest.includes(w))) {
|
||||||
|
ctx.members.forEach((m) => memberIds.add(m.id));
|
||||||
|
for (const w of SHARED_WORDS) strip(w);
|
||||||
|
}
|
||||||
|
for (const m of ctx.members) {
|
||||||
|
if (rest.includes(m.name)) { memberIds.add(m.id); strip(m.name); }
|
||||||
|
}
|
||||||
|
const spouse = ctx.members.find((m) => m.id !== ctx.meId);
|
||||||
|
if (spouse && SPOUSE_WORDS.some((w) => rest.includes(w))) {
|
||||||
|
memberIds.add(spouse.id);
|
||||||
|
for (const w of SPOUSE_WORDS) strip(w);
|
||||||
|
}
|
||||||
|
if (/和|跟|与/.test(input) && memberIds.size > 0) memberIds.add(ctx.meId);
|
||||||
|
if (memberIds.size === 0) memberIds.add(ctx.meId);
|
||||||
|
|
||||||
|
const amount = extractAmount(rest);
|
||||||
|
if (amount) strip(amount.match);
|
||||||
|
|
||||||
|
const wantsIncome = INCOME_WORDS.some((w) => rest.includes(w));
|
||||||
|
const leaves = ctx.categories.filter((c) => c.parentId !== null);
|
||||||
|
const parents = ctx.categories.filter((c) => c.parentId === null);
|
||||||
|
const pick = (list: typeof ctx.categories) =>
|
||||||
|
list
|
||||||
|
.filter((c) => !wantsIncome || c.type === 'income')
|
||||||
|
.sort((a, b) => b.name.length - a.name.length);
|
||||||
|
|
||||||
|
let categoryId: number | null = null;
|
||||||
|
let categoryWord = '';
|
||||||
|
const byName = pick(leaves).find((c) => rest.includes(c.name)) ?? pick(parents).find((c) => rest.includes(c.name));
|
||||||
|
if (byName) { categoryId = byName.id; categoryWord = byName.name; }
|
||||||
|
if (!categoryId) {
|
||||||
|
outer: for (const [name, words] of Object.entries(ALIASES)) {
|
||||||
|
for (const w of words) {
|
||||||
|
if (!rest.includes(w)) continue;
|
||||||
|
const cat = pick(leaves).find((c) => c.name === name);
|
||||||
|
if (cat) { categoryId = cat.id; categoryWord = w; break outer; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!categoryId) {
|
||||||
|
// Fall back to what similar notes were filed under before.
|
||||||
|
const hit = ctx.history
|
||||||
|
.filter((h) => h.note.length >= 2 && rest.includes(h.note))
|
||||||
|
.sort((a, b) => b.note.length - a.note.length)[0];
|
||||||
|
if (hit) categoryId = hit.categoryId;
|
||||||
|
}
|
||||||
|
if (categoryWord) strip(categoryWord);
|
||||||
|
|
||||||
|
const cat = ctx.categories.find((c) => c.id === categoryId);
|
||||||
|
const type = cat?.type ?? (wantsIncome ? 'income' : 'expense');
|
||||||
|
const note = rest
|
||||||
|
.replace(/[,,。.!!]/g, ' ')
|
||||||
|
.replace(/花了|买了|付了|用了|一共|总共/g, ' ')
|
||||||
|
.split(/\s+/)
|
||||||
|
.map((w) => w.replace(/^(和|跟|与|给)+|(和|跟|与|吃|的)+$/g, ''))
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
|
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
amount: amount?.cents ?? null,
|
||||||
|
categoryId,
|
||||||
|
time: date?.time ?? ctx.now,
|
||||||
|
memberIds: [...memberIds],
|
||||||
|
payerId: ctx.meId,
|
||||||
|
note: type === 'income' ? note.replace(/收入|收到|进账|入账/g, '').trim() : note,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadParseContext(db: DB, meId: number): ParseContext {
|
||||||
|
const members = db.prepare('SELECT id, name FROM members ORDER BY sort, id').all() as ParseContext['members'];
|
||||||
|
const categories = (db
|
||||||
|
.prepare('SELECT id, parent_id AS parentId, type, name FROM categories WHERE hidden = 0')
|
||||||
|
.all()) as ParseContext['categories'];
|
||||||
|
const history = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT note, category_id AS categoryId FROM (
|
||||||
|
SELECT note, category_id, COUNT(*) AS n,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY note ORDER BY COUNT(*) DESC) AS rk
|
||||||
|
FROM bills WHERE deleted_at IS NULL AND note != '' GROUP BY note, category_id)
|
||||||
|
WHERE rk = 1`,
|
||||||
|
)
|
||||||
|
.all() as ParseContext['history'];
|
||||||
|
return { now: Date.now(), meId, members, categories, history };
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import webpush from 'web-push';
|
||||||
|
import { kvGet, kvSet, type DB } from './db.js';
|
||||||
|
|
||||||
|
// VAPID keys are generated once and kept in the database.
|
||||||
|
export function vapidKeys(db: DB) {
|
||||||
|
let pub = kvGet(db, 'vapid_public');
|
||||||
|
let priv = kvGet(db, 'vapid_private');
|
||||||
|
if (!pub || !priv) {
|
||||||
|
const keys = webpush.generateVAPIDKeys();
|
||||||
|
pub = keys.publicKey;
|
||||||
|
priv = keys.privateKey;
|
||||||
|
kvSet(db, 'vapid_public', pub);
|
||||||
|
kvSet(db, 'vapid_private', priv);
|
||||||
|
}
|
||||||
|
return { publicKey: pub, privateKey: priv };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSubscription(db: DB, userId: number, sub: { endpoint: string }) {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO push_subscriptions (endpoint, user_id, data) VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT(endpoint) DO UPDATE SET user_id = excluded.user_id, data = excluded.data`,
|
||||||
|
).run(sub.endpoint, userId, JSON.stringify(sub));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeSubscription(db: DB, endpoint: string) {
|
||||||
|
db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ?').run(endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional Bark (iOS push app) endpoints, e.g. "https://bark.example.com/<device key>",
|
||||||
|
// comma separated in BARK_URLS. Delivered alongside Web Push.
|
||||||
|
async function pushToBark(payload: { title: string; body: string; url?: string }) {
|
||||||
|
const urls = (process.env.BARK_URLS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
||||||
|
const link = process.env.PUBLIC_URL ? new URL(payload.url ?? '/', process.env.PUBLIC_URL).href : undefined;
|
||||||
|
await Promise.all(
|
||||||
|
urls.map(async (base) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(base.replace(/\/$/, ''), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ title: payload.title, body: payload.body, group: '记账', url: link }),
|
||||||
|
});
|
||||||
|
if (!res.ok) console.error('bark push failed', res.status);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('bark push failed', err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pushToAll(db: DB, payload: { title: string; body: string; url?: string }) {
|
||||||
|
await pushToBark(payload);
|
||||||
|
const subject = process.env.VAPID_SUBJECT ?? 'mailto:admin@example.com';
|
||||||
|
const { publicKey, privateKey } = vapidKeys(db);
|
||||||
|
const subs = db.prepare('SELECT endpoint, data FROM push_subscriptions').all() as { endpoint: string; data: string }[];
|
||||||
|
await Promise.all(
|
||||||
|
subs.map(async (s) => {
|
||||||
|
try {
|
||||||
|
await webpush.sendNotification(JSON.parse(s.data), JSON.stringify(payload), {
|
||||||
|
vapidDetails: { subject, publicKey, privateKey },
|
||||||
|
TTL: 24 * 3600,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
const status = (err as { statusCode?: number }).statusCode;
|
||||||
|
// The browser dropped this subscription; forget it.
|
||||||
|
if (status === 404 || status === 410) removeSubscription(db, s.endpoint);
|
||||||
|
else console.error('push failed', status, err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// Switches category icons to the extracted 木木记账 set.
|
||||||
|
//
|
||||||
|
// pnpm tsx src/scripts/apply-mumu-icons.ts [--db data/billing.db]
|
||||||
|
//
|
||||||
|
// Only categories still on a default (non-mumu) icon are changed, so icons
|
||||||
|
// picked by hand in the app are kept.
|
||||||
|
import { parseArgs } from 'node:util';
|
||||||
|
import { openDb } from '../db.js';
|
||||||
|
import { listMumuIcons, mumuDir, mumuIconFor } from '../mumu-icons.js';
|
||||||
|
|
||||||
|
const { values } = parseArgs({ options: { db: { type: 'string', default: process.env.DB_PATH ?? 'data/billing.db' } } });
|
||||||
|
const db = openDb(values.db!);
|
||||||
|
|
||||||
|
const available = new Set(listMumuIcons());
|
||||||
|
if (available.size === 0) {
|
||||||
|
console.error(`没有找到图标文件:${mumuDir()},请先运行 deploy/extract-mumu-icons.sh`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = db
|
||||||
|
.prepare('SELECT c.id, c.name, c.icon, p.name AS parent FROM categories c LEFT JOIN categories p ON p.id = c.parent_id')
|
||||||
|
.all() as { id: number; name: string; icon: string | null; parent: string | null }[];
|
||||||
|
const update = db.prepare('UPDATE categories SET icon = ? WHERE id = ?');
|
||||||
|
let changed = 0;
|
||||||
|
const missing: string[] = [];
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.icon?.startsWith('mumu:')) continue;
|
||||||
|
const icon = mumuIconFor(r.name, r.parent ?? undefined);
|
||||||
|
if (!icon || !available.has(icon.slice(5))) { missing.push(r.parent ? `${r.parent}/${r.name}` : r.name); continue; }
|
||||||
|
update.run(icon, r.id);
|
||||||
|
changed++;
|
||||||
|
}
|
||||||
|
console.log(`已更新 ${changed} 个分类图标`);
|
||||||
|
if (missing.length) console.log(`保留原图标:${missing.join('、')}`);
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
// Imports a 木木记账 Excel export.
|
||||||
|
//
|
||||||
|
// pnpm import:mumu <export.xlsx> [--db data/billing.db] [--shared-payer dyc] [--default-member dyc] [--dry-run]
|
||||||
|
//
|
||||||
|
// The export has no "who paid" column, only 成员. A bill for one member is
|
||||||
|
// treated as paid by that member; a bill for several members is treated as
|
||||||
|
// paid by --shared-payer. Re-running is safe: rows already imported are skipped.
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { parseArgs } from 'node:util';
|
||||||
|
import XLSX from 'xlsx';
|
||||||
|
import { createBill } from '../bills.js';
|
||||||
|
import { openDb, type DB } from '../db.js';
|
||||||
|
import { iconFor } from '../icons.js';
|
||||||
|
import { parseCst } from '../time.js';
|
||||||
|
|
||||||
|
const { values, positionals } = parseArgs({
|
||||||
|
allowPositionals: true,
|
||||||
|
options: {
|
||||||
|
db: { type: 'string', default: process.env.DB_PATH ?? 'data/billing.db' },
|
||||||
|
'shared-payer': { type: 'string', default: 'dyc' },
|
||||||
|
'default-member': { type: 'string', default: 'dyc' },
|
||||||
|
'dry-run': { type: 'boolean', default: false },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const file = positionals[0];
|
||||||
|
if (!file) {
|
||||||
|
console.error('usage: import-mumu <export.xlsx> [--db path] [--shared-payer name] [--default-member name] [--dry-run]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEADER = ['时间', '类型', '分类', '二级分类', '金额', '账本', '转出账户', '转入账户', '备注', '账单图片', '报销', '优惠', '标签', '成员'];
|
||||||
|
const MEMBER_COLORS = ['#3b82f6', '#ec4899', '#22c55e', '#f59e0b'];
|
||||||
|
|
||||||
|
type Row = Record<(typeof HEADER)[number], string>;
|
||||||
|
|
||||||
|
function readRows(path: string): Row[] {
|
||||||
|
const book = XLSX.readFile(path);
|
||||||
|
const sheet = book.Sheets[book.SheetNames[0]];
|
||||||
|
const raw = XLSX.utils.sheet_to_json<string[]>(sheet, { header: 1, raw: false, defval: '' });
|
||||||
|
const header = raw[0].map(String);
|
||||||
|
for (const h of ['时间', '类型', '分类', '二级分类', '金额', '账本', '备注', '成员']) {
|
||||||
|
if (!header.includes(h)) throw new Error(`导出文件缺少列:${h}`);
|
||||||
|
}
|
||||||
|
return raw.slice(1).filter((r) => r.some((v) => v !== '')).map((r) => {
|
||||||
|
const row = {} as Row;
|
||||||
|
header.forEach((h, i) => { row[h as keyof Row] = String(r[i] ?? '').trim(); });
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureMember(db: DB, name: string): number {
|
||||||
|
const found = db.prepare('SELECT id FROM members WHERE name = ?').get(name) as { id: number } | undefined;
|
||||||
|
if (found) return found.id;
|
||||||
|
const n = (db.prepare('SELECT COUNT(*) AS n FROM members').get() as { n: number }).n;
|
||||||
|
return Number(
|
||||||
|
db.prepare('INSERT INTO members (name, color, sort) VALUES (?, ?, ?)').run(name, MEMBER_COLORS[n % MEMBER_COLORS.length], n)
|
||||||
|
.lastInsertRowid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureBook(db: DB, name: string): number {
|
||||||
|
const found = db.prepare('SELECT id FROM books WHERE name = ?').get(name) as { id: number } | undefined;
|
||||||
|
if (found) return found.id;
|
||||||
|
const n = (db.prepare('SELECT COUNT(*) AS n FROM books').get() as { n: number }).n;
|
||||||
|
return Number(db.prepare('INSERT INTO books (name, sort) VALUES (?, ?)').run(name, n).lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureCategory(db: DB, type: 'expense' | 'income', name: string, parent: { id: number; name: string } | null): number {
|
||||||
|
const found = db
|
||||||
|
.prepare('SELECT id FROM categories WHERE type = ? AND IFNULL(parent_id, 0) = ? AND name = ?')
|
||||||
|
.get(type, parent?.id ?? 0, name) as { id: number } | undefined;
|
||||||
|
if (found) return found.id;
|
||||||
|
const n = (db.prepare('SELECT COUNT(*) AS n FROM categories WHERE type = ? AND IFNULL(parent_id, 0) = ?').get(type, parent?.id ?? 0) as { n: number }).n;
|
||||||
|
return Number(
|
||||||
|
db.prepare('INSERT INTO categories (parent_id, type, name, icon, sort) VALUES (?, ?, ?, ?, ?)')
|
||||||
|
.run(parent?.id ?? null, type, name, iconFor(name, type, parent?.name), n).lastInsertRowid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = readRows(file);
|
||||||
|
const db = openDb(values['dry-run'] ? ':memory:' : values.db!);
|
||||||
|
|
||||||
|
// Order categories by how often they are used, so the most common come first.
|
||||||
|
const usage = new Map<string, number>();
|
||||||
|
for (const r of rows) {
|
||||||
|
usage.set(`${r.类型}|${r.分类}`, (usage.get(`${r.类型}|${r.分类}`) ?? 0) + 1);
|
||||||
|
usage.set(`${r.类型}|${r.分类}|${r.二级分类}`, (usage.get(`${r.类型}|${r.分类}|${r.二级分类}`) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
const ordered = [...rows].sort(
|
||||||
|
(a, b) =>
|
||||||
|
(usage.get(`${b.类型}|${b.分类}`)! - usage.get(`${a.类型}|${a.分类}`)!) ||
|
||||||
|
(usage.get(`${b.类型}|${b.分类}|${b.二级分类}`)! - usage.get(`${a.类型}|${a.分类}|${a.二级分类}`)!),
|
||||||
|
);
|
||||||
|
|
||||||
|
const seen = new Map<string, number>();
|
||||||
|
let imported = 0, skipped = 0;
|
||||||
|
const problems: string[] = [];
|
||||||
|
|
||||||
|
db.transaction(() => {
|
||||||
|
for (const r of ordered) {
|
||||||
|
const type = r.类型 === '收入' ? 'income' : r.类型 === '支出' ? 'expense' : null;
|
||||||
|
if (!type) { problems.push(`跳过不支持的类型「${r.类型}」:${r.时间} ${r.备注}`); continue; }
|
||||||
|
const parentId = ensureCategory(db, type, r.分类, null);
|
||||||
|
if (r.二级分类) ensureCategory(db, type, r.二级分类, { id: parentId, name: r.分类 });
|
||||||
|
}
|
||||||
|
|
||||||
|
rows.forEach((r, index) => {
|
||||||
|
const type = r.类型 === '收入' ? 'income' : r.类型 === '支出' ? 'expense' : null;
|
||||||
|
if (!type) return;
|
||||||
|
// Identical rows (same minute, amount, category, note) are legitimate repeats,
|
||||||
|
// so the occurrence count is part of the key.
|
||||||
|
const base = [r.时间, r.类型, r.分类, r.二级分类, r.金额, r.账本, r.备注, r.成员].join('\u0001');
|
||||||
|
const occurrence = (seen.get(base) ?? 0) + 1;
|
||||||
|
seen.set(base, occurrence);
|
||||||
|
const importKey = 'mumu:' + crypto.createHash('sha256').update(`${base}\u0001${occurrence}`).digest('hex').slice(0, 32);
|
||||||
|
if (db.prepare('SELECT 1 FROM bills WHERE import_key = ?').get(importKey)) { skipped++; return; }
|
||||||
|
|
||||||
|
const amount = Math.round(Math.abs(Number(r.金额.replace(/,/g, ''))) * 100);
|
||||||
|
if (!Number.isFinite(amount) || amount === 0) { problems.push(`第 ${index + 2} 行金额无效:${r.金额}`); return; }
|
||||||
|
|
||||||
|
const names = r.成员 ? r.成员.split(/[,,]/).map((s) => s.trim()).filter(Boolean) : [values['default-member']!];
|
||||||
|
const memberIds = names.map((n) => ensureMember(db, n));
|
||||||
|
const payerId = type === 'income' ? null : memberIds.length === 1 ? memberIds[0] : ensureMember(db, values['shared-payer']!);
|
||||||
|
|
||||||
|
const parentId = ensureCategory(db, type, r.分类, null);
|
||||||
|
const categoryId = r.二级分类 ? ensureCategory(db, type, r.二级分类, { id: parentId, name: r.分类 }) : parentId;
|
||||||
|
let note = r.备注;
|
||||||
|
if (r.账单图片) note = note ? `${note} [图片] ${r.账单图片}` : `[图片] ${r.账单图片}`;
|
||||||
|
|
||||||
|
createBill(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
bookId: ensureBook(db, r.账本 || '默认账本'),
|
||||||
|
type,
|
||||||
|
categoryId,
|
||||||
|
amount,
|
||||||
|
time: parseCst(r.时间),
|
||||||
|
note,
|
||||||
|
payerId,
|
||||||
|
members: memberIds.map((memberId) => ({ memberId })),
|
||||||
|
excludeBudget: false,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
importKey,
|
||||||
|
);
|
||||||
|
imported++;
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|
||||||
|
const count = (sql: string) => (db.prepare(sql).get() as { n: number }).n;
|
||||||
|
console.log(`导入 ${imported} 条,已存在跳过 ${skipped} 条${values['dry-run'] ? '(试运行,未写入)' : ''}`);
|
||||||
|
console.log(`账本 ${count('SELECT COUNT(*) n FROM books')} 个,成员 ${count('SELECT COUNT(*) n FROM members')} 个,分类 ${count('SELECT COUNT(*) n FROM categories')} 个`);
|
||||||
|
for (const p of problems) console.warn(p);
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
// Fills in payers and exact member shares for bills imported from the Excel
|
||||||
|
// export, using a copy of 木木记账's own database (the export lacks both).
|
||||||
|
//
|
||||||
|
// pnpm tsx src/scripts/sync-mumu-db.ts <mutongji.db> [--db data/billing.db] [--apply]
|
||||||
|
//
|
||||||
|
// Without --apply it only reports what would change. Each 木木 bill is matched
|
||||||
|
// to an imported bill by book, type, category, minute and amount (note breaks
|
||||||
|
// ties). Bills recorded in this app (no import key), and imported bills already
|
||||||
|
// edited in this app, are never touched.
|
||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import { parseArgs } from 'node:util';
|
||||||
|
import { openDb } from '../db.js';
|
||||||
|
import { balances, suggestTransfers } from '../settle.js';
|
||||||
|
|
||||||
|
const { values, positionals } = parseArgs({
|
||||||
|
allowPositionals: true,
|
||||||
|
options: {
|
||||||
|
db: { type: 'string', default: process.env.DB_PATH ?? 'data/billing.db' },
|
||||||
|
apply: { type: 'boolean', default: false },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!positionals[0]) {
|
||||||
|
console.error('usage: sync-mumu-db <mutongji.db> [--db path] [--apply]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const mumu = new Database(positionals[0], { readonly: true, fileMustExist: true });
|
||||||
|
const db = openDb(values.db!);
|
||||||
|
|
||||||
|
const ourMembers = new Map(
|
||||||
|
(db.prepare('SELECT id, name FROM members').all() as { id: number; name: string }[]).map((m) => [m.name, m.id]),
|
||||||
|
);
|
||||||
|
// 木木 keeps one member row per book, so several mids share a name.
|
||||||
|
const mumuMemberName = new Map(
|
||||||
|
(mumu.prepare('SELECT mid, name FROM member').all() as { mid: number; name: string }[]).map((m) => [m.mid, m.name]),
|
||||||
|
);
|
||||||
|
const toOurMember = (mid: number | null | undefined) => {
|
||||||
|
if (mid == null) return null;
|
||||||
|
const name = mumuMemberName.get(Number(mid));
|
||||||
|
return name ? ourMembers.get(name) ?? null : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const minute = (ts: number) => Math.floor(ts / 60000);
|
||||||
|
const cents = (v: number) => Math.round(Math.abs(v) * 100);
|
||||||
|
|
||||||
|
// Imported bills, grouped by matching key.
|
||||||
|
type Ours = { id: number; note: string; payer_id: number | null; edited: number };
|
||||||
|
const ours = new Map<string, Ours[]>();
|
||||||
|
const ourRows = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT b.id, b.type, b.amount, b.time, b.note, b.payer_id, b.updated_at > b.created_at + 1000 AS edited, bk.name AS book,
|
||||||
|
COALESCE(p.name, c.name) AS cat, CASE WHEN p.id IS NULL THEN '' ELSE c.name END AS sub
|
||||||
|
FROM bills b JOIN books bk ON bk.id = b.book_id JOIN categories c ON c.id = b.category_id
|
||||||
|
LEFT JOIN categories p ON p.id = c.parent_id
|
||||||
|
WHERE b.deleted_at IS NULL AND b.import_key IS NOT NULL`,
|
||||||
|
)
|
||||||
|
.all() as (Ours & { type: string; amount: number; time: number; book: string; cat: string; sub: string })[];
|
||||||
|
for (const r of ourRows) {
|
||||||
|
const key = [r.book, r.type, r.cat, r.sub, minute(r.time), r.amount].join('|');
|
||||||
|
if (!ours.has(key)) ours.set(key, []);
|
||||||
|
ours.get(key)!.push(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
const records = mumu
|
||||||
|
.prepare(
|
||||||
|
`SELECT r.rid, r.income, r.billTime, r.amount, IFNULL(r.remark, '') AS remark, r.payer, bk.name AS book,
|
||||||
|
COALESCE(f.name, t.name) AS cat, CASE WHEN f.tid IS NULL THEN '' ELSE t.name END AS sub
|
||||||
|
FROM bill_record r JOIN bill_book bk ON bk.bid = r.bid JOIN bill_type t ON t.tid = r.tid
|
||||||
|
LEFT JOIN bill_type f ON f.tid = t.fatherTid AND t.fatherTid != 0
|
||||||
|
ORDER BY r.rid`,
|
||||||
|
)
|
||||||
|
.all() as { rid: number; income: number; billTime: number; amount: number; remark: string; payer: string | null; book: string; cat: string; sub: string }[];
|
||||||
|
const relStmt = mumu.prepare('SELECT memberId, amount FROM bill_member_rel WHERE billId = ? ORDER BY memberId');
|
||||||
|
|
||||||
|
const updates: { id: number; payerId: number | null; shares: { memberId: number; share: number }[] | null }[] = [];
|
||||||
|
const unmatched: string[] = [];
|
||||||
|
const stats = { payerSet: 0, payerChanged: 0, payerUnknown: 0, unevenShares: 0, shareFallback: 0, edited: 0 };
|
||||||
|
|
||||||
|
for (const r of records) {
|
||||||
|
const type = r.income === 1 ? 'income' : 'expense';
|
||||||
|
const amount = cents(r.amount);
|
||||||
|
const key = [r.book, type, r.cat, r.sub, minute(r.billTime), amount].join('|');
|
||||||
|
const group = ours.get(key);
|
||||||
|
if (!group?.length) {
|
||||||
|
unmatched.push(`${new Date(r.billTime).toISOString()} ${r.book} ${r.cat}/${r.sub} ¥${r.amount} ${r.remark}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Prefer the candidate whose note matches; identical rows are interchangeable.
|
||||||
|
let i = group.findIndex((g) => g.note === r.remark || g.note.startsWith(`${r.remark} [图片]`));
|
||||||
|
if (i < 0) i = 0;
|
||||||
|
const target = group.splice(i, 1)[0];
|
||||||
|
if (target.edited) { stats.edited++; continue; }
|
||||||
|
|
||||||
|
// Shares from 木木's per-member amounts, merging rows for the same person.
|
||||||
|
const merged = new Map<number, number>();
|
||||||
|
for (const m of relStmt.all(r.rid) as { memberId: number; amount: number }[]) {
|
||||||
|
const id = toOurMember(m.memberId);
|
||||||
|
if (id) merged.set(id, (merged.get(id) ?? 0) + Math.round(m.amount * 100));
|
||||||
|
}
|
||||||
|
let shares: { memberId: number; share: number }[] | null = [...merged].map(([memberId, share]) => ({ memberId, share }));
|
||||||
|
const sum = shares.reduce((s, x) => s + x.share, 0);
|
||||||
|
if (shares.length === 0) shares = null; // keep the members from the export
|
||||||
|
else if (sum !== amount) {
|
||||||
|
if (Math.abs(sum - amount) <= shares.length) shares[0].share += amount - sum; // rounding cents
|
||||||
|
else { shares = null; stats.shareFallback++; }
|
||||||
|
}
|
||||||
|
if (shares && shares.length > 1 && new Set(shares.map((s) => s.share)).size > 1 &&
|
||||||
|
Math.max(...shares.map((s) => s.share)) - Math.min(...shares.map((s) => s.share)) > 1) stats.unevenShares++;
|
||||||
|
|
||||||
|
let payerId = type === 'income' ? null : toOurMember(r.payer ? Number(r.payer) : null);
|
||||||
|
// No members recorded in 木木: the export left 成员 blank and the import filled
|
||||||
|
// in a default member, so treat the bill as the payer's own spending instead.
|
||||||
|
if (merged.size === 0 && payerId !== null) shares = [{ memberId: payerId, share: amount }];
|
||||||
|
// No payer recorded: a bill for one person was paid by that person.
|
||||||
|
if (type === 'expense' && payerId === null) {
|
||||||
|
const only = shares?.length === 1 ? shares[0].memberId : null;
|
||||||
|
if (only) payerId = only;
|
||||||
|
else stats.payerUnknown++;
|
||||||
|
}
|
||||||
|
if (payerId !== null) stats.payerSet++;
|
||||||
|
if (type === 'expense' && payerId !== target.payer_id) stats.payerChanged++;
|
||||||
|
updates.push({ id: target.id, payerId, shares });
|
||||||
|
}
|
||||||
|
|
||||||
|
const leftover = [...ours.values()].reduce((s, g) => s + g.length, 0);
|
||||||
|
const before = suggestTransfers(balances(db));
|
||||||
|
|
||||||
|
const apply = db.transaction(() => {
|
||||||
|
const setPayer = db.prepare('UPDATE bills SET payer_id = ?, updated_at = ? WHERE id = ?');
|
||||||
|
const clear = db.prepare('DELETE FROM bill_members WHERE bill_id = ?');
|
||||||
|
const ins = db.prepare('INSERT INTO bill_members (bill_id, member_id, share) VALUES (?, ?, ?)');
|
||||||
|
const now = Date.now();
|
||||||
|
for (const u of updates) {
|
||||||
|
setPayer.run(u.payerId, now, u.id);
|
||||||
|
if (u.shares) {
|
||||||
|
clear.run(u.id);
|
||||||
|
for (const s of u.shares) ins.run(u.id, s.memberId, s.share);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const name = (id: number) => [...ourMembers].find(([, v]) => v === id)?.[0] ?? `#${id}`;
|
||||||
|
const show = (t: { from: number; to: number; amount: number }[]) =>
|
||||||
|
t.length ? t.map((x) => `${name(x.from)} → ${name(x.to)} ¥${(x.amount / 100).toFixed(2)}`).join(';') : '已结清';
|
||||||
|
|
||||||
|
console.log(`木木账单 ${records.length} 条,匹配 ${updates.length} 条,未匹配 ${unmatched.length} 条;已导入但没对上的 ${leftover} 条`);
|
||||||
|
console.log(`付款人:有付款人 ${stats.payerSet} 条(与现在不同 ${stats.payerChanged} 条),共同支出未记录付款人 ${stats.payerUnknown} 条`);
|
||||||
|
console.log(`分摊:非平分 ${stats.unevenShares} 条,金额对不上改为平分 ${stats.shareFallback} 条`);
|
||||||
|
console.log(`在本应用里改过、保留不动 ${stats.edited} 条`);
|
||||||
|
console.log(`结算(更新前):${show(before)}`);
|
||||||
|
if (values.apply) {
|
||||||
|
apply();
|
||||||
|
console.log(`结算(更新后):${show(suggestTransfers(balances(db)))}`);
|
||||||
|
} else {
|
||||||
|
db.exec('BEGIN');
|
||||||
|
apply(); // nested: runs as a savepoint inside the outer transaction
|
||||||
|
console.log(`结算(更新后,预览):${show(suggestTransfers(balances(db)))}`);
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
console.log('试运行,没有写入。加 --apply 才会更新。');
|
||||||
|
}
|
||||||
|
for (const u of unmatched.slice(0, 10)) console.warn('未匹配:', u);
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// Creates or resets a login account linked to a member.
|
||||||
|
//
|
||||||
|
// pnpm user <username> <member name> [password]
|
||||||
|
//
|
||||||
|
// Without a password, a random one is generated and printed.
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { hashPassword, upsertUser } from '../auth.js';
|
||||||
|
import { openDb } from '../db.js';
|
||||||
|
|
||||||
|
const [username, memberName, given] = process.argv.slice(2);
|
||||||
|
if (!username || !memberName) {
|
||||||
|
console.error('usage: user <username> <member name> [password]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = openDb(process.env.DB_PATH ?? 'data/billing.db');
|
||||||
|
const member = db.prepare('SELECT id FROM members WHERE name = ?').get(memberName) as { id: number } | undefined;
|
||||||
|
if (!member) {
|
||||||
|
const names = (db.prepare('SELECT name FROM members').all() as { name: string }[]).map((m) => m.name);
|
||||||
|
console.error(`成员「${memberName}」不存在。现有成员:${names.join('、') || '(无,请先导入数据)'}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const password = given ?? crypto.randomBytes(9).toString('base64url');
|
||||||
|
upsertUser(db, username, await hashPassword(password), member.id);
|
||||||
|
db.prepare('DELETE FROM sessions WHERE user_id = (SELECT id FROM users WHERE username = ?)').run(username);
|
||||||
|
console.log(`账号 ${username}(成员:${memberName})已设置${given ? '' : `,密码:${password}`}`);
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { DB } from './db.js';
|
||||||
|
|
||||||
|
export interface Balance {
|
||||||
|
memberId: number;
|
||||||
|
paid: number; // what this member paid for shared expenses
|
||||||
|
consumed: number; // this member's share of those expenses
|
||||||
|
net: number; // positive: others owe this member
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Transfer {
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Net position of each member across all expense bills with a payer, plus
|
||||||
|
// recorded settlements. Income never affects who owes whom.
|
||||||
|
export function balances(db: DB): Balance[] {
|
||||||
|
const members = db.prepare('SELECT id FROM members ORDER BY sort, id').all() as { id: number }[];
|
||||||
|
const map = new Map<number, Balance>(members.map((m) => [m.id, { memberId: m.id, paid: 0, consumed: 0, net: 0 }]));
|
||||||
|
|
||||||
|
const paid = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT payer_id AS id, SUM(amount) AS total FROM bills
|
||||||
|
WHERE deleted_at IS NULL AND type = 'expense' AND payer_id IS NOT NULL GROUP BY payer_id`,
|
||||||
|
)
|
||||||
|
.all() as { id: number; total: number }[];
|
||||||
|
const consumed = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT bm.member_id AS id, SUM(bm.share) AS total FROM bill_members bm JOIN bills b ON b.id = bm.bill_id
|
||||||
|
WHERE b.deleted_at IS NULL AND b.type = 'expense' AND b.payer_id IS NOT NULL GROUP BY bm.member_id`,
|
||||||
|
)
|
||||||
|
.all() as { id: number; total: number }[];
|
||||||
|
const sent = db
|
||||||
|
.prepare(`SELECT from_member AS id, SUM(amount) AS total FROM settlements WHERE deleted_at IS NULL GROUP BY from_member`)
|
||||||
|
.all() as { id: number; total: number }[];
|
||||||
|
const received = db
|
||||||
|
.prepare(`SELECT to_member AS id, SUM(amount) AS total FROM settlements WHERE deleted_at IS NULL GROUP BY to_member`)
|
||||||
|
.all() as { id: number; total: number }[];
|
||||||
|
|
||||||
|
for (const r of paid) map.get(r.id)!.paid += r.total;
|
||||||
|
for (const r of consumed) map.get(r.id)!.consumed += r.total;
|
||||||
|
for (const b of map.values()) b.net = b.paid - b.consumed;
|
||||||
|
// Paying someone back raises the payer's position and lowers the receiver's.
|
||||||
|
for (const r of sent) map.get(r.id)!.net += r.total;
|
||||||
|
for (const r of received) map.get(r.id)!.net -= r.total;
|
||||||
|
return [...map.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimal transfers that bring every member's net position to zero.
|
||||||
|
export function suggestTransfers(list: Balance[]): Transfer[] {
|
||||||
|
const debtors = list.filter((b) => b.net < 0).map((b) => ({ id: b.memberId, left: -b.net }));
|
||||||
|
const creditors = list.filter((b) => b.net > 0).map((b) => ({ id: b.memberId, left: b.net }));
|
||||||
|
debtors.sort((a, b) => b.left - a.left);
|
||||||
|
creditors.sort((a, b) => b.left - a.left);
|
||||||
|
const out: Transfer[] = [];
|
||||||
|
let i = 0, j = 0;
|
||||||
|
while (i < debtors.length && j < creditors.length) {
|
||||||
|
const amount = Math.min(debtors[i].left, creditors[j].left);
|
||||||
|
out.push({ from: debtors[i].id, to: creditors[j].id, amount });
|
||||||
|
debtors[i].left -= amount;
|
||||||
|
creditors[j].left -= amount;
|
||||||
|
if (debtors[i].left === 0) i++;
|
||||||
|
if (creditors[j].left === 0) j++;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import type { DB } from './db.js';
|
||||||
|
import { sqlMonth, yearRange } from './time.js';
|
||||||
|
|
||||||
|
export interface Range {
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
bookId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rangeWhere(r: Range, alias = 'b') {
|
||||||
|
const where = [`${alias}.deleted_at IS NULL`, `${alias}.time >= ?`, `${alias}.time < ?`];
|
||||||
|
const args: unknown[] = [r.from, r.to];
|
||||||
|
if (r.bookId) { where.push(`${alias}.book_id = ?`); args.push(r.bookId); }
|
||||||
|
return { sql: where.join(' AND '), args };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function totals(db: DB, r: Range) {
|
||||||
|
const w = rangeWhere(r);
|
||||||
|
const row = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT COALESCE(SUM(CASE WHEN type = 'expense' THEN amount END), 0) AS expense,
|
||||||
|
COALESCE(SUM(CASE WHEN type = 'income' THEN amount END), 0) AS income,
|
||||||
|
COUNT(*) AS count
|
||||||
|
FROM bills b WHERE ${w.sql}`,
|
||||||
|
)
|
||||||
|
.get(...w.args) as { expense: number; income: number; count: number };
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Totals per top-level category, or per child when parentId is given.
|
||||||
|
// With memberId, only that member's shares are counted.
|
||||||
|
export function byCategory(
|
||||||
|
db: DB, r: Range, type: 'expense' | 'income', opts: { parentId?: number; memberId?: number } = {},
|
||||||
|
) {
|
||||||
|
const w = rangeWhere(r);
|
||||||
|
const amount = opts.memberId ? 'bm.share' : 'b.amount';
|
||||||
|
const join = opts.memberId ? 'JOIN bill_members bm ON bm.bill_id = b.id AND bm.member_id = ?' : '';
|
||||||
|
const group = opts.parentId ? 'c.id' : 'COALESCE(c.parent_id, c.id)';
|
||||||
|
const args: unknown[] = [];
|
||||||
|
if (opts.memberId) args.push(opts.memberId);
|
||||||
|
args.push(...w.args, type);
|
||||||
|
let parentFilter = '';
|
||||||
|
if (opts.parentId) { parentFilter = 'AND (c.parent_id = ? OR c.id = ?)'; args.push(opts.parentId, opts.parentId); }
|
||||||
|
return db
|
||||||
|
.prepare(
|
||||||
|
`SELECT ${group} AS categoryId, SUM(${amount}) AS amount, COUNT(*) AS count
|
||||||
|
FROM bills b ${join} JOIN categories c ON c.id = b.category_id
|
||||||
|
WHERE ${w.sql} AND b.type = ? ${parentFilter}
|
||||||
|
GROUP BY ${group} ORDER BY amount DESC`,
|
||||||
|
)
|
||||||
|
.all(...args) as { categoryId: number; amount: number; count: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expense per member per month, measured by each member's share.
|
||||||
|
export function memberMonthly(db: DB, r: Range) {
|
||||||
|
const w = rangeWhere(r);
|
||||||
|
return db
|
||||||
|
.prepare(
|
||||||
|
`SELECT ${sqlMonth('b.time')} AS month, bm.member_id AS memberId, SUM(bm.share) AS amount
|
||||||
|
FROM bills b JOIN bill_members bm ON bm.bill_id = b.id
|
||||||
|
WHERE ${w.sql} AND b.type = 'expense'
|
||||||
|
GROUP BY month, bm.member_id ORDER BY month`,
|
||||||
|
)
|
||||||
|
.all(...w.args) as { month: string; memberId: number; amount: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expense split by "own" (bill only for that member) vs "shared" (several members).
|
||||||
|
export function memberBreakdown(db: DB, r: Range) {
|
||||||
|
const w = rangeWhere(r);
|
||||||
|
return db
|
||||||
|
.prepare(
|
||||||
|
`SELECT bm.member_id AS memberId,
|
||||||
|
SUM(CASE WHEN n.cnt = 1 THEN bm.share ELSE 0 END) AS own,
|
||||||
|
SUM(CASE WHEN n.cnt > 1 THEN bm.share ELSE 0 END) AS shared
|
||||||
|
FROM bills b
|
||||||
|
JOIN bill_members bm ON bm.bill_id = b.id
|
||||||
|
JOIN (SELECT bill_id, COUNT(*) AS cnt FROM bill_members GROUP BY bill_id) n ON n.bill_id = b.id
|
||||||
|
WHERE ${w.sql} AND b.type = 'expense'
|
||||||
|
GROUP BY bm.member_id`,
|
||||||
|
)
|
||||||
|
.all(...w.args) as { memberId: number; own: number; shared: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function monthlyTrend(db: DB, r: Range) {
|
||||||
|
const w = rangeWhere(r);
|
||||||
|
return db
|
||||||
|
.prepare(
|
||||||
|
`SELECT ${sqlMonth('b.time')} AS month,
|
||||||
|
COALESCE(SUM(CASE WHEN type = 'expense' THEN amount END), 0) AS expense,
|
||||||
|
COALESCE(SUM(CASE WHEN type = 'income' THEN amount END), 0) AS income
|
||||||
|
FROM bills b WHERE ${w.sql} GROUP BY month ORDER BY month`,
|
||||||
|
)
|
||||||
|
.all(...w.args) as { month: string; expense: number; income: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function annualReport(db: DB, year: number, bookId?: number) {
|
||||||
|
const [from, to] = yearRange(year);
|
||||||
|
const r = { from, to, bookId };
|
||||||
|
const [pf, pt] = yearRange(year - 1);
|
||||||
|
const w = rangeWhere(r);
|
||||||
|
|
||||||
|
const topBills = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, category_id AS categoryId, amount, time, note FROM bills b
|
||||||
|
WHERE ${w.sql} AND type = 'expense' ORDER BY amount DESC LIMIT 10`,
|
||||||
|
)
|
||||||
|
.all(...w.args);
|
||||||
|
const busiestDay = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT strftime('%Y-%m-%d', (time + 28800000) / 1000, 'unixepoch') AS day, SUM(amount) AS amount, COUNT(*) AS count
|
||||||
|
FROM bills b WHERE ${w.sql} AND type = 'expense' GROUP BY day ORDER BY amount DESC LIMIT 1`,
|
||||||
|
)
|
||||||
|
.get(...w.args);
|
||||||
|
const activeDays = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT COUNT(DISTINCT strftime('%Y-%m-%d', (time + 28800000) / 1000, 'unixepoch')) AS n FROM bills b WHERE ${w.sql}`,
|
||||||
|
)
|
||||||
|
.get(...w.args) as { n: number };
|
||||||
|
// Most frequent subcategory: what the family records most often.
|
||||||
|
const habits = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT category_id AS categoryId, COUNT(*) AS count, SUM(amount) AS amount FROM bills b
|
||||||
|
WHERE ${w.sql} AND type = 'expense' GROUP BY category_id ORDER BY count DESC LIMIT 5`,
|
||||||
|
)
|
||||||
|
.all(...w.args);
|
||||||
|
|
||||||
|
return {
|
||||||
|
year,
|
||||||
|
totals: totals(db, r),
|
||||||
|
previous: totals(db, { from: pf, to: pt, bookId }),
|
||||||
|
monthly: monthlyTrend(db, r),
|
||||||
|
categories: byCategory(db, r, 'expense'),
|
||||||
|
incomeCategories: byCategory(db, r, 'income'),
|
||||||
|
members: memberBreakdown(db, r),
|
||||||
|
topBills,
|
||||||
|
busiestDay: busiestDay ?? null,
|
||||||
|
activeDays: activeDays.n,
|
||||||
|
habits,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// All calendar math uses China Standard Time (UTC+8, no daylight saving),
|
||||||
|
// so month boundaries are the same no matter where the server runs.
|
||||||
|
const OFFSET = 8 * 3600 * 1000;
|
||||||
|
|
||||||
|
export function monthRange(month: string): [number, number] {
|
||||||
|
const [y, m] = month.split('-').map(Number);
|
||||||
|
return [Date.UTC(y, m - 1, 1) - OFFSET, Date.UTC(y, m, 1) - OFFSET];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function yearRange(year: number): [number, number] {
|
||||||
|
return [Date.UTC(year, 0, 1) - OFFSET, Date.UTC(year + 1, 0, 1) - OFFSET];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function monthOf(ts: number): string {
|
||||||
|
const d = new Date(ts + OFFSET);
|
||||||
|
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start of the CST calendar day containing ts.
|
||||||
|
export function dayStart(ts: number): number {
|
||||||
|
const d = new Date(ts + OFFSET);
|
||||||
|
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - OFFSET;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parses "YYYY-MM-DD HH:mm" written in CST.
|
||||||
|
export function parseCst(text: string): number {
|
||||||
|
const m = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}))?/.exec(text.trim());
|
||||||
|
if (!m) throw new Error(`bad time: ${text}`);
|
||||||
|
const [, y, mo, d, h = '0', mi = '0'] = m;
|
||||||
|
return Date.UTC(+y, +mo - 1, +d, +h, +mi) - OFFSET;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SQL expression giving the CST month ("YYYY-MM") of a millisecond column.
|
||||||
|
export const sqlMonth = (col: string) => `strftime('%Y-%m', (${col} + ${OFFSET}) / 1000, 'unixepoch')`;
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2023",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src"],
|
||||||
|
"exclude": ["src/**/*.test.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
|
"plugins": ["react", "typescript", "oxc"],
|
||||||
|
"rules": {
|
||||||
|
"react/rules-of-hooks": "error",
|
||||||
|
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "base-nova",
|
||||||
|
"rsc": false,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "src/index.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"rtl": false,
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"menuColor": "default",
|
||||||
|
"menuAccent": "subtle",
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="记账" />
|
||||||
|
<meta name="theme-color" content="#f6f7f9" media="(prefers-color-scheme: light)" />
|
||||||
|
<meta name="theme-color" content="#1b1b1b" media="(prefers-color-scheme: dark)" />
|
||||||
|
<link rel="icon" type="image/png" href="/app-icon-192.png" />
|
||||||
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||||
|
<title>家庭记账</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "oxlint",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@base-ui/react": "^1.9.0",
|
||||||
|
"@fontsource-variable/geist": "^5.3.0",
|
||||||
|
"@tailwindcss/vite": "^4.3.3",
|
||||||
|
"@tanstack/react-query": "^5.105.0",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"cn": "^0.5.0",
|
||||||
|
"lucide-react": "^1.63.0",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
|
"react": "^19.3.1",
|
||||||
|
"react-dom": "^19.3.1",
|
||||||
|
"react-router": "^8.5.1",
|
||||||
|
"recharts": "^3.10.1",
|
||||||
|
"shadcn": "^4.23.0",
|
||||||
|
"sonner": "^2.0.8",
|
||||||
|
"tailwindcss": "^4.3.3",
|
||||||
|
"tw-animate-css": "^1.4.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.19.2",
|
||||||
|
"@types/react": "^19.3.0",
|
||||||
|
"@types/react-dom": "^19.3.0",
|
||||||
|
"@vitejs/plugin-react": "^6.1.2",
|
||||||
|
"oxlint": "^1.89.0",
|
||||||
|
"typescript": "~7.0.2",
|
||||||
|
"vite": "^8.3.5",
|
||||||
|
"vite-plugin-pwa": "^2.0.0",
|
||||||
|
"workbox-precaching": "^7.4.1",
|
||||||
|
"workbox-routing": "^7.4.1",
|
||||||
|
"workbox-window": "^7.4.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 14 KiB |