"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { buttonVariants } from "@suphark/ui/components/ui/button"; import { Progress } from "@suphark/ui/components/ui/progress"; import { focusAfterRemove } from "@suphark/ui/lib/focus-after-remove"; import { formatBytes, formatThaiFullDate } from "@suphark/ui/lib/formatters"; import { cn } from "@suphark/ui/lib/utils"; import { type ReactNode, useCallback, useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { ActionDelete, ActionDownload, StatusError, StatusLoading, StatusSuccess, } from "./semantic-icons"; import { SimpleDialog } from "./simple-dialog"; import { StatusBadge, type Tone } from "./status-badge"; export type ExportJobStatus = "pending" | "running" | "success" | "failed" | "expired"; export interface ExportJob { id: string; /** สถานะ — ตัวพิมพ์ใหญ่จาก Prisma enum (`"RUNNING"`) ใช้ได้เลย */ status: ExportJobStatus | Uppercase; /** ชื่องาน เช่น "248 เอกสาร" หรือ "รายงานผู้ขาย ต.ค. 2569" */ title: ReactNode; /** ความคืบหน้าระหว่างทำ — ไม่ส่ง = แถบวิ่งไม่ระบุสัดส่วน */ progress?: { done: number; total: number; note?: ReactNode }; /** ลิงก์ไฟล์ผลลัพธ์ (เฉพาะ success) */ downloadUrl?: string | null; sizeBytes?: number | bigint | null; /** ข้อความเมื่อล้มเหลว */ error?: ReactNode; createdAt: Date | string; expiresAt?: Date | string | null; /** ข้อความเสริมต่อท้ายบรรทัดรอง เช่น "ข้าม 3 ไฟล์" */ meta?: ReactNode; } const normalize = (status: ExportJob["status"]) => status.toLowerCase() as ExportJobStatus; export const isExportJobActive = (job: Pick) => { const status = normalize(job.status); return status === "pending" || status === "running"; }; const TONE: Record = { pending: "neutral", running: "info", success: "success", failed: "danger", expired: "neutral", }; const DEFAULT_TEXT = { title: "งานส่งออก", button: "งานส่งออก", empty: "ยังไม่มีงานส่งออก", loading: "กำลังโหลด...", pending: "รอคิว", running: "กำลังทำ", success: "พร้อมดาวน์โหลด", failed: "ล้มเหลว", expired: "หมดอายุ", createdAt: "สั่งเมื่อ {date}", expiresAt: "หมดอายุ {date}", download: "ดาวน์โหลด", delete: "ลบงานและไฟล์ผลลัพธ์", deleteFailed: "ลบงานไม่สำเร็จ", activeCount: "{count} กำลังทำ", readyCount: "{count} พร้อม", loadFailed: "โหลดรายการงานไม่สำเร็จ", retry: "ลองใหม่", announceReady: "งานส่งออกพร้อมดาวน์โหลด {count} งาน", announceFailed: "งานส่งออกล้มเหลว {count} งาน", }; type ExportJobsText = typeof DEFAULT_TEXT; function useText(): ExportJobsText { const text = useUiText(); return { ...DEFAULT_TEXT, ...text.exportJobs }; } export interface ExportJobsPanelProps { jobs: ReadonlyArray; /** โหลดครั้งแรก (ยังไม่มีรายการ) */ loading?: boolean; /** ลบงาน — ส่งแล้วมีปุ่มลบในงานที่ไม่ได้กำลังทำ · throw = toast แจ้ง */ onDelete?: (job: ExportJob) => Promise | unknown; /** ข้อความว่างแทนค่าเริ่มต้น */ empty?: ReactNode; /** โหลดไม่สำเร็จ (ยังไม่มีรายการ) — แสดงข้อความแทน "ยังไม่มีงาน" + ปุ่ม `onRetry` */ error?: boolean; onRetry?: () => void; className?: string; } /** * รายการงานส่งออกเบื้องหลัง (สถานะ, ความคืบหน้า, ดาวน์โหลด, ลบ) — ไม่โหลดข้อมูลเอง ใส่ในหน้า/แผ่นได้ * ปุ่มเปิด + กล่อง + โหลดซ้ำทุก 5 วินาทีระหว่างมีงานค้าง ใช้ `ExportJobsButton` (ยกจาก supplychain หน้า audit) */ export function ExportJobsPanel({ jobs, loading, onDelete, empty, error, onRetry, className, }: ExportJobsPanelProps) { const t = useText(); const listRef = useRef(null); const [deleting, setDeleting] = useState(null); if (loading && jobs.length === 0) { return (
); } if (error && jobs.length === 0) { return (
); } if (jobs.length === 0) { return

{empty ?? t.empty}

; } const remove = async (job: ExportJob, button: HTMLElement) => { if (!onDelete) return; setDeleting(job.id); // จำตำแหน่งก่อน await — แอปที่ตัดรายการออกก่อน onDelete จบ ปุ่มหายไปก่อนหลัง await // ลบงานสุดท้าย (รายการกลายเป็นข้อความว่าง) → ปุ่มปิดของกล่อง const dialog = button.closest('[role="dialog"]'); focusAfterRemove(button, listRef.current, () => dialog?.querySelector('[data-slot="dialog-close"]'), ); try { await onDelete(job); } catch (err) { toast.error(err instanceof Error && err.message ? err.message : t.deleteFailed); } finally { setDeleting(null); } }; return (
    {jobs.map((job) => { const status = normalize(job.status); const active = status === "pending" || status === "running"; const percent = status === "success" ? 100 : job.progress && job.progress.total > 0 ? Math.round((job.progress.done / job.progress.total) * 100) : null; const meta = [ t.createdAt.replace("{date}", formatThaiFullDate(job.createdAt)), status === "success" && job.sizeBytes != null ? formatBytes(job.sizeBytes) : null, status === "success" && job.expiresAt ? t.expiresAt.replace("{date}", formatThaiFullDate(job.expiresAt)) : null, ].filter(Boolean); return (
  • {job.title} {t[status]}

    {meta.join(" · ")} {job.meta ? <> · {job.meta} : null}

    {status === "failed" && job.error && (

    {job.error}

    )}
    {status === "success" && job.downloadUrl && ( // ลิงก์จริง (ไม่ใช่ Button render=: Base UI ใส่ role="button" ให้ โปรแกรมอ่านจอจึงไม่รู้ว่าเป็นลิงก์ดาวน์โหลด) {t.download} )} {onDelete && !active && ( )}
    {active && (
    {job.progress?.note ?? (status === "pending" ? t.pending : t.running)}
    )}
  • ); })}
); } export interface ExportJobsButtonProps { /** โหลดรายการงานของผู้ใช้ (ใหม่สุดก่อน) — เรียกตอน mount, ตอนเปิด และทุก `pollMs` ระหว่างเปิดหรือมีงานค้าง */ load: () => Promise>; onDelete?: (job: ExportJob) => Promise | unknown; /** ช่วงโหลดซ้ำ (ms) — ค่าเริ่มต้น 5000 */ pollMs?: number; /** คุมการเปิดจากภายนอก (เช่นเปิดเองทันทีหลังเริ่มงานใหม่) */ open?: boolean; onOpenChange?: (open: boolean) => void; title?: ReactNode; /** คำอธิบายใต้หัวกล่อง เช่น "ไฟล์เก็บไว้ 7 วัน" */ description?: ReactNode; /** เปลี่ยนค่านี้ = โหลดใหม่ทันที (เช่นหลังเริ่มงานใหม่) */ refreshKey?: unknown; className?: string; } /** * ปุ่ม "งานส่งออก" + จำนวนที่กำลังทำ/พร้อม + กล่องรายการ — โหลดเองและโหลดซ้ำระหว่างมีงานค้าง (หยุดเมื่อไม่มี) * * listMyExportJobs().then(toJobs)} onDelete={(job) => deleteExportJob(job.id)} * open={open} onOpenChange={setOpen} description="ไฟล์เก็บไว้ให้ดาวน์โหลด 7 วัน" /> */ export function ExportJobsButton({ load, onDelete, pollMs = 5000, open: openProp, onOpenChange, title, description, refreshKey, className, }: ExportJobsButtonProps) { const t = useText(); const [innerOpen, setInnerOpen] = useState(false); const open = openProp ?? innerOpen; const setOpen = (next: boolean) => { if (openProp === undefined) setInnerOpen(next); onOpenChange?.(next); }; const [jobs, setJobs] = useState>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); // ฟังก์ชันจากแอปมักสร้างใหม่ทุก render — อ่านล่าสุดจาก ref ไม่ให้ effect วิ่งซ้ำ const loadRef = useRef(load); loadRef.current = load; const failedOnce = useRef(false); // คำขอล่าสุดเท่านั้นที่เขียนผล — คำตอบรอบเก่าที่มาช้า (เริ่มก่อนลบ/ก่อนเริ่มงานใหม่) ไม่ทับรายการใหม่ const latest = useRef(0); const inFlight = useRef(0); useEffect( () => () => { latest.current++; }, [], ); const refresh = useCallback( async ({ poll = false }: { poll?: boolean } = {}) => { // รอบจับเวลาข้ามถ้ารอบก่อนยังไม่จบ (load ช้ากว่า pollMs ไม่ให้คำขอซ้อน) — การสั่งโหลดเองไม่ข้าม if (poll && inFlight.current > 0) return; const id = ++latest.current; inFlight.current++; try { const list = await loadRef.current(); if (id !== latest.current) return; setJobs(list); setError(false); failedOnce.current = false; } catch { if (id !== latest.current) return; setError(true); // แจ้งครั้งเดียวจนกว่าจะโหลดสำเร็จอีกครั้ง — ไม่ให้ toast ซ้ำทุก 5 วินาที if (!failedOnce.current) toast.error(t.loadFailed); failedOnce.current = true; } finally { inFlight.current--; if (id === latest.current) setLoading(false); } }, [t.loadFailed], ); // biome-ignore lint/correctness/useExhaustiveDependencies: refreshKey เป็นตัวกระตุ้นโหลดใหม่ useEffect(() => { void refresh(); }, [refresh, refreshKey]); useEffect(() => { if (open) void refresh(); }, [open, refresh]); const activeCount = jobs.filter(isExportJobActive).length; const readyCount = jobs.filter((job) => normalize(job.status) === "success").length; useEffect(() => { if (!open && activeCount === 0) return; const id = setInterval(() => void refresh({ poll: true }), pollMs); return () => clearInterval(id); }, [open, activeCount, pollMs, refresh]); // ประกาศให้ screen reader เมื่องานที่กำลังทำเสร็จ/ล้มเหลว (กล่องปิดอยู่ก็ได้ยิน) — ช่องประกาศอยู่ตลอด เปลี่ยนแค่ข้อความ const lastStatus = useRef(new Map()); const [announce, setAnnounce] = useState(""); useEffect(() => { let ready = 0; let failed = 0; const next = new Map(); for (const job of jobs) { const status = normalize(job.status); const before = lastStatus.current.get(job.id); if (before === "pending" || before === "running") { if (status === "success") ready++; else if (status === "failed") failed++; } next.set(job.id, status); } lastStatus.current = next; const parts = [ ready ? t.announceReady.replace("{count}", String(ready)) : "", failed ? t.announceFailed.replace("{count}", String(failed)) : "", ].filter(Boolean); if (parts.length) setAnnounce(parts.join(" · ")); }, [jobs, t.announceReady, t.announceFailed]); const remove = async (job: ExportJob) => { await onDelete?.(job); await refresh(); }; return ( <> {announce} {activeCount > 0 ? : } {t.button} {(activeCount > 0 || readyCount > 0) && ( 0 ? "info" : "success"} className="ms-0.5"> {(activeCount > 0 ? t.activeCount : t.readyCount).replace( "{count}", String(activeCount > 0 ? activeCount : readyCount), )} )} } > { setLoading(true); void refresh(); }} className="max-h-[420px] overflow-y-auto" /> ); }