From e770826fb673f4d24364acce91800ccf01f6ef08 Mon Sep 17 00:00:00 2001 From: M-Gabrielly Date: Sat, 11 Oct 2025 23:04:08 -0300 Subject: [PATCH] fix(auth): merge profile and persist to localStorage - Impact: prevents profile loss on reload chore(assignment): add professional assignment form - Impact: enables assigning professionals to patients via UI --- .../components/admin/AssignmentForm.tsx | 19 +------ susconecta/hooks/useAuth.tsx | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 17 deletions(-) diff --git a/susconecta/components/admin/AssignmentForm.tsx b/susconecta/components/admin/AssignmentForm.tsx index 4045c92..1160b45 100644 --- a/susconecta/components/admin/AssignmentForm.tsx +++ b/susconecta/components/admin/AssignmentForm.tsx @@ -52,7 +52,7 @@ export default function AssignmentForm({ patientId, open, onClose, onSaved }: Pr if (!selectedProfessional) return toast({ title: 'Selecione um profissional', variant: 'default' }); setLoading(true); try { - await assignRoleToUser({ patient_id: patientId, user_id: selectedProfessional, role }); + await assignRoleToUser({ patient_id: patientId, user_id: selectedProfessional, role }); toast({ title: 'Atribuição criada', variant: 'default' }); onSaved && onSaved(); onClose(); @@ -86,22 +86,7 @@ export default function AssignmentForm({ patientId, open, onClose, onSaved }: Pr -
- - { - const v = String(e.target.value || '').toLowerCase().trim(); - // Map common english values to portuguese expected by backend - if (v === 'doctor') return setRole('medico'); - if (v === 'nurse') return setRole('enfermeiro'); - if (v === 'medico' || v === 'enfermeiro') return setRole(v as PatientAssignmentRole); - // fallback: keep current role (ignore unknown input) - return setRole(role); - }} - /> -
Ex: medico, enfermeiro (inglês: doctor → medico)
-
+ {/* role input removed - only professional select remains; role defaults to 'medico' on submit */} {existing && existing.length > 0 && (
diff --git a/susconecta/hooks/useAuth.tsx b/susconecta/hooks/useAuth.tsx index d0104a8..5871f03 100644 --- a/susconecta/hooks/useAuth.tsx +++ b/susconecta/hooks/useAuth.tsx @@ -2,6 +2,7 @@ import { createContext, useContext, useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react' import { useRouter } from 'next/navigation' import { loginUser, logoutUser, AuthenticationError } from '@/lib/auth' +import { getUserInfo } from '@/lib/api' import { ENV_CONFIG } from '@/lib/env-config' import { isExpired, parseJwt } from '@/lib/jwt' import { httpClient } from '@/lib/http' @@ -131,6 +132,35 @@ export function AuthProvider({ children }: { children: ReactNode }) { // Restaurar sessão válida const userData = JSON.parse(storedUser) as UserData setToken(storedToken) + // Tentar buscar profile consolidado (user-info) e mesclar + try { + const info = await getUserInfo() + if (info?.profile) { + const mapped = { + cpf: (info.profile as any).cpf ?? userData.profile?.cpf, + crm: (info.profile as any).crm ?? userData.profile?.crm, + telefone: info.profile.phone ?? userData.profile?.telefone, + foto_url: info.profile.avatar_url ?? userData.profile?.foto_url, + } + if (userData.profile) { + userData.profile = { ...userData.profile, ...mapped } + } else { + userData.profile = mapped + } + // Persistir o usuário atualizado no localStorage para evitar + // que 'auth_user.profile' fique vazio após um reload completo + try { + if (typeof window !== 'undefined') { + localStorage.setItem(AUTH_STORAGE_KEYS.USER, JSON.stringify(userData)) + } + } catch (e) { + console.warn('[AUTH] Falha ao persistir user (profile) no localStorage:', e) + } + } + } catch (err) { + console.warn('[AUTH] Falha ao buscar user-info na restauração de sessão:', err) + } + setUser(userData) setAuthStatus('authenticated') @@ -195,6 +225,26 @@ export function AuthProvider({ children }: { children: ReactNode }) { console.warn('[AUTH] Erro ao buscar user-info após login (não crítico):', err) } + // Após login, tentar buscar profile consolidado e mesclar antes de persistir + try { + const info = await getUserInfo() + if (info?.profile && response.user) { + const mapped = { + cpf: (info.profile as any).cpf ?? response.user.profile?.cpf, + crm: (info.profile as any).crm ?? response.user.profile?.crm, + telefone: info.profile.phone ?? response.user.profile?.telefone, + foto_url: info.profile.avatar_url ?? response.user.profile?.foto_url, + } + if (response.user.profile) { + response.user.profile = { ...response.user.profile, ...mapped } + } else { + response.user.profile = mapped + } + } + } catch (err) { + console.warn('[AUTH] Falha ao buscar user-info após login (não crítico):', err) + } + saveAuthData( response.access_token, response.user,