%PDF- %PDF-
| Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/ |
| Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/usePendingTopups.ts |
import { useCallback, useEffect, useRef, useState } from "react";
import { apiRequest } from "@/lib/api";
import { useAuth } from "@/contexts/AuthContext";
/** Minta izin notifikasi browser (harus dipanggil dari user gesture). */
export async function requestNotifyPermission(): Promise<
"granted" | "denied" | "default" | "unsupported"
> {
if (typeof Notification === "undefined") return "unsupported";
if (Notification.permission === "granted") return "granted";
try {
return await Notification.requestPermission();
} catch {
return "default";
}
}
/**
* Jumlah order top-up pending (dipakai badge sidebar & halaman admin).
* Polling setiap intervalMs; jika jumlah naik & izin notifikasi diberikan,
* munculkan notifikasi browser ke admin.
*/
export function usePendingTopups(intervalMs = 15000) {
const { user } = useAuth();
const [count, setCount] = useState(0);
const prevRef = useRef(0);
const isAdmin = Number(user?.is_admin) === 1;
useEffect(() => {
if (!isAdmin) {
setCount(0);
prevRef.current = 0;
return;
}
let cancelled = false;
const load = async () => {
try {
const res = await apiRequest<{ orders: { id: number }[] }>(
"/admin/topup?status=pending",
);
if (cancelled) return;
const n = res.orders.length;
const prev = prevRef.current;
prevRef.current = n;
setCount(n);
// Notifikasi hanya saat jumlah NAIK setelah poll pertama (prev>0)
if (
n > prev &&
prev > 0 &&
typeof Notification !== "undefined" &&
Notification.permission === "granted"
) {
try {
new Notification("Order top-up baru", {
body: `${n} order menunggu verifikasi.`,
tag: "topup-pending",
});
} catch {
/* abaikan */
}
}
} catch {
/* biarkan nilai lama */
}
};
load();
const id = setInterval(load, intervalMs);
return () => {
cancelled = true;
clearInterval(id);
};
}, [isAdmin, intervalMs]);
const requestNotify = useCallback(() => requestNotifyPermission(), []);
return { count, requestNotify };
}