DataScope26/WEB
0
1import { useState, useEffect, useCallback } from "react";2import { getCompanyInvites, createInvite as createInviteApi, deleteInvite as deleteInviteApi } from "../services/apiInvites.js";3 4export const useInvites = (companyIdOverride = null) => {5 const [invites, setInvites] = useState([]);6 const [loading, setLoading] = useState(true);7 const [error, setError] = useState(null);8 9 const getToken = () =>10 sessionStorage.getItem("token") || localStorage.getItem("token");11 12 const getCurrentCompanyId = useCallback(() => {13 if (companyIdOverride != null && companyIdOverride !== "") return companyIdOverride;14 15 const storedCompanyId =16 localStorage.getItem("selectedCompanyId") ??17 sessionStorage.getItem("selectedCompanyId");18 19 return storedCompanyId ?? null;20 }, [companyIdOverride]);21 22 const fetchInvites = useCallback(async () => {23 const token = getToken();24 const companyId = getCurrentCompanyId();25 26 if (!token || !companyId) {27 setInvites([]);28 setLoading(false);29 return;30 }31 32 setLoading(true);33 setError(null);34 try {35 const data = await getCompanyInvites(token, companyId);36 if (Array.isArray(data)) {37 setInvites(data);38 } else {39 console.error("getCompanyInvites no devolvió un array:", data);40 setInvites([]);41 setError(new Error("Respuesta inesperada del servidor"));42 }43 } catch (err) {44 setInvites([]);45 setError(err);46 } finally {47 setLoading(false);48 }49 }, [getCurrentCompanyId]);50 51 useEffect(() => {52 fetchInvites();53 }, [fetchInvites]);54 55 const sendInvite = async (companyId, targetUserMail, area) => {56 const token = getToken();57 const resolvedCompanyId = companyId ?? getCurrentCompanyId();58 if (!token || !resolvedCompanyId) throw new Error("Falta la empresa para invitar");59 await createInviteApi(token, resolvedCompanyId, targetUserMail, area);60 await fetchInvites();61 };62 63 // MODIFICADO: Ahora recibe directamente el token mágico de la invitación64 const removeInvite = async (inviteToken) => {65 const token = getToken();66 const companyId = getCurrentCompanyId();67 68 if (!token) {69 throw new Error("No hay sesión activa para borrar la invitación");70 }71 72 if (!inviteToken) {73 throw new Error("Falta el token de la invitación");74 }75 76 if (!companyId) {77 throw new Error("Falta la empresa para autorizar el borrado");78 }79 80 // Enviamos el token de sesión, el ID de la empresa y el token de la invitación81 await deleteInviteApi(token, companyId, inviteToken);82 await fetchInvites();83 };84 85 return { invites, loading, error, sendInvite, deleteInvite: removeInvite, refetch: fetchInvites };86};