feat: add account transfers and refine icons, settings and safety dialogs
This commit is contained in:
1 parent
a4e9d56b8a
commit
da98d02661
33 files changed
+1866
-347
No files matched your search
Binary file not shown.
|
Before Width: | Height: | Size: 926 B After Width: | Height: | Size: 4.6 KiB |
@@ -103,9 +103,9 @@
|
||||
},
|
||||
{
|
||||
"name": "支付宝",
|
||||
"source": "https://i.alipayobjects.com/common/favicon/favicon.ico",
|
||||
"source": "https://raw.githubusercontent.com/simple-icons/simple-icons/develop/icons/alipay.svg",
|
||||
"file": "18.png",
|
||||
"sha256": "b662de58b15b34d1bf4d2a8bc546f7062a3faaa22acd2ecbbbad70f1e7f37a39"
|
||||
"sha256": "8049dde7772116e573864e0d3fab1fd5078c75f88e90dc01f70f63a789889a1a"
|
||||
},
|
||||
{
|
||||
"name": "微信",
|
||||
|
||||
@@ -9,13 +9,14 @@
|
||||
"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:integration": "tsx --test --test-concurrency=1 test/integration.test.ts test/privacy.test.ts test/icons.test.ts test/transfers.test.ts",
|
||||
"icons:seed": "node scripts/seed-icons.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.0",
|
||||
"@nestjs/core": "^11.0.0",
|
||||
"@nestjs/platform-express": "^11.0.0",
|
||||
"@nestjs/swagger": "11.2.6",
|
||||
"@prisma/client": "6.19.0",
|
||||
"archiver": "^8.0.0",
|
||||
"bcryptjs": "^3.0.0",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
ALTER TABLE `User` ADD COLUMN `hiddenMenus` VARCHAR(128) NOT NULL DEFAULT '', DROP COLUMN `showSidebar`;
|
||||
CREATE TABLE `Transfer` (
|
||||
`id` CHAR(36) NOT NULL, `importedFromId` CHAR(36) NULL, `userId` CHAR(36) NOT NULL,
|
||||
`sourceId` CHAR(36) NOT NULL, `targetId` CHAR(36) NOT NULL,
|
||||
`sourceRevisionId` CHAR(36) NOT NULL, `targetRevisionId` CHAR(36) NOT NULL,
|
||||
`sourceCurrency` CHAR(3) NOT NULL, `targetCurrency` CHAR(3) NOT NULL,
|
||||
`amount` DECIMAL(24,8) NOT NULL, `received` DECIMAL(24,8) NOT NULL, `fee` DECIMAL(24,8) NOT NULL,
|
||||
`effectiveDate` DATETIME(3) NOT NULL, `notes` TEXT NOT NULL, `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`), UNIQUE INDEX `Transfer_sourceRevisionId_key` (`sourceRevisionId`), UNIQUE INDEX `Transfer_targetRevisionId_key` (`targetRevisionId`),
|
||||
UNIQUE INDEX `Transfer_userId_importedFromId_key` (`userId`,`importedFromId`), INDEX `Transfer_userId_effectiveDate_idx` (`userId`,`effectiveDate`),
|
||||
CONSTRAINT `Transfer_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `Transfer_sourceId_fkey` FOREIGN KEY (`sourceId`) REFERENCES `Position` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `Transfer_targetId_fkey` FOREIGN KEY (`targetId`) REFERENCES `Position` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `User` ADD COLUMN `showNotes` BOOLEAN NOT NULL DEFAULT true;
|
||||
@@ -10,7 +10,8 @@ model User {
|
||||
username String @unique @db.VarChar(64)
|
||||
passwordHash String @db.VarChar(255)
|
||||
baseCurrency String @default("CNY") @db.Char(3)
|
||||
showSidebar Boolean @default(true)
|
||||
hiddenMenus String @default("") @db.VarChar(128)
|
||||
showNotes Boolean @default(true)
|
||||
idleMinutes Int @default(30)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -18,6 +19,7 @@ model User {
|
||||
rates ExchangeRate[]
|
||||
sessions Session[]
|
||||
icons Icon[]
|
||||
transfers Transfer[]
|
||||
}
|
||||
model Session {
|
||||
id String @id @db.Char(64)
|
||||
@@ -50,6 +52,8 @@ model Position {
|
||||
revisions Revision[]
|
||||
outgoing PositionLink[] @relation("Source")
|
||||
incoming PositionLink[] @relation("Target")
|
||||
transfersOut Transfer[] @relation("TransferSource")
|
||||
transfersIn Transfer[] @relation("TransferTarget")
|
||||
@@index([userId,kind])
|
||||
@@unique([userId,importedFromId])
|
||||
}
|
||||
@@ -100,3 +104,26 @@ model Icon {
|
||||
@@unique([ownerId,hash,shared])
|
||||
@@index([shared,name])
|
||||
}
|
||||
|
||||
model Transfer {
|
||||
id String @id @default(uuid()) @db.Char(36)
|
||||
importedFromId String? @db.Char(36)
|
||||
userId String @db.Char(36)
|
||||
user User @relation(fields:[userId],references:[id],onDelete:Cascade)
|
||||
sourceId String @db.Char(36)
|
||||
targetId String @db.Char(36)
|
||||
source Position @relation("TransferSource",fields:[sourceId],references:[id],onDelete:Cascade)
|
||||
target Position @relation("TransferTarget",fields:[targetId],references:[id],onDelete:Cascade)
|
||||
sourceRevisionId String @unique @db.Char(36)
|
||||
targetRevisionId String @unique @db.Char(36)
|
||||
sourceCurrency String @db.Char(3)
|
||||
targetCurrency String @db.Char(3)
|
||||
amount Decimal @db.Decimal(24,8)
|
||||
received Decimal @db.Decimal(24,8)
|
||||
fee Decimal @db.Decimal(24,8)
|
||||
effectiveDate DateTime @db.DateTime(3)
|
||||
notes String @db.Text
|
||||
createdAt DateTime @default(now())
|
||||
@@unique([userId,importedFromId])
|
||||
@@index([userId,effectiveDate])
|
||||
}
|
||||
@@ -33,7 +33,7 @@ async function main() {
|
||||
source: banks.find((b) => b.name === name + '@3x.png')?.download_url,
|
||||
}));
|
||||
sources.push(
|
||||
{ name: '支付宝', source: 'https://i.alipayobjects.com/common/favicon/favicon.ico' },
|
||||
{ name: '支付宝', source: 'https://raw.githubusercontent.com/simple-icons/simple-icons/develop/icons/alipay.svg' },
|
||||
{ name: '微信', source: 'https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico' },
|
||||
{ name: '京东金融', source: 'https://jr.jd.com/logo.png' },
|
||||
);
|
||||
@@ -43,6 +43,9 @@ async function main() {
|
||||
const res = await fetch(item.source, { signal: AbortSignal.timeout(20000) });
|
||||
if (!res.ok) throw Error('Public icon download failed');
|
||||
const raw = Buffer.from(await res.arrayBuffer());
|
||||
// Alipay's catalog SVG is an inverse mark. Mask within the glyph bounds to omit its frame.
|
||||
const glyphPath = item.name === '支付宝' ? raw.toString().match(/<path d="([^"]+)"/)[1] : '';
|
||||
const rasterSource = item.name === '支付宝' ? Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><mask id="glyph"><rect x="1.5" y="3.17" width="22.3" height="17" fill="white"/><path d="${glyphPath}" fill="black"/></mask></defs><rect width="24" height="24" fill="#1677ff" mask="url(#glyph)"/></svg>`) : raw;
|
||||
const file =
|
||||
String(manifest.length + 1).padStart(2, '0') +
|
||||
(item.source.endsWith('.ico') ? '.ico' : '.png');
|
||||
@@ -50,7 +53,7 @@ async function main() {
|
||||
else
|
||||
await fs.writeFile(
|
||||
path.join(dir, file),
|
||||
await sharp(raw)
|
||||
await sharp(rasterSource, { density: 768 })
|
||||
.resize(256, 256, { fit: 'inside', withoutEnlargement: true })
|
||||
.png()
|
||||
.toBuffer(),
|
||||
|
||||
@@ -3,17 +3,15 @@ const { PrismaClient } = require('@prisma/client');
|
||||
const { readFile } = require('node:fs/promises');
|
||||
const { join } = require('node:path');
|
||||
const { createHash } = require('node:crypto');
|
||||
const sharp = require('sharp');
|
||||
require('reflect-metadata');
|
||||
const { normalizeIcon } = require('../dist/icons');
|
||||
const db = new PrismaClient();
|
||||
async function main() {
|
||||
const dir = join(__dirname, '../assets/icons');
|
||||
const sources = JSON.parse(await readFile(join(dir, 'sources.json'), 'utf8'));
|
||||
// Deterministic IDs make repeated runs safe, without overwriting existing records.
|
||||
// Update only deterministic built-in image IDs; preserve user uploads and financial data.
|
||||
for (const item of sources) {
|
||||
const data = await sharp(await readFile(join(dir, item.file)))
|
||||
.resize(256, 256, { fit: 'inside', withoutEnlargement: true })
|
||||
.png()
|
||||
.toBuffer();
|
||||
const data = await normalizeIcon(await readFile(join(dir, item.file)));
|
||||
const hex = createHash('sha256')
|
||||
.update('worthpath-builtin:' + item.name)
|
||||
.digest('hex');
|
||||
@@ -28,7 +26,7 @@ async function main() {
|
||||
source: item.source,
|
||||
hash: createHash('sha256').update(data).digest('hex'),
|
||||
},
|
||||
update: {},
|
||||
update: { data, source: item.source, hash: createHash('sha256').update(data).digest('hex') },
|
||||
});
|
||||
}
|
||||
console.log(`Shared icon catalog ready: ${sources.length} icons.`);
|
||||
|
||||
@@ -156,10 +156,17 @@ export class AuthController {
|
||||
return { username: user.username, baseCurrency: user.baseCurrency };
|
||||
}
|
||||
@Get('auth/me') async me(@Req() req: UserRequest) {
|
||||
return this.db.user.findUniqueOrThrow({
|
||||
const user = await this.db.user.findUniqueOrThrow({
|
||||
where: { id: req.userId },
|
||||
select: { username: true, baseCurrency: true, showSidebar: true, idleMinutes: true },
|
||||
select: {
|
||||
username: true,
|
||||
baseCurrency: true,
|
||||
hiddenMenus: true,
|
||||
showNotes: true,
|
||||
idleMinutes: true,
|
||||
},
|
||||
});
|
||||
return { ...user, hiddenMenus: user.hiddenMenus.split(',').filter(Boolean) };
|
||||
}
|
||||
@Post('auth/activity') async activity(@Req() r: UserRequest) {
|
||||
await this.db.session.update({
|
||||
|
||||
+134
-6
@@ -25,7 +25,15 @@ import { Prisma } from '@prisma/client';
|
||||
import Decimal from 'decimal.js';
|
||||
import { Database } from './database';
|
||||
import { UserRequest } from './auth';
|
||||
import { positionInput, positionMeta, currency, revisionInput, rateInput } from './validation';
|
||||
import {
|
||||
positionInput,
|
||||
positionMeta,
|
||||
currency,
|
||||
revisionInput,
|
||||
rateInput,
|
||||
hiddenMenus,
|
||||
transferInput,
|
||||
} from './validation';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { toBusinessDate } from './validation';
|
||||
import { iconName, validateStoredIcon } from './icons';
|
||||
@@ -65,7 +73,12 @@ const backupSchema = z
|
||||
baseCurrency: currency,
|
||||
currencies: z.array(currency).max(10),
|
||||
preferences: z
|
||||
.object({ showSidebar: z.boolean(), idleMinutes: z.number().int().min(0).max(1440) })
|
||||
.object({
|
||||
showSidebar: z.boolean().optional(),
|
||||
hiddenMenus: hiddenMenus.optional(),
|
||||
showNotes: z.boolean().optional(),
|
||||
idleMinutes: z.number().int().min(0).max(1440),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
icons: z
|
||||
@@ -81,6 +94,19 @@ const backupSchema = z
|
||||
.strict(),
|
||||
)
|
||||
.optional(),
|
||||
transfers: z
|
||||
.array(
|
||||
transferInput.safeExtend({
|
||||
id: z.string().uuid(),
|
||||
importedFromId: z.string().uuid().nullable().optional(),
|
||||
sourceRevisionId: z.string().uuid(),
|
||||
targetRevisionId: z.string().uuid(),
|
||||
sourceCurrency: currency,
|
||||
targetCurrency: currency,
|
||||
createdAt: timestamp,
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
positions: z.array(record),
|
||||
links: z.array(z.object({ sourceId: z.string().uuid(), targetId: z.string().uuid() }).strict()),
|
||||
rates: z.array(rateInput.safeExtend({ source: z.enum(['manual', 'frankfurter']) })),
|
||||
@@ -122,6 +148,57 @@ export function validateBackup(raw: unknown) {
|
||||
}
|
||||
if (!b.currencies.includes(p.currency)) throw new BadRequestException('币种清单不完整');
|
||||
}
|
||||
const transferIds = new Set<string>(),
|
||||
usedRevisions = new Set<string>();
|
||||
for (const t of b.transfers || []) {
|
||||
const source = ids.get(t.sourceId),
|
||||
target = ids.get(t.targetId);
|
||||
const origin = t.importedFromId || t.id;
|
||||
if (
|
||||
transferIds.has(origin) ||
|
||||
!source ||
|
||||
!target ||
|
||||
source.kind !== 'account' ||
|
||||
target.kind !== 'account' ||
|
||||
source.side !== 'asset' ||
|
||||
target.side !== 'asset' ||
|
||||
source.currency !== t.sourceCurrency ||
|
||||
target.currency !== t.targetCurrency
|
||||
)
|
||||
throw new BadRequestException('转账关联无效');
|
||||
transferIds.add(origin);
|
||||
if (t.sourceCurrency === t.targetCurrency && !new Decimal(t.amount).eq(t.received))
|
||||
throw new BadRequestException('同币种转账金额不一致');
|
||||
for (const [p, revId, reason, delta] of [
|
||||
[source, t.sourceRevisionId, 'transfer_out', new Decimal(t.amount).plus(t.fee).neg()],
|
||||
[target, t.targetRevisionId, 'transfer_in', new Decimal(t.received)],
|
||||
] as const) {
|
||||
const ordered = [...p.revisions].sort(
|
||||
(a, b) =>
|
||||
a.date.localeCompare(b.date) ||
|
||||
(a.sequence || 0) - (b.sequence || 0) ||
|
||||
a.createdAt.localeCompare(b.createdAt),
|
||||
);
|
||||
const index = ordered.findIndex((r) => r.id === revId),
|
||||
current = ordered[index];
|
||||
if (
|
||||
usedRevisions.has(revId) ||
|
||||
index < 1 ||
|
||||
!current ||
|
||||
current.reason !== reason ||
|
||||
current.date !== t.date ||
|
||||
!new Decimal(current.amount).minus(ordered[index - 1].amount).eq(delta)
|
||||
)
|
||||
throw new BadRequestException('转账历史与双方金额不一致');
|
||||
usedRevisions.add(revId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
b.positions.some((p) =>
|
||||
p.revisions.some((r) => r.reason.startsWith('transfer_') && !usedRevisions.has(r.id)),
|
||||
)
|
||||
)
|
||||
throw new BadRequestException('缺少配对转账记录');
|
||||
const links = new Set<string>();
|
||||
for (const l of b.links) {
|
||||
const s = ids.get(l.sourceId),
|
||||
@@ -187,7 +264,7 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
const [user, ps, rates] = await Promise.all([
|
||||
client.user.findUniqueOrThrow({
|
||||
where: { id: userId },
|
||||
select: { baseCurrency: true, showSidebar: true, idleMinutes: true },
|
||||
select: { baseCurrency: true, hiddenMenus: true, showNotes: true, idleMinutes: true },
|
||||
}),
|
||||
client.position.findMany({
|
||||
where: { userId },
|
||||
@@ -234,12 +311,17 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
],
|
||||
},
|
||||
});
|
||||
const transfers = await client.transfer.findMany({ where: { userId } });
|
||||
return backupSchema.parse({
|
||||
format: 'worthpath',
|
||||
version: 2,
|
||||
exportedAt: new Date().toISOString(),
|
||||
baseCurrency: user.baseCurrency,
|
||||
preferences: { showSidebar: user.showSidebar, idleMinutes: user.idleMinutes },
|
||||
preferences: {
|
||||
hiddenMenus: user.hiddenMenus.split(',').filter(Boolean),
|
||||
showNotes: user.showNotes,
|
||||
idleMinutes: user.idleMinutes,
|
||||
},
|
||||
currencies: [
|
||||
...new Set([
|
||||
user.baseCurrency,
|
||||
@@ -254,6 +336,14 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
hash: i.hash,
|
||||
image: Buffer.from(i.data).toString('base64'),
|
||||
})),
|
||||
transfers: transfers.map(({ userId, effectiveDate, ...t }) => ({
|
||||
...t,
|
||||
amount: t.amount.toString(),
|
||||
received: t.received.toString(),
|
||||
fee: t.fee.toString(),
|
||||
date: businessTime(effectiveDate),
|
||||
createdAt: t.createdAt.toISOString(),
|
||||
})),
|
||||
positions,
|
||||
links: ps.flatMap((p) =>
|
||||
p.outgoing.map((l) => ({ sourceId: l.sourceId, targetId: l.targetId })),
|
||||
@@ -353,6 +443,7 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
(a.currency + a.baseCurrency + a.date).localeCompare(b.currency + b.baseCurrency + b.date),
|
||||
);
|
||||
data.currencies.sort();
|
||||
data.transfers?.sort((a, b) => a.id.localeCompare(b.id));
|
||||
data.icons?.sort((a, b) => a.id.localeCompare(b.id));
|
||||
return createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
||||
}
|
||||
@@ -393,6 +484,7 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
revisions: b.positions.reduce((n, p) => n + p.revisions.length, 0),
|
||||
rates: b.rates.length,
|
||||
icons: (b.icons || []).length,
|
||||
transfers: (b.transfers || []).length,
|
||||
baseCurrency: b.baseCurrency,
|
||||
currentBaseCurrency: existing.baseCurrency,
|
||||
message:
|
||||
@@ -458,7 +550,8 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
});
|
||||
iconMapping.set(i.id, row.id);
|
||||
}
|
||||
const mapping = new Map<string, string>();
|
||||
const mapping = new Map<string, string>(),
|
||||
revisionMapping = new Map<string, string>();
|
||||
for (const p of b.positions) {
|
||||
const row = await tx.position.create({
|
||||
data: {
|
||||
@@ -495,7 +588,37 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
},
|
||||
});
|
||||
mapping.set(p.id, row.id);
|
||||
const originals = [...p.revisions].sort(
|
||||
(a, b) =>
|
||||
a.date.localeCompare(b.date) ||
|
||||
(a.sequence || 0) - (b.sequence || 0) ||
|
||||
a.createdAt.localeCompare(b.createdAt),
|
||||
);
|
||||
const restored = await tx.revision.findMany({
|
||||
where: { positionId: row.id },
|
||||
orderBy: { sequence: 'asc' },
|
||||
});
|
||||
originals.forEach((v, i) => revisionMapping.set(v.id, restored[i].id));
|
||||
}
|
||||
for (const t of b.transfers || [])
|
||||
await tx.transfer.create({
|
||||
data: {
|
||||
userId: r.userId,
|
||||
importedFromId: t.importedFromId || t.id,
|
||||
sourceId: mapping.get(t.sourceId)!,
|
||||
targetId: mapping.get(t.targetId)!,
|
||||
sourceRevisionId: revisionMapping.get(t.sourceRevisionId)!,
|
||||
targetRevisionId: revisionMapping.get(t.targetRevisionId)!,
|
||||
sourceCurrency: t.sourceCurrency,
|
||||
targetCurrency: t.targetCurrency,
|
||||
amount: t.amount,
|
||||
received: t.received,
|
||||
fee: t.fee,
|
||||
effectiveDate: toBusinessDate(t.date),
|
||||
notes: t.notes,
|
||||
createdAt: new Date(t.createdAt),
|
||||
},
|
||||
});
|
||||
for (const l of b.links)
|
||||
await tx.positionLink.create({
|
||||
data: { sourceId: mapping.get(l.sourceId)!, targetId: mapping.get(l.targetId)! },
|
||||
@@ -516,7 +639,12 @@ export class BackupController implements OnModuleDestroy, OnModuleInit {
|
||||
if (!ps.length && !rs.length)
|
||||
await tx.user.update({
|
||||
where: { id: r.userId },
|
||||
data: { baseCurrency: b.baseCurrency, ...b.preferences },
|
||||
data: {
|
||||
baseCurrency: b.baseCurrency,
|
||||
idleMinutes: b.preferences?.idleMinutes,
|
||||
hiddenMenus: b.preferences?.hiddenMenus?.join(','),
|
||||
showNotes: b.preferences?.showNotes,
|
||||
},
|
||||
});
|
||||
return { ok: true, positions: b.positions.length };
|
||||
},
|
||||
|
||||
+13
-2
@@ -32,9 +32,20 @@ export async function normalizeIcon(data: Buffer) {
|
||||
const meta = await image.metadata();
|
||||
if (!['png', 'jpeg', 'webp'].includes(meta.format || '') || (meta.pages || 1) > 1)
|
||||
throw Error();
|
||||
return await image
|
||||
const resized = await image
|
||||
.rotate()
|
||||
.resize(256, 256, { fit: 'inside', withoutEnlargement: true })
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
// Neutral white logo backgrounds become transparent; coloured marks remain unchanged.
|
||||
const { data: pixels, info } = resized;
|
||||
for (let i = 0; i < pixels.length; i += 4) {
|
||||
const low = Math.min(pixels[i], pixels[i + 1], pixels[i + 2]);
|
||||
const high = Math.max(pixels[i], pixels[i + 1], pixels[i + 2]);
|
||||
if (low >= 245 && high - low <= 8) pixels[i + 3] = 0;
|
||||
}
|
||||
return await sharp(pixels, { raw: { width: info.width, height: info.height, channels: 4 } })
|
||||
.png()
|
||||
.toBuffer();
|
||||
} catch {
|
||||
@@ -95,7 +106,7 @@ export class IconsController {
|
||||
if (!icon) throw new NotFoundException('图标不存在');
|
||||
res.setHeader('Content-Type', 'image/png');
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.send(Buffer.from(icon.data));
|
||||
res.send(await normalizeIcon(Buffer.from(icon.data)));
|
||||
}
|
||||
@Post('upload')
|
||||
@UseInterceptors(
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import 'reflect-metadata';
|
||||
import 'dotenv/config';
|
||||
import { setupOpenApi } from './openapi';
|
||||
import { Module, Catch, ArgumentsHost, ExceptionFilter, HttpException } from '@nestjs/common';
|
||||
import { NestFactory, APP_GUARD } from '@nestjs/core';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import helmet from 'helmet';
|
||||
import { json } from 'express';
|
||||
import { AuthController, AuthGuard, AuthService } from './auth';
|
||||
import { TransfersController } from './transfers';
|
||||
import { PortfolioController } from './portfolio';
|
||||
import { BackupController } from './backup';
|
||||
import { IconsController, IconsService } from './icons';
|
||||
@@ -50,6 +52,7 @@ class SafeErrors implements ExceptionFilter {
|
||||
{ provide: APP_GUARD, useClass: AuthGuard },
|
||||
],
|
||||
controllers: [
|
||||
TransfersController,
|
||||
IconsController,
|
||||
AuthController,
|
||||
PortfolioController,
|
||||
@@ -74,6 +77,7 @@ async function bootstrap() {
|
||||
next();
|
||||
});
|
||||
app.useGlobalFilters(new SafeErrors());
|
||||
setupOpenApi(app);
|
||||
app.enableShutdownHooks();
|
||||
await app.listen(Number(process.env.PORT || 3100), '0.0.0.0');
|
||||
console.log('WorthPath API ready');
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
credentials,
|
||||
positionInput,
|
||||
positionMeta,
|
||||
revisionInput,
|
||||
transferInput,
|
||||
currency,
|
||||
hiddenMenus,
|
||||
} from './validation';
|
||||
export function setupOpenApi(app: INestApplication) {
|
||||
const document = SwaggerModule.createDocument(
|
||||
app,
|
||||
new DocumentBuilder()
|
||||
.setTitle('WorthPath API')
|
||||
.setVersion('1.1')
|
||||
.setDescription(
|
||||
'个人资产管理接口。金额使用十进制字符串;登录会话由 HttpOnly Cookie 传递,数据归属由服务端验证。',
|
||||
)
|
||||
.addCookieAuth('wp_session', { type: 'apiKey', in: 'cookie' }, 'session')
|
||||
.addSecurityRequirements('session')
|
||||
.build(),
|
||||
);
|
||||
const bodies: Record<string, z.ZodType> = {
|
||||
'POST /api/auth/register': credentials,
|
||||
'POST /api/auth/login': credentials,
|
||||
'POST /api/auth/reveal': credentials.pick({ password: true }),
|
||||
'POST /api/positions': positionInput,
|
||||
'PATCH /api/positions/{id}': positionMeta,
|
||||
'POST /api/positions/{id}/revisions': revisionInput,
|
||||
'PUT /api/positions/{id}/revisions/{revisionId}': revisionInput,
|
||||
'PUT /api/positions/{id}/links': z
|
||||
.object({ targetIds: z.array(z.string().uuid()).max(20) })
|
||||
.strict(),
|
||||
'POST /api/transfers': transferInput,
|
||||
'PATCH /api/settings': z
|
||||
.object({
|
||||
baseCurrency: currency.optional(),
|
||||
hiddenMenus: hiddenMenus.optional(),
|
||||
showNotes: z.boolean().optional(),
|
||||
idleMinutes: z.number().int().min(0).max(1440).optional(),
|
||||
})
|
||||
.strict(),
|
||||
'POST /api/backup/clear': z.object({ confirmation: z.literal('确定清空') }),
|
||||
'POST /api/backup/import-file': z.object({
|
||||
token: z.string().uuid(),
|
||||
confirmed: z.literal(true),
|
||||
}),
|
||||
};
|
||||
for (const [path, entry] of Object.entries(document.paths)) {
|
||||
for (const method of ['get', 'post', 'patch', 'put'] as const) {
|
||||
const operation = entry[method];
|
||||
if (!operation) continue;
|
||||
operation.summary = `${method.toUpperCase()} ${path}`;
|
||||
if (path === '/api/health' || ['/api/auth/register', '/api/auth/login'].includes(path))
|
||||
operation.security = [];
|
||||
const schema = bodies[method.toUpperCase() + ' ' + path];
|
||||
if (schema)
|
||||
operation.requestBody = {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: z.toJSONSchema(schema, { target: 'openapi-3.0' }) as any,
|
||||
},
|
||||
},
|
||||
};
|
||||
operation.responses['400'] = {
|
||||
description: '请求格式、金额或业务校验失败,返回 { message }',
|
||||
};
|
||||
operation.responses['401'] = { description: '未登录或会话失效' };
|
||||
operation.responses['403'] = { description: '请求来源或访问权限不受信任' };
|
||||
operation.responses['409'] = { description: '数据冲突或业务记录不可修改' };
|
||||
if (path === '/api/backup' && method === 'get')
|
||||
operation.responses['200'] = {
|
||||
description: '该用户全部数据的 ZIP 文件',
|
||||
content: { 'application/zip': { schema: { type: 'string', format: 'binary' } } },
|
||||
};
|
||||
if (path === '/api/backup/upload' || path === '/api/icons/upload') {
|
||||
const properties = {
|
||||
file: { type: 'string', format: 'binary' },
|
||||
...(path.includes('icons')
|
||||
? {
|
||||
name: { type: 'string', description: '共享图标必须包含中文' },
|
||||
shared: { type: 'string', enum: ['false', 'true'], default: 'false' },
|
||||
confirmed: { type: 'string', enum: ['true'], description: '共享发布必须确认' },
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
operation.requestBody = {
|
||||
required: true,
|
||||
content: {
|
||||
'multipart/form-data': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: path.includes('icons') ? ['file', 'name'] : ['file'],
|
||||
properties: properties as any,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (['/api/backup/preview', '/api/backup/import'].includes(path))
|
||||
operation.requestBody = {
|
||||
required: true,
|
||||
description: '旧版 JSON 兼容入口;新版请使用 upload + import-file(支持完整 ZIP 备份)',
|
||||
content: {
|
||||
'application/json': { schema: { type: 'object', additionalProperties: true } },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
SwaggerModule.setup('api/docs', app, document, {
|
||||
jsonDocumentUrl: 'api/openapi.json',
|
||||
swaggerOptions: { persistAuthorization: false, validatorUrl: null, withCredentials: true },
|
||||
});
|
||||
}
|
||||
+42
-14
@@ -102,6 +102,7 @@ export class PortfolioController {
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
const v = revisionInput.parse(b);
|
||||
if (v.reason.startsWith('transfer_')) throw new BadRequestException('请使用账户转账接口');
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const p = await tx.position.findFirst({
|
||||
@@ -109,6 +110,12 @@ export class PortfolioController {
|
||||
});
|
||||
if (!p) throw new NotFoundException('项目不存在');
|
||||
if (p.archived) throw new ConflictException('请先恢复归档项目');
|
||||
const lastTransfer = await tx.revision.findFirst({
|
||||
where: { positionId: p.id, reason: { in: ['transfer_out', 'transfer_in'] } },
|
||||
orderBy: [{ effectiveDate: 'desc' }, { sequence: 'desc' }],
|
||||
});
|
||||
if (lastTransfer && toBusinessDate(v.date) < lastTransfer.effectiveDate)
|
||||
throw new ConflictException('余额调整时间不能早于已有转账;请使用当前时间调整');
|
||||
if (v.reason === 'repayment') {
|
||||
if (p.side !== 'liability') throw new BadRequestException('还款记录只能用于负债');
|
||||
const prior = await tx.revision.findFirst({
|
||||
@@ -137,22 +144,43 @@ export class PortfolioController {
|
||||
@Param('revisionId') revisionId: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
const v = revisionInput.parse(b),
|
||||
p = await this.own(r.userId, id, r.revealed);
|
||||
if (p.archived) throw new ConflictException('请先恢复归档项目');
|
||||
if (!p.revisions.some((x) => x.id === revisionId))
|
||||
throw new NotFoundException('历史记录不存在');
|
||||
await this.db.revision.update({
|
||||
where: { id: revisionId },
|
||||
data: {
|
||||
amount: v.amount,
|
||||
effectiveDate: toBusinessDate(v.date),
|
||||
notes: v.notes,
|
||||
reason: 'correction',
|
||||
const v = revisionInput.parse(b);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
const p = await tx.position.findFirst({
|
||||
where: { id, userId: r.userId, ...(r.revealed ? {} : { hidden: false }) },
|
||||
include: { revisions: true },
|
||||
});
|
||||
if (!p) throw new NotFoundException('项目不存在');
|
||||
if (p.archived) throw new ConflictException('请先恢复归档项目');
|
||||
const original = p.revisions.find((h) => h.id === revisionId);
|
||||
if (!original) throw new NotFoundException('历史记录不存在');
|
||||
if (
|
||||
p.revisions.some(
|
||||
(h) =>
|
||||
h.reason.startsWith('transfer_') &&
|
||||
(+h.effectiveDate >= +original.effectiveDate ||
|
||||
toBusinessDate(v.date) < h.effectiveDate),
|
||||
)
|
||||
)
|
||||
throw new ConflictException(
|
||||
'转账及其之前的历史不可单独更正;请新增余额调整,保留转账双方一致',
|
||||
);
|
||||
await tx.revision.update({
|
||||
where: { id: revisionId },
|
||||
data: {
|
||||
amount: v.amount,
|
||||
effectiveDate: toBusinessDate(v.date),
|
||||
notes: v.notes,
|
||||
reason: 'correction',
|
||||
},
|
||||
});
|
||||
return { ok: true };
|
||||
},
|
||||
});
|
||||
return { ok: true };
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
}
|
||||
|
||||
@Put('positions/:id/links') async link(
|
||||
@Req() r: UserRequest,
|
||||
@Param('id') id: string,
|
||||
|
||||
+15
-4
@@ -12,7 +12,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { Database } from './database';
|
||||
import { UserRequest } from './auth';
|
||||
import { currency, date, rateValue, today } from './validation';
|
||||
import { currency, date, rateValue, today, hiddenMenus } from './validation';
|
||||
import { z } from 'zod';
|
||||
import Decimal from 'decimal.js';
|
||||
// Fixed public request; no user currency choices, identifiers or amounts leave the server.
|
||||
@@ -168,10 +168,17 @@ export class SettingsController {
|
||||
@Get('settings') async settings(@Req() r: UserRequest) {
|
||||
const u = await this.db.user.findUniqueOrThrow({
|
||||
where: { id: r.userId },
|
||||
select: { username: true, baseCurrency: true, showSidebar: true, idleMinutes: true },
|
||||
select: {
|
||||
username: true,
|
||||
baseCurrency: true,
|
||||
hiddenMenus: true,
|
||||
showNotes: true,
|
||||
idleMinutes: true,
|
||||
},
|
||||
});
|
||||
return {
|
||||
...u,
|
||||
hiddenMenus: u.hiddenMenus.split(',').filter(Boolean),
|
||||
lastActivity: (await this.db.session.findUniqueOrThrow({ where: { id: r.sessionId } }))
|
||||
.lastActivity,
|
||||
revealed: r.revealed,
|
||||
@@ -190,13 +197,17 @@ export class SettingsController {
|
||||
const data = z
|
||||
.object({
|
||||
baseCurrency: currency.optional(),
|
||||
showSidebar: z.boolean().optional(),
|
||||
hiddenMenus: hiddenMenus.optional(),
|
||||
showNotes: z.boolean().optional(),
|
||||
idleMinutes: z.number().int().min(0).max(1440).optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine((v) => Object.keys(v).length > 0)
|
||||
.parse(b);
|
||||
await this.db.user.update({ where: { id: r.userId }, data });
|
||||
await this.db.user.update({
|
||||
where: { id: r.userId },
|
||||
data: { ...data, hiddenMenus: data.hiddenMenus?.join(',') },
|
||||
});
|
||||
this.fx.invalidate(r.userId);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Req,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import Decimal from 'decimal.js';
|
||||
import { Database } from './database';
|
||||
import { UserRequest } from './auth';
|
||||
import { transferInput, toBusinessDate } from './validation';
|
||||
import { businessTime } from './calculation';
|
||||
@Controller('api/transfers')
|
||||
export class TransfersController {
|
||||
constructor(private db: Database) {}
|
||||
@Get() async list(@Req() r: UserRequest) {
|
||||
const visibility = { userId: r.userId, ...(r.revealed ? {} : { hidden: false }) };
|
||||
const rows = await this.db.transfer.findMany({
|
||||
where: { userId: r.userId, source: visibility, target: visibility },
|
||||
include: { source: { select: { name: true } }, target: { select: { name: true } } },
|
||||
orderBy: [{ effectiveDate: 'desc' }, { createdAt: 'desc' }],
|
||||
});
|
||||
return rows.map(({ userId, importedFromId, effectiveDate, ...v }) => ({
|
||||
...v,
|
||||
date: businessTime(effectiveDate),
|
||||
}));
|
||||
}
|
||||
@Post() async create(@Req() r: UserRequest, @Body() body: unknown) {
|
||||
const v = transferInput.parse(body),
|
||||
when = toBusinessDate(v.date);
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
if (v.requestId) {
|
||||
const existing = await tx.transfer.findFirst({
|
||||
where: { id: v.requestId, userId: r.userId },
|
||||
});
|
||||
if (existing) {
|
||||
if (
|
||||
existing.sourceId !== v.sourceId ||
|
||||
existing.targetId !== v.targetId ||
|
||||
!new Decimal(existing.amount.toString()).eq(v.amount) ||
|
||||
!new Decimal(existing.received.toString()).eq(v.received) ||
|
||||
!new Decimal(existing.fee.toString()).eq(v.fee) ||
|
||||
+existing.effectiveDate !== +when ||
|
||||
existing.notes !== v.notes
|
||||
)
|
||||
throw new ConflictException('转账请求标识已使用,请刷新后重试');
|
||||
return { id: existing.id };
|
||||
}
|
||||
}
|
||||
const accounts = await tx.position.findMany({
|
||||
where: {
|
||||
id: { in: [v.sourceId, v.targetId] },
|
||||
userId: r.userId,
|
||||
kind: 'account',
|
||||
side: 'asset',
|
||||
archived: false,
|
||||
...(r.revealed ? {} : { hidden: false }),
|
||||
},
|
||||
include: {
|
||||
revisions: { orderBy: [{ effectiveDate: 'desc' }, { sequence: 'desc' }], take: 1 },
|
||||
},
|
||||
});
|
||||
if (accounts.length !== 2)
|
||||
throw new BadRequestException('只能在自己的启用资产账户之间转账(隐藏账户须先解锁)');
|
||||
const source = accounts.find((p) => p.id === v.sourceId)!,
|
||||
target = accounts.find((p) => p.id === v.targetId)!;
|
||||
if (accounts.some((p) => !p.revisions[0] || +p.revisions[0].effectiveDate > +when))
|
||||
throw new ConflictException('转账时间不能早于任一账户的最新余额记录,请以当前余额转账');
|
||||
if (source.currency === target.currency && !new Decimal(v.amount).eq(v.received))
|
||||
throw new BadRequestException('同币种转出与到账金额必须一致,手续费单独填写');
|
||||
const debit = new Decimal(v.amount).plus(v.fee),
|
||||
before = new Decimal(source.revisions[0].amount.toString());
|
||||
if (before.lt(debit)) throw new BadRequestException('转出账户余额不足(含手续费)');
|
||||
const after = new Decimal(target.revisions[0].amount.toString()).plus(v.received);
|
||||
if (after.gte('10000000000000000'))
|
||||
throw new BadRequestException('到账后的金额超出支持范围');
|
||||
const outgoing = await tx.revision.create({
|
||||
data: {
|
||||
positionId: source.id,
|
||||
amount: before.minus(debit).toFixed(),
|
||||
effectiveDate: when,
|
||||
notes: v.notes,
|
||||
reason: 'transfer_out',
|
||||
},
|
||||
});
|
||||
const incoming = await tx.revision.create({
|
||||
data: {
|
||||
positionId: target.id,
|
||||
amount: after.toFixed(),
|
||||
effectiveDate: when,
|
||||
notes: v.notes,
|
||||
reason: 'transfer_in',
|
||||
},
|
||||
});
|
||||
const row = await tx.transfer.create({
|
||||
data: {
|
||||
id: v.requestId,
|
||||
userId: r.userId,
|
||||
sourceId: source.id,
|
||||
targetId: target.id,
|
||||
sourceRevisionId: outgoing.id,
|
||||
targetRevisionId: incoming.id,
|
||||
sourceCurrency: source.currency,
|
||||
targetCurrency: target.currency,
|
||||
amount: v.amount,
|
||||
received: v.received,
|
||||
fee: v.fee,
|
||||
effectiveDate: when,
|
||||
notes: v.notes,
|
||||
},
|
||||
});
|
||||
return { id: row.id };
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,15 @@ export const revisionInput = z
|
||||
date: businessDate,
|
||||
notes,
|
||||
reason: z
|
||||
.enum(['initial', 'balance', 'valuation', 'repayment', 'correction'])
|
||||
.enum([
|
||||
'initial',
|
||||
'balance',
|
||||
'valuation',
|
||||
'repayment',
|
||||
'correction',
|
||||
'transfer_out',
|
||||
'transfer_in',
|
||||
])
|
||||
.default('balance'),
|
||||
})
|
||||
.strict();
|
||||
@@ -108,3 +116,22 @@ export const credentials = z
|
||||
.refine((s) => Buffer.byteLength(s, 'utf8') <= 72, '密码最多 72 字节'),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const menuKey = z.enum(['overview', 'account', 'asset', 'debt', 'history']);
|
||||
export const hiddenMenus = z
|
||||
.array(menuKey)
|
||||
.max(5)
|
||||
.refine((v) => new Set(v).size === v.length, '菜单不可重复');
|
||||
export const transferInput = z
|
||||
.object({
|
||||
requestId: z.string().uuid().optional(),
|
||||
sourceId: z.string().uuid(),
|
||||
targetId: z.string().uuid(),
|
||||
amount: amount.refine((v) => /[1-9]/.test(v), '转出金额必须大于零'),
|
||||
received: amount.refine((v) => /[1-9]/.test(v), '到账金额必须大于零'),
|
||||
fee: amount.default('0'),
|
||||
date: businessDate,
|
||||
notes,
|
||||
})
|
||||
.strict()
|
||||
.refine((v) => v.sourceId !== v.targetId, '不能向同一账户转账');
|
||||
+18
-6
@@ -16,6 +16,7 @@ const files = [
|
||||
'links.json',
|
||||
'rates.json',
|
||||
'icons.json',
|
||||
'transfers.json',
|
||||
] as const;
|
||||
const sha = (s: Buffer | string) => createHash('sha256').update(s).digest('hex');
|
||||
export function packBackup(b: Backup) {
|
||||
@@ -32,6 +33,7 @@ export function packBackup(b: Backup) {
|
||||
'links.json': b.links,
|
||||
'rates.json': b.rates,
|
||||
'icons.json': b.icons || [],
|
||||
'transfers.json': b.transfers || [],
|
||||
};
|
||||
const contents = Object.fromEntries(
|
||||
files.map((name) => [name, JSON.stringify(data[name], null, 2)]),
|
||||
@@ -39,7 +41,7 @@ export function packBackup(b: Backup) {
|
||||
contents['manifest.json'] = JSON.stringify(
|
||||
{
|
||||
format: 'worthpath',
|
||||
version: 4,
|
||||
version: 5,
|
||||
exportedAt: b.exportedAt,
|
||||
files: files.map((name) => ({ name, sha256: sha(contents[name]) })),
|
||||
},
|
||||
@@ -114,18 +116,22 @@ export async function readBackupZip(input: string | Buffer): Promise<unknown> {
|
||||
const manifest = z
|
||||
.object({
|
||||
format: z.literal('worthpath'),
|
||||
version: z.union([z.literal(3), z.literal(4)]),
|
||||
version: z.union([z.literal(3), z.literal(4), z.literal(5)]),
|
||||
exportedAt: z.iso.datetime(),
|
||||
files: z
|
||||
.array(
|
||||
z.object({ name: z.enum(files), sha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),
|
||||
)
|
||||
.min(files.length - 1)
|
||||
.min(files.length - 2)
|
||||
.max(files.length),
|
||||
})
|
||||
.strict()
|
||||
.parse(parse('manifest.json'));
|
||||
const expected = manifest.version === 3 ? files.filter((f) => f !== 'icons.json') : [...files];
|
||||
const expected = files.filter(
|
||||
(f) =>
|
||||
(manifest.version >= 4 || f !== 'icons.json') &&
|
||||
(manifest.version >= 5 || f !== 'transfers.json'),
|
||||
);
|
||||
if (
|
||||
contents.size !== expected.length + 1 ||
|
||||
new Set(manifest.files.map((f) => f.name)).size !== expected.length ||
|
||||
@@ -137,7 +143,12 @@ export async function readBackupZip(input: string | Buffer): Promise<unknown> {
|
||||
.object({
|
||||
baseCurrency: z.string(),
|
||||
preferences: z
|
||||
.object({ showSidebar: z.boolean(), idleMinutes: z.number().int().min(0).max(1440) })
|
||||
.object({
|
||||
showSidebar: z.boolean().optional(),
|
||||
hiddenMenus: z.array(z.string()).optional(),
|
||||
showNotes: z.boolean().optional(),
|
||||
idleMinutes: z.number().int().min(0).max(1440),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
})
|
||||
@@ -169,7 +180,8 @@ export async function readBackupZip(input: string | Buffer): Promise<unknown> {
|
||||
positions: positions.map((p) => ({ ...p, revisions: grouped.get(p.id) || [] })),
|
||||
links: parse('links.json'),
|
||||
rates: parse('rates.json'),
|
||||
...(manifest.version === 4 ? { icons: parse('icons.json') } : {}),
|
||||
...(manifest.version >= 5 ? { transfers: parse('transfers.json') } : {}),
|
||||
...(manifest.version >= 4 ? { icons: parse('icons.json') } : {}),
|
||||
};
|
||||
} catch {
|
||||
throw new BadRequestException(
|
||||
|
||||
@@ -53,7 +53,7 @@ test('real MySQL: authentication, isolation, history, backup and atomic failures
|
||||
'Content-Type': 'application/json',
|
||||
Origin: 'https://untrusted.invalid',
|
||||
},
|
||||
body: JSON.stringify({ showSidebar: true }),
|
||||
body: JSON.stringify({ hiddenMenus: [] }),
|
||||
})
|
||||
).status,
|
||||
process.env.WEB_ORIGIN === '*' ? 200 : 403,
|
||||
|
||||
@@ -236,11 +236,12 @@ test('privacy, minute history, backup-gated clear and idle sessions remain user
|
||||
assert.equal(await db.position.count({ where: { userId: b.id } }), 3);
|
||||
assert.equal((await call('/auth/me', 'GET', undefined, a.cookie)).status, 200);
|
||||
assert.equal(
|
||||
(await call('/settings', 'PATCH', { showSidebar: false, idleMinutes: 1 }, a.cookie)).status,
|
||||
(await call('/settings', 'PATCH', { hiddenMenus: ['asset'], idleMinutes: 1 }, a.cookie))
|
||||
.status,
|
||||
200,
|
||||
);
|
||||
const prefs = (await call('/settings', 'GET', undefined, a.cookie)).data;
|
||||
assert.equal(prefs.showSidebar, false);
|
||||
assert.deepEqual(prefs.hiddenMenus, ['asset']);
|
||||
assert.equal(prefs.idleMinutes, 1);
|
||||
assert.equal((await call('/settings', 'PATCH', { idleMinutes: -1 }, a.cookie)).status, 400);
|
||||
await db.session.update({
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, randomBytes } from 'node:crypto';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { readBackupZip } from '../src/zip';
|
||||
import { normalizeIcon } from '../src/icons';
|
||||
import sharp from 'sharp';
|
||||
const base = process.env.TEST_API_URL || 'http://127.0.0.1:3100/api';
|
||||
test('transfers are atomic, scoped, retry-safe, decimal exact and included in backups', async () => {
|
||||
const db = new PrismaClient(),
|
||||
names: string[] = [];
|
||||
async function call(path: string, cookie = '', method = 'GET', data?: unknown) {
|
||||
const r = await fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
Cookie: cookie,
|
||||
Origin: process.env.WEB_ORIGIN === '*' ? 'http://localhost:5173' : process.env.WEB_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()))) as any)
|
||||
: await r.json(),
|
||||
cookie: r.headers.get('set-cookie')?.split(';')[0] || '',
|
||||
};
|
||||
}
|
||||
async function account() {
|
||||
const username = 'wp_transfer_' + randomUUID(),
|
||||
password = randomBytes(18).toString('hex');
|
||||
names.push(username);
|
||||
const r = await call('/auth/register', '', 'POST', { username, password });
|
||||
assert.equal(r.status, 201);
|
||||
return { ...r, id: (await db.user.findUniqueOrThrow({ where: { username } })).id, password };
|
||||
}
|
||||
async function position(
|
||||
cookie: string,
|
||||
name: string,
|
||||
amount = '100',
|
||||
currency = 'CNY',
|
||||
side = 'asset',
|
||||
) {
|
||||
const r = await call('/positions', cookie, 'POST', {
|
||||
name,
|
||||
kind: 'account',
|
||||
category: side === 'asset' ? 'bank' : 'credit_card',
|
||||
side,
|
||||
currency,
|
||||
amount,
|
||||
date: '2026-09-01T10:35',
|
||||
});
|
||||
assert.equal(r.status, 201);
|
||||
return r.data.id as string;
|
||||
}
|
||||
try {
|
||||
const a = await account(),
|
||||
b = await account();
|
||||
const sourceId = await position(a.cookie, '转出账户'),
|
||||
targetId = await position(a.cookie, '转入账户', '10'),
|
||||
other = await position(b.cookie, '他人账户');
|
||||
const request = {
|
||||
sourceId,
|
||||
targetId,
|
||||
amount: '25',
|
||||
received: '25',
|
||||
fee: '1',
|
||||
date: '2026-09-02T10:35',
|
||||
notes: '转账验收',
|
||||
requestId: randomUUID(),
|
||||
};
|
||||
assert.equal((await call('/transfers', '', 'POST', request)).status, 401);
|
||||
assert.equal(
|
||||
(await call('/transfers', a.cookie, 'POST', { ...request, targetId: other })).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/transfers', a.cookie, 'POST', { ...request, sourceId: targetId })).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/transfers', a.cookie, 'POST', { ...request, userId: b.id })).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/transfers', a.cookie, 'POST', { ...request, amount: '100', received: '100' }))
|
||||
.status,
|
||||
400,
|
||||
);
|
||||
assert.equal(await db.transfer.count({ where: { userId: a.id } }), 0);
|
||||
assert.equal(await db.revision.count({ where: { positionId: sourceId } }), 1);
|
||||
assert.equal((await call('/transfers', a.cookie, 'POST', request)).status, 201);
|
||||
assert.equal((await call('/transfers', a.cookie, 'POST', request)).status, 201);
|
||||
assert.equal(await db.transfer.count({ where: { userId: a.id } }), 1);
|
||||
assert.equal(
|
||||
(await call('/transfers', a.cookie, 'POST', { ...request, amount: '24', received: '24' }))
|
||||
.status,
|
||||
409,
|
||||
);
|
||||
const rows = (await call('/positions', a.cookie)).data;
|
||||
assert.equal(rows.find((p: any) => p.id === sourceId).amount, '74');
|
||||
assert.equal(rows.find((p: any) => p.id === targetId).amount, '35');
|
||||
assert.equal((await call('/overview', a.cookie)).data.net, '109.00');
|
||||
assert.equal((await call('/transfers', b.cookie)).data.length, 0);
|
||||
const revision = rows.find((p: any) => p.id === sourceId).history.at(-1);
|
||||
assert.equal(
|
||||
(
|
||||
await call(`/positions/${sourceId}/revisions/${revision.id}`, a.cookie, 'PUT', {
|
||||
amount: '70',
|
||||
date: request.date,
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call(`/positions/${sourceId}/revisions`, a.cookie, 'POST', {
|
||||
amount: '70',
|
||||
date: request.date,
|
||||
reason: 'transfer_out',
|
||||
})
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call(`/positions/${sourceId}/revisions`, a.cookie, 'POST', {
|
||||
amount: '80',
|
||||
date: '2026-09-01T12:00',
|
||||
reason: 'balance',
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
assert.equal((await call('/settings', a.cookie, 'PATCH', { showNotes: 'false' })).status, 400);
|
||||
const debt = await position(a.cookie, '信用卡', '10', 'CNY', 'liability');
|
||||
assert.equal(
|
||||
(
|
||||
await call('/transfers', a.cookie, 'POST', {
|
||||
...request,
|
||||
requestId: randomUUID(),
|
||||
targetId: debt,
|
||||
})
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call('/transfers', a.cookie, 'POST', {
|
||||
...request,
|
||||
requestId: randomUUID(),
|
||||
date: '2026-09-01T10:34',
|
||||
})
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
const usd = await position(a.cookie, '美元账户', '20', 'USD');
|
||||
assert.equal(
|
||||
(
|
||||
await call('/transfers', a.cookie, 'POST', {
|
||||
...request,
|
||||
requestId: randomUUID(),
|
||||
sourceId: usd,
|
||||
amount: '1.00000001',
|
||||
received: '7.10000001',
|
||||
fee: '0',
|
||||
date: '2026-09-02T11:00',
|
||||
})
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/positions', a.cookie)).data.find((p: any) => p.id === usd).amount,
|
||||
'18.99999999',
|
||||
);
|
||||
const race = await Promise.all(
|
||||
[1, 2].map(() =>
|
||||
call('/transfers', a.cookie, 'POST', {
|
||||
...request,
|
||||
requestId: randomUUID(),
|
||||
sourceId: usd,
|
||||
amount: '15',
|
||||
received: '100',
|
||||
fee: '0',
|
||||
date: '2026-09-03T10:00',
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(race.filter((r) => r.status === 201).length, 1);
|
||||
assert.equal(race.filter((r) => [400, 409].includes(r.status)).length, 1);
|
||||
assert.equal(
|
||||
(
|
||||
await call('/settings', a.cookie, 'PATCH', {
|
||||
hiddenMenus: ['asset', 'debt'],
|
||||
showNotes: false,
|
||||
idleMinutes: 15,
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.deepEqual((await call('/settings', a.cookie)).data.hiddenMenus, ['asset', 'debt']);
|
||||
assert.equal((await call('/settings', a.cookie)).data.showNotes, false);
|
||||
assert.equal(
|
||||
(await call('/settings', a.cookie, 'PATCH', { hiddenMenus: ['settings'] })).status,
|
||||
400,
|
||||
);
|
||||
assert.equal((await call('/settings', a.cookie, 'PATCH', { showSidebar: false })).status, 400);
|
||||
const backup = (await call('/backup', a.cookie)).data;
|
||||
assert.equal(backup.transfers.length, 3);
|
||||
assert.equal(backup.preferences.showNotes, false);
|
||||
assert.deepEqual(backup.preferences.hiddenMenus, ['asset', 'debt']);
|
||||
const broken = structuredClone(backup);
|
||||
broken.transfers[0].amount = '999';
|
||||
assert.equal(
|
||||
(await call('/backup/import', b.cookie, 'POST', { confirmed: true, backup: broken })).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(await db.transfer.count({ where: { userId: b.id } }), 0);
|
||||
assert.equal(
|
||||
(await call('/backup/import', b.cookie, 'POST', { confirmed: true, backup })).status,
|
||||
201,
|
||||
);
|
||||
const restored = (await call('/backup', b.cookie)).data;
|
||||
assert.equal(restored.transfers.length, 3);
|
||||
// Appending into an existing space preserves its display preferences.
|
||||
assert.equal((await call('/settings', b.cookie)).data.showNotes, true);
|
||||
const c = await account();
|
||||
assert.equal(
|
||||
(await call('/backup/import', c.cookie, 'POST', { confirmed: true, backup })).status,
|
||||
201,
|
||||
);
|
||||
assert.equal((await call('/settings', c.cookie)).data.showNotes, false);
|
||||
for (const t of restored.transfers) {
|
||||
assert.ok(
|
||||
restored.positions
|
||||
.find((p: any) => p.id === t.sourceId)
|
||||
?.revisions.some((r: any) => r.id === t.sourceRevisionId),
|
||||
);
|
||||
assert.ok(
|
||||
restored.positions
|
||||
.find((p: any) => p.id === t.targetId)
|
||||
?.revisions.some((r: any) => r.id === t.targetRevisionId),
|
||||
);
|
||||
}
|
||||
await call('/positions/' + sourceId, a.cookie, 'PATCH', {
|
||||
name: '转出账户',
|
||||
category: 'bank',
|
||||
hidden: true,
|
||||
});
|
||||
const visibleTransfers = (await call('/transfers', a.cookie)).data;
|
||||
assert.equal(visibleTransfers.length, 2);
|
||||
assert.ok(
|
||||
visibleTransfers.every((t: any) => t.sourceId !== sourceId && t.targetId !== sourceId),
|
||||
);
|
||||
assert.equal(
|
||||
(await call('/transfers', a.cookie, 'POST', { ...request, requestId: randomUUID() })).status,
|
||||
400,
|
||||
);
|
||||
} finally {
|
||||
await db.user.deleteMany({ where: { username: { in: names } } });
|
||||
await db.$disconnect();
|
||||
}
|
||||
});
|
||||
test('icon processing creates transparent white cutouts and preserves brand colour', async () => {
|
||||
const pixels = Buffer.from([255, 255, 255, 255, 10, 120, 60, 255]);
|
||||
const input = await sharp(pixels, { raw: { width: 2, height: 1, channels: 4 } })
|
||||
.png()
|
||||
.toBuffer();
|
||||
const output = await sharp(await normalizeIcon(input))
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer();
|
||||
assert.equal(output[3], 0);
|
||||
assert.deepEqual([...output.subarray(4)], [10, 120, 60, 255]);
|
||||
});
|
||||
test('OpenAPI exposes authenticated routes and actual transfer request fields', async () => {
|
||||
const r = await fetch(base + '/openapi.json');
|
||||
assert.equal(r.status, 200);
|
||||
const doc = await r.json();
|
||||
assert.ok(doc.paths['/api/transfers']);
|
||||
assert.ok(
|
||||
doc.paths['/api/transfers'].post.requestBody.content['application/json'].schema.properties
|
||||
.requestId,
|
||||
);
|
||||
assert.equal(doc.components.securitySchemes.session.in, 'cookie');
|
||||
assert.doesNotMatch(JSON.stringify(doc), /passwordHash|DATABASE_URL|ghp_/);
|
||||
const html = await fetch(base + '/docs');
|
||||
assert.equal(html.status, 200);
|
||||
assert.match(await html.text(), /swagger-ui/);
|
||||
});
|
||||
@@ -10,9 +10,10 @@ const empty = () =>
|
||||
version: 2,
|
||||
exportedAt: new Date().toISOString(),
|
||||
baseCurrency: 'CNY',
|
||||
preferences: { showSidebar: false, idleMinutes: 9 },
|
||||
preferences: { hiddenMenus: ['asset'], showNotes: false, idleMinutes: 9 },
|
||||
currencies: ['CNY'],
|
||||
icons: [],
|
||||
transfers: [],
|
||||
positions: [],
|
||||
rates: [],
|
||||
links: [],
|
||||
@@ -43,6 +44,7 @@ test('ZIP contains separate JSON files and restores settings without authenticat
|
||||
'manifest.json',
|
||||
'rates.json',
|
||||
'settings.json',
|
||||
'transfers.json',
|
||||
]);
|
||||
assert.doesNotMatch(JSON.stringify(contents), /password|token|session|userId/i);
|
||||
assert.deepEqual(validateBackup(await readBackupZip(await archive(contents))), b);
|
||||
@@ -99,11 +101,28 @@ test('backup accepts over 1000 positions, 10000 revisions per position and 20000
|
||||
test('legacy v3 ZIP remains readable without icons', async () => {
|
||||
const contents = packBackup(empty());
|
||||
delete contents['icons.json'];
|
||||
delete contents['transfers.json'];
|
||||
const manifest = JSON.parse(contents['manifest.json']);
|
||||
manifest.version = 3;
|
||||
manifest.files = manifest.files.filter((f: { name: string }) => f.name !== 'icons.json');
|
||||
manifest.files = manifest.files.filter(
|
||||
(f: { name: string }) => !['icons.json', 'transfers.json'].includes(f.name),
|
||||
);
|
||||
contents['manifest.json'] = JSON.stringify(manifest);
|
||||
const restored = validateBackup(await readBackupZip(await archive(contents)));
|
||||
assert.equal(restored.icons, undefined);
|
||||
assert.deepEqual(restored.positions, []);
|
||||
});
|
||||
|
||||
test('legacy v4 ZIP remains readable without transfers', async () => {
|
||||
const contents = packBackup(empty());
|
||||
delete contents['transfers.json'];
|
||||
const manifest = JSON.parse(contents['manifest.json']);
|
||||
manifest.version = 4;
|
||||
manifest.files = manifest.files.filter((f: { name: string }) => f.name !== 'transfers.json');
|
||||
contents['manifest.json'] = JSON.stringify(manifest);
|
||||
const restored = validateBackup(await readBackupZip(await archive(contents)));
|
||||
assert.deepEqual(restored.icons, []);
|
||||
assert.equal(restored.transfers, undefined);
|
||||
assert.equal(restored.preferences?.showNotes, false);
|
||||
assert.deepEqual(restored.preferences?.hiddenMenus, ['asset']);
|
||||
});
|
||||
+443
-286
@@ -33,6 +33,9 @@ import {
|
||||
type Total,
|
||||
} from './api';
|
||||
import './style.css';
|
||||
import { IconPicker } from './IconPicker';
|
||||
import { TransferForm } from './TransferForm';
|
||||
import type { Transfer } from './api';
|
||||
import { IconLibrary, iconUrl } from './IconLibrary';
|
||||
const labels: Record<string, string> = {
|
||||
overview: '资产总览',
|
||||
@@ -77,7 +80,7 @@ function Currency({ value, onChange }: { value: string; onChange: (v: string) =>
|
||||
}
|
||||
function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<label className="field">
|
||||
<label className={label === '备注' ? 'field note-field' : 'field'}>
|
||||
<span>{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
@@ -101,7 +104,7 @@ function Modal({
|
||||
>
|
||||
<section role="dialog" aria-modal="true" aria-label={title} className="modal">
|
||||
<header>
|
||||
<h2>{title}</h2>
|
||||
<h2 className={title.includes('清空本账号数据') ? 'danger-text' : undefined}>{title}</h2>
|
||||
<button className="icon" aria-label="关闭" onClick={close}>
|
||||
<X size={20} />
|
||||
</button>
|
||||
@@ -217,10 +220,14 @@ export default function App() {
|
||||
baseCurrency: string;
|
||||
currentBaseCurrency: string;
|
||||
} | null>(null);
|
||||
const [clearStep, setClearStep] = useState(0);
|
||||
const [clearStep, setClearStep] = useState(0),
|
||||
[clearConfirmation, setClearConfirmation] = useState(0);
|
||||
const [settingsSection, setSettingsSection] = useState('general'),
|
||||
[transfers, setTransfers] = useState<Transfer[]>([]);
|
||||
const activityAt = useRef(0);
|
||||
function clearAccount() {
|
||||
setClearStep(0);
|
||||
setClearConfirmation(0);
|
||||
activityAt.current = 0;
|
||||
sessionGeneration.current++;
|
||||
loadGeneration.current++;
|
||||
@@ -228,6 +235,7 @@ export default function App() {
|
||||
setPositions([]);
|
||||
setOverview(null);
|
||||
setRates([]);
|
||||
setTransfers([]);
|
||||
setFxStatus(null);
|
||||
setModal(null);
|
||||
setSelected(null);
|
||||
@@ -249,7 +257,7 @@ export default function App() {
|
||||
request = ++loadGeneration.current;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [p, o, s] = await Promise.all([
|
||||
const [p, o, s, t] = await Promise.all([
|
||||
api<Position[]>('/positions'),
|
||||
api<Overview>('/overview'),
|
||||
api<
|
||||
@@ -258,6 +266,7 @@ export default function App() {
|
||||
fxStatus: { state: string; message: string; attemptedAt: string | null };
|
||||
}
|
||||
>('/settings'),
|
||||
api<Transfer[]>('/transfers'),
|
||||
]);
|
||||
if (session !== sessionGeneration.current || request !== loadGeneration.current) return;
|
||||
if (o.revealed !== !!s.revealed) {
|
||||
@@ -272,8 +281,10 @@ export default function App() {
|
||||
setPositions(s.revealed ? p : p.filter((position) => !position.hidden));
|
||||
setOverview(o);
|
||||
setRates(s.rates);
|
||||
setTransfers(t);
|
||||
setFxStatus(s.fxStatus);
|
||||
setUser(s);
|
||||
setPage((current) => (s.hiddenMenus.includes(current) ? 'settings' : current));
|
||||
} catch (e) {
|
||||
if (session === sessionGeneration.current && request === loadGeneration.current) report(e);
|
||||
} finally {
|
||||
@@ -514,16 +525,17 @@ export default function App() {
|
||||
['history', HistoryIcon],
|
||||
['settings', Settings],
|
||||
] as const;
|
||||
const visibleNav = nav.filter(([key]) => !(user.hiddenMenus || []).includes(key));
|
||||
return (
|
||||
<div className={'app' + (user.showSidebar === false ? ' sidebar-hidden' : '')}>
|
||||
{user.showSidebar !== false && (
|
||||
<div className={user.showNotes === false ? 'app notes-hidden' : 'app'}>
|
||||
{
|
||||
<aside className="sidebar">
|
||||
<div className="brand">
|
||||
<span>W</span> WorthPath
|
||||
</div>
|
||||
<p className="nav-caption">我的资产空间</p>
|
||||
<nav>
|
||||
{nav.map(([key, Icon]) => (
|
||||
<nav style={{ gridTemplateColumns: `repeat(${visibleNav.length}, 1fr)` }}>
|
||||
{visibleNav.map(([key, Icon]) => (
|
||||
<button
|
||||
key={key}
|
||||
className={page === key ? 'active' : ''}
|
||||
@@ -553,26 +565,10 @@ export default function App() {
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
}
|
||||
<main>
|
||||
<header className="topbar">
|
||||
<span>个人财务 / {labels[page]}</span>
|
||||
{user.showSidebar === false && (
|
||||
<select
|
||||
aria-label="页面导航"
|
||||
value={page}
|
||||
onChange={(e) => {
|
||||
setPage(e.target.value);
|
||||
setSelected(null);
|
||||
}}
|
||||
>
|
||||
{nav.map(([key]) => (
|
||||
<option key={key} value={key}>
|
||||
{labels[key]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<div>
|
||||
<span className="currency-pill">本位币 {user.baseCurrency}</span>
|
||||
<button
|
||||
@@ -621,7 +617,14 @@ export default function App() {
|
||||
: '保留原币金额,追踪长期变化。'}
|
||||
</p>
|
||||
</div>
|
||||
{['overview', 'account', 'asset', 'debt'].includes(page) && !p && newAction}
|
||||
<div className="actions">
|
||||
{page === 'account' && !p && (
|
||||
<button className="secondary" onClick={() => setModal({ kind: 'transfer' })}>
|
||||
账户间转账
|
||||
</button>
|
||||
)}
|
||||
{['overview', 'account', 'asset', 'debt'].includes(page) && !p && newAction}
|
||||
</div>
|
||||
</div>
|
||||
{error && (
|
||||
<div className="notice error" role="alert">
|
||||
@@ -808,7 +811,7 @@ export default function App() {
|
||||
)
|
||||
: '缺少汇率'}
|
||||
</p>
|
||||
<p>{p.notes || '暂无备注'}</p>
|
||||
<p className="notes-display">{p.notes || '暂无备注'}</p>
|
||||
<small>币种和资产负债属性创建后固定。归档项目仍计入总览。</small>
|
||||
</div>
|
||||
<div className="actions">
|
||||
@@ -936,6 +939,28 @@ export default function App() {
|
||||
))}
|
||||
{page === 'history' && (
|
||||
<section className="panel">
|
||||
<h2>账户转账</h2>
|
||||
{transfers.length ? (
|
||||
<div className="transfer-list">
|
||||
{transfers.map((t) => (
|
||||
<article key={t.id}>
|
||||
<div>
|
||||
<strong>
|
||||
{t.source.name} → {t.target.name}
|
||||
</strong>
|
||||
<small>{displayTime(t.date)}</small>
|
||||
</div>
|
||||
<p>
|
||||
{money(t.amount, t.sourceCurrency)} → {money(t.received, t.targetCurrency)}{' '}
|
||||
· 手续费 {money(t.fee, t.sourceCurrency)}
|
||||
</p>
|
||||
{t.notes && <p className="muted notes-display">{t.notes}</p>}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="muted">暂无账户间转账记录。</p>
|
||||
)}
|
||||
<h2>全部金额变化</h2>
|
||||
<p className="muted">原币绝对余额记录;负债减少即还款。选择项目可查看详情并更正。</p>
|
||||
<HistoryTable
|
||||
@@ -951,13 +976,32 @@ export default function App() {
|
||||
)}
|
||||
{page === 'settings' && (
|
||||
<>
|
||||
<section className="panel">
|
||||
<IconLibrary />
|
||||
<section className="settings-switch panel">
|
||||
<label>
|
||||
设置分类
|
||||
<select
|
||||
value={settingsSection}
|
||||
onChange={(e) => setSettingsSection(e.target.value)}
|
||||
>
|
||||
<option value="general">个人与菜单设置</option>
|
||||
<option value="icons">图标库</option>
|
||||
<option value="rates">每日汇率</option>
|
||||
<option value="backup">备份与恢复</option>
|
||||
<option className="danger-text" value="clear">
|
||||
清空本账号数据
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</section>
|
||||
<div className="settings-grid">
|
||||
{settingsSection === 'icons' && (
|
||||
<section className="panel">
|
||||
<IconLibrary />
|
||||
</section>
|
||||
)}
|
||||
<div className="settings-grid">
|
||||
<section className="panel" hidden={settingsSection !== 'general'}>
|
||||
<div className="panel-title">
|
||||
<h2>本位币与个人设置</h2>
|
||||
<h2>个人与菜单设置</h2>
|
||||
<button className="text" disabled={busy} onClick={() => void logout()}>
|
||||
<LogOut size={16} />
|
||||
退出登录
|
||||
@@ -974,33 +1018,68 @@ export default function App() {
|
||||
() =>
|
||||
api('/settings', 'PATCH', {
|
||||
baseCurrency: f.get('baseCurrency'),
|
||||
showSidebar: f.get('showSidebar') === 'true',
|
||||
hiddenMenus: ['overview', 'account', 'asset', 'debt', 'history'].filter(
|
||||
(key) => !f.has('menu_' + key),
|
||||
),
|
||||
idleMinutes: Number(f.get('idleMinutes')),
|
||||
showNotes: f.has('showNotes'),
|
||||
}),
|
||||
'个人设置已保存',
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="左侧菜单栏">
|
||||
<select
|
||||
name="showSidebar"
|
||||
key={String(user.showSidebar)}
|
||||
defaultValue={String(user.showSidebar)}
|
||||
>
|
||||
<option value="true">显示</option>
|
||||
<option value="false">隐藏(顶部仍可切换页面)</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="无操作自动退出(分钟)">
|
||||
<p className="muted">
|
||||
选择需要显示的菜单项。设置入口始终保留,隐藏仅影响导航,不删除数据。
|
||||
</p>
|
||||
<div className="menu-preferences">
|
||||
{['overview', 'account', 'asset', 'debt', 'history'].map((key) => (
|
||||
<label key={key} className="switch-row">
|
||||
<span>{labels[key]}</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
aria-label={labels[key] + '显示'}
|
||||
name={'menu_' + key}
|
||||
key={key + String(user.hiddenMenus)}
|
||||
defaultChecked={!(user.hiddenMenus || []).includes(key)}
|
||||
/>
|
||||
<span className="switch-state" aria-hidden="true">
|
||||
显示
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<label className="switch-row">
|
||||
<span>显示备注</span>
|
||||
<input
|
||||
name="idleMinutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="1440"
|
||||
required
|
||||
defaultValue={user.idleMinutes}
|
||||
key={user.idleMinutes}
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
name="showNotes"
|
||||
aria-label="显示备注"
|
||||
key={String(user.showNotes)}
|
||||
defaultChecked={user.showNotes !== false}
|
||||
/>
|
||||
<span className="switch-state" aria-hidden="true">
|
||||
显示
|
||||
</span>
|
||||
</label>
|
||||
<p className="muted">
|
||||
关闭后隐藏列表、详情及编辑表单中的备注,已有备注仍会保留在备份中。
|
||||
</p>
|
||||
<Field label="无操作自动退出(分钟)">
|
||||
<select
|
||||
name="idleMinutes"
|
||||
key={user.idleMinutes}
|
||||
defaultValue={user.idleMinutes}
|
||||
>
|
||||
{[...new Set([0, 5, 15, 30, 60, 120, 1440, user.idleMinutes])]
|
||||
.sort((a, b) => a - b)
|
||||
.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n === 0 ? '关闭自动退出' : n + ' 分钟'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<p className="muted">
|
||||
0 为关闭;最长 1440 分钟。到时退出登录并清除页面数据,浏览器标签页保留。
|
||||
@@ -1021,7 +1100,7 @@ export default function App() {
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
<section className="panel">
|
||||
<section className="panel" hidden={settingsSection !== 'rates'}>
|
||||
<h2>每日汇率</h2>
|
||||
{fxStatus && (
|
||||
<p
|
||||
@@ -1056,7 +1135,7 @@ export default function App() {
|
||||
<p className="muted">公共参考汇率可能与银行成交价不同;休市日日期可能滞后。</p>
|
||||
</section>
|
||||
</div>
|
||||
<section className="panel">
|
||||
<section className="panel" hidden={settingsSection !== 'rates'}>
|
||||
<h2>已保存汇率</h2>
|
||||
{rates.length ? (
|
||||
<div className="table-wrap">
|
||||
@@ -1087,8 +1166,8 @@ export default function App() {
|
||||
<Empty title="没有保存的外币汇率" body="添加外币项目后更新并保存自动汇率。" />
|
||||
)}
|
||||
</section>
|
||||
<section className="panel">
|
||||
<h2>清空本账号数据</h2>
|
||||
<section className="panel" hidden={settingsSection !== 'clear'}>
|
||||
<h2 className="danger-text">清空本账号数据</h2>
|
||||
<p className="muted">
|
||||
清除本账号全部账户、资产、债务、历史、私有图标和汇率(包括隐藏项目);保留登录账号、个人设置和已发布的共享图标。请先下载备份并确认文件已保存。
|
||||
</p>
|
||||
@@ -1122,14 +1201,8 @@ export default function App() {
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const confirmation = new FormData(e.currentTarget).get('confirmation');
|
||||
void act(async () => {
|
||||
await api('/backup/clear', 'POST', { confirmation });
|
||||
setClearStep(0);
|
||||
setSelected(null);
|
||||
setBackup(null);
|
||||
setPreview(null);
|
||||
}, '本账号数据已清空');
|
||||
if (new FormData(e.currentTarget).get('confirmation') === '确定清空')
|
||||
setClearConfirmation(1);
|
||||
}}
|
||||
>
|
||||
<Field label="输入“确定清空”以确认">
|
||||
@@ -1145,11 +1218,12 @@ export default function App() {
|
||||
取消清空 / 重新下载
|
||||
</button>
|
||||
)}
|
||||
<hr />
|
||||
</section>
|
||||
<section className="panel" hidden={settingsSection !== 'backup'}>
|
||||
<h2>数据备份与恢复</h2>
|
||||
<p className="muted">
|
||||
ZIP 内分文件保存可读
|
||||
JSON,包括全部账户、资产、债务、历史、关联、币种、设置、汇率及图标,不限制记录条数;不包含任何认证凭据。备份含个人财务信息,请妥善保管。
|
||||
JSON,包括全部账户、资产、债务、历史、关联、币种、设置、汇率、图标及配对转账,不限制记录条数;不包含任何认证凭据。备份含个人财务信息,请妥善保管。
|
||||
</p>
|
||||
<div className="actions">
|
||||
<a
|
||||
@@ -1246,245 +1320,322 @@ export default function App() {
|
||||
<footer>WorthPath · 记录你的积累,理解你的财富</footer>
|
||||
</div>
|
||||
</main>
|
||||
{clearConfirmation > 0 && (
|
||||
<Modal
|
||||
key={clearConfirmation}
|
||||
title={
|
||||
clearConfirmation === 1 ? '第一次确认:清空本账号数据' : '第二次确认:清空本账号数据'
|
||||
}
|
||||
close={() => {
|
||||
if (!busy) setClearConfirmation(0);
|
||||
}}
|
||||
>
|
||||
<p className="danger-text">
|
||||
{clearConfirmation === 1
|
||||
? '将清空本账号全部财务数据及私有图标,请确认备份已保存。'
|
||||
: '这是最后一次确认。清空后只能通过备份恢复,其他用户的数据不受影响。'}
|
||||
</p>
|
||||
<p className="muted">登录账号、个人设置和已发布的共享图标会保留。</p>
|
||||
<div className="modal-actions clear-confirm-actions">
|
||||
{clearConfirmation === 1 ? (
|
||||
<>
|
||||
<button
|
||||
autoFocus
|
||||
className="secondary"
|
||||
disabled={busy}
|
||||
onClick={() => setClearConfirmation(0)}
|
||||
>
|
||||
取消清空
|
||||
</button>
|
||||
<button className="danger" disabled={busy} onClick={() => setClearConfirmation(2)}>
|
||||
继续清空
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
className="danger"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void act(async () => {
|
||||
await api('/backup/clear', 'POST', { confirmation: '确定清空' });
|
||||
setClearConfirmation(0);
|
||||
setClearStep(0);
|
||||
setSelected(null);
|
||||
setBackup(null);
|
||||
setPreview(null);
|
||||
}, '本账号数据已清空')
|
||||
}
|
||||
>
|
||||
{busy ? '正在清空…' : '最终确认清空'}
|
||||
</button>
|
||||
<button
|
||||
autoFocus
|
||||
className="secondary"
|
||||
disabled={busy}
|
||||
onClick={() => setClearConfirmation(0)}
|
||||
>
|
||||
取消清空
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" className="notice error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</Modal>
|
||||
)}
|
||||
{modal && (
|
||||
<Modal
|
||||
title={
|
||||
modal.kind === 'reveal'
|
||||
? '验证密码以显示隐藏资产'
|
||||
: modal.kind === 'edit'
|
||||
? '编辑项目'
|
||||
: modal.kind === 'revision'
|
||||
? '更新余额 / 估值'
|
||||
: modal.kind === 'correction'
|
||||
? '更正历史记录'
|
||||
: modal.kind === 'links'
|
||||
? '管理债务关联'
|
||||
: '新增' + labels[modal.kind]
|
||||
modal.kind === 'transfer'
|
||||
? '账户间转账'
|
||||
: modal.kind === 'reveal'
|
||||
? '验证密码以显示隐藏资产'
|
||||
: modal.kind === 'edit'
|
||||
? '编辑项目'
|
||||
: modal.kind === 'revision'
|
||||
? '更新余额 / 估值'
|
||||
: modal.kind === 'correction'
|
||||
? '更正历史记录'
|
||||
: modal.kind === 'links'
|
||||
? '管理债务关联'
|
||||
: '新增' + labels[modal.kind]
|
||||
}
|
||||
close={() => {
|
||||
if (!busy) setModal(null);
|
||||
}}
|
||||
>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget),
|
||||
v = Object.fromEntries(f.entries()),
|
||||
kind = modal.kind,
|
||||
mp = modal.p;
|
||||
if (kind === 'reveal') {
|
||||
void act(
|
||||
() => api('/auth/reveal', 'POST', { password: f.get('password') }),
|
||||
'隐藏项目已解锁 5 分钟',
|
||||
);
|
||||
} else if (kind === 'links') {
|
||||
void act(
|
||||
() =>
|
||||
api('/positions/' + mp!.id + '/links', 'PUT', {
|
||||
targetIds: f.getAll('targetIds'),
|
||||
}),
|
||||
'关联已更新',
|
||||
);
|
||||
} else if (kind === 'revision' || kind === 'correction') {
|
||||
void act(
|
||||
() =>
|
||||
api(
|
||||
'/positions/' + mp!.id + '/revisions' + (modal.h ? '/' + modal.h.id : ''),
|
||||
modal.h ? 'PUT' : 'POST',
|
||||
v,
|
||||
),
|
||||
'金额历史已保存,总览已重新计算',
|
||||
);
|
||||
} else if (kind === 'edit') {
|
||||
void act(
|
||||
() =>
|
||||
api('/positions/' + mp!.id, 'PATCH', {
|
||||
...v,
|
||||
...(f.has('iconId') ? { iconId: f.get('iconId') || null } : {}),
|
||||
archived: mp!.archived,
|
||||
hidden: f.get('hidden') === 'on',
|
||||
}),
|
||||
'项目资料已保存',
|
||||
);
|
||||
} else {
|
||||
const category = String(v.category),
|
||||
side =
|
||||
kind === 'debt' ||
|
||||
(kind === 'account' && ['credit_card', 'loan'].includes(category))
|
||||
? 'liability'
|
||||
: 'asset';
|
||||
void act(
|
||||
() =>
|
||||
api('/positions', 'POST', {
|
||||
...v,
|
||||
...(f.has('iconId') ? { iconId: f.get('iconId') || null } : {}),
|
||||
kind,
|
||||
side,
|
||||
hidden: f.get('hidden') === 'on',
|
||||
}),
|
||||
'项目已添加',
|
||||
);
|
||||
{modal.kind === 'transfer' ? (
|
||||
<TransferForm
|
||||
accounts={positions.filter(
|
||||
(p) => p.kind === 'account' && p.side === 'asset' && !p.archived,
|
||||
)}
|
||||
busy={busy}
|
||||
submit={(v) =>
|
||||
void act(() => api('/transfers', 'POST', v), '转账已保存,双方余额已更新')
|
||||
}
|
||||
}}
|
||||
>
|
||||
{modal.kind === 'reveal' && (
|
||||
<Field label="登录密码">
|
||||
<input
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
maxLength={72}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{['account', 'asset', 'debt', 'edit'].includes(modal.kind) && (
|
||||
<>
|
||||
<label className="check-line">
|
||||
<input name="hidden" type="checkbox" defaultChecked={modal.p?.hidden} />
|
||||
隐藏此项目(密码验证后可查看和编辑)
|
||||
</label>
|
||||
{(modal.kind === 'account' || modal.p?.kind === 'account') && (
|
||||
<IconLibrary
|
||||
key={modal.p?.id || 'new-account'}
|
||||
picker
|
||||
initialId={modal.p?.iconId}
|
||||
/>
|
||||
)}
|
||||
<Field label="名称">
|
||||
/>
|
||||
) : (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget),
|
||||
v = Object.fromEntries(f.entries()),
|
||||
kind = modal.kind,
|
||||
mp = modal.p;
|
||||
if (kind === 'reveal') {
|
||||
void act(
|
||||
() => api('/auth/reveal', 'POST', { password: f.get('password') }),
|
||||
'隐藏项目已解锁 5 分钟',
|
||||
);
|
||||
} else if (kind === 'links') {
|
||||
void act(
|
||||
() =>
|
||||
api('/positions/' + mp!.id + '/links', 'PUT', {
|
||||
targetIds: f.getAll('targetIds'),
|
||||
}),
|
||||
'关联已更新',
|
||||
);
|
||||
} else if (kind === 'revision' || kind === 'correction') {
|
||||
void act(
|
||||
() =>
|
||||
api(
|
||||
'/positions/' + mp!.id + '/revisions' + (modal.h ? '/' + modal.h.id : ''),
|
||||
modal.h ? 'PUT' : 'POST',
|
||||
v,
|
||||
),
|
||||
'金额历史已保存,总览已重新计算',
|
||||
);
|
||||
} else if (kind === 'edit') {
|
||||
void act(
|
||||
() =>
|
||||
api('/positions/' + mp!.id, 'PATCH', {
|
||||
...v,
|
||||
...(f.has('iconId') ? { iconId: f.get('iconId') || null } : {}),
|
||||
archived: mp!.archived,
|
||||
hidden: f.get('hidden') === 'on',
|
||||
}),
|
||||
'项目资料已保存',
|
||||
);
|
||||
} else {
|
||||
const category = String(v.category),
|
||||
side =
|
||||
kind === 'debt' ||
|
||||
(kind === 'account' && ['credit_card', 'loan'].includes(category))
|
||||
? 'liability'
|
||||
: 'asset';
|
||||
void act(
|
||||
() =>
|
||||
api('/positions', 'POST', {
|
||||
...v,
|
||||
...(f.has('iconId') ? { iconId: f.get('iconId') || null } : {}),
|
||||
kind,
|
||||
side,
|
||||
hidden: f.get('hidden') === 'on',
|
||||
}),
|
||||
'项目已添加',
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{modal.kind === 'reveal' && (
|
||||
<Field label="登录密码">
|
||||
<input
|
||||
name="name"
|
||||
defaultValue={modal.p?.name}
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
maxLength={100}
|
||||
autoFocus
|
||||
maxLength={72}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="类别">
|
||||
<select
|
||||
name="category"
|
||||
defaultValue={modal.p?.category || categories[modal.kind]?.[0][0]}
|
||||
>
|
||||
{categories[modal.p?.kind || modal.kind].map(([v, label]) => (
|
||||
<option key={v} value={v}>
|
||||
{label}
|
||||
</option>
|
||||
)}
|
||||
{['account', 'asset', 'debt', 'edit'].includes(modal.kind) && (
|
||||
<>
|
||||
<label className="check-line">
|
||||
<input name="hidden" type="checkbox" defaultChecked={modal.p?.hidden} />
|
||||
隐藏此项目(密码验证后可查看和编辑)
|
||||
</label>
|
||||
{(modal.kind === 'account' || modal.p?.kind === 'account') && (
|
||||
<IconPicker key={modal.p?.id || 'new-account'} initialId={modal.p?.iconId} />
|
||||
)}
|
||||
<Field label="名称">
|
||||
<input
|
||||
name="name"
|
||||
defaultValue={modal.p?.name}
|
||||
required
|
||||
maxLength={100}
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
<Field label="类别">
|
||||
<select
|
||||
name="category"
|
||||
defaultValue={modal.p?.category || categories[modal.kind]?.[0][0]}
|
||||
>
|
||||
{categories[modal.p?.kind || modal.kind].map(([v, label]) => (
|
||||
<option key={v} value={v}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{modal.kind === 'account' && (
|
||||
<p className="muted">信用卡、贷款账户自动计入负债,其余账户计入资产。</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{['account', 'asset', 'debt'].includes(modal.kind) && (
|
||||
<Field label="原币币种">
|
||||
<select name="currency" defaultValue={user.baseCurrency}>
|
||||
{currencies.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{modal.kind === 'account' && (
|
||||
<p className="muted">信用卡、贷款账户自动计入负债,其余账户计入资产。</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{['account', 'asset', 'debt'].includes(modal.kind) && (
|
||||
<Field label="原币币种">
|
||||
<select name="currency" defaultValue={user.baseCurrency}>
|
||||
{currencies.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{['account', 'asset', 'debt', 'revision', 'correction'].includes(modal.kind) && (
|
||||
<Field label={'变更后的绝对金额' + (modal.p ? '(' + modal.p.currency + ')' : '')}>
|
||||
<input
|
||||
name="amount"
|
||||
inputMode="decimal"
|
||||
required
|
||||
pattern="(0|[1-9][0-9]{0,15})(\.[0-9]{1,8})?"
|
||||
defaultValue={modal.h?.after || modal.p?.amount || ''}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{['account', 'asset', 'debt', 'revision', 'correction'].includes(modal.kind) && (
|
||||
<Field label={'业务时间(北京时间,精确到分钟)'}>
|
||||
<input
|
||||
type={'datetime-local'}
|
||||
name="date"
|
||||
required
|
||||
min={'1900-01-01T00:00'}
|
||||
max={nowMinute()}
|
||||
defaultValue={modal.h?.time || nowMinute()}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{modal.kind === 'revision' && (
|
||||
<>
|
||||
<Field label="变更原因">
|
||||
<select
|
||||
name="reason"
|
||||
defaultValue={modal.p?.kind === 'asset' ? 'valuation' : 'balance'}
|
||||
>
|
||||
<option value="balance">余额更新</option>
|
||||
<option value="valuation">估值更新</option>
|
||||
{modal.p?.side === 'liability' && (
|
||||
<option value="repayment">还款(填写还款后欠款)</option>
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
<p className="muted">
|
||||
填写更新后的余额或剩余欠款,每次保存会新增历史。已有错误记录请在历史中更正。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{modal.kind === 'correction' && (
|
||||
<p className="notice warning">
|
||||
这将修改选中的历史金额并重算后续变化,请确认日期和余额。
|
||||
</p>
|
||||
)}
|
||||
{modal.kind === 'links' ? (
|
||||
<div className="link-options">
|
||||
{positions.filter((p) => p.kind !== 'debt').length ? (
|
||||
positions
|
||||
.filter((p) => p.kind !== 'debt')
|
||||
.map((p) => (
|
||||
<label key={p.id}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="targetIds"
|
||||
value={p.id}
|
||||
defaultChecked={modal.p!.outgoing.some((l) => l.targetId === p.id)}
|
||||
/>
|
||||
{p.name} · {labels[p.kind]}
|
||||
</label>
|
||||
))
|
||||
) : (
|
||||
<p>请先创建账户或独立资产。</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
modal.kind !== 'reveal' && (
|
||||
<Field label="备注">
|
||||
<textarea
|
||||
name="notes"
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
defaultValue={modal.h?.notes || modal.p?.notes || ''}
|
||||
)}
|
||||
{['account', 'asset', 'debt', 'revision', 'correction'].includes(modal.kind) && (
|
||||
<Field label={'变更后的绝对金额' + (modal.p ? '(' + modal.p.currency + ')' : '')}>
|
||||
<input
|
||||
name="amount"
|
||||
inputMode="decimal"
|
||||
required
|
||||
pattern="(0|[1-9][0-9]{0,15})(\.[0-9]{1,8})?"
|
||||
defaultValue={modal.h?.after || modal.p?.amount || ''}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</Field>
|
||||
)
|
||||
)}
|
||||
{error && (
|
||||
<div role="alert" className="notice error">
|
||||
{error}
|
||||
)}
|
||||
{['account', 'asset', 'debt', 'revision', 'correction'].includes(modal.kind) && (
|
||||
<Field label={'业务时间(北京时间,精确到分钟)'}>
|
||||
<input
|
||||
type={'datetime-local'}
|
||||
name="date"
|
||||
required
|
||||
min={'1900-01-01T00:00'}
|
||||
max={nowMinute()}
|
||||
defaultValue={modal.h?.time || nowMinute()}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{modal.kind === 'revision' && (
|
||||
<>
|
||||
<Field label="变更原因">
|
||||
<select
|
||||
name="reason"
|
||||
defaultValue={modal.p?.kind === 'asset' ? 'valuation' : 'balance'}
|
||||
>
|
||||
<option value="balance">余额更新</option>
|
||||
<option value="valuation">估值更新</option>
|
||||
{modal.p?.side === 'liability' && (
|
||||
<option value="repayment">还款(填写还款后欠款)</option>
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
<p className="muted">
|
||||
填写更新后的余额或剩余欠款,每次保存会新增历史。已有错误记录请在历史中更正。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{modal.kind === 'correction' && (
|
||||
<p className="notice warning">
|
||||
这将修改选中的历史金额并重算后续变化,请确认日期和余额。
|
||||
</p>
|
||||
)}
|
||||
{modal.kind === 'links' ? (
|
||||
<div className="link-options">
|
||||
{positions.filter((p) => p.kind !== 'debt').length ? (
|
||||
positions
|
||||
.filter((p) => p.kind !== 'debt')
|
||||
.map((p) => (
|
||||
<label key={p.id}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="targetIds"
|
||||
value={p.id}
|
||||
defaultChecked={modal.p!.outgoing.some((l) => l.targetId === p.id)}
|
||||
/>
|
||||
{p.name} · {labels[p.kind]}
|
||||
</label>
|
||||
))
|
||||
) : (
|
||||
<p>请先创建账户或独立资产。</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
modal.kind !== 'reveal' && (
|
||||
<Field label="备注">
|
||||
<textarea
|
||||
name="notes"
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
defaultValue={modal.h?.notes || modal.p?.notes || ''}
|
||||
/>
|
||||
</Field>
|
||||
)
|
||||
)}
|
||||
{error && (
|
||||
<div role="alert" className="notice error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="modal-actions">
|
||||
<button
|
||||
className="secondary"
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setModal(null)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button className="primary" disabled={busy}>
|
||||
{busy ? '正在保存…' : modal.kind === 'correction' ? '确认更正' : '保存'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="modal-actions">
|
||||
<button
|
||||
className="secondary"
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setModal(null)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button className="primary" disabled={busy}>
|
||||
{busy ? '正在保存…' : modal.kind === 'correction' ? '确认更正' : '保存'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
@@ -1508,7 +1659,7 @@ function HistoryTable({
|
||||
<th>变更前</th>
|
||||
<th>变更后</th>
|
||||
<th>变化额</th>
|
||||
<th>备注</th>
|
||||
<th className="notes-cell">备注</th>
|
||||
{correct && <th>操作</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -1533,6 +1684,8 @@ function HistoryTable({
|
||||
valuation: '估值更新',
|
||||
repayment: '还款',
|
||||
correction: '更正',
|
||||
transfer_out: '转账转出',
|
||||
transfer_in: '转账到账',
|
||||
} as Record<string, string>
|
||||
)[h.reason]
|
||||
}
|
||||
@@ -1544,7 +1697,11 @@ function HistoryTable({
|
||||
<td className="notes-cell">{h.notes || '—'}</td>
|
||||
{correct && (
|
||||
<td>
|
||||
<button className="text" onClick={() => correct(h)}>
|
||||
<button
|
||||
className="text"
|
||||
disabled={h.reason.startsWith('transfer_')}
|
||||
onClick={() => correct(h)}
|
||||
>
|
||||
更正
|
||||
</button>
|
||||
</td>
|
||||
|
||||
@@ -5,9 +5,11 @@ export const iconUrl = (id: string) => '/api/icons/' + encodeURIComponent(id) +
|
||||
export function IconLibrary({
|
||||
initialId,
|
||||
picker = false,
|
||||
onSelect,
|
||||
}: {
|
||||
initialId?: string | null;
|
||||
picker?: boolean;
|
||||
onSelect?: (id: string) => void;
|
||||
}) {
|
||||
const [selected, select] = useState(initialId || ''),
|
||||
[q, search] = useState(''),
|
||||
@@ -113,7 +115,6 @@ export function IconLibrary({
|
||||
</p>
|
||||
{picker && (
|
||||
<div className="icon-selection">
|
||||
<input type="hidden" name="iconId" value={selected} />
|
||||
{selected ? (
|
||||
<>
|
||||
<img src={iconUrl(selected)} alt="当前账户图标" />
|
||||
@@ -189,6 +190,11 @@ export function IconLibrary({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{onSelect && (
|
||||
<button type="button" className="primary" onClick={() => onSelect(selected)}>
|
||||
应用所选图标
|
||||
</button>
|
||||
)}
|
||||
<details className="icon-upload">
|
||||
<summary>上传我的图标 / 导入共享图标</summary>
|
||||
<label>
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { IconLibrary, iconUrl } from './IconLibrary';
|
||||
export function IconPicker({ initialId }: { initialId?: string | null }) {
|
||||
const [id, setId] = useState(initialId || ''),
|
||||
[open, setOpen] = useState(false);
|
||||
const dialog = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const prior = document.activeElement as HTMLElement;
|
||||
dialog.current?.querySelector<HTMLInputElement>('input[type=search]')?.focus();
|
||||
function key(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopImmediatePropagation();
|
||||
setOpen(false);
|
||||
}
|
||||
if (e.key === 'Tab') {
|
||||
const controls = [
|
||||
...(dialog.current?.querySelectorAll<HTMLElement>(
|
||||
'button:not(:disabled), input, select, summary',
|
||||
) || []),
|
||||
].filter((v) => v.offsetParent !== null);
|
||||
const index = controls.indexOf(document.activeElement as HTMLElement);
|
||||
if (e.shiftKey && index <= 0) {
|
||||
e.preventDefault();
|
||||
controls.at(-1)?.focus();
|
||||
} else if (!e.shiftKey && index === controls.length - 1) {
|
||||
e.preventDefault();
|
||||
controls[0]?.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', key, true);
|
||||
return () => {
|
||||
document.removeEventListener('keydown', key, true);
|
||||
prior?.focus();
|
||||
};
|
||||
}, [open]);
|
||||
return (
|
||||
<div className="account-icon-field">
|
||||
<input type="hidden" name="iconId" value={id} />
|
||||
{id && <img src={iconUrl(id)} alt="已选账户图标" />}
|
||||
<button type="button" className="secondary" onClick={() => setOpen(true)}>
|
||||
{id ? '更换图标' : '选择图标'}
|
||||
</button>
|
||||
{id && (
|
||||
<button type="button" className="text" onClick={() => setId('')}>
|
||||
移除
|
||||
</button>
|
||||
)}
|
||||
{open &&
|
||||
createPortal(
|
||||
<div
|
||||
className="icon-picker-backdrop"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) setOpen(false);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={dialog}
|
||||
className="icon-picker-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="选择账户图标"
|
||||
>
|
||||
<div className="panel-title">
|
||||
<h2>账户图标</h2>
|
||||
<button type="button" className="secondary" onClick={() => setOpen(false)}>
|
||||
关闭图标选择
|
||||
</button>
|
||||
</div>
|
||||
<IconLibrary
|
||||
picker
|
||||
initialId={id}
|
||||
onSelect={(value) => {
|
||||
setId(value);
|
||||
setOpen(false);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { nowMinute, money, requestUuid, type Position } from './api';
|
||||
export function TransferForm({
|
||||
accounts,
|
||||
busy,
|
||||
submit,
|
||||
}: {
|
||||
accounts: Position[];
|
||||
busy: boolean;
|
||||
submit: (data: unknown) => void;
|
||||
}) {
|
||||
const [requestId] = useState(() => requestUuid());
|
||||
const [sourceId, setSource] = useState(accounts[0]?.id || ''),
|
||||
[targetId, setTarget] = useState(accounts[1]?.id || ''),
|
||||
[amount, setAmount] = useState('');
|
||||
const source = accounts.find((p) => p.id === sourceId),
|
||||
target = accounts.find((p) => p.id === targetId);
|
||||
const same = source?.currency === target?.currency;
|
||||
function save(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
submit(Object.fromEntries(new FormData(e.currentTarget)));
|
||||
}
|
||||
if (accounts.length < 2)
|
||||
return <p>请先创建至少两个启用中的资产账户。隐藏账户需验证密码后才能选择。</p>;
|
||||
return (
|
||||
<form onSubmit={save} className="transfer-form">
|
||||
<input type="hidden" name="requestId" value={requestId} />
|
||||
<p className="muted">
|
||||
双方余额同时更新。手续费从转出账户额外扣除;转账时间不能早于双方最新余额记录。
|
||||
</p>
|
||||
<label>
|
||||
转出账户
|
||||
<select name="sourceId" value={sourceId} onChange={(e) => setSource(e.target.value)}>
|
||||
{accounts.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name} · {money(p.amount, p.currency)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
转入账户
|
||||
<select name="targetId" value={targetId} onChange={(e) => setTarget(e.target.value)}>
|
||||
{accounts.map((p) => (
|
||||
<option key={p.id} value={p.id} disabled={p.id === sourceId}>
|
||||
{p.name} · {p.currency}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="form-columns">
|
||||
<label>
|
||||
转出金额({source?.currency})
|
||||
<input
|
||||
name="amount"
|
||||
required
|
||||
inputMode="decimal"
|
||||
pattern="(0|[1-9][0-9]{0,15})(\.[0-9]{1,8})?"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
实际到账({target?.currency})
|
||||
{same ? (
|
||||
<input name="received" required readOnly value={amount} />
|
||||
) : (
|
||||
<input
|
||||
key={targetId}
|
||||
name="received"
|
||||
required
|
||||
inputMode="decimal"
|
||||
pattern="(0|[1-9][0-9]{0,15})(\.[0-9]{1,8})?"
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
{!same && (
|
||||
<p className="notice warning">跨币种请填写银行实际到账金额;本次转账不修改公共参考汇率。</p>
|
||||
)}
|
||||
<label>
|
||||
额外手续费({source?.currency})
|
||||
<input
|
||||
name="fee"
|
||||
required
|
||||
defaultValue="0"
|
||||
inputMode="decimal"
|
||||
pattern="(0|[1-9][0-9]{0,15})(\.[0-9]{1,8})?"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
转账时间(北京时间)
|
||||
<input
|
||||
name="date"
|
||||
type="datetime-local"
|
||||
required
|
||||
defaultValue={nowMinute()}
|
||||
max={nowMinute()}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
备注
|
||||
<textarea className="note-input" name="notes" maxLength={2000} rows={2} />
|
||||
</label>
|
||||
<button className="primary" disabled={busy || sourceId === targetId}>
|
||||
{busy ? '正在转账…' : '确认转账'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
+24
-1
@@ -20,7 +20,8 @@ export async function api<T>(path: string, method = 'GET', data?: unknown): Prom
|
||||
export type User = {
|
||||
username: string;
|
||||
baseCurrency: string;
|
||||
showSidebar: boolean;
|
||||
hiddenMenus: string[];
|
||||
showNotes: boolean;
|
||||
idleMinutes: number;
|
||||
revealed?: boolean;
|
||||
revealUntil?: string | null;
|
||||
@@ -103,3 +104,25 @@ export function money(v: string, currency: string) {
|
||||
const [whole, frac] = v.split('.');
|
||||
return `${currency} ${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}${frac !== undefined ? '.' + frac : ''}`;
|
||||
}
|
||||
|
||||
export type Transfer = {
|
||||
id: string;
|
||||
source: { name: string };
|
||||
target: { name: string };
|
||||
sourceCurrency: string;
|
||||
targetCurrency: string;
|
||||
amount: string;
|
||||
received: string;
|
||||
fee: string;
|
||||
date: string;
|
||||
notes: string;
|
||||
};
|
||||
|
||||
// getRandomValues also works when a development tunnel uses plain HTTP.
|
||||
export function requestUuid() {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 15) | 64;
|
||||
bytes[8] = (bytes[8] & 63) | 128;
|
||||
const hex = Array.from(bytes, (v) => v.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
@@ -6,6 +6,111 @@
|
||||
font-weight: 400;
|
||||
line-height: 1.6;
|
||||
}
|
||||
/* Keep native hidden panels hidden even when component classes use grid/flex. */
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
.settings-grid {
|
||||
grid-template-columns: 1fr !important;
|
||||
}
|
||||
.settings-switch {
|
||||
max-width: 560px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.settings-switch label,
|
||||
.transfer-form label {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
.menu-preferences,
|
||||
.form-columns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 18px;
|
||||
}
|
||||
.transfer-form {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
.account-icon-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 14px 0 22px;
|
||||
}
|
||||
.account-icon-field img {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
object-fit: contain;
|
||||
}
|
||||
.icon-picker-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 100;
|
||||
background: #19392d70;
|
||||
backdrop-filter: blur(5px);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.icon-picker-dialog {
|
||||
width: min(800px, 100%);
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
padding: 28px;
|
||||
background: #f7faf8;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px #14342940;
|
||||
}
|
||||
.icon-option {
|
||||
background: transparent !important;
|
||||
border: 0 !important;
|
||||
border-radius: 12px;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
button.icon-option:hover {
|
||||
background: #e7f1eb !important;
|
||||
}
|
||||
.icon-option.selected {
|
||||
background: #dceee4 !important;
|
||||
box-shadow: inset 0 0 0 2px #388569;
|
||||
}
|
||||
.position-icon {
|
||||
background: transparent !important;
|
||||
}
|
||||
.transfer-list {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin: 20px 0 30px;
|
||||
}
|
||||
.transfer-list article {
|
||||
border: 1px solid #dce5df;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
.transfer-list article > div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.transfer-list p {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.menu-preferences,
|
||||
.form-columns {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.icon-picker-backdrop {
|
||||
padding: 10px;
|
||||
}
|
||||
.icon-picker-dialog {
|
||||
padding: 18px;
|
||||
max-height: 94vh;
|
||||
border-radius: 14px;
|
||||
}
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@@ -996,3 +1101,79 @@ footer {
|
||||
vertical-align: middle;
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
.danger-text {
|
||||
color: #b42318 !important;
|
||||
}
|
||||
.clear-confirm-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.switch-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.switch-row > span:first-child {
|
||||
flex: 1;
|
||||
}
|
||||
.switch-row input[role='switch'] {
|
||||
appearance: none;
|
||||
width: 44px;
|
||||
height: 26px;
|
||||
min-height: 26px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 20px;
|
||||
background: #c8d0cd;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
margin: 0;
|
||||
transition: background 0.2s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.switch-row input[role='switch']::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
left: 3px;
|
||||
top: 3px;
|
||||
background: white;
|
||||
box-shadow: 0 1px 3px #0002;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
.switch-row input[role='switch']:checked {
|
||||
background: #167b5b;
|
||||
}
|
||||
.switch-row input[role='switch']:checked::after {
|
||||
transform: translateX(18px);
|
||||
}
|
||||
.switch-row input[role='switch']:focus-visible {
|
||||
outline: 3px solid #a4d8c1;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.switch-state {
|
||||
min-width: 32px;
|
||||
font-size: 13px;
|
||||
color: #167b5b;
|
||||
}
|
||||
.switch-row input:not(:checked) + .switch-state {
|
||||
font-size: 0;
|
||||
color: #68766f;
|
||||
}
|
||||
.switch-row input:not(:checked) + .switch-state::after {
|
||||
content: '隐藏';
|
||||
font-size: 13px;
|
||||
}
|
||||
.notes-hidden .note-field,
|
||||
.notes-hidden .notes-display,
|
||||
.notes-hidden .notes-cell,
|
||||
.notes-hidden label:has(.note-input) {
|
||||
display: none !important;
|
||||
}
|
||||
Reference in new issue
Block a user