mergerelatoriosnovo
This commit is contained in:
commit
fa3c9fea16
@ -1,11 +1,11 @@
|
|||||||
// src/PagesMedico/FormNovoRelatorio.jsx
|
|
||||||
import React, { useEffect, useState, useRef } from 'react';
|
import React, { useEffect, useState, useRef } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import API_KEY from '../components/utils/apiKeys';
|
import API_KEY from '../components/utils/apiKeys';
|
||||||
import { useAuth } from '../components/utils/AuthProvider';
|
import { useAuth } from '../components/utils/AuthProvider';
|
||||||
import TiptapEditor from './TiptapEditor';
|
import TiptapEditor from './TiptapEditor';
|
||||||
import { GetAllPatients, GetPatientByID } from '../components/utils/Functions-Endpoints/Patient';
|
import { GetAllPatients } from '../components/utils/Functions-Endpoints/Patient';
|
||||||
import { GetAllDoctors, GetDoctorByID } from '../components/utils/Functions-Endpoints/Doctor';
|
import { GetAllDoctors } from '../components/utils/Functions-Endpoints/Doctor';
|
||||||
|
import { UserInfos } from '../components/utils/Functions-Endpoints/General';
|
||||||
import './styleMedico/FormNovoRelatorio.css';
|
import './styleMedico/FormNovoRelatorio.css';
|
||||||
|
|
||||||
const FormNovoRelatorio = () => {
|
const FormNovoRelatorio = () => {
|
||||||
@ -18,7 +18,6 @@ const FormNovoRelatorio = () => {
|
|||||||
const [loadingPatients, setLoadingPatients] = useState(true);
|
const [loadingPatients, setLoadingPatients] = useState(true);
|
||||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||||
|
|
||||||
// formulário
|
|
||||||
const [form, setForm] = useState({
|
const [form, setForm] = useState({
|
||||||
patient_id: '',
|
patient_id: '',
|
||||||
patient_name: '',
|
patient_name: '',
|
||||||
@ -28,19 +27,14 @@ const FormNovoRelatorio = () => {
|
|||||||
contentHtml: '',
|
contentHtml: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
// campos de busca (texto)
|
|
||||||
const [patientQuery, setPatientQuery] = useState('');
|
const [patientQuery, setPatientQuery] = useState('');
|
||||||
const [doctorQuery, setDoctorQuery] = useState('');
|
const [doctorQuery, setDoctorQuery] = useState('');
|
||||||
|
|
||||||
// dropdown control
|
|
||||||
const [showPatientDropdown, setShowPatientDropdown] = useState(false);
|
const [showPatientDropdown, setShowPatientDropdown] = useState(false);
|
||||||
const [showDoctorDropdown, setShowDoctorDropdown] = useState(false);
|
const [showDoctorDropdown, setShowDoctorDropdown] = useState(false);
|
||||||
|
|
||||||
const patientRef = useRef();
|
const patientRef = useRef();
|
||||||
const doctorRef = useRef();
|
const doctorRef = useRef();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// carregar pacientes e médicos
|
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
const loadPatients = async () => {
|
const loadPatients = async () => {
|
||||||
setLoadingPatients(true);
|
setLoadingPatients(true);
|
||||||
@ -69,7 +63,6 @@ const FormNovoRelatorio = () => {
|
|||||||
return () => { mounted = false; };
|
return () => { mounted = false; };
|
||||||
}, [authHeader]);
|
}, [authHeader]);
|
||||||
|
|
||||||
// fechar dropdowns quando clicar fora
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleClick = (e) => {
|
const handleClick = (e) => {
|
||||||
if (patientRef.current && !patientRef.current.contains(e.target)) setShowPatientDropdown(false);
|
if (patientRef.current && !patientRef.current.contains(e.target)) setShowPatientDropdown(false);
|
||||||
@ -103,7 +96,6 @@ const FormNovoRelatorio = () => {
|
|||||||
`;
|
`;
|
||||||
};
|
};
|
||||||
|
|
||||||
// escolher paciente (clicando na lista)
|
|
||||||
const choosePatient = async (patient) => {
|
const choosePatient = async (patient) => {
|
||||||
setForm(prev => ({
|
setForm(prev => ({
|
||||||
...prev,
|
...prev,
|
||||||
@ -127,7 +119,6 @@ const FormNovoRelatorio = () => {
|
|||||||
setShowDoctorDropdown(false);
|
setShowDoctorDropdown(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
// filtrar pela query (startsWith)
|
|
||||||
const filteredPatients = patientQuery
|
const filteredPatients = patientQuery
|
||||||
? patients.filter(p => (p.full_name || '').toLowerCase().startsWith(patientQuery.toLowerCase())).slice(0, 40)
|
? patients.filter(p => (p.full_name || '').toLowerCase().startsWith(patientQuery.toLowerCase())).slice(0, 40)
|
||||||
: [];
|
: [];
|
||||||
@ -138,7 +129,7 @@ const FormNovoRelatorio = () => {
|
|||||||
|
|
||||||
const handleEditorChange = (html) => setForm(prev => ({ ...prev, contentHtml: html }));
|
const handleEditorChange = (html) => setForm(prev => ({ ...prev, contentHtml: html }));
|
||||||
|
|
||||||
// salvar novo relatório (agora com Prefer: return=representation e dispatch para refresh)
|
// 🔹 Agora com created_by sendo o ID do usuário logado
|
||||||
const handleSubmit = async (e) => {
|
const handleSubmit = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!form.patient_id) return alert('Selecione o paciente (clicando no item) antes de salvar.');
|
if (!form.patient_id) return alert('Selecione o paciente (clicando no item) antes de salvar.');
|
||||||
@ -150,18 +141,34 @@ const FormNovoRelatorio = () => {
|
|||||||
if (authHeader) myHeaders.append('Authorization', authHeader);
|
if (authHeader) myHeaders.append('Authorization', authHeader);
|
||||||
myHeaders.append('Content-Type', 'application/json');
|
myHeaders.append('Content-Type', 'application/json');
|
||||||
myHeaders.append('Accept', 'application/json');
|
myHeaders.append('Accept', 'application/json');
|
||||||
// pedir que o Supabase retorne a representação do registro criado
|
|
||||||
myHeaders.append('Prefer', 'return=representation');
|
myHeaders.append('Prefer', 'return=representation');
|
||||||
|
|
||||||
// monta o payload apenas com campos válidos
|
|
||||||
const payload = {
|
const payload = {
|
||||||
patient_id: form.patient_id,
|
patient_id: form.patient_id,
|
||||||
content: form.contentHtml,
|
|
||||||
content_html: form.contentHtml,
|
content_html: form.contentHtml,
|
||||||
requested_by: form.doctor_name || ''
|
requested_by: form.doctor_name || ''
|
||||||
};
|
};
|
||||||
// só inclui created_by se tiver um id válido
|
|
||||||
if (form.doctor_id) payload.created_by = form.doctor_id;
|
// Busca o id do usuário logado (via token)
|
||||||
|
let userId = null;
|
||||||
|
try {
|
||||||
|
const token = authHeader?.replace(/^Bearer\s+/i, '') || '';
|
||||||
|
const userInfo = await UserInfos(token);
|
||||||
|
userId =
|
||||||
|
userInfo?.id ||
|
||||||
|
userInfo?.user?.id ||
|
||||||
|
userInfo?.sub ||
|
||||||
|
userInfo?.data?.id;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Não foi possível obter o ID do usuário logado:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userId) {
|
||||||
|
payload.created_by = userId;
|
||||||
|
} else {
|
||||||
|
console.warn('ID do usuário não encontrado, created_by não será incluído.');
|
||||||
|
}
|
||||||
|
|
||||||
payload.status = 'draft';
|
payload.status = 'draft';
|
||||||
|
|
||||||
const res = await fetch('https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/reports', {
|
const res = await fetch('https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/reports', {
|
||||||
@ -171,11 +178,10 @@ const FormNovoRelatorio = () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
// tenta ler JSON, se não for JSON lê o texto
|
|
||||||
let txt;
|
let txt;
|
||||||
try {
|
try {
|
||||||
txt = await res.json();
|
txt = await res.json();
|
||||||
} catch (err) {
|
} catch {
|
||||||
txt = await res.text();
|
txt = await res.text();
|
||||||
}
|
}
|
||||||
console.error('Erro POST criar relatório:', res.status, txt);
|
console.error('Erro POST criar relatório:', res.status, txt);
|
||||||
@ -185,9 +191,7 @@ const FormNovoRelatorio = () => {
|
|||||||
const created = await res.json();
|
const created = await res.json();
|
||||||
console.log('Relatório criado:', created);
|
console.log('Relatório criado:', created);
|
||||||
|
|
||||||
// dispara refresh global para a lista (DoctorRelatorioManager está escutando)
|
|
||||||
window.dispatchEvent(new Event('reports:refresh'));
|
window.dispatchEvent(new Event('reports:refresh'));
|
||||||
|
|
||||||
alert('Relatório criado com sucesso!');
|
alert('Relatório criado com sucesso!');
|
||||||
navigate('/medico/relatorios');
|
navigate('/medico/relatorios');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@ -1,32 +1,41 @@
|
|||||||
import API_KEY from "../apiKeys";
|
import API_KEY from "../apiKeys";
|
||||||
|
|
||||||
const UserInfos = async (access_token) => {
|
// Função para pegar as informações do usuário logado
|
||||||
|
const UserInfos = async (access_token) => {
|
||||||
|
if (!access_token) throw new Error("access_token é obrigatório em UserInfos");
|
||||||
|
|
||||||
let Token = access_token.replace('bearer', 'Bearer')
|
// Normaliza o formato do token
|
||||||
|
const Token = access_token.replace(/^bearer/i, "Bearer");
|
||||||
|
|
||||||
|
const myHeaders = new Headers();
|
||||||
|
myHeaders.append("apikey", API_KEY);
|
||||||
|
myHeaders.append("Authorization", Token);
|
||||||
|
|
||||||
var myHeaders = new Headers();
|
const requestOptions = {
|
||||||
myHeaders.append("apikey", API_KEY);
|
method: "GET",
|
||||||
|
|
||||||
myHeaders.append("Authorization", Token);
|
|
||||||
|
|
||||||
var requestOptions = {
|
|
||||||
method: 'GET',
|
|
||||||
headers: myHeaders,
|
headers: myHeaders,
|
||||||
redirect: 'follow'
|
redirect: "follow",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userInfo = await fetch(
|
||||||
|
`https://yuanqfswhberkoevtmfr.supabase.co/functions/v1/user-info`,
|
||||||
|
requestOptions
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!userInfo.ok) {
|
||||||
|
const text = await userInfo.text();
|
||||||
|
console.error("Erro em UserInfos:", userInfo.status, text);
|
||||||
|
throw new Error(`Erro ${userInfo.status} ao buscar informações do usuário`);
|
||||||
|
}
|
||||||
|
|
||||||
const userInfo = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/functions/v1/user-info`, requestOptions)
|
const userInfoData = await userInfo.json();
|
||||||
const userInfoData = await userInfo.json()
|
console.log("Dados do usuário:", userInfoData);
|
||||||
console.log(userInfoData, "Dados do usuário")
|
return userInfoData;
|
||||||
return userInfoData
|
} catch (error) {
|
||||||
}
|
console.error("Erro na função UserInfos:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const UploadFotoAvatar = ( userID,access_token,file) => {
|
export { UserInfos };
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export {UserInfos}
|
|
||||||
Loading…
x
Reference in New Issue
Block a user