101 lines
2.6 KiB
TypeScript
101 lines
2.6 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect } from "react";
|
|
import { ref, onValue, off, update, push, remove } from "firebase/database";
|
|
import { db } from "@/lib/firebase";
|
|
import { useAuth } from "@/hooks/useAuth";
|
|
import { Mesa, MesaEstado } from "@/types/mesa";
|
|
|
|
export function useMesas() {
|
|
const { user } = useAuth();
|
|
const [mesas, setMesas] = useState<Mesa[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
if (!user?.email) return;
|
|
|
|
const mesasRef = ref(db, "Mesas");
|
|
|
|
const unsubscribe = onValue(mesasRef, (snapshot) => {
|
|
try {
|
|
const data = snapshot.val();
|
|
const list: Mesa[] = [];
|
|
|
|
if (data) {
|
|
Object.keys(data).forEach((key) => {
|
|
const item = data[key];
|
|
if (item?.restauranteEmail === user.email) {
|
|
list.push({
|
|
id: key,
|
|
...item
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
// Sort by table number
|
|
list.sort((a, b) => a.numero - b.numero);
|
|
|
|
setMesas(list);
|
|
} catch (error) {
|
|
console.error("[useMesas] Error processing data:", error);
|
|
setMesas([]);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
});
|
|
|
|
return () => off(mesasRef, "value", unsubscribe);
|
|
}, [user?.email]);
|
|
|
|
const updateMesaEstado = async (mesaId: string, novoEstado: MesaEstado) => {
|
|
try {
|
|
await update(ref(db, `Mesas/${mesaId}`), {
|
|
estado: novoEstado
|
|
});
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error("Erro ao atualizar estado da mesa:", error);
|
|
return { success: false, error };
|
|
}
|
|
};
|
|
|
|
const addMesa = async (numero: number, capacidade: number) => {
|
|
if (!user?.email) return { success: false, error: "Utilizador não autenticado" };
|
|
|
|
try {
|
|
const newMesaRef = push(ref(db, "Mesas"));
|
|
const mesaData: Mesa = {
|
|
id: newMesaRef.key as string,
|
|
numero,
|
|
capacidade,
|
|
estado: "Livre",
|
|
restauranteEmail: user.email
|
|
};
|
|
await update(newMesaRef, mesaData);
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error("Erro ao adicionar mesa:", error);
|
|
return { success: false, error };
|
|
}
|
|
};
|
|
|
|
const deleteMesa = async (mesaId: string) => {
|
|
try {
|
|
await remove(ref(db, `Mesas/${mesaId}`));
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error("Erro ao remover mesa:", error);
|
|
return { success: false, error };
|
|
}
|
|
};
|
|
|
|
return {
|
|
mesas,
|
|
loading,
|
|
updateMesaEstado,
|
|
addMesa,
|
|
deleteMesa
|
|
};
|
|
}
|