277 lines
7.9 KiB
TypeScript
277 lines
7.9 KiB
TypeScript
import { casesApi } from '@/lib/api/cases';
|
|
import type { LabCaseAttachmentMeta, LabCaseDetail } from '@/types/cases';
|
|
|
|
export type CaseUploadJob = {
|
|
id: string;
|
|
caseId: string;
|
|
fileName: string;
|
|
sizeBytes: number;
|
|
percent: number;
|
|
failed: boolean;
|
|
};
|
|
|
|
type DraftBridge = {
|
|
/** Flush the open draft before the first file in this batch is posted. */
|
|
prepare: () => Promise<boolean>;
|
|
/** Remember the new file id locally so a later autosave does not unlink it. */
|
|
commit: (attachment: LabCaseAttachmentMeta) => void;
|
|
/** Release the draft lock. One extra save only if the form changed during the upload. */
|
|
settle: () => void;
|
|
};
|
|
|
|
type StoredHandler = (caseId: string, attachment: LabCaseAttachmentMeta) => void;
|
|
type FailureHandler = (error: unknown) => void;
|
|
|
|
const EMPTY: CaseUploadJob[] = [];
|
|
const jobs: CaseUploadJob[] = [];
|
|
const files = new Map<string, File>();
|
|
const bridges = new Map<string, DraftBridge>();
|
|
const prepared = new Set<string>();
|
|
/** Files posted this session. A stale case fetch must not drop them, and must not refetch. */
|
|
const known = new Map<string, LabCaseAttachmentMeta[]>();
|
|
let byCase = new Map<string, CaseUploadJob[]>();
|
|
const listeners = new Set<() => void>();
|
|
let storedHandler: StoredHandler | null = null;
|
|
let failureHandler: FailureHandler | null = null;
|
|
let chain: Promise<void> = Promise.resolve();
|
|
let emitTimer: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
function rebuild() {
|
|
const next = new Map<string, CaseUploadJob[]>();
|
|
for (const job of jobs) {
|
|
const list = next.get(job.caseId);
|
|
if (list) list.push(job);
|
|
else next.set(job.caseId, [job]);
|
|
}
|
|
byCase = next;
|
|
}
|
|
|
|
function emit() {
|
|
for (const listener of listeners) listener();
|
|
}
|
|
|
|
function publish(immediate = false) {
|
|
rebuild();
|
|
if (listeners.size === 0) return;
|
|
if (immediate) {
|
|
if (emitTimer) clearTimeout(emitTimer);
|
|
emitTimer = null;
|
|
emit();
|
|
return;
|
|
}
|
|
if (emitTimer) return;
|
|
emitTimer = setTimeout(() => {
|
|
emitTimer = null;
|
|
if (listeners.size > 0) emit();
|
|
}, 150);
|
|
}
|
|
|
|
export function subscribeCaseUploads(listener: () => void) {
|
|
listeners.add(listener);
|
|
return () => {
|
|
listeners.delete(listener);
|
|
};
|
|
}
|
|
|
|
export function caseUploadSnapshot(caseId: string): CaseUploadJob[] {
|
|
return byCase.get(caseId) ?? EMPTY;
|
|
}
|
|
|
|
export function registerDraftUploadBridge(caseId: string, bridge: DraftBridge) {
|
|
bridges.set(caseId, bridge);
|
|
const waiting = known.get(caseId);
|
|
if (waiting?.length) {
|
|
for (const attachment of waiting) bridge.commit(attachment);
|
|
}
|
|
return () => {
|
|
if (bridges.get(caseId) === bridge) bridges.delete(caseId);
|
|
};
|
|
}
|
|
|
|
export function registerCaseFileStored(handler: StoredHandler) {
|
|
storedHandler = handler;
|
|
return () => {
|
|
if (storedHandler === handler) storedHandler = null;
|
|
};
|
|
}
|
|
|
|
export function onCaseUploadFailure(handler: FailureHandler) {
|
|
failureHandler = handler;
|
|
return () => {
|
|
if (failureHandler === handler) failureHandler = null;
|
|
};
|
|
}
|
|
|
|
export function forgetKnownCaseFile(caseId: string, attachmentId: string) {
|
|
const list = known.get(caseId);
|
|
if (!list) return;
|
|
const next = list.filter((file) => file.id !== attachmentId);
|
|
if (next.length === 0) known.delete(caseId);
|
|
else known.set(caseId, next);
|
|
}
|
|
|
|
const EMPTY_IDS: ReadonlySet<string> = new Set();
|
|
|
|
export function knownAttachmentIds(caseId: string): ReadonlySet<string> {
|
|
const list = known.get(caseId);
|
|
if (!list?.length) return EMPTY_IDS;
|
|
return new Set(list.map((file) => file.id));
|
|
}
|
|
|
|
/**
|
|
* Keep files posted this session on top of a fetch.
|
|
* A response that already includes them must not forget them: a slower fetch
|
|
* from before the upload can still arrive and would drop the file.
|
|
*/
|
|
export function withKnownAttachments(
|
|
caseId: string,
|
|
files: LabCaseAttachmentMeta[],
|
|
): LabCaseAttachmentMeta[] {
|
|
const list = known.get(caseId);
|
|
if (!list?.length) return files;
|
|
const ids = new Set(files.map((file) => file.id));
|
|
const missing = list.filter((file) => !ids.has(file.id));
|
|
if (missing.length === 0) return files;
|
|
return [...files, ...missing];
|
|
}
|
|
|
|
export function withKnownCaseFiles(detail: LabCaseDetail): LabCaseDetail {
|
|
const attachments = withKnownAttachments(detail.id, detail.attachments);
|
|
if (attachments === detail.attachments) return detail;
|
|
return { ...detail, attachments };
|
|
}
|
|
|
|
export function caseHasActiveUpload(caseId: string): boolean {
|
|
return prepared.has(caseId) || jobs.some((job) => job.caseId === caseId && !job.failed);
|
|
}
|
|
|
|
function remember(caseId: string, attachment: LabCaseAttachmentMeta) {
|
|
const list = known.get(caseId) ?? [];
|
|
if (!list.some((file) => file.id === attachment.id)) {
|
|
list.push(attachment);
|
|
known.set(caseId, list);
|
|
}
|
|
}
|
|
|
|
function deliver(caseId: string, attachment: LabCaseAttachmentMeta) {
|
|
remember(caseId, attachment);
|
|
bridges.get(caseId)?.commit(attachment);
|
|
storedHandler?.(caseId, attachment);
|
|
}
|
|
|
|
function hasPending(caseId: string, exceptId?: string) {
|
|
return jobs.some((job) => job.caseId === caseId && !job.failed && job.id !== exceptId);
|
|
}
|
|
|
|
const idleWaiters = new Map<string, Set<() => void>>();
|
|
|
|
function notifyIdle(caseId: string) {
|
|
if (caseHasActiveUpload(caseId)) return;
|
|
const waiters = idleWaiters.get(caseId);
|
|
if (!waiters?.size) return;
|
|
idleWaiters.delete(caseId);
|
|
for (const resolve of waiters) resolve();
|
|
}
|
|
|
|
/** Resolves once this case has no upload still posting. */
|
|
export function whenCaseUploadsIdle(caseId: string): Promise<void> {
|
|
if (!caseHasActiveUpload(caseId)) return Promise.resolve();
|
|
return new Promise((resolve) => {
|
|
const waiters = idleWaiters.get(caseId) ?? new Set();
|
|
waiters.add(resolve);
|
|
idleWaiters.set(caseId, waiters);
|
|
});
|
|
}
|
|
|
|
function settleIfIdle(caseId: string, exceptId?: string) {
|
|
if (hasPending(caseId, exceptId)) return;
|
|
prepared.delete(caseId);
|
|
bridges.get(caseId)?.settle();
|
|
notifyIdle(caseId);
|
|
}
|
|
|
|
function failQueued(caseId: string) {
|
|
for (const item of jobs) {
|
|
if (item.caseId !== caseId || item.failed) continue;
|
|
item.failed = true;
|
|
item.percent = 0;
|
|
files.delete(item.id);
|
|
}
|
|
}
|
|
|
|
async function runJob(job: CaseUploadJob) {
|
|
if (job.failed) return;
|
|
const bridge = bridges.get(job.caseId);
|
|
if (bridge && !prepared.has(job.caseId)) {
|
|
prepared.add(job.caseId);
|
|
let ready = false;
|
|
try {
|
|
ready = await bridge.prepare();
|
|
} catch {
|
|
ready = false;
|
|
}
|
|
if (!ready) {
|
|
prepared.delete(job.caseId);
|
|
failQueued(job.caseId);
|
|
publish(true);
|
|
settleIfIdle(job.caseId);
|
|
return;
|
|
}
|
|
}
|
|
|
|
const file = files.get(job.id);
|
|
if (!file) {
|
|
job.failed = true;
|
|
publish(true);
|
|
settleIfIdle(job.caseId, job.id);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await casesApi.uploadAttachments(job.caseId, [file], (percent) => {
|
|
job.percent = percent;
|
|
publish(false);
|
|
});
|
|
const attachment = response.data[0];
|
|
if (!attachment) throw new Error('empty upload');
|
|
const index = jobs.findIndex((item) => item.id === job.id);
|
|
if (index >= 0) jobs.splice(index, 1);
|
|
files.delete(job.id);
|
|
publish(true);
|
|
deliver(job.caseId, attachment);
|
|
settleIfIdle(job.caseId);
|
|
} catch (error) {
|
|
job.failed = true;
|
|
job.percent = 0;
|
|
files.delete(job.id);
|
|
publish(true);
|
|
failureHandler?.(error);
|
|
settleIfIdle(job.caseId, job.id);
|
|
}
|
|
}
|
|
|
|
export function enqueueCaseFileUpload(caseId: string, file: File) {
|
|
const job: CaseUploadJob = {
|
|
id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
caseId,
|
|
fileName: file.name,
|
|
sizeBytes: file.size,
|
|
percent: 0,
|
|
failed: false,
|
|
};
|
|
jobs.unshift(job);
|
|
files.set(job.id, file);
|
|
publish(true);
|
|
chain = chain.then(() => runJob(job)).catch(() => undefined);
|
|
}
|
|
|
|
export function dismissCaseUploadJob(jobId: string) {
|
|
const index = jobs.findIndex((job) => job.id === jobId);
|
|
if (index < 0 || !jobs[index].failed) return;
|
|
const caseId = jobs[index].caseId;
|
|
jobs.splice(index, 1);
|
|
files.delete(jobId);
|
|
publish(true);
|
|
settleIfIdle(caseId);
|
|
}
|