fix: refresh asynchronous conversion status
This commit is contained in:
parent
63c6cec81b
commit
add83528d2
|
|
@ -8,6 +8,29 @@ import { useAuthStore } from "./auth";
|
|||
|
||||
let syncPromise: Promise<void> | null = null;
|
||||
let syncTriggersStarted = false;
|
||||
let conversionPollTimer: number | null = null;
|
||||
let conversionPollAttempts = 0;
|
||||
const conversionPollEntryIds = new Set<string>();
|
||||
|
||||
function scheduleConversionPoll(entryIds: string[], resetAttempts = true) {
|
||||
for (const entryId of entryIds) conversionPollEntryIds.add(entryId);
|
||||
if (conversionPollTimer !== null || typeof window === "undefined") return;
|
||||
if (resetAttempts) conversionPollAttempts = 0;
|
||||
const poll = async () => {
|
||||
conversionPollTimer = null;
|
||||
const store = useEntryStore();
|
||||
await store.syncEntries();
|
||||
await store.refreshLocalEntries();
|
||||
const remaining = [...conversionPollEntryIds].filter((entryId) =>
|
||||
store.entries.some((entry) => entry.id === entryId && entry.conversionStatus === "pending"),
|
||||
);
|
||||
conversionPollEntryIds.clear();
|
||||
if (!remaining.length || conversionPollAttempts >= 6) return;
|
||||
conversionPollAttempts += 1;
|
||||
scheduleConversionPoll(remaining, false);
|
||||
};
|
||||
conversionPollTimer = window.setTimeout(() => void poll(), 1_500);
|
||||
}
|
||||
|
||||
export const useEntryStore = defineStore("entries", {
|
||||
state: () => ({
|
||||
|
|
@ -62,6 +85,7 @@ export const useEntryStore = defineStore("entries", {
|
|||
this.syncing = true;
|
||||
this.syncError = "";
|
||||
try {
|
||||
const conversionIds = new Set<string>();
|
||||
while (true) {
|
||||
const pending = (await db.syncOperations
|
||||
.filter((operation) => operation.syncedAt === null)
|
||||
|
|
@ -70,6 +94,11 @@ export const useEntryStore = defineStore("entries", {
|
|||
.sort((left, right) => left.createdAt.localeCompare(right.createdAt))
|
||||
.slice(0, 200);
|
||||
if (!pending.length) break;
|
||||
for (const operation of pending) {
|
||||
if (operation.action !== "delete" && operation.payload.currency !== "CNY" && operation.payload.conversionStatus === "pending") {
|
||||
conversionIds.add(operation.entityId);
|
||||
}
|
||||
}
|
||||
const pushed = await apiRequest<{ acceptedOperationIds: string[] }>("/api/sync/push", {
|
||||
method: "POST",
|
||||
body: { operations: pending },
|
||||
|
|
@ -104,6 +133,7 @@ export const useEntryStore = defineStore("entries", {
|
|||
cursor = pulled.cursor;
|
||||
hasMore = pulled.hasMore;
|
||||
} while (hasMore);
|
||||
if (conversionIds.size) scheduleConversionPoll([...conversionIds]);
|
||||
this.lastSyncedAt = new Date().toISOString();
|
||||
} catch (error) {
|
||||
this.syncError = error instanceof Error ? error.message : "同步失败";
|
||||
|
|
|
|||
Loading…
Reference in New Issue