import { useEffect, useMemo, useState } from "react"; import PageMeta from "../../components/common/PageMeta"; import { apiGet, apiPost, apiPut } from "../../lib/api"; import { useToastOnError } from "../../hooks/useToastOnError"; import { Modal } from "../../components/ui/modal"; import { useModal } from "../../hooks/useModal"; type VoucherRow = { id: number; pegawai_id?: number | null; pegawai_nama?: string | null; pegawai_nip?: string | null; kode: string; saldo: number; aktif: boolean; catatan?: string | null; created_at?: string; }; type VoucherHistoryRow = { id: number; kode: string; tipe: "USE" | "TOPUP" | string; jumlah: number; saldo_before: number; saldo_after: number; nomor_penjualan?: string | null; created_at?: string; }; type PegawaiRow = { id: number; nama: string; nip?: string | null; is_aktif?: boolean; }; export default function Vouchers() { const [rows, setRows] = useState([]); const [pegawai, setPegawai] = useState([]); const [store, setStore] = useState({ nama: "Toko", alamat: "", telepon: "", logo: "", }); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [msg, setMsg] = useState(null); const [q, setQ] = useState(""); const [history, setHistory] = useState([]); const [historyLoading, setHistoryLoading] = useState(false); const [historyQ, setHistoryQ] = useState(""); const { isOpen, openModal, closeModal } = useModal(); const [saving, setSaving] = useState(false); const [form, setForm] = useState({ pegawaiId: "", kode: "", saldo: "", catatan: "", aktif: true, }); const [topupOpen, setTopupOpen] = useState(false); const [topupSaving, setTopupSaving] = useState(false); const [topup, setTopup] = useState({ id: 0, kode: "", amount: "" }); useToastOnError(error); const load = () => { setLoading(true); setError(null); apiGet<{ data: VoucherRow[] }>("/admin-api/vouchers") .then((res) => setRows(res.data)) .catch((e) => setError(e?.message || "Gagal memuat voucher")) .finally(() => setLoading(false)); }; const loadHistory = (qValue?: string) => { setHistoryLoading(true); const params = qValue ? `?limit=100&tipe=USE&q=${encodeURIComponent(qValue)}` : "?limit=100&tipe=USE"; apiGet<{ data: VoucherHistoryRow[] }>(`/admin-api/vouchers/history${params}`) .then((res) => setHistory(res.data)) .catch((e) => setError(e?.message || "Gagal memuat riwayat")) .finally(() => setHistoryLoading(false)); }; useEffect(() => { load(); loadHistory(); apiGet<{ data: PegawaiRow[] }>("/admin-api/pegawai") .then((res) => setPegawai(res.data || [])) .catch(() => {}); apiGet<{ data: any }>("/admin-api/pengaturan") .then((res) => { const t = res?.data?.toko || {}; setStore({ nama: t?.nama || "Toko", alamat: t?.alamat || "", telepon: t?.telepon || "", logo: t?.logo || "", }); }) .catch(() => {}); }, []); const filtered = useMemo(() => { const s = q.trim().toLowerCase(); if (!s) return rows; return rows.filter((r) => [ r.kode, r.catatan || "", r.pegawai_nama || "", r.pegawai_nip || "", ].some((v) => v.toLowerCase().includes(s)) ); }, [rows, q]); const resetForm = () => { setForm({ pegawaiId: "", kode: "", saldo: "", catatan: "", aktif: true }); }; const submit = async () => { if (!form.pegawaiId) { setError("Pegawai wajib dipilih."); return; } setSaving(true); setError(null); setMsg(null); try { const res = await apiPost<{ data?: VoucherRow }>("/admin-api/vouchers", { pegawai_id: Number(form.pegawaiId), kode: form.kode.trim() || null, saldo: form.saldo.trim() ? Number(form.saldo) : 0, catatan: form.catatan.trim() || null, aktif: form.aktif, }); const kode = res?.data?.kode || ""; setMsg(kode ? `Voucher berhasil dibuat: ${kode}` : "Voucher berhasil dibuat."); if (res?.data) { printVoucher(res.data, "Pembuatan Voucher"); } resetForm(); closeModal(); load(); loadHistory(historyQ); } catch (e: any) { setError(e?.message || "Gagal menyimpan voucher"); } finally { setSaving(false); } }; const toggleAktif = async (row: VoucherRow) => { setError(null); setMsg(null); try { await apiPut(`/admin-api/vouchers/${row.id}`, { aktif: !row.aktif }); setMsg("Status voucher diperbarui."); load(); } catch (e: any) { setError(e?.message || "Gagal memperbarui status"); } }; const openTopup = (row: VoucherRow) => { setTopup({ id: row.id, kode: row.kode, amount: "" }); setTopupOpen(true); }; const submitTopup = async () => { if (!topup.amount || Number(topup.amount) <= 0) { return setError("Nominal top up harus lebih dari 0."); } setTopupSaving(true); setError(null); setMsg(null); try { const res = await apiPut<{ data?: VoucherRow }>(`/admin-api/vouchers/${topup.id}`, { add_saldo: Number(topup.amount), }); setMsg("Saldo voucher berhasil ditambahkan."); if (res?.data) { printVoucher(res.data, "Top Up Voucher"); } setTopupOpen(false); setTopup({ id: 0, kode: "", amount: "" }); load(); loadHistory(historyQ); } catch (e: any) { setError(e?.message || "Gagal top up saldo"); } finally { setTopupSaving(false); } }; const printVoucher = (voucher: VoucherRow, title: string) => { const win = window.open("", "_blank", "width=520,height=640"); if (!win) { setError("Popup diblokir. Izinkan popup untuk mencetak."); return; } const html = ` ${title}
${store.logo ? `` : ""}

${store.nama}

${store.alamat ? `
${store.alamat}
` : ""} ${store.telepon ? `
Telp: ${store.telepon}
` : ""}
${title}
Kode
${voucher.kode}
${ voucher.pegawai_nama ? `
Pegawai
${voucher.pegawai_nama}${ voucher.pegawai_nip ? ` (${voucher.pegawai_nip})` : "" }
` : "" }
Saldo
Rp ${Number(voucher.saldo || 0).toLocaleString("id-ID")}
Status
${voucher.aktif ? "Aktif" : "Nonaktif"}
${voucher.catatan ? `
Catatan
${voucher.catatan}
` : ""}
${new Date().toLocaleString("id-ID")}
`; win.document.open(); win.document.write(html); win.document.close(); }; return ( <>

Voucher (Deposit)

{msg && (
{msg}
)} {error && (
{error}
)}
Tambah Voucher
setForm((f) => ({ ...f, kode: e.target.value }))} placeholder="Kode voucher (kosongkan untuk otomatis)" 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, saldo: e.target.value }))} placeholder="Saldo awal" type="number" min={0} 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, catatan: e.target.value }))} placeholder="Catatan (opsional)" className="h-11 rounded-xl border border-gray-200 bg-white px-4 text-sm dark:border-gray-800 dark:bg-gray-950" />
setTopupOpen(false)} className="max-w-[520px] p-6 lg:p-8" >
Top Up Voucher
Kode: {topup.kode}
setTopup((t) => ({ ...t, amount: e.target.value }))} placeholder="Nominal top up" type="number" min={1} className="h-11 rounded-xl border border-gray-200 bg-white px-4 text-sm dark:border-gray-800 dark:bg-gray-950" />
Daftar Voucher
setQ(e.target.value)} placeholder="Cari kode / catatan..." className="h-10 w-full sm:w-[320px] 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-950" />
{loading ? (
Memuat...
) : (
{filtered.map((r) => ( ))} {filtered.length === 0 && ( )}
Kode Pegawai Saldo Status Catatan Aksi
{r.kode} {r.pegawai_nama ? `${r.pegawai_nama}${r.pegawai_nip ? ` (${r.pegawai_nip})` : ""}` : "-"} Rp {Number(r.saldo || 0).toLocaleString("id-ID")} {r.aktif ? "Aktif" : "Nonaktif"} {r.catatan || "-"}
Tidak ada voucher.
)}
Riwayat Pemakaian Voucher
setHistoryQ(e.target.value)} placeholder="Cari kode voucher..." className="h-10 w-full sm:w-[240px] 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-950" />
{historyLoading ? (
Memuat...
) : history.length === 0 ? (
Belum ada riwayat.
) : (
{history.map((h) => ( ))}
Waktu Kode Tipe Jumlah Saldo Sebelum Saldo Sesudah No Transaksi
{h.created_at ? new Date(h.created_at).toLocaleString("id-ID") : "-"} {h.kode} {h.tipe === "USE" ? "Pemakaian" : h.tipe === "TOPUP" ? "Top Up" : h.tipe} Rp {Number(h.jumlah || 0).toLocaleString("id-ID")} Rp {Number(h.saldo_before || 0).toLocaleString("id-ID")} Rp {Number(h.saldo_after || 0).toLocaleString("id-ID")} {h.nomor_penjualan || "-"}
)}
); }