import { useEffect, useMemo, useState } from "react"; import PageMeta from "../../components/common/PageMeta"; import { apiDelete, apiGet, apiPost, apiPut } from "../../lib/api"; import { useToastOnError } from "../../hooks/useToastOnError"; import { Modal } from "../../components/ui/modal"; import { useModal } from "../../hooks/useModal"; type DistributorRow = { id: number; nama: string; alamat: string | null; telepon: string | null; created_at: string; }; export default function Distributor() { const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [msg, setMsg] = useState(null); const [q, setQ] = useState(""); const { isOpen, openModal, closeModal } = useModal(); const { isOpen: importOpen, openModal: openImport, closeModal: closeImport } = useModal(); useToastOnError(error); const [editing, setEditing] = useState(null); const [form, setForm] = useState({ nama: "", alamat: "", telepon: "", }); const [importFile, setImportFile] = useState(null); const [importing, setImporting] = useState(false); const load = async () => { setLoading(true); setError(null); try { const res = await apiGet<{ data: DistributorRow[] }>( `/admin-api/distributor${q.trim() ? `?q=${encodeURIComponent(q.trim())}` : ""}` ); setRows(res.data); } catch (e: any) { setError(e?.message || "Gagal memuat distributor"); } finally { setLoading(false); } }; useEffect(() => { load(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const filtered = useMemo(() => { const s = q.trim().toLowerCase(); if (!s) return rows; return rows.filter((r) => [r.nama, r.alamat || "", r.telepon || ""].some((v) => v.toLowerCase().includes(s) ) ); }, [rows, q]); const startCreate = () => { setEditing(null); setForm({ nama: "", alamat: "", telepon: "" }); setMsg(null); setError(null); }; const startEdit = (r: DistributorRow) => { setEditing(r); setMsg(null); setError(null); setForm({ nama: r.nama || "", alamat: r.alamat || "", telepon: r.telepon || "", }); }; const save = async () => { if (!form.nama.trim()) { setError("Nama distributor wajib diisi."); return; } setSaving(true); setError(null); setMsg(null); try { if (editing) { await apiPut(`/admin-api/distributor/${editing.id}`, { nama: form.nama.trim(), alamat: form.alamat.trim() || null, telepon: form.telepon.trim() || null, }); setMsg("Distributor berhasil diperbarui."); } else { await apiPost(`/admin-api/distributor`, { nama: form.nama.trim(), alamat: form.alamat.trim() || null, telepon: form.telepon.trim() || null, }); setMsg("Distributor berhasil ditambahkan."); } startCreate(); await load(); } catch (e: any) { setError(e?.message || "Gagal menyimpan distributor"); } finally { setSaving(false); } }; const remove = async (r: DistributorRow) => { if (!confirm(`Hapus distributor "${r.nama}"?`)) return; setError(null); setMsg(null); try { await apiDelete(`/admin-api/distributor/${r.id}`); setMsg("Distributor berhasil dihapus."); await load(); } catch (e: any) { setError(e?.message || "Gagal menghapus distributor"); } }; const importExcel = async () => { if (!importFile) { setError("Pilih file Excel/CSV terlebih dulu."); return; } setImporting(true); setError(null); setMsg(null); try { const fd = new FormData(); fd.append("file", importFile); const res = await fetch("/admin-api/distributor/import", { method: "POST", body: fd, credentials: "same-origin", headers: { "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "", Accept: "application/json", }, }); if (!res.ok) { const text = await res.text(); throw new Error(text || `Import gagal (${res.status})`); } const json = await res.json(); setMsg(json?.message || "Import berhasil."); setImportFile(null); await load(); } catch (e: any) { setError(e?.message || "Import gagal"); } finally { setImporting(false); } }; return ( <>

Distributor

setQ(e.target.value)} placeholder="Cari nama / alamat / telepon" className="h-10 w-[260px] rounded-xl border border-gray-200 bg-white px-4 text-sm outline-none focus:ring-2 focus:ring-blue-500/30 dark:border-gray-800 dark:bg-gray-900" />
{!isOpen && msg && (
{msg}
)} {!isOpen && error && (
{error}
)}
{editing ? `Edit Distributor #${editing.id}` : "Tambah Distributor"}
{msg && (
{msg}
)} {error && (
{error}
)}
setForm((f) => ({ ...f, nama: e.target.value }))} placeholder="Nama distributor" className="h-11 rounded-xl border border-gray-200 bg-white px-4 text-sm dark:border-gray-800 dark:bg-gray-950" /> setForm((f) => ({ ...f, telepon: e.target.value })) } placeholder="Telepon" className="h-11 rounded-xl border border-gray-200 bg-white px-4 text-sm dark:border-gray-800 dark:bg-gray-950" /> setForm((f) => ({ ...f, alamat: e.target.value }))} placeholder="Alamat" className="h-11 rounded-xl border border-gray-200 bg-white px-4 text-sm dark:border-gray-800 dark:bg-gray-950 md:col-span-2" />
Import Distributor
Format kolom:{" "} nama, alamat, telepon. Baris pertama boleh header.
Download Template setImportFile(e.target.files?.[0] || null)} className="text-sm" />
Daftar Distributor
{loading ? (
Memuat...
) : (
{filtered.map((r) => ( ))} {filtered.length === 0 && ( )}
Nama Alamat Telepon Aksi
{r.nama} {r.alamat || "-"} {r.telepon || "-"}
Tidak ada data.
)}
); }