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

import { useCallback, useEffect, useState } from "react";
import Card, { CardBody, CardHeader } from "@/components/ui/Card";
import Button from "@/components/ui/Button";
import StatCard from "@/components/dashboard/StatCard";
import { apiRequest } from "@/lib/api";
import { formatCompact, formatDateTime } from "@/lib/format";
import type { AdminUsageResponse } from "@/types/api";

type UsageSortKey = "name" | "email" | "requests" | "input_tokens" | "last_used_at";

function IconClockMini({ className = "h-3.5 w-3.5" }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden>
      <circle cx="12" cy="12" r="8.5" stroke="currentColor" strokeWidth="1.7" />
      <path
        d="M12 7.5V12l3 2"
        stroke="currentColor"
        strokeWidth="1.7"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SortButton({
  label,
  active,
  dir,
  onClick,
  align = "left",
}: {
  label: string;
  active: boolean;
  dir: "asc" | "desc";
  onClick: () => void;
  align?: "left" | "right";
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`group inline-flex items-center gap-1 align-middle font-semibold uppercase tracking-wider transition ${
        active ? "text-blue-300" : "text-slate-500 hover:text-slate-300"
      }`}
    >
      {align === "right" && <span className="order-2">{label}</span>}
      {align === "left" && <span>{label}</span>}
      <span
        className={`text-[9px] leading-none ${active ? "text-blue-300" : "text-slate-600 group-hover:text-slate-400"}`}
      >
        {active ? (dir === "asc" ? "▲" : "▼") : "↕"}
      </span>
    </button>
  );
}

