DriftLedger/tests/importRealFiles.test.ts
fengmengqi 7fa345b558 feat: 品牌重命名为浮记(DriftLedger),全面升级精度安全与架构
品牌与配置
- 重命名 Bean Mobile → 浮记(DriftLedger),slug 改为 drift-ledger
- 所有 Config Plugin 从 app.json 动态读取 appId,替换硬编码 com.beancount.mobile
- 预构建时自动从 constants.ts 同步支付包名列表到 Kotlin 端
- size-optimization 插件新增 NDK 版本强制统一(27.1.12297006)
- 添加 app icon(direction_a_feather.png)
Decimal 精度改造
- 全面消除 parseFloat 用于金额计算的场景,改用 string decimal 运算
- 新增 divideDecimals(除法)、toDateString(Date→YYYY-MM-DD)
- negateDecimal 零值特殊处理,避免产生 "-0"
- 年报/月报/预算/信用卡/汇率/图表统计等模块全部迁移
- 去重指纹用 parseDecimal 归一化金额格式
- 转账识别增加 normalizeAmount,支持不同精度格式配对(100 vs 100.00)
架构变更
- mobile.bean → main.bean:移除启动时合并迁移逻辑,直接读写 main.bean
- TransactionDraft.sourceEventId → sourceEventIds(数组,支持转账双方)
- 新增 buildPostings() 纯函数,从 transactionBuilder 提取复式分录构建逻辑
- 新增 csvUtils.ts(引号感知 CSV 行拆分),statements/adapters 共用
- 新增 accessibilityParser.ts:从 automationPipeline 提取微信/支付宝文本解析
- 新增 floatingBillManager.ts:悬浮窗草稿管理(LRU+超时)与排序数据构建
- 新增 txKeyStore.ts:交易级去重键持久化(原子写入+500条LRU)
- ledger.ts 新增 resolveIncludes 选项,支持 include 指令递归解析
- metadataStore CRUD 用 createCrudActions 工厂消除7组实体重复代码
安全与持久化
- PIN 哈希改用带盐 SHA-256,兼容旧版无 salt 数据迁移
- storePersistence 从 persistTo 回调改为 subscribe 自动触发
- 持久化增加深比较跳过无变化写入 + 滞后重试
- 新增 flushPersistence(),App 切后台时立即刷盘
- CrashReporter 新增文件持久化(CrashFs 抽象)
- settingsStore hydrate 期间跳过自动持久化(skipPersist 标志)
去重与管道
- batchDedup 改用日期索引 Map,候选查找从 O(n) 降至 O(1)
- dedupAgainstHistory 按日期分组,仅扫描时间窗口内候选
- OcrProcessor 从布尔标志改为 Promise 队列,不再丢弃并发请求
- 去重缓存改用 Map<hash,timestamp> LRU,阈值超20%时批量淘汰
- 悬浮球全局开关(floatingBallEnabled) + 原生 bridge API
其他改进
- recurring 计算修复月/年溢出(1月31日+1月→2月28日,闰年2月29日)
- 预算进度按 posting 分录金额求和(不再仅过滤负数金额)
- recurring.ts 用 Date.parse 本地时间替代 toISOString 的 UTC 偏移
- 信用卡账单日/还款日限制不超过28,防止月份溢出
- 类别模糊匹配增加最小长度2,避免单字符误匹配
- 还款检测排除 refund 方向,避免退款被误判为还款
- WebDAV 同步增加 HTTP 日期格式解析
- Git 合并策略改为以 remote 为基础追加 local 独有行
性能优化
- commonStyles 全局 useMemo 缓存
- Button/Card 的 pressIn/pressOut 改用 useCallback
- TransactionCard/AccountTreeNode 包裹 React.memo
- PostingEditor 用 refs + 函数式更新避免重建
- CreditCard 页预计算账户余额 Map,避免渲染循环重复遍历
- OCR 处理器单例复用,配置变更时才重建
- getLocalAuth/getAccessibilityBridge 结果缓存
测试
- 新增 decimal/constants/channelConfig/transactionBuilder 单测
- 修复金额格式断言(-24.5→-24.50),匹配字符串精度行为
- billPipeline 新增不同格式金额配对、指纹唯一性测试
2026-07-21 15:16:44 +08:00

109 lines
5.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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('彩棠'));
// 彩棠退款/收入事件(金额 238.00
expect(caitangEvents.some(e => e.amount === '238.00')).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!');
});
});