Some checks failed
CI / Test (ubuntu-latest) (push) Has been cancelled
CI / Test (windows-latest) (push) Has been cancelled
CI / Lint (ubuntu-latest) (push) Has been cancelled
CI / Lint (windows-latest) (push) Has been cancelled
CI / Check (ubuntu-latest) (push) Has been cancelled
CI / Check (windows-latest) (push) Has been cancelled
CI / CI OK (push) Has been cancelled
CodeQL / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Website on push / Deploy Push Playground Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Docs Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Antd Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Element Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Naive Ftp (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
Lock Threads / action (push) Has been cancelled
Issue Close Require / close-issues (push) Has been cancelled
Close stale issues / stale (push) Has been cancelled
68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
import { useUserStore } from '@vben/stores';
|
|
|
|
import type { SpreadsheetHistoryEntry } from '../types';
|
|
import {
|
|
appendLocalHistory,
|
|
listUnsyncedHistory,
|
|
markHistorySynced,
|
|
} from '../history/localHistoryStore';
|
|
import { saveHistoryBatch } from '../history/remoteHistoryApi';
|
|
|
|
let syncTimer: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
function uuid() {
|
|
return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
}
|
|
|
|
export function useEditHistory(
|
|
tableName: string,
|
|
sheetKey?: string,
|
|
enabled = true,
|
|
) {
|
|
const userStore = useUserStore();
|
|
|
|
async function recordChange(
|
|
payload: Omit<
|
|
SpreadsheetHistoryEntry,
|
|
'id' | 'tableName' | 'sheetKey' | 'userId' | 'userName' | 'synced' | 'createdAt'
|
|
>,
|
|
) {
|
|
if (!enabled) return;
|
|
|
|
const entry: SpreadsheetHistoryEntry = {
|
|
id: uuid(),
|
|
tableName,
|
|
sheetKey,
|
|
userId: Number(userStore.userInfo?.userId ?? 0),
|
|
userName: String(
|
|
userStore.userInfo?.nick_name ??
|
|
userStore.userInfo?.username ??
|
|
'未知用户',
|
|
),
|
|
createdAt: new Date().toISOString(),
|
|
synced: false,
|
|
...payload,
|
|
};
|
|
|
|
await appendLocalHistory(entry);
|
|
scheduleSync();
|
|
return entry;
|
|
}
|
|
|
|
function scheduleSync() {
|
|
if (syncTimer) clearTimeout(syncTimer);
|
|
syncTimer = setTimeout(async () => {
|
|
try {
|
|
const pending = await listUnsyncedHistory();
|
|
if (!pending.length) return;
|
|
const res = await saveHistoryBatch(pending);
|
|
await markHistorySynced(res.saved_ids ?? pending.map((p) => p.id));
|
|
} catch {
|
|
// retry on next change
|
|
}
|
|
}, 2000);
|
|
}
|
|
|
|
return { recordChange, scheduleSync };
|
|
}
|