export default function AdminUsagePage() {
  const [days, setDays] = useState(30);
  const [data, setData] = useState<AdminUsageResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [q, setQ] = useState("");
  const [debouncedQ, setDebouncedQ] = useState("");
  const [page, setPage] = useState(1);
  const [limit] = useState(10);
  const [sort, setSort] = useState<UsageSortKey>("requests");
  const [order, setOrder] = useState<"asc" | "desc">("desc");

  useEffect(() => {
    const t = setTimeout(() => setDebouncedQ(q), 300);
    return () => clearTimeout(t);
  }, [q]);

  // Ganti kriteria → kembali ke halaman 1.
  useEffect(() => {
    setPage(1);
  }, [days, debouncedQ, sort, order]);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const p = new URLSearchParams({
        days: String(days),
        page: String(page),
        limit: String(limit),
        sort,
        order,
      });
      if (debouncedQ.trim()) p.set("q", debouncedQ.trim());
      const res = await apiRequest<AdminUsageResponse>(`/admin/usage?${p.toString()}`);
      setData(res);
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal memuat");
    } finally {
      setLoading(false);
    }
  }, [days, page, limit, sort, order, debouncedQ]);

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

  const applySort = (key: UsageSortKey) => {
    setSort((prev) => {
      if (prev === key) {
        setOrder((o) => (o === "asc" ? "desc" : "asc"));
        return prev;
      }
      setOrder("desc");
      return key;
    });
  };

  const total = data?.total ?? 0;
  const from = total === 0 ? 0 : (page - 1) * limit + 1;
  const to = Math.min(page * limit, total);

  const iconProps = {
    className: "h-5 w-5",
    fill: "none",
    viewBox: "0 0 24 24",
    stroke: "currentColor",
    strokeWidth: 1.7,
  } as const;

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-end gap-3">
        <div className="flex items-center gap-1 rounded-xl border border-white/[0.06] bg-white/[0.03] p-1">
          {[
            { v: 1, label: "Hari ini" },
            { v: 7, label: "7 hari" },
            { v: 30, label: "30 hari" },
            { v: 90, label: "90 hari" },
          ].map((o) => (
            <button
              key={o.v}
              onClick={() => setDays(o.v)}
              className={`rounded-lg px-3.5 py-1.5 text-xs font-medium transition-colors ${
                days === o.v
                  ? "bg-white/[0.08] text-white"
                  : "text-slate-500 hover:text-slate-300"
              }`}
            >
              {o.label}
            </button>
          ))}
        </div>
        <label className="flex items-center gap-2 text-xs text-slate-500 md:hidden">
          <span className="shrink-0">Urutkan</span>
          <select
            value={sort}
            onChange={(e) => applySort(e.target.value as UsageSortKey)}
            className="input-solid h-9 rounded-full px-3 text-xs"
          >
            <option value="requests">Requests</option>
            <option value="name">Nama</option>
            <option value="input_tokens">Input Tokens</option>
            <option value="last_used_at">Terakhir pakai</option>
          </select>
        </label>
      </div>

      {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>
      )}

      {loading && !data && (
        <div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <div
              key={i}
              className="h-24 animate-pulse rounded-2xl border border-white/[0.04] bg-white/[0.02] sm:h-28"
            />
          ))}
        </div>
      )}

      {data && (
        <>
          <div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <StatCard
              label="Total Requests"
              value={data.usage.requests}
              accent="pink"
              icon={
                <svg {...iconProps}>
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM3.75 12h.007v.008H3.75V12zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm-.375 5.25h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"
                  />
                </svg>
              }
            />
            <StatCard
              label="Input Tokens"
              value={data.usage.input_tokens}
              accent="fuchsia"
              icon={
                <svg {...iconProps}>
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z"
                  />
                </svg>
              }
            />
            <StatCard
              label="Cached Tokens"
              value={data.usage.cached_tokens}
              accent="rose"
              icon={
                <svg {...iconProps}>
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7l4.029-1.523a.75.75 0 01.93.539v.011a.75.75 0 01-.539.93l-4.029 1.523a8.25 8.25 0 01-13.803 3.7l-3.182-3.182v-.001z"
                  />
                </svg>
              }
            />
            <StatCard
              label="Output Tokens"
              value={data.usage.output_tokens}
              accent="hot"
              icon={
                <svg {...iconProps}>
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"
                  />
                </svg>
              }
            />
          </div>

          <Card>
            <CardHeader
              title="Rincian per Pengguna"
              subtitle={`Pemakaian ${days === 1 ? "hari ini" : `${days} hari terakhir`}`}
              action={
                <input
                  type="search"
                  placeholder="Cari nama / email…"
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                  className="input-solid w-full sm:w-56"
                />
              }
            />
            <CardBody className="p-0">
              {data.detail.length === 0 ? (
                <div className="px-5 py-10 text-center text-sm text-slate-500">
                  Belum ada pemakaian pada rentang ini.
                </div>
              ) : (
                <>
                  {/* ── Mobile: kartu per pengguna ── */}
                  <div className="divide-y divide-white/[0.04] md:hidden">
                    {data.detail.map((row) => (
                      <div key={row.user_id} className="p-4">
                        <p className="font-medium text-white">{row.name}</p>
                        <p className="truncate text-xs text-slate-500">
                          {row.email}
                        </p>
                        <p className="mt-1 flex items-center gap-1.5 text-[10px] tabular-nums text-slate-500">
                          <IconClockMini className="text-slate-500" />
                          Terakhir pakai: {formatDateTime(row.last_used_at)}
                        </p>
                        <div className="mt-2.5 grid grid-cols-2 gap-2 text-xs">
                          <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-2.5 py-1.5">
                            <p className="text-[10px] text-slate-500">Requests</p>
                            <p className="font-semibold tabular-nums text-slate-200">
                              {row.requests}
                            </p>
                          </div>
                          <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-2.5 py-1.5">
                            <p className="text-[10px] text-slate-500">Input Tokens</p>
                            <p className="font-medium tabular-nums text-slate-300">
                              {formatCompact(row.input_tokens)}
                            </p>
                          </div>
                          <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-2.5 py-1.5">
                            <p className="text-[10px] text-slate-500">Cached Tokens</p>
                            <p className="font-medium tabular-nums text-slate-400">
                              {formatCompact(row.cached_tokens)}
                            </p>
                          </div>
                          <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-2.5 py-1.5">
                            <p className="text-[10px] text-slate-500">Output Tokens</p>
                            <p className="font-medium tabular-nums text-slate-300">
                              {formatCompact(row.output_tokens)}
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* ── Desktop: tabel (rapat + sortable) ── */}
                  <div className="hidden overflow-x-auto md:block">
                  <table className="w-full min-w-[680px] 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-4 py-2.5 font-semibold">
                          <SortButton
                            label="Pengguna"
                            active={sort === "name"}
                            dir={order}
                            onClick={() => applySort("name")}
                          />
                        </th>
                        <th className="px-3 py-2.5 text-right font-semibold">
                          <SortButton
                            label="Requests"
                            active={sort === "requests"}
                            dir={order}
                            align="right"
                            onClick={() => applySort("requests")}
                          />
                        </th>
                        <th className="px-3 py-2.5 text-right font-semibold">
                          <SortButton
                            label="Input"
                            active={sort === "input_tokens"}
                            dir={order}
                            align="right"
                            onClick={() => applySort("input_tokens")}
                          />
                        </th>
                        <th className="px-3 py-2.5 text-right font-semibold text-slate-500">
                          Cached
                        </th>
                        <th className="px-3 py-2.5 text-right font-semibold text-slate-500">
                          Output
                        </th>
                        <th className="px-4 py-2.5 text-right font-semibold">
                          <SortButton
                            label="Terakhir pakai"
                            active={sort === "last_used_at"}
                            dir={order}
                            align="right"
                            onClick={() => applySort("last_used_at")}
                          />
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.detail.map((row) => (
                        <tr
                          key={row.user_id}
                          className="border-b border-white/[0.04] align-middle transition-colors last:border-0 hover:bg-white/[0.02]"
                        >
                          <td className="px-4 py-2.5">
                            <p className="font-medium text-white">{row.name}</p>
                            <p className="text-[11px] text-slate-500">{row.email}</p>
                          </td>
                          <td className="px-3 py-2.5 text-right font-medium tabular-nums text-slate-300">
                            {row.requests}
                          </td>
                          <td className="px-3 py-2.5 text-right font-medium tabular-nums whitespace-nowrap text-slate-300">
                            {formatCompact(row.input_tokens)}
                          </td>
                          <td className="px-3 py-2.5 text-right font-medium tabular-nums whitespace-nowrap text-slate-400">
                            {formatCompact(row.cached_tokens)}
                          </td>
                          <td className="px-3 py-2.5 text-right font-medium tabular-nums whitespace-nowrap text-slate-400">
                            {formatCompact(row.output_tokens)}
                          </td>
                          <td className="px-4 py-2.5 text-right">
                            <span className="inline-flex items-center gap-1 text-[10px] tabular-nums text-slate-500">
                              <IconClockMini />
                              {formatDateTime(row.last_used_at)}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  </div>

                  {/* Pagination */}
                  {total > limit && (
                    <div className="flex items-center justify-between gap-3 border-t border-white/[0.04] px-4 py-3">
                      <p className="text-xs text-slate-500">
                        Menampilkan {from}–{to} dari {total} pengguna · Halaman{" "}
                        {page} dari {Math.max(1, Math.ceil(total / limit))}
                      </p>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          disabled={page <= 1 || loading}
                          onClick={() => setPage((p) => Math.max(1, p - 1))}
                        >
                          Sebelumnya
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          disabled={page >= Math.ceil(total / limit) || loading}
                          onClick={() => setPage((p) => p + 1)}
                        >
                          Berikutnya
                        </Button>
                      </div>
                    </div>
                  )}
                </>
              )}
            </CardBody>
          </Card>
        </>
      )}
    </div>
  );
}

Zerion Mini Shell 1.0