96 lines
2.6 KiB
TypeScript
96 lines
2.6 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { collection, onSnapshot, query, orderBy, limit, where, FirestoreError } from "firebase/firestore";
|
|
import { onAuthStateChanged } from "firebase/auth";
|
|
import { db, auth } from "@/lib/firebase";
|
|
import type { AlertEvent } from "@/lib/types";
|
|
|
|
const toISO = (v: unknown): string =>
|
|
(v as { toDate?: () => Date })?.toDate?.()?.toISOString?.() ??
|
|
(typeof v === "string" ? v : new Date().toISOString());
|
|
|
|
export function useAlerts(limitCount = 50) {
|
|
const [alerts, setAlerts] = useState<AlertEvent[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
let unsubFirestore: (() => void) | undefined;
|
|
|
|
const unsubAuth = onAuthStateChanged(auth, (user) => {
|
|
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
|
|
|
|
if (!user) {
|
|
setAlerts([]);
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
|
|
const q = query(
|
|
collection(db, "alert_events"),
|
|
orderBy("triggered_at", "desc"),
|
|
limit(limitCount)
|
|
);
|
|
unsubFirestore = onSnapshot(q, (snap) => {
|
|
setAlerts(snap.docs.map((d) => {
|
|
const data = d.data();
|
|
return {
|
|
...data,
|
|
triggered_at: toISO(data.triggered_at),
|
|
} as AlertEvent;
|
|
}));
|
|
setLoading(false);
|
|
}, (err: FirestoreError) => {
|
|
console.error("useAlerts:", err);
|
|
setError(err.message);
|
|
setLoading(false);
|
|
});
|
|
});
|
|
|
|
return () => {
|
|
unsubAuth();
|
|
if (unsubFirestore) unsubFirestore();
|
|
};
|
|
}, [limitCount]);
|
|
|
|
return { alerts, loading, error };
|
|
}
|
|
|
|
export function useUnacknowledgedAlerts() {
|
|
const [alerts, setAlerts] = useState<AlertEvent[]>([]);
|
|
|
|
useEffect(() => {
|
|
let unsubFirestore: (() => void) | undefined;
|
|
|
|
const unsubAuth = onAuthStateChanged(auth, (user) => {
|
|
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
|
|
|
|
if (!user) {
|
|
setAlerts([]);
|
|
return;
|
|
}
|
|
|
|
const q = query(
|
|
collection(db, "alert_events"),
|
|
where("acknowledged", "==", false),
|
|
orderBy("triggered_at", "desc"),
|
|
limit(100)
|
|
);
|
|
unsubFirestore = onSnapshot(q, (snap) => {
|
|
setAlerts(snap.docs.map((d) => {
|
|
const data = d.data();
|
|
return { ...data, triggered_at: toISO(data.triggered_at) } as AlertEvent;
|
|
}));
|
|
}, (err: FirestoreError) => { console.error("useUnacknowledgedAlerts:", err); });
|
|
});
|
|
|
|
return () => {
|
|
unsubAuth();
|
|
if (unsubFirestore) unsubFirestore();
|
|
};
|
|
}, []);
|
|
|
|
return alerts;
|
|
}
|