refactor: integrate current user data across components
- Replaced instances of `authStore` with `currentUser` to streamline user authentication handling. - Updated permission checks and user-related data retrieval to utilize the new `useQuery` for better performance and clarity. - Cleaned up component structures and improved formatting for consistency and readability. - Enhanced error handling and user feedback mechanisms in various components to improve user experience.
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { useConvexClient, useQuery } from "convex-svelte";
|
||||
import { api } from "@sgse-app/backend/convex/_generated/api";
|
||||
import { authStore } from "$lib/stores/auth.svelte";
|
||||
import AprovarFerias from "$lib/components/AprovarFerias.svelte";
|
||||
import WizardSolicitacaoFerias from "$lib/components/ferias/WizardSolicitacaoFerias.svelte";
|
||||
import WizardSolicitacaoAusencia from "$lib/components/ausencias/WizardSolicitacaoAusencia.svelte";
|
||||
@@ -13,6 +12,7 @@
|
||||
import { X, Calendar } from "lucide-svelte";
|
||||
|
||||
const client = useConvexClient();
|
||||
const currentUser = useQuery(api.auth.getCurrentUser, {});
|
||||
|
||||
let abaAtiva = $state<
|
||||
| "meu-perfil"
|
||||
@@ -54,23 +54,17 @@
|
||||
|
||||
// Carregar perfil ao montar a página para garantir dados atualizados (apenas uma vez)
|
||||
$effect(() => {
|
||||
if (authStore.autenticado && authStore.usuario && !perfilCarregado) {
|
||||
if (currentUser?.data && !perfilCarregado) {
|
||||
perfilCarregado = true;
|
||||
// Atualizar authStore com dados mais recentes do backend
|
||||
authStore.refresh().catch((error) => {
|
||||
console.error("Erro ao carregar perfil:", error);
|
||||
perfilCarregado = false; // Permite tentar novamente em caso de erro
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Sincronizar com authStore - atualiza automaticamente quando o authStore muda
|
||||
// Isso garante que a foto/avatar seja carregada imediatamente ao abrir a página
|
||||
// Sincronizar com currentUser - atualiza automaticamente quando o usuário muda
|
||||
$effect(() => {
|
||||
const usuario = authStore.usuario;
|
||||
const usuario = currentUser?.data;
|
||||
if (usuario) {
|
||||
// Atualizar foto de perfil (pode ser null ou string)
|
||||
fotoPerfilLocal = usuario.fotoPerfilUrl ?? null;
|
||||
fotoPerfilLocal = usuario.fotoPerfil ?? null;
|
||||
// Atualizar avatar (pode ser undefined ou string)
|
||||
avatarLocal = usuario.avatar ?? null;
|
||||
} else {
|
||||
@@ -81,43 +75,32 @@
|
||||
}
|
||||
});
|
||||
|
||||
// FuncionarioId disponível diretamente do authStore
|
||||
// FuncionarioId disponível diretamente do usuário atual
|
||||
const funcionarioIdDisponivel = $derived(
|
||||
authStore.usuario?.funcionarioId ?? null,
|
||||
currentUser?.data?.funcionarioId ?? null,
|
||||
);
|
||||
|
||||
// Debug: Verificar funcionarioId
|
||||
$effect(() => {
|
||||
console.log("🔍 [Perfil] funcionarioId:", authStore.usuario?.funcionarioId);
|
||||
console.log("🔍 [Perfil] Usuário completo:", authStore.usuario);
|
||||
console.log(
|
||||
"🔍 [Perfil] funcionarioIdDisponivel:",
|
||||
funcionarioIdDisponivel,
|
||||
);
|
||||
console.log("🔍 [Perfil] Botão habilitado?", !!funcionarioIdDisponivel);
|
||||
});
|
||||
|
||||
// Queries
|
||||
const funcionarioQuery = $derived(
|
||||
authStore.usuario?.funcionarioId
|
||||
currentUser?.data?.funcionarioId
|
||||
? useQuery(api.funcionarios.getById, {
|
||||
id: authStore.usuario.funcionarioId,
|
||||
id: currentUser.data.funcionarioId,
|
||||
})
|
||||
: { data: null },
|
||||
);
|
||||
|
||||
const solicitacoesSubordinadosQuery = $derived(
|
||||
authStore.usuario?._id
|
||||
currentUser?.data?._id
|
||||
? useQuery(api.ferias.listarSolicitacoesSubordinados, {
|
||||
gestorId: authStore.usuario._id as Id<"usuarios">,
|
||||
gestorId: currentUser.data._id as Id<"usuarios">,
|
||||
})
|
||||
: { data: [] },
|
||||
);
|
||||
|
||||
const ausenciasSubordinadosQuery = $derived(
|
||||
authStore.usuario?._id
|
||||
currentUser?.data?._id
|
||||
? useQuery(api.ausencias.listarSolicitacoesSubordinados, {
|
||||
gestorId: authStore.usuario._id as Id<"usuarios">,
|
||||
gestorId: currentUser.data._id as Id<"usuarios">,
|
||||
})
|
||||
: { data: [] },
|
||||
);
|
||||
@@ -147,9 +130,9 @@
|
||||
);
|
||||
|
||||
const meusTimesGestorQuery = $derived(
|
||||
authStore.usuario?._id
|
||||
currentUser?.data?._id
|
||||
? useQuery(api.times.listarPorGestor, {
|
||||
gestorId: authStore.usuario._id as Id<"usuarios">,
|
||||
gestorId: currentUser.data._id as Id<"usuarios">,
|
||||
})
|
||||
: { data: [] },
|
||||
);
|
||||
@@ -312,12 +295,9 @@
|
||||
// 5. Aguardar um pouco para garantir que o backend processou
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
|
||||
// 6. Atualizar authStore para obter a URL da foto atualizada
|
||||
await authStore.refresh();
|
||||
|
||||
// 7. Atualizar localmente com a URL do authStore (substitui o preview temporário)
|
||||
if (authStore.usuario?.fotoPerfilUrl) {
|
||||
fotoPerfilLocal = authStore.usuario.fotoPerfilUrl;
|
||||
// 6. Atualizar localmente com a URL retornada pelo backend (ou pelo currentUser)
|
||||
if (currentUser?.data?.fotoPerfil) {
|
||||
fotoPerfilLocal = currentUser.data.fotoPerfil;
|
||||
avatarLocal = null;
|
||||
}
|
||||
|
||||
@@ -343,8 +323,8 @@
|
||||
} catch (e: any) {
|
||||
erroUpload = e.message || "Erro ao fazer upload da foto";
|
||||
// Reverter mudança local se houver erro
|
||||
fotoPerfilLocal = authStore.usuario?.fotoPerfilUrl || null;
|
||||
avatarLocal = authStore.usuario?.avatar || null;
|
||||
fotoPerfilLocal = currentUser?.data?.fotoPerfil || null;
|
||||
avatarLocal = currentUser?.data?.avatar || null;
|
||||
} finally {
|
||||
uploadandoFoto = false;
|
||||
}
|
||||
@@ -368,12 +348,9 @@
|
||||
// 3. Aguardar um pouco para garantir que o backend processou
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
|
||||
// 4. Atualizar authStore e aguardar conclusão
|
||||
await authStore.refresh();
|
||||
|
||||
// 5. Garantir que os estados locais estão sincronizados com o authStore
|
||||
if (authStore.usuario?.avatar) {
|
||||
avatarLocal = authStore.usuario.avatar;
|
||||
// 4. Garantir que os estados locais estão sincronizados com o usuário atual
|
||||
if (currentUser?.data?.avatar) {
|
||||
avatarLocal = currentUser.data.avatar;
|
||||
fotoPerfilLocal = null;
|
||||
}
|
||||
|
||||
@@ -396,8 +373,8 @@
|
||||
} catch (e: any) {
|
||||
erroUpload = e.message || "Erro ao salvar avatar";
|
||||
// Reverter mudança local se houver erro
|
||||
avatarLocal = authStore.usuario?.avatar || null;
|
||||
fotoPerfilLocal = authStore.usuario?.fotoPerfilUrl || null;
|
||||
avatarLocal = currentUser?.data?.avatar || null;
|
||||
fotoPerfilLocal = currentUser?.data?.fotoPerfil || null;
|
||||
} finally {
|
||||
uploadandoFoto = false;
|
||||
}
|
||||
@@ -457,7 +434,7 @@
|
||||
class="bg-white text-purple-700 flex items-center justify-center"
|
||||
>
|
||||
<span class="text-5xl font-black"
|
||||
>{authStore.usuario?.nome
|
||||
>{currentUser.data?.nome
|
||||
.substring(0, 2)
|
||||
.toUpperCase()}</span
|
||||
>
|
||||
@@ -498,7 +475,7 @@
|
||||
<!-- Informações do Usuário PREMIUM -->
|
||||
<div class="flex-1 text-white text-center md:text-left">
|
||||
<h1 class="text-5xl font-black mb-3 drop-shadow-lg">
|
||||
{authStore.usuario?.nome}
|
||||
{currentUser.data?.nome}
|
||||
</h1>
|
||||
|
||||
{#if funcionario?.descricaoCargo}
|
||||
@@ -540,7 +517,7 @@
|
||||
d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
{authStore.usuario?.email}
|
||||
{currentUser.data?.email}
|
||||
</p>
|
||||
|
||||
<div
|
||||
@@ -549,7 +526,7 @@
|
||||
<div
|
||||
class="badge badge-lg bg-white/90 text-purple-700 border-0 font-bold shadow-lg px-4"
|
||||
>
|
||||
{authStore.usuario?.role?.nome || "Usuário"}
|
||||
{currentUser.data?.role?.nome || "Usuário"}
|
||||
</div>
|
||||
|
||||
{#if meuTime}
|
||||
@@ -747,7 +724,7 @@
|
||||
<div>
|
||||
<p class="text-white/80 text-sm font-medium">Seu Perfil</p>
|
||||
<p class="text-2xl font-black">
|
||||
{authStore.usuario?.role?.nome || "Usuário"}
|
||||
{currentUser.data?.role?.nome || "Usuário"}
|
||||
</p>
|
||||
</div>
|
||||
<svg
|
||||
@@ -909,7 +886,7 @@
|
||||
>Nome Completo</span
|
||||
>
|
||||
<p class="text-base-content font-semibold text-lg">
|
||||
{authStore.usuario?.nome}
|
||||
{currentUser.data?.nome}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -941,7 +918,7 @@
|
||||
<p
|
||||
class="text-base-content font-semibold text-lg break-all"
|
||||
>
|
||||
{authStore.usuario?.email}
|
||||
{currentUser.data?.email}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -971,7 +948,7 @@
|
||||
>Perfil de Acesso</span
|
||||
>
|
||||
<div class="badge badge-primary badge-lg mt-1 font-bold">
|
||||
{authStore.usuario?.role?.nome || "Usuário"}
|
||||
{currentUser.data?.role?.nome || "Usuário"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1697,7 +1674,7 @@
|
||||
type="button"
|
||||
class="btn btn-warning gap-2"
|
||||
onclick={() => {
|
||||
const funcionarioId = authStore.usuario?.funcionarioId;
|
||||
const funcionarioId = currentUser?.data?.funcionarioId;
|
||||
console.log(
|
||||
"🔍 [Perfil] Click no botão - funcionarioId:",
|
||||
funcionarioId,
|
||||
@@ -1706,7 +1683,7 @@
|
||||
mostrarWizardAusencia = true;
|
||||
} else {
|
||||
alert(
|
||||
`Não foi possível identificar seu funcionário.\n\nVerifique no console (F12) o objeto usuario:\n${JSON.stringify(authStore.usuario, null, 2)}\n\nEntre em contato com o suporte se o problema persistir.`,
|
||||
`Não foi possível identificar seu funcionário.\n\nVerifique no console (F12) o objeto usuario:\n${JSON.stringify(currentUser?.data, null, 2)}\n\nEntre em contato com o suporte se o problema persistir.`,
|
||||
);
|
||||
}
|
||||
}}
|
||||
@@ -2158,10 +2135,10 @@
|
||||
{#if solicitacaoSelecionada}
|
||||
<dialog class="modal modal-open">
|
||||
<div class="modal-box max-w-4xl">
|
||||
{#if authStore.usuario}
|
||||
{#if currentUser.data}
|
||||
<AprovarFerias
|
||||
solicitacao={solicitacaoSelecionada}
|
||||
gestorId={authStore.usuario._id}
|
||||
gestorId={currentUser.data._id}
|
||||
onSucesso={recarregar}
|
||||
onCancelar={() => (solicitacaoSelecionada = null)}
|
||||
/>
|
||||
@@ -2210,7 +2187,7 @@
|
||||
class="bg-primary text-primary-content flex items-center justify-center"
|
||||
>
|
||||
<span class="text-4xl font-bold"
|
||||
>{authStore.usuario?.nome
|
||||
>{currentUser.data?.nome
|
||||
.substring(0, 2)
|
||||
.toUpperCase()}</span
|
||||
>
|
||||
@@ -2517,14 +2494,14 @@
|
||||
{/if}
|
||||
|
||||
<!-- Modal de Aprovação de Ausências -->
|
||||
{#if solicitacaoAusenciaAprovar && authStore.usuario}
|
||||
{#if solicitacaoAusenciaAprovar && currentUser.data}
|
||||
{#await client.query( api.ausencias.obterDetalhes, { solicitacaoId: solicitacaoAusenciaAprovar }, ) then detalhes}
|
||||
{#if detalhes}
|
||||
<dialog class="modal modal-open">
|
||||
<div class="modal-box max-w-4xl">
|
||||
<AprovarAusencias
|
||||
solicitacao={detalhes}
|
||||
gestorId={authStore.usuario._id}
|
||||
gestorId={currentUser.data._id}
|
||||
onSucesso={() => {
|
||||
solicitacaoAusenciaAprovar = null;
|
||||
}}
|
||||
|
||||
Reference in New Issue
Block a user