%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/pages/
Upload File :
Create Path :
Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/pages/AdminTopupPage.tsx

import { useCallback, useEffect, useState } from "react";
import Button from "@/components/ui/Button";
import Card, { CardBody, CardHeader } from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import Modal from "@/components/ui/Modal";
import { apiRequest } from "@/lib/api";
import { usePendingTopups } from "@/hooks/usePendingTopups";
import { formatDateTime } from "@/lib/format";
import type { TopupOrder } from "@/types/api";

function formatIDR(n: number): string {
  return n.toLocaleString("id-ID", {
    style: "currency",
    currency: "IDR",
    maximumFractionDigits: 0,
  });
}

function isExpired(o: TopupOrder): boolean {
  return o.status === "pending" && new Date(o.expires_at) < new Date();
}

const filters = [
  { value: "pending", label: "Menunggu" },
  { value: "paid", label: "Terbayar" },
  { value: "expired", label: "Kedaluwarsa" },
  { value: "", label: "Semua" },
];

export default function AdminTopupPage() {
  const { count: pendingTopups, requestNotify } = usePendingTopups();
  const [orders, setOrders] = useState<TopupOrder[]>([]);
  const [filter, setFilter] = useState<string>("pending");
  const [q, setQ] = useState("");
  const [debouncedQ, setDebouncedQ] = useState("");
  const [loading, setLoading] = useState(true);
  const [workingId, setWorkingId] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [delTarget, setDelTarget] = useState<TopupOrder | null>(null);
  const [delBusy, setDelBusy] = useState(false);
  const [notifyState, setNotifyState] = useState<
    "unsupported" | "prompt" | "granted" | "denied"
  >("prompt");

  // Debounce pencarian (Β±300ms) supaya tidak spam request per ketikan.
  useEffect(() => {
    const t = setTimeout(() => setDebouncedQ(q), 300);
    return () => clearTimeout(t);
  }, [q]);

  const load = useCallback(
    async (silent = false) => {
      if (!silent) setLoading(true);
      try {
        const p = new URLSearchParams();
        if (filter) p.set("status", filter);
        if (debouncedQ.trim()) p.set("q", debouncedQ.trim());
        const res = await apiRequest<{ orders: TopupOrder[] }>(
          `/admin/topup${p.toString() ? `?${p.toString()}` : ""}`,
        );
        setOrders(res.orders);
        setError(null);
      } catch (e) {
        setError(e instanceof Error ? e.message : "Gagal memuat order");
      } finally {
        if (!silent) setLoading(false);
      }
    },
    [filter, debouncedQ],
  );

  // Muat awal + auto-refresh setiap 5 detik
  useEffect(() => {
    load();
    const id = setInterval(() => load(true), 5000);
    return () => clearInterval(id);
  }, [load]);

  // Status izin notifikasi
  useEffect(() => {
    if (typeof Notification === "undefined") setNotifyState("unsupported");
    else if (Notification.permission === "granted") setNotifyState("granted");
    else if (Notification.permission === "denied") setNotifyState("denied");
    else setNotifyState("prompt");
  }, []);

  const handleEnableNotify = async () => {
    const p = await requestNotify();
    if (p === "granted") setNotifyState("granted");
    else if (p === "denied") setNotifyState("denied");
    else setNotifyState("prompt");
  };

  const verify = async (id: number) => {
    setWorkingId(id);
    try {
      await apiRequest(`/admin/topup/${id}/verify`, {
        method: "POST",
        body: { note: "Verifikasi manual oleh admin" },
      });
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal verifikasi");
    } finally {
      setWorkingId(null);
    }
  };

  const handleDelete = async () => {
    if (!delTarget) return;
    setDelBusy(true);
    try {
      await apiRequest(`/admin/topup/${delTarget.id}`, {
        method: "DELETE",
      });
      setDelTarget(null);
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal menghapus order");
      setDelTarget(null);
    } finally {
      setDelBusy(false);
    }
  };

  return (
    <div className="space-y-4">
      {error && (
        <div className="rounded-xl border border-red-500/25 bg-red-500/10 px-4 py-3 text-sm text-red-300">
          {error}
        </div>
      )}

      <Card>
        <CardHeader
          title="Daftar Order"
          subtitle="Klik verifikasi setelah pembayaran masuk"
          action={
            <div className="flex flex-wrap items-center gap-3">
              {pendingTopups > 0 && (
                <Badge tone="warning">
                  <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-amber-400" />
                  {pendingTopups} menunggu
                </Badge>
              )}
              {notifyState === "granted" ? (
                <Badge tone="success">
                  <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
                  Notifikasi aktif
                </Badge>
              ) : notifyState === "prompt" ? (
                <Button variant="ghost" size="sm" onClick={handleEnableNotify}>
                  πŸ”” Aktifkan notifikasi
                </Button>
              ) : notifyState === "denied" ? (
                <Badge tone="default">
                  Notifikasi diblokir browser
                </Badge>
              ) : null}
              <input
                type="search"
                placeholder="Cari nama / email / kode / nominal…"
                value={q}
                onChange={(e) => setQ(e.target.value)}
                className="input-solid w-full sm:w-48"
              />
              <div className="flex items-center gap-1 rounded-xl border border-white/[0.06] bg-white/[0.03] p-1">
                {filters.map((f) => (
                  <button
                    key={f.value || "all"}
                    onClick={() => setFilter(f.value)}
                    className={`rounded-lg px-3.5 py-1.5 text-xs font-medium transition-colors ${
                      filter === f.value
                        ? "bg-white/[0.08] text-white"
                        : "text-slate-500 hover:text-slate-300"
                    }`}
                  >
                    {f.label}
                  </button>
                ))}
              </div>
            </div>
          }
        />
        <CardBody className="p-0">
          {loading ? (
            <div className="space-y-3 p-5">
              {[...Array(3)].map((_, i) => (
                <div
                  key={i}
                  className="h-14 animate-pulse rounded-xl bg-white/[0.02]"
                />
              ))}
            </div>
          ) : orders.length === 0 ? (
            <div className="px-5 py-10 text-center text-sm text-slate-500">
              {debouncedQ.trim() ? "Tidak ada order yang cocok dengan pencarian." : "Tidak ada order dengan filter ini."}
            </div>
          ) : (
            <>
              {/* ── Mobile: kartu order ── */}
              <div className="divide-y divide-white/[0.04] md:hidden">
                {orders.map((o) => {
                  const expired = isExpired(o);
                  return (
                    <div
                      key={o.id}
                      className={`p-4 ${expired ? "opacity-45" : ""}`}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <p className="font-mono text-xs text-slate-400">
                            #{String(o.id).padStart(6, "0")}
                          </p>
                          <p className="mt-0.5 truncate text-sm font-medium text-slate-200">
                            {o.user_name || `User #${o.user_id}`}
                          </p>
                          {o.user_email && (
                            <p className="truncate text-[11px] text-slate-600">
                              {o.user_email}
                            </p>
                          )}
                        </div>
                        {o.status === "pending" ? (
                          <Badge tone="warning">Menunggu</Badge>
                        ) : o.status === "paid" ? (
                          <Badge tone="success">Terbayar</Badge>
                        ) : (
                          <Badge tone="danger">Kedaluwarsa</Badge>
                        )}
                      </div>

                      <div className="mt-3 flex items-end justify-between gap-2">
                        <div>
                          <p className="text-lg font-bold tabular-nums text-white">
                            {formatIDR(Number(o.amount))}
                          </p>
                          {o.unique_code != null && (
                            <p className="text-[11px] font-medium text-slate-500">
                              + {o.unique_code} ={" "}
                              <span className="text-brand-200">
                                {formatIDR(Number(o.amount) + o.unique_code)}
                              </span>
                            </p>
                          )}
                        </div>
                        <p className="text-right text-[10px] tabular-nums text-slate-500">
                          {formatDateTime(o.created_at)}
                        </p>
                      </div>

                      <div className="mt-3 flex flex-wrap gap-2">
                        {o.status === "pending" && !expired && (
                          <Button
                            variant="primary"
                            size="sm"
                            isLoading={workingId === o.id}
                            onClick={() => verify(o.id)}
                          >
                            Verifikasi
                          </Button>
                        )}
                        <Button
                          variant="subtle"
                          size="sm"
                          onClick={() => setDelTarget(o)}
                          className="text-red-400 hover:bg-red-500/10 hover:text-red-300"
                        >
                          Hapus
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* ── Desktop: tabel ── */}
              <div className="hidden overflow-x-auto md:block">
              <table className="w-full min-w-[820px] text-left text-sm">
                <thead>
                  <tr className="border-b border-white/[0.06] bg-white/[0.02] text-[11px] uppercase tracking-wider text-slate-500">
                    <th className="px-5 py-3 font-semibold">Order</th>
                    <th className="px-4 py-3 font-semibold">User</th>
                    <th className="px-4 py-3 text-right font-semibold">
                      Nominal
                    </th>
                    <th className="px-4 py-3 text-right font-semibold">
                      Kode
                    </th>
                    <th className="px-4 py-3 font-semibold">Status</th>
                    <th className="px-4 py-3 text-right font-semibold">
                      Dibuat
                    </th>
                    <th className="px-5 py-3 text-right font-semibold">
                      Aksi
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {orders.map((o) => {
                    const expired = isExpired(o);
                    return (
                      <tr
                        key={o.id}
                        className={`border-b border-white/[0.04] transition-colors last:border-0 ${
                          expired
                            ? "opacity-45 hover:bg-transparent"
                            : "hover:bg-white/[0.02]"
                        }`}
                      >
                        <td className="px-5 py-3.5 font-mono text-xs text-slate-400">
                          #{String(o.id).padStart(6, "0")}
                        </td>
                        <td className="px-4 py-3.5">
                          <p className="text-sm font-medium text-slate-200">
                            {o.user_name || `User #${o.user_id}`}
                          </p>
                          {o.user_email && (
                            <p className="mt-0.5 truncate text-[11px] text-slate-600">
                              {o.user_email}
                            </p>
                          )}
                        </td>
                        <td className="px-4 py-3.5 text-right font-semibold tabular-nums text-white">
                          {formatIDR(Number(o.amount))}
                          {o.unique_code != null && (
                            <p className="text-[11px] font-medium text-slate-500">
                              + {o.unique_code} ={" "}
                              <span className="text-brand-200">
                                {formatIDR(Number(o.amount) + o.unique_code)}
                              </span>
                            </p>
                          )}
                        </td>
                        <td className="px-4 py-3.5 text-right">
                          {o.unique_code != null ? (
                            <span className="rounded-md border border-white/[0.06] bg-white/[0.03] px-1.5 py-0.5 font-mono text-xs font-bold tabular-nums text-brand-200">
                              {o.unique_code}
                            </span>
                          ) : (
                            <span className="text-xs text-slate-600">β€”</span>
                          )}
                        </td>
                        <td className="px-4 py-3.5">
                          {expired ? (
                            <Badge tone="default">Kadaluarsa</Badge>
                          ) : o.status === "paid" ? (
                            <Badge tone="success">Terbayar</Badge>
                          ) : o.status === "pending" ? (
                            <Badge tone="warning">Menunggu</Badge>
                          ) : o.status === "expired" ? (
                            <Badge tone="default">Kedaluwarsa</Badge>
                          ) : (
                            <Badge tone="danger">Gagal</Badge>
                          )}
                        </td>
                        <td className="px-4 py-3.5 text-right text-xs tabular-nums text-slate-500">
                          {formatDateTime(o.created_at)}
                        </td>
                        <td className="px-5 py-3.5 text-right">
                          <div className="flex items-center justify-end gap-2">
                            {o.status === "pending" && !expired && (
                              <Button
                                size="sm"
                                isLoading={workingId === o.id}
                                onClick={() => verify(o.id)}
                              >
                                Tandai Terbayar
                              </Button>
                            )}
                            {o.status !== "paid" && (
                              <Button
                                variant="subtle"
                                size="sm"
                                title="Hapus order (belum terbayar)"
                                className="text-red-400 hover:bg-red-500/10 hover:text-red-300"
                                onClick={() => setDelTarget(o)}
                              >
                                Hapus
                              </Button>
                            )}
                            {o.status === "paid" && (
                              <span className="text-xs text-slate-600">
                                β€”
                              </span>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              </div>
            </>
          )}
        </CardBody>
      </Card>

      <Modal
        open={Boolean(delTarget)}
        onClose={() => {
          if (!delBusy) setDelTarget(null);
        }}
        title="Hapus Order Top Up?"
        subtitle="Order yang belum terbayar akan dihapus permanen."
        width="max-w-sm"
      >
        <div className="space-y-4">
          <div className="rounded-xl border border-red-500/25 bg-red-500/10 px-4 py-3 text-xs leading-relaxed text-red-300">
            Anda akan menghapus order{" "}
            <strong>#{String(delTarget?.id ?? "").padStart(6, "0")}</strong>{" "}
            senilai <strong>{formatIDR(Number(delTarget?.amount ?? 0))}</strong>.
            Order belum terbayar, jadi saldo user tidak terpengaruh. User akan
            bisa membuat kode QRIS baru untuk order ini.
          </div>
          <div className="flex justify-end gap-2">
            <Button
              variant="ghost"
              onClick={() => setDelTarget(null)}
              disabled={delBusy}
            >
              Batal
            </Button>
            <Button
              variant="danger"
              isLoading={delBusy}
              onClick={handleDelete}
            >
              Ya, Hapus
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

Zerion Mini Shell 1.0