Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions client/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { api, setCsrf } from './api';
import { useWorkspace } from './stores/workspace';
import { oidcMessage, takeHashParam } from './oidc';
import { clearSnapshot, loadSnapshot, reconcileSnapshot, type OfflineSnapshot } from './offline';
import { enableReconcileDrafts, clearAllReconcileDrafts } from './reconcileDraft';

const initialTheme = readThemeEnvelope() ? {} : { preset: colors, mode: 'auto' as const };
const route = useRoute();
Expand All @@ -36,6 +37,7 @@ function expired() {
setCsrf('');
loggedIn.value = false;
void clearSnapshot();
void clearAllReconcileDrafts();
offline.value = null;
error.value = '登录已失效,请重新登录。';
}
Expand Down Expand Up @@ -68,6 +70,7 @@ onMounted(async () => {
try {
const session = await api<{ csrf: string }>('/auth/session');
setCsrf(session.csrf);
enableReconcileDrafts();
loggedIn.value = true;
const version = await api<{ dataEpoch: string }>('/offline/version');
await reconcileSnapshot(version.dataEpoch);
Expand Down Expand Up @@ -95,6 +98,7 @@ async function login() {
{ username: username.value, password: password.value },
);
setCsrf(result.csrf);
enableReconcileDrafts();
password.value = '';
initialized.value = true;
loggedIn.value = true;
Expand All @@ -114,6 +118,7 @@ async function logout() {
} finally {
setCsrf('');
loggedIn.value = false;
await clearAllReconcileDrafts();
await clearSnapshot();
offline.value = null;
}
Expand Down
138 changes: 116 additions & 22 deletions client/src/pages/ReconcilePage.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, computed, watch, onBeforeUnmount } from 'vue';
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { SSelect, SIcon } from '@vean/ui';
import {
buildPresetMapping,
Expand All @@ -23,12 +23,17 @@ import {
import { api } from '../api';
import { shortDate } from '../format';
import { useWorkspace } from '../stores/workspace';
import { loadReconcileDraft, saveReconcileDraft, clearReconcileDraft, type ReconcileDraft } from '../reconcileDraft';
import PageShell from '../components/PageShell.vue';
import BillEditor from '../components/BillEditor.vue';
import DateRangeInput from '../components/fields/DateRangeInput.vue';
import StatementSourceCard, { type StatementSource } from '../components/StatementSourceCard.vue';

const store = useWorkspace();
const restoring = ref(true);
const cacheError = ref('');
let cacheOwner = '';
let persistTimer: ReturnType<typeof setTimeout> | undefined;

const sources = ref<StatementSource[]>([]);
const dragging = ref(false);
Expand Down Expand Up @@ -160,6 +165,7 @@ function clearAllSources() {
manualRange.value = false;
rangeFrom.value = '';
rangeTo.value = '';
if (cacheOwner) void clearReconcileDraft(cacheOwner).catch(e => { cacheError.value = (e as Error).message; });
}

const autoRange = computed(() => {
Expand Down Expand Up @@ -205,6 +211,7 @@ const allTransactions = computed<BankTransaction[]>(() =>
);

async function fetchBills() {
if (restoring.value) return;
const accounts = boundAccountIds.value;
if (!accounts.length || !rangeFrom.value || !rangeTo.value) {
bills.value = [];
Expand Down Expand Up @@ -249,7 +256,7 @@ async function fetchBills() {

watch(
[boundAccountIds, rangeFrom, rangeTo, () => store.revision],
() => void fetchBills(),
() => { if (!restoring.value) void fetchBills(); },
{ immediate: true },
);

Expand All @@ -263,28 +270,42 @@ const result = computed(() =>
}),
);

// 当核验结果变化时,同步清理失效勾选,并为新唯一命中的 pending 账单默认勾选。
watch(
result,
res => {
const nextChecked = new Set<string>();
const pendingMatchedIds = new Set(res.matched.filter(m => m.bill.status === 'pending').map(m => m.bill.id));
for (const id of pendingMatchedIds) {
if (!userUncheckedIds.value.has(id)) nextChecked.add(id);
// 重新读取服务器账单后再判断哪些手动选择仍然有效;不缓存旧的匹配结论。
function reconcileSelections() {
if (restoring.value || loadingBills.value) return;
const current = result.value;
const validChoices = new Map(current.ambiguous.map(item => [
item.bill.id,
new Set(item.candidates.map(candidate => candidate.transaction.id)),
]));
const nextSelections = Object.fromEntries(
Object.entries(manualSelections.value).filter(([billId, txId]) => validChoices.get(billId)?.has(txId)),
);
if (Object.keys(nextSelections).length !== Object.keys(manualSelections.value).length) {
manualSelections.value = nextSelections;
return; // 重新计算匹配结果后再次校验。
}
const nextChecked = new Set<string>();
for (const item of current.matched) {
if (item.bill.status === 'pending' && !userUncheckedIds.value.has(item.bill.id)) {
nextChecked.add(item.bill.id);
}
for (const item of res.ambiguous) {
if (item.bill.status !== 'pending') continue;
const chosen = manualSelections.value[item.bill.id];
if (chosen && item.candidates.some(c => c.transaction.id === chosen)) {
if (checkedIds.value.has(item.bill.id) || !userUncheckedIds.value.has(item.bill.id)) {
nextChecked.add(item.bill.id);
}
}
}
for (const item of current.ambiguous) {
if (item.bill.status !== 'pending') continue;
const chosen = manualSelections.value[item.bill.id];
if (chosen && validChoices.get(item.bill.id)?.has(chosen) && !userUncheckedIds.value.has(item.bill.id)) {
nextChecked.add(item.bill.id);
}
}
if ([...nextChecked].some(id => !checkedIds.value.has(id)) ||
[...checkedIds.value].some(id => !nextChecked.has(id))) {
checkedIds.value = nextChecked;
},
{ immediate: true },
);
}
}

watch(result, reconcileSelections, { immediate: true });
watch(loadingBills, busy => { if (!busy) reconcileSelections(); });

function toggleCheck(billId: string, checked: boolean) {
const next = new Set(checkedIds.value);
Expand Down Expand Up @@ -371,8 +392,79 @@ async function confirmSelectedPaid() {
submitting.value = false;
}

function currentDraft(): ReconcileDraft {
return {
sources: sources.value.map(source => ({
id: source.id,
label: source.label,
encoding: source.encoding,
preset: source.preset,
rows: source.rows.map(row => [...row]),
accountId: source.accountId,
currency: source.currency,
mapping: { ...source.mapping },
})),
tolerance: tolerance.value,
includePaid: includePaid.value,
manualRange: manualRange.value,
rangeFrom: rangeFrom.value,
rangeTo: rangeTo.value,
manualSelections: { ...manualSelections.value },
checkedIds: [...checkedIds.value],
userUncheckedIds: [...userUncheckedIds.value],
};
}

function persistDraft() {
if (restoring.value || !cacheOwner) return;
void saveReconcileDraft(cacheOwner, currentDraft()).catch(e => {
cacheError.value = (e as Error).message;
});
}

watch(
[sources, tolerance, includePaid, manualRange, rangeFrom, rangeTo, manualSelections, checkedIds, userUncheckedIds],
() => {
if (restoring.value || !cacheOwner) return;
clearTimeout(persistTimer);
persistTimer = setTimeout(persistDraft, 350);
},
{ deep: true },
);

onMounted(async () => {
try {
const profile = await api<{ username: string }>('/profile');
cacheOwner = profile.username;
const draft = await loadReconcileDraft(cacheOwner);
if (draft) {
const activeAccountIds = new Set(store.accounts.map(a => a.id));
sources.value = draft.sources
.filter(s => Array.isArray(s.rows) && s.rows.length > 0)
.map(s => reparseSource({ ...s, accountId: activeAccountIds.has(s.accountId) ? s.accountId : '' }));
sourceSeq = sources.value.length;
tolerance.value = draft.tolerance;
includePaid.value = draft.includePaid;
manualRange.value = draft.manualRange;
manualSelections.value = draft.manualSelections ?? {};
checkedIds.value = new Set(draft.checkedIds ?? []);
userUncheckedIds.value = new Set(draft.userUncheckedIds ?? []);
if (draft.manualRange) {
rangeFrom.value = draft.rangeFrom;
rangeTo.value = draft.rangeTo;
}
}
} catch (e) {
cacheError.value = `无法恢复本机核验进度:${(e as Error).message}`;
} finally {
restoring.value = false;
await fetchBills();
}
});

onBeforeUnmount(() => {
sources.value = [];
clearTimeout(persistTimer);
persistDraft();
pasteText.value = '';
bills.value = [];
});
Expand All @@ -387,6 +479,8 @@ onBeforeUnmount(() => {
</RouterLink>
</template>

<p v-if="cacheError" class="error" role="alert">{{ cacheError }}</p>
<p v-if="restoring" class="muted">正在恢复本机核验进度…</p>
<!-- 1. 导入流水区 -->
<section class="panel stack" style="margin-bottom: 16px">
<div
Expand Down
142 changes: 142 additions & 0 deletions client/src/reconcileDraft.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import type { Currency, DateToleranceMode, StatementMapping, StatementPresetId } from '@ccm/shared';

// 本机核验草稿不包含原始 CSV 字节、服务器账单或匹配结果。
// 为了支持用户再次调整列映射,保留解码后的表格行;属于敏感数据,IndexedDB 不加密。
export interface ReconcileDraftSource {
id: string;
label: string;
encoding: 'utf-8' | 'shift_jis' | 'text';
preset: StatementPresetId | null;
rows: string[][];
accountId: string;
currency: Currency;
mapping: StatementMapping;
}

export interface ReconcileDraft {
sources: ReconcileDraftSource[];
tolerance: DateToleranceMode;
includePaid: boolean;
manualRange: boolean;
rangeFrom: string;
rangeTo: string;
manualSelections: Record<string, string>;
checkedIds: string[];
userUncheckedIds: string[];
}

interface StoredDraft extends ReconcileDraft {
version: 1;
updatedAt: number;
}

const DATABASE = 'useecard-reconcile-workspace';
const STORE = 'drafts';
const TTL_MS = 24 * 60 * 60 * 1000;
const MAX_BYTES = 10 * 1024 * 1024;

let enabled = true;
let generation = 0;
let pending: Promise<void> = Promise.resolve();
const memory = new Map<string, StoredDraft>();

function database(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DATABASE, 1);
request.onupgradeneeded = () => {
if (!request.result.objectStoreNames.contains(STORE)) request.result.createObjectStore(STORE);
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}

async function withStore<T>(
mode: IDBTransactionMode,
action: (store: IDBObjectStore, done: (value: T) => void) => void,
): Promise<T> {
const db = await database();
try {
return await new Promise<T>((resolve, reject) => {
const tx = db.transaction(STORE, mode);
let result: T;
action(tx.objectStore(STORE), value => { result = value; });
tx.oncomplete = () => resolve(result);
tx.onerror = () => reject(tx.error);
tx.onabort = () => reject(tx.error ?? new Error('本机缓存事务中断'));
});
} finally {
db.close();
}
}

function serialize(task: () => Promise<void>): Promise<void> {
const result = pending.catch(() => undefined).then(task);
pending = result.catch(() => undefined);
return result;
}

function expired(value: StoredDraft): boolean {
return value.version !== 1 ||
!Number.isFinite(value.updatedAt) ||
Date.now() - value.updatedAt > TTL_MS ||
value.updatedAt > Date.now() + 60_000;
}

export function enableReconcileDrafts(): void {
enabled = true;
}

export async function loadReconcileDraft(owner: string): Promise<ReconcileDraft | null> {
if (!enabled || !owner) return null;
let draft = memory.get(owner);
if (!draft) {
await pending;
if (!enabled) return null;
draft = await withStore<StoredDraft | undefined>('readonly', (store, done) => {
const request = store.get(owner);
request.onsuccess = () => done(request.result as StoredDraft | undefined);
});
}
if (!draft) return null;
if (expired(draft)) {
await clearReconcileDraft(owner);
return null;
}
memory.set(owner, draft);
const { version: _version, updatedAt: _updatedAt, ...data } = draft;
return structuredClone(data);
}

export function saveReconcileDraft(owner: string, draft: ReconcileDraft): Promise<void> {
if (!enabled || !owner) return Promise.resolve();
const stored: StoredDraft = { ...structuredClone(draft), version: 1, updatedAt: Date.now() };
if (new Blob([JSON.stringify(stored)]).size > MAX_BYTES) {
return Promise.reject(new Error('核验数据超过 10 MB,无法持久化本机缓存'));
}
memory.set(owner, stored);
const ticket = generation;
return serialize(async () => {
if (!enabled || ticket !== generation) return;
await withStore<void>('readwrite', (store) => { store.put(stored, owner); });
});
}

export function clearReconcileDraft(owner: string): Promise<void> {
if (!owner) return Promise.resolve();
memory.delete(owner);
generation++;
return serialize(async () => {
await withStore<void>('readwrite', store => { store.delete(owner); });
});
}

// 退出或会话失效时先同步禁止后续写入,再依次清空所有本机核验草稿。
export function clearAllReconcileDrafts(): Promise<void> {
enabled = false;
generation++;
memory.clear();
return serialize(async () => {
await withStore<void>('readwrite', store => { store.clear(); });
});
}