"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { Dropzone } from "@suphark/ui/components/shared/dropzone"; import { Notice } from "@suphark/ui/components/shared/notice"; import { StatusBadge } from "@suphark/ui/components/shared/status-badge"; import { useSheetOnMobile } from "@suphark/ui/components/shared/ui-defaults"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Checkbox } from "@suphark/ui/components/ui/checkbox"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@suphark/ui/components/ui/dialog"; import { Spinner } from "@suphark/ui/components/ui/spinner"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@suphark/ui/components/ui/table"; import { useFrozenWhileOpen } from "@suphark/ui/hooks/use-frozen-while-open"; import { type DrawerParts, useLazyDrawer } from "@suphark/ui/hooks/use-lazy-drawer"; import { useIsMobile } from "@suphark/ui/hooks/use-mobile"; import { cn } from "@suphark/ui/lib/utils"; import { FileSpreadsheetIcon } from "lucide-react"; import { type ReactNode, useEffect, useId, useRef, useState } from "react"; export interface ImportColumn { key: string; header: ReactNode; /** ค่าเริ่มต้นอ่าน `row[key]` */ cell?: (row: Row) => ReactNode; } export interface ImportResult { created?: number; updated?: number; /** แถวที่ฝั่ง server ข้าม (ไม่รวมแถวที่ผิดตอนตรวจทาน) */ skipped?: number; /** ข้อความเพิ่มในหน้าผลลัพธ์ */ message?: ReactNode; /** มีค่า = นำเข้าไม่สำเร็จ แสดงข้อความนี้แล้วอยู่หน้าตรวจทานต่อ */ error?: string; } interface Parsed { row: Row; index: number; errors: string[]; } /** * นำเข้าไฟล์ (Excel/CSV/JSON) 3 ขั้น: เลือกไฟล์ (+ ลิงก์ไฟล์แม่แบบ) → ตรวจทาน (แถวที่ผิดพร้อมเหตุผล, * เลือกข้ามแถวที่ผิดได้) → ผลลัพธ์ · แพ็กเกจไม่อ่านไฟล์เอง: แอปส่ง `parse` (exceljs/papaparse ฯลฯ) และ `commit` (server action) * * readRates(file)} * validate={(row) => (row.price < 0 ? "ราคาติดลบ" : null)} * columns={[{ key: "code", header: "รหัส" }, { key: "name", header: "ชื่อ" }]} * commit={(rows) => importRates(rows)} onDone={() => router.refresh()} sheetOnMobile /> * * - เลขแถวที่แสดง = `rowNumber(index)` (ค่าเริ่มต้น index + 2 คือแถวใน Excel ที่มีหัวตาราง 1 แถว) * - `commit` throw หรือคืน `{ error }` = แสดงข้อความ อยู่หน้าตรวจทานให้ลองใหม่ * - ปิดกล่อง = เริ่มใหม่ทั้งหมด */ export function ImportDialog({ open, onOpenChange, sheetOnMobile: sheetOnMobileProp, contentClassName, ...bodyProps }: { open: boolean; onOpenChange: (open: boolean) => void; title: ReactNode; description?: ReactNode; /** ส่งต่อให้ input file เช่น ".xlsx,.csv" */ accept?: string; maxBytes?: number; /** ลิงก์ดาวน์โหลดไฟล์แม่แบบ */ template?: { href: string; label?: ReactNode }; /** คำอธิบายใต้ช่องวางไฟล์ เช่น "คอลัมน์: รหัส, ชื่อ, หน่วย, ราคา" */ hint?: ReactNode; parse: (file: File) => Promise> | ReadonlyArray; validate?: (row: Row, index: number) => string | ReadonlyArray | null | undefined; columns: ReadonlyArray>; commit: (rows: Row[]) => Promise | ImportResult | undefined; onDone?: (result: ImportResult) => void; rowNumber?: (index: number) => number; /** อนุญาตให้นำเข้าเฉพาะแถวที่ถูกเมื่อมีแถวผิด (ค่าเริ่มต้น true) */ allowPartial?: boolean; /** จำนวนแถวตัวอย่างเมื่อไม่มีแถวผิด (ค่าเริ่มต้น 5) */ previewLimit?: number; /** จอ < 768px เป็นแผ่นล่าง */ sheetOnMobile?: boolean; contentClassName?: string; }) { const sheetOnMobile = useSheetOnMobile(sheetOnMobileProp); const isMobile = useIsMobile(); // Drawer โหลดเมื่อต้องใช้ (ระหว่างโหลดแสดงกล่องกลางจอ) const drawer = useLazyDrawer(sheetOnMobile && isMobile); // ตรึงแบบระหว่างเปิด — หมุนจอแล้วไม่ remount (ไฟล์ที่เลือก/ผลตรวจไม่หาย) const sheet = useFrozenWhileOpen(sheetOnMobile && isMobile && drawer !== null, open); // กำลังอ่านไฟล์/นำเข้า — ปิดไม่ได้ (Esc/คลิกนอก/ปัดลง) ไม่งั้นเปิดใหม่แล้วกดนำเข้าซ้ำ = ข้อมูลซ้ำ const busyRef = useRef(false); const requestOpenChange = (next: boolean) => { if (!next && busyRef.current) return; onOpenChange(next); }; if (sheet && drawer) { const { Drawer, DrawerContent } = drawer; return ( onOpenChange(false)} /> ); } return ( onOpenChange(false)} /> ); } type Step = "select" | "review" | "result"; const INVALID_LIMIT = 200; function ImportBody({ title, description, accept, maxBytes, template, hint, parse, validate, columns, commit, onDone, rowNumber = (i) => i + 2, allowPartial = true, previewLimit = 5, drawer, busyRef, close, }: { title: ReactNode; description?: ReactNode; accept?: string; maxBytes?: number; template?: { href: string; label?: ReactNode }; hint?: ReactNode; parse: (file: File) => Promise> | ReadonlyArray; validate?: (row: Row, index: number) => string | ReadonlyArray | null | undefined; columns: ReadonlyArray>; commit: (rows: Row[]) => Promise | ImportResult | undefined; onDone?: (result: ImportResult) => void; rowNumber?: (index: number) => number; allowPartial?: boolean; previewLimit?: number; /** ชิ้นส่วน Drawer ในโหมดแผ่นล่าง · null = กล่องกลางจอ */ drawer: DrawerParts | null; busyRef: { current: boolean }; close: () => void; }) { const t = useUiText().importDialog; const [step, setStep] = useState("select"); const [file, setFile] = useState(null); const [parsed, setParsed] = useState[]>([]); const [busy, setBusy] = useState(false); useEffect(() => { busyRef.current = busy; return () => { busyRef.current = false; }; }, [busy, busyRef]); const [error, setError] = useState(null); const [skipInvalid, setSkipInvalid] = useState(true); const [result, setResult] = useState(null); const skipId = useId(); const invalid = parsed.filter((p) => p.errors.length > 0); // ไฟล์ผิดแม่แบบหลายหมื่นแถว render ทั้งหมด = แท็บค้าง — แสดงแค่ส่วนแรก บอกจำนวนที่เหลือ const shownInvalid = invalid.slice(0, INVALID_LIMIT); const hiddenInvalid = invalid.length - shownInvalid.length; const valid = parsed.filter((p) => p.errors.length === 0); const canCommit = valid.length > 0 && (invalid.length === 0 || (allowPartial && skipInvalid)); const sheet = drawer !== null; const P = drawer ? { Header: drawer.DrawerHeader, Title: drawer.DrawerTitle, Description: drawer.DrawerDescription, Footer: drawer.DrawerFooter, } : { Header: DialogHeader, Title: DialogTitle, Description: DialogDescription, Footer: DialogFooter, }; const readFile = async (picked: File) => { setFile(picked); setError(null); setBusy(true); try { const rows = await parse(picked); const list = rows.map((row, index) => { const out = validate?.(row, index); const errors = out == null ? [] : typeof out === "string" ? [out] : [...out]; return { row, index, errors: errors.filter(Boolean) }; }); if (list.length === 0) { setError(t?.emptyFile ?? "ไม่พบข้อมูลในไฟล์"); return; } setParsed(list); setStep("review"); } catch (e) { setError(e instanceof Error && e.message ? e.message : (t?.readFailed ?? "อ่านไฟล์ไม่ได้")); } finally { setBusy(false); } }; const runCommit = async () => { setError(null); setBusy(true); try { const res = (await commit(valid.map((p) => p.row))) ?? {}; if (res.error) { setError(res.error); return; } setResult(res); setStep("result"); onDone?.(res); } catch (e) { setError(e instanceof Error && e.message ? e.message : (t?.commitFailed ?? "นำเข้าไม่สำเร็จ")); } finally { setBusy(false); } }; const steps: Array<[Step, string]> = [ ["select", t?.stepSelect ?? "เลือกไฟล์"], ["review", t?.stepReview ?? "ตรวจทาน"], ["result", t?.stepResult ?? "ผลลัพธ์"], ]; const stepIndex = steps.findIndex(([s]) => s === step); const cellOf = (row: Row, col: ImportColumn): ReactNode => col.cell ? col.cell(row) : String((row as Record)[col.key] ?? ""); const importLabel = (t?.importCount ?? "นำเข้า {count} แถว").replace( "{count}", valid.length.toLocaleString("th-TH"), ); return ( <> {title} {description && {description}}
    {steps.map(([key, label], i) => (
  1. {i + 1} {label}
  2. ))}
{error && {error}} {step === "select" && ( <> {busy ? (
{(t?.reading ?? "กำลังอ่าน {name}…").replace("{name}", file?.name ?? "")}
) : ( } onFiles={(files) => { const first = files[0]; if (first) void readFile(first); }} onRejected={(_, reason) => setError( reason === "size" ? (t?.tooLarge ?? "ไฟล์ใหญ่เกินกำหนด") : (t?.wrongType ?? "ชนิดไฟล์ไม่ตรงกับที่รับ"), ) } /> )} {template && ( {template.label ?? t?.template ?? "ดาวน์โหลดไฟล์แม่แบบ"} )} )} {step === "review" && ( <>
{file?.name} {(t?.validCount ?? "ถูกต้อง {count}").replace("{count}", String(valid.length))} {invalid.length > 0 && ( {(t?.invalidCount ?? "ผิด {count}").replace("{count}", String(invalid.length))} )}
{invalid.length > 0 ? ( sheet ? (
    {shownInvalid.map((p) => (
  • {t?.row ?? "แถว"} {rowNumber(p.index)} {columns[0] && <> · {cellOf(p.row, columns[0])}} {p.errors.join(" · ")}
  • ))}
) : ( ) ) : null} {hiddenInvalid > 0 && (

{(t?.moreInvalid ?? "และอีก {count} แถวที่ผิด — แก้ในไฟล์แล้วเลือกใหม่").replace( "{count}", hiddenInvalid.toLocaleString(), )}

)} {invalid.length > 0 ? null : ( <>

{(t?.preview ?? "ตัวอย่าง {count} แถวแรก").replace( "{count}", String(Math.min(previewLimit, valid.length)), )}

)} {invalid.length > 0 && allowPartial && valid.length > 0 && ( )} {invalid.length > 0 && (!allowPartial || valid.length === 0) && (

{t?.fixFirst ?? "แก้แถวที่ผิดในไฟล์แล้วเลือกไฟล์ใหม่"}

)} )} {step === "result" && result && ( <>
{( [ [t?.created ?? "เพิ่มใหม่", result.created ?? valid.length, "text-success"], [t?.updated ?? "อัปเดต", result.updated ?? 0, ""], [t?.skipped ?? "ข้าม", (result.skipped ?? 0) + invalid.length, "text-destructive"], ] as const ).map(([label, count, tone]) => (
{label}
0 && tone)}> {count.toLocaleString("th-TH")}
))}
{result.message &&
{result.message}
} )}
{step === "select" && ( )} {step === "review" && ( <> )} {step === "result" && } ); } function RowsTable({ rows, columns, cellOf, rowNumber, rowLabel, problemLabel, }: { rows: ReadonlyArray>; columns: ReadonlyArray>; cellOf: (row: Row, col: ImportColumn) => ReactNode; rowNumber: (index: number) => number; rowLabel: string; problemLabel?: string; }) { return ( {rowLabel} {columns.map((c) => ( {c.header} ))} {problemLabel && {problemLabel}} {rows.map((p) => ( 0 && "bg-destructive-subtle/60")}> {rowNumber(p.index)} {columns.map((c) => ( {cellOf(p.row, c)} ))} {problemLabel && ( {p.errors.join(" · ")} )} ))}
); }