%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/AdminQrisPage.tsx

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

const API_BASE: string = import.meta.env.VITE_API_BASE_URL ?? "";
const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
const ACCEPTED = ["image/png", "image/jpeg", "image/webp", "image/gif"];

export default function AdminQrisPage() {
  const [settings, setSettings] = useState<QrisAdminResponse["settings"]>(null);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [fileName, setFileName] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const load = useCallback(async (silent = false) => {
    if (!silent) setLoading(true);
    try {
      const res = await apiRequest<QrisAdminResponse>("/admin/qris");
      setSettings(res.configured ? res.settings : null);
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal memuat konfigurasi QRIS");
    } finally {
      if (!silent) setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const handlePick = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith("image/")) {
      setError("File harus berupa gambar (PNG/JPEG/WebP/GIF).");
      return;
    }
    if (file.size > MAX_IMAGE_BYTES) {
      setError("Ukuran gambar maksimal 20 MB.");
      return;
    }
    const reader = new FileReader();
    reader.onload = () => {
      setPreview(String(reader.result));
      setFileName(file.name);
      setError(null);
      setSuccess(null);
    };
    reader.readAsDataURL(file);
  };

  const handleUpload = async () => {
    if (!preview) return;
    setBusy(true);
    setError(null);
    setSuccess(null);
    try {
      await apiRequest("/admin/qris", {
        method: "POST",
        body: { image: preview },
      });
      setPreview(null);
      setFileName(null);
      setSuccess("Gambar QRIS berhasil disimpan. Top up sekarang memakai QRIS dinamis.");
      await load(true);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal mengupload QRIS");
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async () => {
    setBusy(true);
    setError(null);
    setSuccess(null);
    try {
      await apiRequest("/admin/qris", { method: "DELETE" });
      setConfirmDelete(false);
      setSettings(null);
      setPreview(null);
      setFileName(null);
      setSuccess("Konfigurasi QRIS dihapus. Top up kembali memakai fallback statis.");
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal menghapus QRIS");
    } finally {
      setBusy(false);
    }
  };

  const imageUrl = settings
    ? `${API_BASE}/api/qris/image?t=${encodeURIComponent(settings.updated_at)}`
    : null;

  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>
      )}
      {success && (
        <div className="rounded-xl border border-emerald-500/25 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-300">
          {success}
        </div>
      )}

      {/* Status saat ini */}
      <Card>
        <CardHeader
          title="Gambar QRIS Saat Ini"
          subtitle="Gambar statis milik merchant — dasar pembuatan QRIS dinamis saat top up"
          action={
            settings ? (
              <Badge tone="success">Terkonfigurasi</Badge>
            ) : (
              <Badge tone="default">Belum diatur</Badge>
            )
          }
        />
        <CardBody>
          {loading ? (
            <div className="flex h-48 items-center justify-center">
              <div className="h-8 w-8 animate-spin rounded-full border-2 border-brand-500/30 border-t-brand-400" />
            </div>
          ) : settings ? (
            <div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start">
              <div className="rounded-2xl border border-white/[0.08] bg-white p-3 shadow-soft">
                <img
                  src={imageUrl ?? ""}
                  alt="QRIS merchant"
                  className="h-44 w-44 object-contain"
                />
              </div>
              <div className="flex-1 space-y-3 text-sm">
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3">
                    <p className="text-[11px] uppercase tracking-wider text-slate-500">
                      Nama merchant
                    </p>
                    <p className="mt-1 font-medium text-slate-200">
                      {settings.merchant_name || "—"}
                    </p>
                  </div>
                  <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3">
                    <p className="text-[11px] uppercase tracking-wider text-slate-500">
                      Kota
                    </p>
                    <p className="mt-1 font-medium text-slate-200">
                      {settings.merchant_city || "—"}
                    </p>
                  </div>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <span className="chip">
                    Diperbarui:{" "}
                    <span className="tabular-nums">{formatDateTime(settings.updated_at)}</span>
                  </span>
                  <span className="chip">Tipe: {settings.method}</span>
                </div>
                {confirmDelete ? (
                  <div className="flex flex-wrap items-center gap-2 rounded-xl border border-red-500/25 bg-red-500/10 px-4 py-3">
                    <p className="flex-1 text-xs leading-relaxed text-red-200">
                      Hapus QRIS? Top up akan kembali memakai fallback statis (env).
                      Aksi ini permanen.
                    </p>
                    <Button
                      variant="danger"
                      size="sm"
                      isLoading={busy}
                      onClick={handleDelete}
                    >
                      Ya, hapus
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setConfirmDelete(false)}
                      disabled={busy}
                    >
                      Batal
                    </Button>
                  </div>
                ) : (
                  <Button
                    variant="subtle"
                    size="sm"
                    className="text-red-400 hover:bg-red-500/10 hover:text-red-300"
                    onClick={() => setConfirmDelete(true)}
                    disabled={busy}
                  >
                    Hapus QRIS
                  </Button>
                )}
              </div>
            </div>
          ) : (
            <div className="flex h-48 flex-col items-center justify-center gap-3 text-center">
              <div className="flex h-14 w-14 items-center justify-center rounded-2xl border border-white/[0.06] bg-white/[0.02] text-slate-500">
                <svg
                  className="h-7 w-7"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={1.5}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5zM13.5 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5z"
                  />
                </svg>
              </div>
              <p className="max-w-sm text-sm text-slate-500">
                Belum ada gambar QRIS. Upload gambar QRIS statis milik merchant di
                bawah — sistem akan otomatis membacanya dan menjadikannya QRIS
                dinamis saat user top up.
              </p>
            </div>
          )}
        </CardBody>
      </Card>

      {/* Upload */}
      <Card>
        <CardHeader
          title="Upload / Ganti QRIS"
          subtitle="PNG, JPEG, WebP, atau GIF — maks 20 MB"
        />

        <CardBody>
          <div className="space-y-4">
            <div
              className="flex items-center justify-center rounded-2xl border-2 border-dashed border-white/[0.08] bg-white/[0.02] px-4 py-8 transition-colors hover:border-brand-400/30 hover:bg-brand-500/[0.03]"
              onClick={() => fileRef.current?.click()}
              role="button"
              aria-label="Pilih gambar QRIS"
            >
              <div className="flex flex-col items-center gap-3 text-center">
                {preview ? (
                  <img
                    src={preview}
                    alt="Pratinjau QRIS"
                    className="h-40 w-40 rounded-xl border border-white/[0.08] bg-white object-contain p-2"
                  />
                ) : (
                  <div className="flex h-12 w-12 items-center justify-center rounded-2xl border border-white/[0.06] bg-white/[0.02] text-slate-500">
                    <svg
                      className="h-6 w-6"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={1.5}
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"
                      />
                    </svg>
                  </div>
                )}
                <div>
                  <p className="text-sm font-medium text-slate-300">
                    {fileName || "Klik untuk memilih gambar QRIS"}
                  </p>
                  <p className="mt-0.5 text-xs text-slate-500">
                    QR code di gambar akan dibaca otomatis oleh sistem.
                  </p>
                </div>
              </div>
            </div>
            <input
              ref={fileRef}
              type="file"
              accept={ACCEPTED.join(",")}
              onChange={handlePick}
              className="hidden"
            />

            <div className="flex flex-wrap items-center justify-end gap-2">
              {preview && (
                <Button
                  variant="ghost"
                  onClick={() => {
                    setPreview(null);
                    setFileName(null);
                  }}
                  disabled={busy}
                >
                  Batal
                </Button>
              )}
              <Button
                isLoading={busy}
                disabled={!preview}
                onClick={handleUpload}
              >
                {settings ? "Ganti QRIS" : "Simpan QRIS"}
              </Button>
            </div>
          </div>
        </CardBody>
      </Card>
    </div>
  );
}

Zerion Mini Shell 1.0