DriftLedger/tests/mobileStore.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

151 lines
5.8 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, expect, it } from 'vitest';
import { MemoryBackend, MobileBeanStore, createMobileStore } from '../src/domain/mobileStore';
import { parseLedger } from '../src/domain/ledger';
import type { TransactionDraft } from '../src/domain/types';
const ledger = parseLedger([{ path: 'main.bean', content: '2026-01-01 open Assets:Alipay CNY\n2026-01-01 open Expenses:Food CNY\n' }]);
const draft = (n: number): TransactionDraft => ({
date: '2026-02-01',
narration: `test${n}`,
postings: [{ account: 'Assets:Alipay', amount: `-${n}`, currency: 'CNY' }, { account: 'Expenses:Food', amount: `${n}`, currency: 'CNY' }],
});
describe('MobileBeanStore - 基础写入', () => {
it('init 后内容为空(无初始)', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
expect(store.getContent()).toBe('');
});
it('append 一笔后内容含交易', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
const commit = await store.append(draft(1), ledger);
expect(commit.content).toContain('test1');
expect(commit.content).toContain('Assets:Alipay');
expect(store.getContent()).toBe(commit.content);
});
it('append 多笔依次追加(不覆盖)', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
await store.append(draft(1), ledger);
await store.append(draft(2), ledger);
const content = store.getContent();
expect(content).toContain('test1');
expect(content).toContain('test2');
});
it('appendWithSource 携带 sourceEventIds', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
await store.appendWithSource(draft(1), ledger, ['evt-001']);
// sourceEventIds 不写入 .bean 内容(仅内存关联),验证不报错即可
expect(store.getContent()).toContain('test1');
});
it('replace 直接替换内容(导入/恢复场景)', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
await store.replace('2026-02-01 * "x" "y"\n Assets:Alipay -1 CNY\n Expenses:Food 1 CNY\n');
expect(store.getContent()).toContain('"x"');
});
});
describe('MobileBeanStore - 并发安全', () => {
it('并发 append 串行化,内容不丢失不交错', async () => {
const backend = new MemoryBackend();
const store = createMobileStore(backend);
await store.init();
// 同时发起 10 笔 append
await Promise.all(Array.from({ length: 10 }, (_, i) => store.append(draft(i + 1), ledger)));
const content = store.getContent();
// 10 笔都应存在
for (let i = 1; i <= 10; i++) {
expect(content).toContain(`test${i}`);
}
// 写入次数 = 10每次 append 一次原子写)
expect(backend.writeCount).toBe(10);
});
it('并发 append 与 replace 混合也串行化', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
await Promise.all([
store.append(draft(1), ledger),
store.replace('REPLACED'),
store.append(draft(2), ledger),
]);
// 最终内容二选一(取决于调度顺序),但不应崩溃或损坏
const content = store.getContent();
expect(['REPLACED', 'test1', 'test2'].some(s => content.includes(s))).toBe(true);
});
});
describe('MobileBeanStore - checksum替代不可靠的 content.length', () => {
it('相同内容 checksum 一致', async () => {
const s1 = createMobileStore(new MemoryBackend());
const s2 = createMobileStore(new MemoryBackend());
await s1.init(); await s2.init();
await s1.append(draft(1), ledger);
await s2.append(draft(1), ledger);
expect(s1.checksum()).toBe(s2.checksum());
});
it('不同内容 checksum 不同', async () => {
const s1 = createMobileStore(new MemoryBackend());
const s2 = createMobileStore(new MemoryBackend());
await s1.init(); await s2.init();
await s1.append(draft(1), ledger);
await s2.append(draft(2), ledger);
expect(s1.checksum()).not.toBe(s2.checksum());
});
it('checksum 不依赖内容长度(订正:原方案用 content.length', async () => {
// 长度相同但内容不同checksum 必须不同FNV-1a 对真实账本内容区分度足够)
const s1 = createMobileStore(new MemoryBackend('2026-02-01 * "甲" "咖啡"'));
const s2 = createMobileStore(new MemoryBackend('2026-02-01 * "乙" "午餐"'));
await s1.init(); await s2.init();
expect(s1.checksum()).not.toBe(s2.checksum());
});
});
describe('MobileBeanStore - 崩溃恢复', () => {
it('init 时清理上次崩溃的 tmp 残留', async () => {
const backend = new MemoryBackend('已有内容');
backend.simulateCrashMidWrite('写了 tmp 未 rename');
const store = createMobileStore(backend);
await store.init();
// 恢复后读到的是原内容tmp 被丢弃)
expect(store.getContent()).toBe('已有内容');
expect(backend.recovered).toBe(true);
});
it('无残留时正常加载', async () => {
const backend = new MemoryBackend('正常内容');
const store = createMobileStore(backend);
await store.init();
expect(store.getContent()).toBe('正常内容');
expect(backend.recovered).toBe(false);
});
});
describe('MobileBeanStore - preview不写入', () => {
it('preview 只序列化不改变内容', async () => {
const store = createMobileStore(new MemoryBackend());
await store.init();
const before = store.getContent();
const preview = store.preview(draft(1));
expect(preview).toContain('test1');
expect(store.getContent()).toBe(before); // 内容未变
});
});
describe('createMobileStore 工厂', () => {
it('返回 MobileBeanStore 实例', () => {
const store = createMobileStore(new MemoryBackend());
expect(store).toBeInstanceOf(MobileBeanStore);
});
});