Files
pos/resources/js/admin/tailadmin/pages/Pos/Vouchers.tsx
2026-03-06 03:26:11 +07:00

571 lines
22 KiB
TypeScript

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<VoucherRow[]>([]);
const [pegawai, setPegawai] = useState<PegawaiRow[]>([]);
const [store, setStore] = useState({
nama: "Toko",
alamat: "",
telepon: "",
logo: "",
});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [msg, setMsg] = useState<string | null>(null);
const [q, setQ] = useState("");
const [history, setHistory] = useState<VoucherHistoryRow[]>([]);
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 = `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>${title}</title>
<style>
@page { margin: 6mm; }
body { font-family: "Courier New", monospace; padding: 0; color: #111; }
.receipt { width: 58mm; }
h1 { font-size: 13px; margin: 0 0 4px; text-align: center; }
.muted { color: #666; font-size: 10px; text-align: center; }
.logo { display: block; margin: 0 auto 6px; max-height: 48px; max-width: 90px; object-fit: contain; }
.divider { border-top: 1px dashed #666; margin: 6px 0; }
.row { display: flex; justify-content: space-between; font-size: 11px; }
.bold { font-weight: bold; }
</style>
</head>
<body>
<div class="receipt">
${store.logo ? `<img src="${store.logo}" class="logo" alt="Logo">` : ""}
<h1>${store.nama}</h1>
${store.alamat ? `<div class="muted">${store.alamat}</div>` : ""}
${store.telepon ? `<div class="muted">Telp: ${store.telepon}</div>` : ""}
<div class="divider"></div>
<div class="muted">${title}</div>
<div class="divider"></div>
<div class="row bold"><div>Kode</div><div>${voucher.kode}</div></div>
${
voucher.pegawai_nama
? `<div class="row"><div>Pegawai</div><div>${voucher.pegawai_nama}${
voucher.pegawai_nip ? ` (${voucher.pegawai_nip})` : ""
}</div></div>`
: ""
}
<div class="row"><div>Saldo</div><div>Rp ${Number(voucher.saldo || 0).toLocaleString("id-ID")}</div></div>
<div class="row"><div>Status</div><div>${voucher.aktif ? "Aktif" : "Nonaktif"}</div></div>
${voucher.catatan ? `<div class="row"><div>Catatan</div><div>${voucher.catatan}</div></div>` : ""}
<div class="divider"></div>
<div class="muted">${new Date().toLocaleString("id-ID")}</div>
</div>
<script>window.print();</script>
</body>
</html>`;
win.document.open();
win.document.write(html);
win.document.close();
};
return (
<>
<PageMeta title="Voucher" description="Voucher deposit" />
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-semibold text-gray-800 dark:text-white/90">
Voucher (Deposit)
</h1>
<button
type="button"
onClick={() => {
resetForm();
openModal();
}}
className="h-10 rounded-xl bg-blue-600 px-4 text-sm font-semibold text-white hover:bg-blue-700"
>
Tambah Voucher
</button>
</div>
{msg && (
<div className="rounded-xl bg-emerald-50 px-4 py-3 text-sm text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300">
{msg}
</div>
)}
{error && (
<div className="rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700 dark:bg-red-500/10 dark:text-red-300">
{error}
</div>
)}
<Modal
isOpen={isOpen}
onClose={closeModal}
className="max-w-[700px] p-6 lg:p-8"
>
<div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-800 dark:bg-gray-900">
<div className="text-sm font-semibold text-gray-800 dark:text-white/90">
Tambah Voucher
</div>
<div className="mt-4 grid gap-3 md:grid-cols-2">
<select
value={form.pegawaiId}
onChange={(e) =>
setForm((f) => ({ ...f, pegawaiId: e.target.value }))
}
className="h-11 rounded-xl border border-gray-200 bg-white px-4 text-sm dark:border-gray-800 dark:bg-gray-950"
>
<option value="">Pilih pegawai</option>
{pegawai.map((p) => (
<option key={p.id} value={p.id}>
{p.nama} {p.nip ? `(${p.nip})` : ""}
</option>
))}
</select>
<input
value={form.kode}
onChange={(e) => 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"
/>
<input
value={form.saldo}
onChange={(e) => 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"
/>
<input
value={form.catatan}
onChange={(e) => 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"
/>
<label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
<input
type="checkbox"
checked={!form.aktif}
onChange={(e) => setForm((f) => ({ ...f, aktif: !e.target.checked }))}
/>
Nonaktif
</label>
<button
type="button"
onClick={submit}
disabled={saving}
className="h-11 rounded-xl bg-blue-600 px-5 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-60"
>
{saving ? "Menyimpan..." : "Simpan Voucher"}
</button>
</div>
</div>
</Modal>
<Modal
isOpen={topupOpen}
onClose={() => setTopupOpen(false)}
className="max-w-[520px] p-6 lg:p-8"
>
<div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-800 dark:bg-gray-900">
<div className="text-sm font-semibold text-gray-800 dark:text-white/90">
Top Up Voucher
</div>
<div className="mt-3 text-xs text-gray-500">
Kode: <span className="font-semibold">{topup.kode}</span>
</div>
<div className="mt-4 grid gap-3">
<input
value={topup.amount}
onChange={(e) => 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"
/>
<button
type="button"
onClick={submitTopup}
disabled={topupSaving}
className="h-11 rounded-xl bg-blue-600 px-5 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-60"
>
{topupSaving ? "Menyimpan..." : "Tambah Saldo"}
</button>
</div>
</div>
</Modal>
<div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-800 dark:bg-gray-900">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="text-sm font-semibold text-gray-800 dark:text-white/90">
Daftar Voucher
</div>
<input
value={q}
onChange={(e) => 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"
/>
</div>
{loading ? (
<div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
Memuat...
</div>
) : (
<div className="mt-4 overflow-x-auto">
<table className="min-w-full text-sm">
<thead>
<tr className="text-left text-gray-500 dark:text-gray-400">
<th className="py-2 pr-4">Kode</th>
<th className="py-2 pr-4">Pegawai</th>
<th className="py-2 pr-4">Saldo</th>
<th className="py-2 pr-4">Status</th>
<th className="py-2 pr-4">Catatan</th>
<th className="py-2 pr-4">Aksi</th>
</tr>
</thead>
<tbody>
{filtered.map((r) => (
<tr
key={r.id}
className="border-t border-gray-100 dark:border-gray-800"
>
<td className="py-3 pr-4 font-medium text-gray-800 dark:text-white/90">
{r.kode}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
{r.pegawai_nama
? `${r.pegawai_nama}${r.pegawai_nip ? ` (${r.pegawai_nip})` : ""}`
: "-"}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
Rp {Number(r.saldo || 0).toLocaleString("id-ID")}
</td>
<td className="py-3 pr-4">
<span
className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold ${
r.aktif
? "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300"
: "bg-red-50 text-red-700 dark:bg-red-500/10 dark:text-red-300"
}`}
>
{r.aktif ? "Aktif" : "Nonaktif"}
</span>
</td>
<td className="py-3 pr-4 text-gray-600 dark:text-gray-400">
{r.catatan || "-"}
</td>
<td className="py-3 pr-4">
<button
type="button"
onClick={() => openTopup(r)}
className="mr-2 h-8 rounded-lg border border-gray-200 bg-white px-3 text-xs font-semibold hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-950"
>
Top Up
</button>
<button
type="button"
onClick={() => printVoucher(r, "Cetak Voucher")}
className="mr-2 h-8 rounded-lg border border-gray-200 bg-white px-3 text-xs font-semibold hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-950"
>
Print
</button>
<button
type="button"
onClick={() => toggleAktif(r)}
className="h-8 rounded-lg border border-gray-200 bg-white px-3 text-xs font-semibold hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-950"
>
{r.aktif ? "Nonaktifkan" : "Aktifkan"}
</button>
</td>
</tr>
))}
{filtered.length === 0 && (
<tr>
<td
colSpan={6}
className="py-6 text-center text-gray-500 dark:text-gray-400"
>
Tidak ada voucher.
</td>
</tr>
)}
</tbody>
</table>
</div>
)}
</div>
<div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-800 dark:bg-gray-900">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="text-sm font-semibold text-gray-800 dark:text-white/90">
Riwayat Pemakaian Voucher
</div>
<div className="flex w-full gap-2 sm:w-auto">
<input
value={historyQ}
onChange={(e) => 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"
/>
<button
type="button"
onClick={() => loadHistory(historyQ)}
className="h-10 rounded-xl border border-gray-200 bg-white px-4 text-sm font-semibold hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-950"
>
Cari
</button>
</div>
</div>
{historyLoading ? (
<div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
Memuat...
</div>
) : history.length === 0 ? (
<div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
Belum ada riwayat.
</div>
) : (
<div className="mt-4 overflow-x-auto">
<table className="min-w-full text-sm">
<thead>
<tr className="text-left text-gray-500 dark:text-gray-400">
<th className="py-2 pr-4">Waktu</th>
<th className="py-2 pr-4">Kode</th>
<th className="py-2 pr-4">Tipe</th>
<th className="py-2 pr-4">Jumlah</th>
<th className="py-2 pr-4">Saldo Sebelum</th>
<th className="py-2 pr-4">Saldo Sesudah</th>
<th className="py-2 pr-4">No Transaksi</th>
</tr>
</thead>
<tbody>
{history.map((h) => (
<tr
key={h.id}
className="border-t border-gray-100 dark:border-gray-800"
>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
{h.created_at
? new Date(h.created_at).toLocaleString("id-ID")
: "-"}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
{h.kode}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
{h.tipe === "USE" ? "Pemakaian" : h.tipe === "TOPUP" ? "Top Up" : h.tipe}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
Rp {Number(h.jumlah || 0).toLocaleString("id-ID")}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
Rp {Number(h.saldo_before || 0).toLocaleString("id-ID")}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
Rp {Number(h.saldo_after || 0).toLocaleString("id-ID")}
</td>
<td className="py-3 pr-4 text-gray-700 dark:text-gray-200">
{h.nomor_penjualan || "-"}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
</>
);
}