79 lines
2.2 KiB
TypeScript
79 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
import { useAppRouter } from "@/hooks/use-app-router";
|
|
import { useState, useTransition } from "react";
|
|
import { RefreshCw } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
|
|
type SyncPayload = {
|
|
ok?: boolean;
|
|
error?: string;
|
|
data?: {
|
|
total: number;
|
|
inserted: number;
|
|
updated: number;
|
|
imagesSaved: number;
|
|
};
|
|
};
|
|
|
|
export function FacultySyncButton() {
|
|
const router = useAppRouter();
|
|
const [pending, startTransition] = useTransition();
|
|
const [busy, setBusy] = useState(false);
|
|
const [message, setMessage] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
async function onSync() {
|
|
setBusy(true);
|
|
setMessage(null);
|
|
setError(null);
|
|
try {
|
|
const res = await fetch("/api/admin/faculty/sync", { method: "POST" });
|
|
const body = (await res.json()) as SyncPayload;
|
|
if (!res.ok || !body.ok || !body.data) {
|
|
setError(body.error ?? "همگام سازی ناموفق بود");
|
|
return;
|
|
}
|
|
const { total, inserted, updated, imagesSaved } = body.data;
|
|
setMessage(
|
|
`${total} استاد خوانده شد — ${inserted} جدید، ${updated} به روز` +
|
|
(imagesSaved > 0 ? `، ${imagesSaved} تصویر` : ""),
|
|
);
|
|
startTransition(() => {
|
|
router.refresh();
|
|
});
|
|
} catch {
|
|
setError("ارتباط با سرور برقرار نشد");
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
const loading = busy || pending;
|
|
|
|
return (
|
|
<div className="flex flex-col items-stretch gap-1.5 sm:items-end">
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={onSync}
|
|
disabled={loading}
|
|
className="gap-2"
|
|
>
|
|
<RefreshCw className={loading ? "size-4 animate-spin" : "size-4"} />
|
|
{loading ? "در حال بروزرسانی…" : "بروزرسانی از شبکه اساتید"}
|
|
</Button>
|
|
{message ? (
|
|
<p className="max-w-xs text-xs text-muted-foreground" role="status">
|
|
{message}
|
|
</p>
|
|
) : null}
|
|
{error ? (
|
|
<p className="max-w-xs text-xs text-destructive" role="alert">
|
|
{error}
|
|
</p>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|