chore: add project files and setup gitignore
This commit is contained in:
94
reserva-mesa-dashboard/hooks/useMesas.ts
Normal file
94
reserva-mesa-dashboard/hooks/useMesas.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
"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) => {
|
||||
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);
|
||||
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
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user