import { pickFanavaranRecordId } from "./fanavaran-other-people"; export type FanavaranAttachmentStage = { status?: string; lastError?: string | null; lastTriedAt?: Date | string; nextRetryAt?: Date | string; files?: unknown[]; attempts?: unknown[]; }; export function fanavaranAttachmentStatus( stage?: FanavaranAttachmentStage | null, ) { if (!stage) return undefined; const records = (rows: unknown) => (Array.isArray(rows) ? rows : []).filter( (row): row is Record => !!row && typeof row === "object", ); const files = records(stage.files).flatMap((row) => { const fileId = pickFanavaranRecordId(row.fileId); if (fileId == null) return []; return [ { fileId, fileName: String(row.fileName ?? ""), source: row.source as string | undefined, submittedAt: row.submittedAt as Date | string | undefined, }, ]; }); const attempts = records(stage.attempts).map((row) => ({ fileName: String(row.fileName ?? ""), source: row.source as string | undefined, status: String(row.status ?? "unknown"), fileId: pickFanavaranRecordId(row.fileId) ?? undefined, error: row.error as string | undefined, attemptedAt: row.attemptedAt as Date | string | undefined, trackingCode: row.trackingCode as string | undefined, })); const uploadedNames = new Set(files.map((file) => file.fileName)); const latest = new Map( attempts.map((attempt) => [attempt.fileName, attempt]), ); // Skipped (including format-waived) files are intentional omissions, not blockers. const outstanding = [...latest.values()].filter( (attempt) => !uploadedNames.has(attempt.fileName) && attempt.status !== "success" && attempt.status !== "skipped", ); const lastProblem = outstanding.at(-1); const status = lastProblem ? files.length ? "partial" : lastProblem.status : files.length ? "success" : records(stage.files).length ? "unconfirmed" : (stage.status ?? "not_recorded"); return { status, uploadedCount: files.length, lastError: lastProblem?.error ?? (files.length ? null : (stage.lastError ?? (status === "unconfirmed" ? "No valid Fanavaran image ID was recorded; remote receipt is unconfirmed." : null))), lastTriedAt: stage.lastTriedAt, nextRetryAt: stage.nextRetryAt, files, attempts, }; }