feat: improve quick bookkeeping and asset inclusion

Add commemorative assets, session undo, paired repayment, month/day markers and filters. Compact account cards, move transfer entry, persist backup metadata, and update Chinese documentation.
This commit is contained in:
陈煜 committed 2026-10-04 16:01:24 +08:00
1 parent ad6466cb6b
commit 096f1577c2
22 files changed
+1465 -73

No files matched your search

+2 -2
View File
@@ -5,11 +5,11 @@
"dev": "node scripts/dev.cjs",
"build": "tsc",
"typecheck": "tsc --noEmit",
"test": "tsx --test --test-concurrency=1 test/calculation.test.ts test/update.test.ts test/zip.test.ts test/metals.test.ts ../web/test/i18n.test.ts test/account-deletion.test.ts test/mcp-hosts.test.ts test/mcp-http.test.ts test/network.test.ts",
"test": "tsx --test --test-concurrency=1 test/calculation.test.ts test/update.test.ts test/zip.test.ts test/metals.test.ts ../web/test/i18n.test.ts test/account-deletion.test.ts test/mcp-hosts.test.ts test/mcp-http.test.ts test/network.test.ts ../web/test/quick-entry.test.ts",
"db:generate": "prisma generate",
"db:migrate": "node scripts/database.cjs deploy",
"db:status": "node scripts/database.cjs status",
"test:integration": "tsx --test --test-concurrency=1 test/integration.test.ts test/privacy.test.ts test/icons.test.ts test/transfers.test.ts test/queries.test.ts test/debts.test.ts test/update-integration.test.ts test/record-edit.test.ts test/security-backup.test.ts test/credit-balance.test.ts test/group-order.test.ts test/settings-plans.test.ts test/inclusion-metals.test.ts test/account-deletion-integration.test.ts",
"test:integration": "tsx --test --test-concurrency=1 test/integration.test.ts test/privacy.test.ts test/icons.test.ts test/transfers.test.ts test/queries.test.ts test/debts.test.ts test/update-integration.test.ts test/record-edit.test.ts test/security-backup.test.ts test/credit-balance.test.ts test/group-order.test.ts test/settings-plans.test.ts test/inclusion-metals.test.ts test/account-deletion-integration.test.ts test/quick-entry-integration.test.ts",
"test:performance": "tsx scripts/performance.ts after",
"test:mcp": "tsx --test --test-concurrency=1 test/mcp.test.ts test/oauth-duration.test.ts",
"mcp:probe": "tsx scripts/mcp-probe.ts",
@@ -0,0 +1 @@
ALTER TABLE `Position` ADD COLUMN `lastRepaymentMonth` CHAR(7) NULL COMMENT '最后手动标记已完成还款的业务月份,UTC+8 YYYY-MM;空表示未标记';
@@ -0,0 +1 @@
ALTER TABLE `Position` ADD COLUMN `lastBookedDate` CHAR(10) NULL COMMENT '最后手动标记已完成记账的业务日期,UTC+8 YYYY-MM-DD;空表示未标记';
+4
View File
@@ -218,6 +218,10 @@ model Position {
hidden Boolean @default(false)
/// 是否参与资产负债总额及净资产轨迹
included Boolean @default(true)
/// 最后手动标记已完成还款的业务月份,UTC+8 YYYY-MM;空表示未标记
lastRepaymentMonth String? @db.Char(7)
/// 最后手动标记已完成记账的业务日期,UTC+8 YYYY-MM-DD;空表示未标记
lastBookedDate String? @db.Char(10)
/// 贵金属品种:gold 黄金或 silver 白银
metalType String? @db.VarChar(12)
/// 贵金属总重量,单位克
+11
View File
@@ -1,3 +1,4 @@
import { repaymentMonth, date } from './validation';
import { BACKUP_ZIP_VERSION } from './backup-format';
import { Injectable } from '@nestjs/common';
import { metalConfig, metalPriceInput, storedMetalPurity } from './metals';
@@ -63,6 +64,8 @@ const record = positionMeta
notes: z.string().max(2000),
archived: z.boolean(),
hidden: z.boolean(),
lastRepaymentMonth: repaymentMonth.optional(),
lastBookedDate: date.nullable().optional(),
metalType: z.enum(['gold', 'silver']).nullable(),
metalGrams: amount.nullable(),
metalCostPerGram: metalConfig.shape.metalCostPerGram.nonoptional(),
@@ -172,6 +175,10 @@ export function validateBackup(raw: unknown) {
throw new BadRequestException('图标关联无效');
const revisionIds = new Set<string>();
for (const p of b.positions) {
if (p.lastBookedDate && p.kind !== 'account')
throw new BadRequestException('仅账户支持当天记账标记');
if (p.lastRepaymentMonth && (p.kind !== 'account' || p.side !== 'liability'))
throw new BadRequestException('还款月份仅适用于欠款账户');
if (p.metalType || p.metalGrams || p.autoValuation || p.metalCostPerGram != null) {
if (p.kind !== 'asset' || p.category !== 'gold')
throw new BadRequestException('贵金属估价关联无效');
@@ -393,6 +400,8 @@ export class BackupBusinessService implements OnModuleDestroy, OnModuleInit {
archived: p.archived,
hidden: p.hidden,
included: p.included,
lastRepaymentMonth: p.lastRepaymentMonth,
lastBookedDate: p.lastBookedDate,
metalType: p.metalType,
metalGrams: p.metalGrams?.toString() ?? null,
metalCostPerGram: p.metalCostPerGram?.toString() ?? null,
@@ -700,6 +709,8 @@ export class BackupBusinessService implements OnModuleDestroy, OnModuleInit {
archived: p.archived,
hidden: p.hidden,
included: p.included,
lastRepaymentMonth: p.lastRepaymentMonth ?? null,
lastBookedDate: p.lastBookedDate ?? null,
metalType: p.metalType,
metalGrams: p.metalGrams,
metalCostPerGram: p.metalCostPerGram,
+6
View File
@@ -7,6 +7,9 @@ import {
credentials,
credentialChange,
positionInput,
repaymentMarkInput,
bookedMarkInput,
inclusionInput,
positionMeta,
revisionInput,
transferInput,
@@ -35,6 +38,9 @@ export function setupOpenApi(app: INestApplication) {
'POST /api/auth/reveal': z.object({ password: credentials.shape.password.optional() }).strict(),
'POST /api/positions': positionInput,
'PATCH /api/positions/{id}': positionMeta,
'PATCH /api/positions/{id}/repayment-mark': repaymentMarkInput,
'PATCH /api/positions/{id}/booked-mark': bookedMarkInput,
'PATCH /api/positions/{id}/inclusion': inclusionInput,
'POST /api/positions/{id}/revisions': revisionInput,
'PUT /api/positions/{id}/revisions/{revisionId}': revisionInput,
'PUT /api/positions/{id}/links': z
+86
View File
@@ -18,6 +18,9 @@ import { Database } from './database';
import { UserRequest } from './auth';
import {
positionInput,
repaymentMarkInput,
bookedMarkInput,
inclusionInput,
positionMeta,
revisionInput,
today,
@@ -158,6 +161,68 @@ export class PortfolioBusinessService {
});
return { ok: true };
}
async quickMeta(r: UserRequest, id: string, raw: unknown, operation: 'booked' | 'included') {
const v = operation === 'booked' ? bookedMarkInput.parse(raw) : inclusionInput.parse(raw);
return this.db.serial(async (tx) => {
await tx.$queryRaw(
Prisma.sql`SELECT id FROM Position WHERE id = ${id} AND userId = ${r.userId} FOR UPDATE`,
);
const p = await tx.position.findFirst({
where: { id, userId: r.userId, ...(r.revealed ? {} : { hidden: false }) },
});
if (!p) throw new NotFoundException('项目不存在');
if (operation === 'booked' && (p.kind !== 'account' || p.archived))
throw new BadRequestException('仅启用账户支持当天记账标记');
if (operation === 'included' && p.kind !== 'asset')
throw new BadRequestException('仅独立资产支持此快速统计开关');
if (v.expectedUpdatedAt && p.updatedAt.toISOString() !== v.expectedUpdatedAt)
throw new ConflictException('项目已变化,请刷新后重试');
if (
('expectedDate' in v && p.lastBookedDate !== v.expectedDate) ||
('expectedIncluded' in v && p.included !== v.expectedIncluded)
)
throw new ConflictException('标记已变化,请刷新后重试');
const updated = await tx.position.update({
where: { id },
data: 'date' in v ? { lastBookedDate: v.date } : { included: v.included },
});
return {
lastBookedDate: updated.lastBookedDate,
included: updated.included,
updatedAt: updated.updatedAt,
};
});
}
async repaymentMark(r: UserRequest, id: string, raw: unknown) {
const input = repaymentMarkInput.parse(raw);
return this.db.serial(async (tx) => {
await tx.$queryRaw(
Prisma.sql`SELECT id FROM Position WHERE id = ${id} AND userId = ${r.userId} FOR UPDATE`,
);
const p = await tx.position.findFirst({
where: { id, userId: r.userId, ...(r.revealed ? {} : { hidden: false }) },
});
if (!p) throw new NotFoundException('账户不存在');
if (p.kind !== 'account' || p.side !== 'liability')
throw new BadRequestException('仅欠款账户支持还款月份标记');
if (p.archived) throw new ConflictException('请先恢复归档账户');
if (
p.lastRepaymentMonth !== input.expectedMonth ||
(input.expectedUpdatedAt && p.updatedAt.toISOString() !== input.expectedUpdatedAt)
)
throw new ConflictException('还款标记已变化,请刷新后重试');
const updated = await tx.position.update({
where: { id },
data: { lastRepaymentMonth: input.month },
});
return {
lastRepaymentMonth: input.month,
previousMonth: p.lastRepaymentMonth,
updatedAt: updated.updatedAt.toISOString(),
};
});
}
async deletion(r: UserRequest, id: string) {
const p = await this.own(r.userId, id, r.revealed);
const [historyCount, movementCount, scheduleCount, linkCount] = await Promise.all([
@@ -408,6 +473,27 @@ export class PortfolioController {
) {
return this.service.edit(r, id, b);
}
@Patch('positions/:id/booked-mark') async bookedMark(
@Req() r: UserRequest,
@Param('id') id: string,
@Body() b: unknown,
) {
return this.service.quickMeta(r, id, b, 'booked');
}
@Patch('positions/:id/inclusion') async inclusion(
@Req() r: UserRequest,
@Param('id') id: string,
@Body() b: unknown,
) {
return this.service.quickMeta(r, id, b, 'included');
}
@Patch('positions/:id/repayment-mark') async repaymentMark(
@Req() r: UserRequest,
@Param('id') id: string,
@Body() b: unknown,
) {
return this.service.repaymentMark(r, id, b);
}
@Get('positions/:id/deletion') async deletion(@Req() r: UserRequest, @Param('id') id: string) {
return this.service.deletion(r, id);
}
+28
View File
@@ -217,3 +217,31 @@ export const settingsInput = z
})
.strict()
.refine((v) => Object.keys(v).length > 0);
export const repaymentMonth = z
.string()
.regex(/^(19|[2-9]\d)\d{2}-(0[1-9]|1[0-2])$/)
.refine((v) => v <= today().slice(0, 7), '不能标记未来还款月份')
.nullable();
export const repaymentMarkInput = z
.object({
month: repaymentMonth,
expectedMonth: repaymentMonth,
expectedUpdatedAt: z.iso.datetime().optional(),
})
.strict();
export const bookedMarkInput = z
.object({
date: date.nullable(),
expectedDate: date.nullable(),
expectedUpdatedAt: z.iso.datetime().optional(),
})
.strict();
export const inclusionInput = z
.object({
included: z.boolean(),
expectedIncluded: z.boolean(),
expectedUpdatedAt: z.iso.datetime().optional(),
})
.strict();
@@ -0,0 +1,269 @@
import 'dotenv/config';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { randomUUID, randomBytes, createHash } from 'node:crypto';
import { PrismaClient } from '@prisma/client';
import { today } from '../src/validation';
import { readBackupZip } from '../src/zip';
import { fixtureFetch } from './backup-fixture';
const base = process.env.TEST_API_URL || 'http://127.0.0.1:3100/api';
const origin = process.env.WEB_ORIGIN === '*' ? 'http://localhost:5173' : process.env.WEB_ORIGIN!;
test('quick entries undo paired repayment and balance, persist monthly marks, protect privacy and survive ZIP restore', async () => {
const db = new PrismaClient(),
users: string[] = [];
async function user() {
const u = await db.user.create({
data: { username: 'quick_' + randomUUID(), passwordHash: 'unused', idleMinutes: 0 },
});
users.push(u.id);
const token = randomBytes(32).toString('hex'),
sid = createHash('sha256').update(token).digest('hex');
await db.session.create({
data: { id: sid, userId: u.id, expiresAt: new Date(Date.now() + 3600000) },
});
return { id: u.id, cookie: 'wp_session=' + token, sid };
}
async function call(u: any, path: string, method = 'GET', data?: unknown) {
const r = await fixtureFetch(base + path, {
method,
headers: {
Cookie: u.cookie,
Origin: origin,
...(data ? { 'Content-Type': 'application/json' } : {}),
},
body: data ? JSON.stringify(data) : undefined,
});
return {
status: r.status,
data: r.headers.get('content-type')?.includes('application/zip')
? await readBackupZip(Buffer.from(await r.arrayBuffer()))
: await r.json(),
};
}
try {
const a = await user(),
b = await user();
const create = async (
name: string,
kind: string,
side: string,
category: string,
amount: string,
hidden = false,
) => {
const r = await call(a, '/positions', 'POST', {
name,
kind,
side,
category,
amount,
hidden,
currency: 'CNY',
date: '2026-09-01T10:00',
});
assert.equal(r.status, 201);
return r.data.id as string;
};
const cash = await create('付款账户', 'account', 'asset', 'bank', '1000');
const card = await create('欠款账户', 'account', 'liability', 'credit_card', '200');
for (const category of ['commemorative_coin', 'commemorative_note']) {
const id = await create(category, 'asset', 'asset', category, '50');
assert.equal((await call(a, '/positions/' + id)).data.category, category);
}
const coin = (await db.position.findFirst({
where: { userId: a.id, category: 'commemorative_coin' },
}))!;
const inclusionPath = '/positions/' + coin.id + '/inclusion';
assert.equal(
(await call(b, inclusionPath, 'PATCH', { included: false, expectedIncluded: true })).status,
404,
);
assert.equal(
(
await call(a, inclusionPath, 'PATCH', {
included: false,
expectedIncluded: true,
expectedUpdatedAt: coin.updatedAt.toISOString(),
})
).status,
200,
);
assert.equal((await call(a, '/positions/' + coin.id)).data.included, false);
assert.equal(
(await call(a, inclusionPath, 'PATCH', { included: true, expectedIncluded: true })).status,
409,
);
assert.equal(
(
await call(a, '/positions/' + cash + '/inclusion', 'PATCH', {
included: false,
expectedIncluded: true,
})
).status,
400,
);
const bookedPath = '/positions/' + cash + '/booked-mark',
day = today();
const booked = await call(a, bookedPath, 'PATCH', { date: day, expectedDate: null });
assert.equal(booked.status, 200);
assert.equal((await call(a, '/positions/' + cash)).data.lastBookedDate, day);
assert.equal(
(await call(a, bookedPath, 'PATCH', { date: null, expectedDate: null })).status,
409,
);
assert.equal(
(await call(b, bookedPath, 'PATCH', { date: null, expectedDate: day })).status,
404,
);
assert.equal(
(await call(a, bookedPath, 'PATCH', { date: '2099-01-01', expectedDate: day })).status,
400,
);
assert.equal(
(
await call(a, bookedPath, 'PATCH', {
date: null,
expectedDate: day,
expectedUpdatedAt: booked.data.updatedAt,
})
).status,
200,
);
assert.equal(
(await call(a, bookedPath, 'PATCH', { date: day, expectedDate: null })).status,
200,
);
assert.equal(
(
await call(a, '/positions/' + coin.id + '/booked-mark', 'PATCH', {
date: day,
expectedDate: null,
})
).status,
400,
);
const revision = await call(a, '/positions/' + cash + '/revisions', 'POST', {
amount: '1050.87654321',
date: '2026-09-02T10:00',
});
assert.equal(revision.status, 201);
assert.equal(
(await call(a, '/positions/' + cash + '/revisions/' + revision.data.id, 'DELETE')).status,
200,
);
assert.equal((await call(a, '/positions/' + cash)).data.amount, '1000');
const payment = await call(a, '/transfers', 'POST', {
sourceId: cash,
targetId: card,
amount: '30',
received: '30',
fee: '0',
date: '2026-09-03T10:00',
requestId: randomUUID(),
});
assert.equal(payment.status, 201);
assert.equal((await call(a, '/positions/' + cash)).data.amount, '970');
assert.equal((await call(a, '/positions/' + card)).data.amount, '170');
assert.equal((await call(a, '/transfers/' + payment.data.id, 'DELETE')).status, 200);
assert.equal((await call(a, '/positions/' + cash)).data.amount, '1000');
assert.equal((await call(a, '/positions/' + card)).data.amount, '200');
const month = today().slice(0, 7),
path = '/positions/' + card + '/repayment-mark';
assert.equal((await call(b, path, 'PATCH', { month, expectedMonth: null })).status, 404);
assert.equal(
(
await call(a, '/positions/' + cash + '/repayment-mark', 'PATCH', {
month,
expectedMonth: null,
})
).status,
400,
);
assert.equal(
(await call(a, path, 'PATCH', { month: '2099-01', expectedMonth: null })).status,
400,
);
const before = await call(a, '/positions/' + card);
const marked = await call(a, path, 'PATCH', {
month,
expectedMonth: null,
expectedUpdatedAt: before.data.updatedAt,
});
assert.equal(marked.status, 200);
assert.equal((await call(a, '/positions/' + card)).data.lastRepaymentMonth, month);
assert.equal((await call(a, '/positions/' + card)).data.amount, '200');
assert.equal((await call(a, path, 'PATCH', { month: null, expectedMonth: null })).status, 409);
const restored = await call(a, path, 'PATCH', {
month: null,
expectedMonth: month,
expectedUpdatedAt: marked.data.updatedAt,
});
assert.equal(restored.status, 200);
assert.equal((await call(a, '/positions/' + card)).data.lastRepaymentMonth, null);
await call(a, path, 'PATCH', { month, expectedMonth: null });
assert.equal(
(
await call(a, path, 'PATCH', {
month: null,
expectedMonth: month,
expectedUpdatedAt: marked.data.updatedAt,
})
).status,
409,
);
const old = '2026-09';
const changed = await call(a, path, 'PATCH', { month: old, expectedMonth: month });
assert.equal(changed.status, 200);
assert.equal((await call(a, '/positions/' + card)).data.lastRepaymentMonth, old);
const hidden = await create('隐藏欠款', 'account', 'liability', 'loan', '5', true);
assert.equal(
(
await call(a, '/positions/' + hidden + '/repayment-mark', 'PATCH', {
month,
expectedMonth: null,
})
).status,
404,
);
await db.session.update({
where: { id: a.sid },
data: { revealUntil: new Date(Date.now() + 600000) },
});
assert.equal(
(
await call(a, '/positions/' + hidden + '/repayment-mark', 'PATCH', {
month,
expectedMonth: null,
})
).status,
200,
);
await db.position.update({ where: { id: hidden }, data: { archived: true } });
assert.equal(
(
await call(a, '/positions/' + hidden + '/repayment-mark', 'PATCH', {
month: null,
expectedMonth: month,
})
).status,
409,
);
const backup = await call(a, '/backup');
assert.equal(backup.status, 200);
assert.equal(backup.data.positions.find((p: any) => p.id === card).lastRepaymentMonth, old);
const imported = await call(b, '/backup/restore-fixture', 'POST', {
confirmed: true,
backup: backup.data,
});
assert.equal(imported.status, 201);
const rows = await db.position.findMany({ where: { userId: b.id } });
assert.equal(rows.find((p) => p.name === '欠款账户')?.lastRepaymentMonth, old);
assert.equal(rows.find((p) => p.name === '隐藏欠款')?.lastRepaymentMonth, month);
assert.equal(rows.find((p) => p.name === '付款账户')?.lastBookedDate, day);
assert.equal(rows.find((p) => p.category === 'commemorative_coin')?.included, false);
} finally {
await db.user.deleteMany({ where: { id: { in: users } } });
await db.$disconnect();
}
});