DriftLedger/tests/importRealFiles.test.ts
fengmengqi 76a5853ab6 feat: 重构渠道模型与管道架构,全面升级 UI 主题和报表功能
核心重构 — 去除 channel 字段,引入 sourceAccount 模型:
- 从 ImportedEvent、Rule、EnhancedRule、OcrRule 等接口中彻底移除 channel 字段
- rules.ts 中 resolveChannelAccount → resolveSourceAccount,规则匹配与账户解析不再依赖渠道概念
- dedup.ts 重写去重逻辑:从基于渠道匹配改为基于交易对手(counterparty)匹配,支持相同金额/交易对手/时间窗口的多级置信度判断
- transferRecognizer.ts 增加资产负债表账户校验,确保转账双方均为 Assets/Liabilities 类账户
- 全局替换影响:types、rules、ocr、adapters、adapters-migrations、所有服务层和测试
新增基础设施:
- domain/constants.ts — 统一常量定义(支付包名、截图关键词、去重参数、方向检测函数 detectDirection()),消除 OCR/SMS/截图等模块的重复定义
- domain/channelConfig.ts — 渠道配置系统(支付宝/微信/银行),支持按包名和名称查找
- domain/pipelineSingleton.ts — 共享 BillPipeline 单例,解决 importStore/automationStore 的互斥锁共享问题
- domain/transactionBuilder.ts — 统一交易构建入口 buildAndSaveTransaction(),同时服务手动录入和无障碍监听
OCR 增强:
- 新增账单详情页解析(parseDetailPageBill),支持支付宝/微信详情页结构化提取
- checkIsDetailPage() 识别详情页特征词,防止误提取(如"消费1次"被误读为金额)
- 金额正则支持千分位逗号分隔,商户名正则改用 lookahead 边界匹配
- 时间解析支持中文格式(年月日)和跨年推断
- OcrProcessor 新增详情页路由,跳过 Layer 1 规则匹配
UI 全面升级:
- 主题重设计:accent 色从绿色改为靛蓝(#4F46E5),深色模式适配 OLED 纯黑,引入 Quicksand/Caveat 字体
- 新增 commonStyles.ts 统一 chip/input/modal 等通用样式
- 首页 Bento 网格布局:净资产英雄卡片 + 定期账单/月度统计并排展示
- 报表新增周报标签页,月报整合日历视图(支持点击查看当日交易明细)
- TrendLine 图表从 View 条形图重写为 SVG 贝塞尔曲线
- CategoryPicker 从水平滚动改为 4 列网格 + emoji 图标
- Button/Card 增加 press 缩放动画
管道与自动化改进:
- automationPipeline.ts 新增 handleIncomingBillEvent() 实时账单处理(悬浮账单卡片 + 前台 Alert 确认)
- 新增无障碍文本直解析 parseAndProcessAccessibilityTexts(),微信/支付宝详情页绕过 OCR
- rules.ts 新增智能还款检测(花呗/信用卡还款自动路由)和退款视为收入处理
- metadataStore 默认规则精简为 6 条通用规则,移除约 20 条个人化硬编码规则
存储与同步:
- storePersistence.ts 原子写入 + 崩溃恢复 + 重试机制
- 备份升级到 v2 格式,包含 settings 和 metadata
- 同步路径统一从 mobile.bean 改为 main.bean
- _layout.tsx 启动时自动迁移旧 mobile.bean 到 main.bean
其他:
- 删除独立日历页面,功能合并到报表月报标签
- i18n 清理:移除渠道相关翻译,新增 50+ 翻译键
- docs/android-build-guide.md 重写为 APK 体积优化指南
- 新增 design-system/beancount-mobile/MASTER.md 设计系统文档
- 测试全面更新覆盖以上所有变更
2026-07-18 18:02:45 +08:00

109 lines
5.1 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import fs from 'fs';
import path from 'path';
import * as XLSX from 'xlsx';
import { importStatement } from '../src/domain/statements';
import { batchDedup } from '../src/domain/dedup';
// @ts-ignore
const GbkTextDecoder = (() => {
const origDecoder = global.TextDecoder;
const origEncoder = global.TextEncoder;
global.TextDecoder = undefined as any;
global.TextEncoder = undefined as any;
const dec = require('text-encoding-gbk').TextDecoder;
global.TextDecoder = origDecoder;
global.TextEncoder = origEncoder;
return dec;
})();
describe('Real Files Import Integrity and Health Test', () => {
it('should parse both files and pass all field validation checks', () => {
const exampleDir = path.join(__dirname, '../example');
const files = fs.readdirSync(exampleDir);
const xlsxFileName = files.find(f => f.endsWith('.xlsx') && !f.startsWith('~$'));
const csvFileName = files.find(f => f.endsWith('.csv') && !f.startsWith('~$'));
expect(xlsxFileName).toBeDefined();
expect(csvFileName).toBeDefined();
// 1. Parse WeChat Excel file
const xlsxPath = path.join(exampleDir, xlsxFileName!);
const workbook = XLSX.readFile(xlsxPath);
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const wechatCsv = XLSX.utils.sheet_to_csv(worksheet);
const wechatEvents = importStatement(wechatCsv, 'wechat-csv-v1');
// 2. Parse Alipay CSV file
const csvPath = path.join(exampleDir, csvFileName!);
const csvBuffer = fs.readFileSync(csvPath);
const decoder = new GbkTextDecoder('gbk');
const alipayCsv = decoder.decode(csvBuffer);
const alipayEvents = importStatement(alipayCsv, 'alipay-csv-v1');
const allEvents = [...wechatEvents, ...alipayEvents];
console.log(`Total events to validate: ${allEvents.length}`);
const seenIds = new Set<string>();
for (let i = 0; i < allEvents.length; i++) {
const e = allEvents[i];
const errMsg = `Failed validation at index ${i} (ID: ${e.id})`;
// A. ID Validation
expect(e.id, `${errMsg}: ID should be a non-empty string`).toBeTruthy();
expect(typeof e.id, `${errMsg}: ID should be a string`).toBe('string');
expect(seenIds.has(e.id), `${errMsg}: ID ${e.id} is duplicated!`).toBe(false);
seenIds.add(e.id);
// B. Date and Time Format Validation
expect(e.occurredAt, `${errMsg}: occurredAt should be a non-empty string`).toBeTruthy();
// Date should match YYYY-MM-DD format prefix
expect(e.occurredAt, `${errMsg}: occurredAt "${e.occurredAt}" does not start with YYYY-MM-DD`).toMatch(/^\d{4}-\d{2}-\d{2}/);
// Parsing the date should be valid (not NaN)
const parsedTime = Date.parse(e.occurredAt);
expect(Number.isNaN(parsedTime), `${errMsg}: occurredAt "${e.occurredAt}" is not a valid date string`).toBe(false);
// C. Amount Format Validation
expect(e.amount, `${errMsg}: amount should be a non-empty string`).toBeTruthy();
// Amount must be a valid signed decimal string
expect(e.amount, `${errMsg}: amount "${e.amount}" is not a valid signed decimal string`).toMatch(/^-?\d+(\.\d+)?$/);
const parsedAmount = parseFloat(e.amount);
expect(Number.isNaN(parsedAmount), `${errMsg}: amount "${e.amount}" cannot be parsed into a number`).toBe(false);
// D. Currency Code Validation
expect(e.currency, `${errMsg}: currency should be a non-empty string`).toBeTruthy();
expect(e.currency, `${errMsg}: currency "${e.currency}" is invalid`).toMatch(/^[A-Z]{3}$/);
// E. Direction Validation
expect(e.direction, `${errMsg}: direction "${e.direction}" is invalid`).toMatch(/^(income|expense|transfer|refund|fee)$/);
// F. Column Shift / Misalignment Check
// Ensure data has not shifted (e.g. headers appeared as values)
const headerKeywords = ['金额', '交易时间', '交易对方', '收/支', '商品', '备注', '交易单号', '商户单号'];
headerKeywords.forEach(kw => {
expect(e.amount.includes(kw), `${errMsg}: amount "${e.amount}" contains header keyword "${kw}"`).toBe(false);
expect(e.occurredAt.includes(kw), `${errMsg}: occurredAt "${e.occurredAt}" contains header keyword "${kw}"`).toBe(false);
});
}
console.log('✓ All 468 events passed structural integrity checks!');
// 3. Run Deduplication
const { accepted, duplicates } = batchDedup(allEvents);
console.log(`✓ Deduplication executed: ${accepted.length} accepted, ${duplicates.length} duplicates.`);
// 4. Verify specific test cases (Caitang refund and Metro rides)
const caitangEvents = accepted.filter(e => e.counterparty.includes('彩棠'));
expect(caitangEvents.some(e => (e.direction === 'refund' || e.direction === 'income') && parseFloat(e.amount) === 238)).toBe(true);
expect(caitangEvents.some(e => e.direction === 'expense' && parseFloat(e.amount) === -238)).toBe(true);
const metroEvents = accepted.filter(e => e.counterparty.includes('长沙地铁') && e.occurredAt.startsWith('2026-04-25'));
expect(metroEvents.length).toBe(2);
console.log('✓ Refund and Metro rides specific test cases passed!');
});
});