deu certo, o card começou a vir e ser renderizado, porem agora preciso fazer funcionar as barras dinamicas, que neste componente comparativo que vou deixar funciona
import EstiloNovoAtendimento from "./NovoAtendimento.module.css";
import React, { useState, useEffect } from "react";
import { useApi } from "../../lib/doctorApi";
import { AppointmentRequestDTO, ProcedureDTO } from "./types";
import DropdownSelect from "./DropdownSelect";
import CardProcedimento from "./CardProcedimento";
import { v4 as uuidv4 } from "uuid"; // Importa a função para gerar UUIDs
import { toMoney } from "../utils/FormatedData";
import Anexo from "../ui/Anexo";
import { useLocation } from "react-router-dom";
const CoresInput = [
"#25AAE1", // Cor 1
"#8696BB", // Cor 2
"#39465F", // Cor 3
"#D56D98", // Cor 4
];
const NovoAtendimento: React.FC = () => {
const updateProcedimento = (index: number, novosDados: ProcedureDTO) => {
setAtendimento(prev => {
const newProcedures = [...prev.procedures];
newProcedures[index] = novosDados;
// Calcula os novos totais
const totalProcedures = {
expected: 0,
glossed: 0,
lost: 0,
paid: 0,
};
const totalValue = {
expected: 0,
glossed: 0,
lost: 0,
paid: 0,
};
newProcedures.forEach((proc) => {
if (proc.expectedValue > 0) {
totalProcedures.expected += 1;
totalValue.expected += proc.expectedValue;
}
if (proc.glossedValue > 0) {
totalProcedures.glossed += 1;
totalValue.glossed += proc.glossedValue;
}
if (proc.lostValue > 0) {
totalProcedures.lost += 1;
totalValue.lost += proc.lostValue;
}
if (proc.paidValue > 0) {
totalProcedures.paid += 1;
totalValue.paid += proc.paidValue;
}
});
// Retorna o novo estado com todos os valores atualizados
return {
...prev,
procedures: newProcedures,
paymentInfo: {
...prev.paymentInfo,
info: {
...prev.paymentInfo.info,
totalProcedures,
totalValues: totalValue,
totalSum: totalValue.expected + totalValue.glossed + totalValue.lost + totalValue.paid
}
}
};
});
};
const enviarDadosAtendimento = async () => {
setLoading(true);
try {
const endpoint = appointmentId
? appointments/update/${appointmentId}
: "appointments/create";
const method = appointmentId ? 'post' : 'post';
const result = await api[method](endpoint, atendimento);
if (result?.data?.success) {
if (result.data.result?.id && result.data.result.id !== atendimento.id) {
setAtendimento(prev => ({
...prev,
id: result.data.result.id
}));
}
}
} catch (e: any) {
setErrorMessage(e?.response?.data?.messages?.join(", ") || "Erro ao salvar atendimento");
} finally {
setLoading(false);
}
};
// Função para obter parâmetros da URL
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const appointmentId = queryParams.get("id");
// Efeito para carregar dados do atendimento se houver ID
useEffect(() => {
const fetchAtendimento = async () => {
if (!appointmentId) return;
setLoading(true);
try {
const response = await api.get(`appointments/get/${appointmentId}`);
if (response.data.success) {
const dados = response.data.result;
// Atualiza o estado do atendimento com todos os dados relevantes
setAtendimento({
...dados,
related: {
patient: dados.related.patient ? {
id: dados.related.patient.id,
name: dados.related.patient.name
} : undefined,
payer: dados.related.payer ? {
id: dados.related.payer.id,
name: dados.related.payer.name
} : undefined,
place: dados.related.place ? {
id: dados.related.place.id,
name: dados.related.place.name
} : undefined
},
paymentInfo: {
method: dados.paymentInfo.method,
info: {
totalSum: dados.paymentInfo.info.totalSum,
healthInsurance: dados.paymentInfo.info.healthInsurance,
totalValues: dados.paymentInfo.info.totalValues,
totalProcedures: dados.paymentInfo.info.totalProcedures
}
},
serviceInfo: {
guideCode: dados.serviceInfo.guideCode,
date: dados.serviceInfo.date,
totalValue: dados.serviceInfo.totalValue
},
procedures: dados.procedures || [],
status: dados.status,
id: dados.id
});
// Atualiza o radio button da modalidade
if (dados.paymentInfo?.method) {
const radioElement = document.querySelector(`input[name="modalidade"][value="${dados.paymentInfo.method}"]`) as HTMLInputElement;
if (radioElement) {
radioElement.checked = true;
}
}
// Atualiza a data do atendimento
if (dados.serviceInfo?.date) {
const dateInput = document.querySelector('input[name="data"]') as HTMLInputElement;
if (dateInput) {
dateInput.value = dados.serviceInfo.date;
}
}
// Atualiza o código da guia
if (dados.serviceInfo?.guideCode) {
const guideInput = document.querySelector('input[name="codigo"]') as HTMLInputElement;
if (guideInput) {
guideInput.value = dados.serviceInfo.guideCode;
}
}
}
} catch (error) {
console.error("Erro ao carregar atendimento:", error);
setErrorMessage("Erro ao carregar dados do atendimento");
} finally {
setLoading(false);
}
};
fetchAtendimento();
}, [appointmentId]);
const handleAdicionarProcedimento = () => {
const novoProcedimento: ProcedureDTO = {
id: uuidv4(),
createdAt: new Date(),
updatedAt: new Date(),
cbhpmCode: "",
cbhpmName: "",
expectedValue: 0,
glossedValue: 0,
lostValue: 0,
paidValue: 0,
placeId: atendimento.related.place?.id || "",
payerId: atendimento.related.payer?.id || "",
patientId: atendimento.related.patient?.id || "",
statusOfActivity: "draft",
attachments: [],
};
setAtendimento(prev => ({
...prev,
procedures: [...prev.procedures, novoProcedimento]
}));
setMostrarCard(true); // Garante que os cards sejam mostrados ao adicionar
};
const handleExcluirProcedimento = (id: string) => {
// Filtra o array de procedimentos, mantendo apenas aqueles cujo id não coincide.
const novosProcedimentos = atendimento.procedures.filter(
(proc) => proc.id !== id
);
// Cria uma cópia do estado de atendimento e atualiza a lista de procedimentos
setAtendimento((prev) => ({
...prev,
procedures: novosProcedimentos, // Atualiza a lista de procedimentos
}));
// Opcional: Se existir alguma lógica que dependa da atualização da barra gráfica, você pode chamar:
};
// Atualiza o localStorage sempre que procedimentos mudar
const [mostrarCard, setMostrarCard] = useState(false);
const [anexos, setAnexos] = useState<
{ id: string; fileName: string; extension: string }[]
([]); // Estado para os arquivos anexados
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const api = useApi(); // useApi é tratado como estável
const [atendimento, setAtendimento] = useState({
status: {
glossed: false,
lost: false,
received: false,
draft: false,
validated: false,
derived: false,
finished: false,
},
related: {
place: undefined,
payer: undefined,
patient: undefined,
},
paymentInfo: {
method: "healthInsurance",
info: {
totalSum: 0,
healthInsurance: {
cardNumber: "",
},
totalValues: {
expected: 0,
glossed: 0,
lost: 0,
paid: 0,
},
totalProcedures: {
expected: 0,
glossed: 0,
lost: 0,
paid: 0,
},
},
},
serviceInfo: {
guideCode: "",
date: "",
totalValue: 0,
},
procedures: [],
});
return (
{appointmentId ? "Editar Atendimento" : "Cadastro de Atendimento"}
<form>
<div className={EstiloNovoAtendimento.divValores}>
<div className={EstiloNovoAtendimento.inputValores}>
<label className={EstiloNovoAtendimento.total}>Total:</label>
{[
atendimento.paymentInfo.info.totalValues.expected,
atendimento.paymentInfo.info.totalValues.glossed,
atendimento.paymentInfo.info.totalValues.lost,
atendimento.paymentInfo.info.totalValues.paid,
].map((valor, index) => (
<div key={index}>
<span
style={{
color: CoresInput[index],
fontSize: "14px",
marginRight: "2px",
}}
>
R$
</span>
<input
key={index}
type="number"
value={valor.toFixed(2)}
placeholder="R$ 0,00"
style={{ color: CoresInput[index] }}
readOnly
/>
</div>
))}
</div>
<div className={EstiloNovoAtendimento.divBarraGrafico}>
<label className={EstiloNovoAtendimento.labelTotal}>
R$ {toMoney(atendimento.paymentInfo.info.totalSum)}
{/* Aqui já usará o total atualizado */}
</label>
<div className={EstiloNovoAtendimento.graficoRepresentativo}>
<div className={EstiloNovoAtendimento.barraFixa}>
{[
atendimento.paymentInfo.info.totalValues.expected,
atendimento.paymentInfo.info.totalValues.glossed,
atendimento.paymentInfo.info.totalValues.lost,
atendimento.paymentInfo.info.totalValues.paid,
].map((valor, index) => {
const totalSum = atendimento.paymentInfo.info.totalSum;
const isAllZero =
atendimento.paymentInfo.info.totalValues.expected === 0 &&
atendimento.paymentInfo.info.totalValues.glossed === 0 &&
atendimento.paymentInfo.info.totalValues.lost === 0 &&
atendimento.paymentInfo.info.totalValues.paid === 0;
const percentage =
totalSum > 0 ? (valor / totalSum) * 100 : 0;
const minWidth = 5; // largura mínima em percentual
// Calcula a largura, levando em conta a largura mínima
const width = percentage < minWidth ? minWidth : percentage;
return (
<div
key={`grafico-${index}`}
style={{
backgroundColor: isAllZero
? "transparent"
: CoresInput[index],
width: `${isAllZero ? 0 : width}%`,
height: "100%",
}}
/>
);
})}
</div>
</div>
</div>
</div>
<div className={EstiloNovoAtendimento.container}>
<div className={EstiloNovoAtendimento.modalidade}>
<span className={EstiloNovoAtendimento.span}>Modalidade:</span>
<div className={EstiloNovoAtendimento.divMargin}>
<input
className={EstiloNovoAtendimento.radio}
type="radio"
id="convenio"
name="modalidade"
value="healthInsurance"
checked={atendimento.paymentInfo.method === "healthInsurance"}
onChange={() => {
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: "healthInsurance",
},
}));
}}
/>
<label
htmlFor="convenio"
className={EstiloNovoAtendimento.labelModalidade}
>
Convênio
</label>
<input
className={EstiloNovoAtendimento.radio}
type="radio"
id="particular"
name="modalidade"
value="particular"
onChange={() => {
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: "private", // Atualize para "particular"
},
}));
}}
/>
<label
htmlFor="particular"
className={EstiloNovoAtendimento.labelModalidade}
>
Particular
</label>
<input
className={EstiloNovoAtendimento.radio}
type="radio"
id="plantao"
name="modalidade"
value="plantao"
onChange={() => {
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: "onDuty", // Atualize para "plantao"
},
}));
}}
/>
<label
htmlFor="plantao"
className={EstiloNovoAtendimento.labelModalidade}
>
Plantão
</label>
</div>
</div>
<DropdownSelect
endpoint="places/find?skip=0&limit=2000&payer=true"
parseData={(data) =>
data.result.list.map((local: any) => ({
id: local.id,
name: local.name,
}))
}
onSelect={(selectedItem) => {
setAtendimento((prev) => ({
...prev,
related: {
...prev.related,
payer: { id: selectedItem.id, name: selectedItem.name },
},
}));
}}
value={atendimento.related.payer?.id || ""}
label={atendimento.related.payer?.name || "Fonte Pagadora"}
isEditing={!!appointmentId}
/>
</div>
<div className={EstiloNovoAtendimento.container}>
<DropdownSelect
endpoint="patients/find?skip=0&limit=2000"
parseData={(data) =>
data.result.list.map((item: any) => ({
id: item.id,
name: item.name,
}))
}
onSelect={(selectedItem) => {
setAtendimento((prev) => ({
...prev,
related: {
...prev.related,
patient: { id: selectedItem.id, name: selectedItem.name },
},
}));
}}
value={atendimento.related.patient?.id || ""}
label={atendimento.related.patient?.name || "Paciente"}
isEditing={!!appointmentId}
/>
<DropdownSelect
endpoint="places/find?skip=0&limit=2000&place=true"
parseData={(data) =>
data.result.list.map((local: any) => ({
id: local.id,
name: local.name,
}))
}
onSelect={(selectedItem) => {
setAtendimento((prev) => ({
...prev,
related: {
...prev.related,
place: { id: selectedItem.id, name: selectedItem.name },
},
}));
}}
value={atendimento.related.place?.id || ""}
label={atendimento.related.place?.name || "Local de Atendimento"}
isEditing={!!appointmentId}
/>
</div>
<div className={EstiloNovoAtendimento.container}>
<div className={EstiloNovoAtendimento.organizador}>
<span>Código da guia (opcional)</span>
<input
className={EstiloNovoAtendimento.input300}
type="text"
name="codigo"
placeholder="Digite"
value={atendimento.serviceInfo.guideCode}
onChange={(e) => {
const codigo = e.target.value;
// Atualiza o estado de atendimento com o código da guia
setAtendimento((prev) => ({
...prev,
serviceInfo: {
...prev.serviceInfo,
guideCode: codigo, // Atualiza o guideCode com o valor do input
},
}));
}}
/>
</div>
<div className={EstiloNovoAtendimento.organizador}>
<span>Data</span>
<input
className={EstiloNovoAtendimento.inputData}
type="date"
name="data"
placeholder="dd/mm/yyyy"
value={atendimento.createdAt?.toISOString()}
onChange={(e) => {
const data = e.target.value;
setAtendimento((prev) => ({
...prev,
serviceInfo: {
...prev.serviceInfo,
date: data,
},
}));
}}
/>
</div>
</div>
</form>
{/* deveria ficar aqui */}
<div className={EstiloNovoAtendimento.divbutton}>
<button
type="button" // tipo "button" para evitar o envio do formulário
onClick={handleAdicionarProcedimento} // Chama a função ao clicar
className={EstiloNovoAtendimento.buttonProcedimento}
>
Adicionar Procedimento
</button>
</div>
{/* Segunda barra gráfica com funcionalidade ajustada */}
<div className={EstiloNovoAtendimento.divValores2}>
<div className={EstiloNovoAtendimento.inputProcedimentos}>
{[
atendimento.paymentInfo.info.totalProcedures.expected,
atendimento.paymentInfo.info.totalProcedures.glossed,
atendimento.paymentInfo.info.totalProcedures.lost,
atendimento.paymentInfo.info.totalProcedures.paid,
].map((valor, index) => (
<input
key={index}
type="number"
value={valor.toFixed(0)} // Mostra a contagem
placeholder="0"
// Barra apenas visual, não editável
style={{ color: CoresInput[index] }} // Cor correspondente à respectiva
/>
))}
</div>
<div className={EstiloNovoAtendimento.divBarraGrafico}>
<div className={EstiloNovoAtendimento.divTotal}>
<img
src="/procedimento.png"
alt=""
className={EstiloNovoAtendimento.icone}
/>
<label className={EstiloNovoAtendimento.labelProcedimento}>
<label>{atendimento.procedures.length}</label> Procedimento
{atendimento.procedures.length !== 1 ? 's' : ''}
</label>
</div>
<div className={EstiloNovoAtendimento.graficoRepresentativo}>
<div className={EstiloNovoAtendimento.barraFixa}>
{[
atendimento.paymentInfo.info.totalProcedures.expected,
atendimento.paymentInfo.info.totalProcedures.glossed,
atendimento.paymentInfo.info.totalProcedures.lost,
atendimento.paymentInfo.info.totalProcedures.paid,
].map((valor, index) => {
const totalProcedures = atendimento.procedures.length;
const isAllZero =
atendimento.paymentInfo.info.totalProcedures.expected === 0 &&
atendimento.paymentInfo.info.totalProcedures.glossed === 0 &&
atendimento.paymentInfo.info.totalProcedures.lost === 0 &&
atendimento.paymentInfo.info.totalProcedures.paid === 0;
// Cálculo da largura da barra, com um tratamento para os valores zero
const width =
totalProcedures > 0 ? (valor / totalProcedures) * 100 : 0;
// Definindo o tamanho mínimo da barra
const minWidth = 5; // Defina seu valor mínimo em porcentagem que representa a largura desejada para 0
const displayWidth = isAllZero ? 0 : Math.max(width, minWidth);
return (
<div
key={`grafico-${index}`}
style={{
backgroundColor: isAllZero
? "transparent"
: CoresInput[index],
width: `${displayWidth}%`,
height: "100%",
}}
/>
);
})}
</div>
</div>
{/* Botão de expandir/recolher */}
<div
className={`${EstiloNovoAtendimento.expandirProcedimentos} ${
atendimento.procedures.length === 0 ? EstiloNovoAtendimento.disabled : ''
}`}
onClick={() => atendimento.procedures.length > 0 && setMostrarCard(!mostrarCard)}
style={{
opacity: atendimento.procedures.length === 0 ? '0.5' : '1'
}}
>
<img
src="/setaBaixo.png"
alt="Expandir/recolher"
className={EstiloNovoAtendimento.iconSeta}
/>
<label className={EstiloNovoAtendimento.labelExpandir}>
{mostrarCard ? "Recolher" : "Expandir"}
</label>
</div>
</div>
</div>
{/* Renderiza os procedimentos quando mostrarCard for true */}
{mostrarCard && atendimento.procedures.length > 0 && (
<div className={EstiloNovoAtendimento.procedimentosContainer}>
{atendimento.procedures.map((proc, index) => (
<CardProcedimento
key={proc.id}
index={index}
procedure={proc}
updateProcedimento={updateProcedimento}
handleExcluir={handleExcluirProcedimento}
/>
))}
</div>
)}
<Anexo
attachments={atendimento.attachments || []}
setAttachments={(novosAnexos) => {
setAtendimento((prev) => ({
...prev,
attachments: novosAnexos,
}));
}}
/>
<div className={EstiloNovoAtendimento.divbutton}>
{errorMessage && (
<div className={EstiloNovoAtendimento.errorMessage}>
{errorMessage}
</div>
)}
<button
className={EstiloNovoAtendimento.buttonSalvar}
disabled={loading}
onClick={enviarDadosAtendimento}
>
{loading ? "Salvando" : "Salvar"}
</button>
</div>
</div>
);
};
export default NovoAtendimento;
como faço pra que no editarAtendimento tbm sejam alimentadas as barras ?
import React, { useState, useEffect } from "react";
import { useApi } from "../../lib/doctorApi";
import { AppointmentRequestDTO, ProcedureDTO } from "./types";
import DropdownSelect from "./DropdownSelect";
import CardProcedimento from "./CardProcedimento";
import { v4 as uuidv4 } from "uuid";
import { toMoney } from "../utils/FormatedData";
import Anexo from "../ui/Anexo";
import { useParams } from "react-router-dom";
import EstiloNovoAtendimento from "./NovoAtendimento.module.css";
const CoresInput = ["#25AAE1", "#8696BB", "#39465F", "#D56D98"];
const EditarAtendimento: React.FC = () => {
const { id: appointmentId } = useParams<{ id: string }>();
const [atendimento, setAtendimento] = useState({
status: {
glossed: false,
lost: false,
received: false,
draft: false,
validated: false,
derived: false,
finished: false,
},
related: {
place: undefined,
payer: undefined,
patient: undefined,
},
paymentInfo: {
method: "healthInsurance",
info: {
totalSum: 0,
healthInsurance: {
cardNumber: "",
},
totalValues: {
expected: 0,
glossed: 0,
lost: 0,
paid: 0,
},
totalProcedures: {
expected: 0,
glossed: 0,
lost: 0,
paid: 0,
},
},
},
serviceInfo: {
guideCode: "",
date: "",
totalValue: 0,
},
procedures: [],
});
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [mostrarCard, setMostrarCard] = useState(false);
const api = useApi();
const filtrarDadosAtendimento = (result: any, idBuscado: string) => {
const atendimentoEncontrado = result.list.find(
(atend: any) => atend.id === idBuscado
);
if (!atendimentoEncontrado) return null;
const atendimentoEditavel = {
modalidade: atendimentoEncontrado.paymentInfo.method,
fontePagadora: atendimentoEncontrado.related.payer
? {
id: atendimentoEncontrado.related.payer.id,
name: atendimentoEncontrado.related.payer.name,
}
: undefined,
paciente: atendimentoEncontrado.related.patient
? {
id: atendimentoEncontrado.related.patient.id,
name: atendimentoEncontrado.related.patient.name,
}
: undefined,
localAtendimento: atendimentoEncontrado.related.place
? {
id: atendimentoEncontrado.related.place.id,
name: atendimentoEncontrado.related.place.name,
}
: undefined,
codigoGuia: atendimentoEncontrado.serviceInfo.guideCode,
data: atendimentoEncontrado.serviceInfo.date,
procedures: atendimentoEncontrado.procedures || [], // Certifique-se de pegar os procedimentos.
};
return atendimentoEditavel;
};
useEffect(() => {
const fetchAppointments = async () => {
try {
const params = new URLSearchParams(window.location.search);
const idBuscado = params.get("id");
if (!idBuscado) {
console.error("ID não encontrado na URL");
return;
}
const response = await api.get(
`/appointments/find?${params.toString()}`
);
console.log("Dados dos atendimentos:", response.data);
const dadosFiltrados = filtrarDadosAtendimento(
response.data.result,
idBuscado
);
if (dadosFiltrados) {
// Convertendo o valor da modalidade para o formato esperado pelo radio button
let modalidadeConvertida: "healthInsurance" | "private" | "onDuty" =
"healthInsurance"; // valor padrão
switch (dadosFiltrados.modalidade) {
case "healthInsurance":
modalidadeConvertida = "healthInsurance"; // Convênio
break;
case "private":
modalidadeConvertida = "private"; // Particular
break;
case "onDuty":
modalidadeConvertida = "onDuty"; // Plantão
break;
}
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: modalidadeConvertida,
},
related: {
payer: dadosFiltrados.fontePagadora,
patient: dadosFiltrados.paciente,
place: dadosFiltrados.localAtendimento,
},
serviceInfo: {
...prev.serviceInfo,
guideCode: dadosFiltrados.codigoGuia,
date: dadosFiltrados.data,
},
procedures: dadosFiltrados.procedures, // Este é o ponto crucial
}));
// Encontrar e marcar o radio button correto
const radioButton = document.querySelector(
`input[type="radio"][value="${modalidadeConvertida}"]`
) as HTMLInputElement;
if (radioButton) {
radioButton.checked = true;
}
}
} catch (error) {
console.error("Erro ao buscar atendimentos:", error);
setErrorMessage("Erro ao carregar dados do atendimento");
}
};
fetchAppointments();
}, []);
useEffect(() => {
const fetchAtendimento = async () => {
if (!appointmentId) return;
setLoading(true);
try {
const response = await api.get(
`/appointments/find?id=${appointmentId}`
);
if (response.data.success && response.data.result.list.length > 0) {
const dados = response.data.result.list[0];
setAtendimento(dados);
} else {
setErrorMessage("Atendimento não encontrado");
}
} catch (error) {
setErrorMessage("Erro ao carregar dados do atendimento");
} finally {
setLoading(false);
}
};
fetchAtendimento();
}, [appointmentId]);
const enviarDadosAtendimento = async () => {
if (!atendimento) return;
setLoading(true);
try {
const result = await api.put(
appointments/update/${appointmentId},
atendimento
);
if (result?.data?.success) {
setAtendimento((prev) => ({
...prev,
id: result.data.result.id,
}));
}
} catch (e: any) {
setErrorMessage(
e?.response?.data?.messages?.join(", ") || "Erro ao salvar atendimento"
);
} finally {
setLoading(false);
}
};
// Renderização dos radio buttons usando o estado
const renderRadioButtons = () => (
<input
className={EstiloNovoAtendimento.radio}
type="radio"
id="convenio"
name="modalidade"
value="healthInsurance"
checked={atendimento.paymentInfo.method === "healthInsurance"}
onChange={() => {
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: "healthInsurance",
},
}));
}}
/>
Convênio
<input
className={EstiloNovoAtendimento.radio}
type="radio"
id="particular"
name="modalidade"
value="private"
checked={atendimento.paymentInfo.method === "private"}
onChange={() => {
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: "private",
},
}));
}}
/>
<label
htmlFor="particular"
className={EstiloNovoAtendimento.labelModalidade}
>
Particular
</label>
<input
className={EstiloNovoAtendimento.radio}
type="radio"
id="plantao"
name="modalidade"
value="onDuty"
checked={atendimento.paymentInfo.method === "onDuty"}
onChange={() => {
setAtendimento((prev) => ({
...prev,
paymentInfo: {
...prev.paymentInfo,
method: "onDuty",
},
}));
}}
/>
<label
htmlFor="plantao"
className={EstiloNovoAtendimento.labelModalidade}
>
Plantão
</label>
</div>
);
// Update procedure function
const updateProcedimento = (index: number, novosDados: ProcedureDTO) => {
if (atendimento) {
const cloneAtendimento = { ...atendimento };
cloneAtendimento.procedures[index] = novosDados;
setAtendimento(cloneAtendimento);
}
};
// Renderização e verificação do estado de loading
if (loading || !atendimento) return Carregando...;
return (
Editar Atendimento
{mostrarCard && {/* Your expandable content goes here */}}
Total:
{[
atendimento.paymentInfo.info.totalValues.expected,
atendimento.paymentInfo.info.totalValues.glossed,
atendimento.paymentInfo.info.totalValues.lost,
atendimento.paymentInfo.info.totalValues.paid,
].map((valor, index) => (
<span
style={{
color: CoresInput[index],
fontSize: "14px",
marginRight: "2px",
}}
>
R</span 0,00"
style={{ color: CoresInput[index] }}
readOnly
/>
))}
<div className={EstiloNovoAtendimento.divBarraGrafico}>
<label className={EstiloNovoAtendimento.labelTotal}>
R$ {toMoney(atendimento.paymentInfo.info.totalSum)}
</label>
<div className={EstiloNovoAtendimento.graficoRepresentativo}>
<div className={EstiloNovoAtendimento.barraFixa}>
{[
atendimento.paymentInfo.info.totalValues.expected,
atendimento.paymentInfo.info.totalValues.glossed,
atendimento.paymentInfo.info.totalValues.lost,
atendimento.paymentInfo.info.totalValues.paid,
].map((valor, index) => {
const totalSum = atendimento.paymentInfo.info.totalSum;
const isAllZero =
atendimento.paymentInfo.info.totalValues.expected === 0 &&
atendimento.paymentInfo.info.totalValues.glossed === 0 &&
atendimento.paymentInfo.info.totalValues.lost === 0 &&
atendimento.paymentInfo.info.totalValues.paid === 0;
const percentage =
totalSum > 0 ? (valor / totalSum) * 100 : 0;
const minWidth = 5;
const width = percentage < minWidth ? minWidth : percentage;
return (
<div
key={`grafico-${index}`}
style={{
backgroundColor: isAllZero
? "transparent"
: CoresInput[index],
width: `${isAllZero ? 0 : width}%`,
height: "100%",
}}
/>
);
})}
</div>
</div>
</div>
</div>
<div className={EstiloNovoAtendimento.container}>
<div className={EstiloNovoAtendimento.modalidade}>
<span>Modalidade:</span>
{renderRadioButtons()}
</div>
</div>
<div className={EstiloNovoAtendimento.container}>
<DropdownSelect
endpoint="places/find?skip=0&limit=2000&payer=true"
parseData={(data) =>
data.result.list.map((local: any) => ({
id: local.id,
name: local.name,
}))
}
onSelect={(selectedItem) => {
setAtendimento((prev) => ({
...prev,
related: {
...prev.related,
payer: { id: selectedItem.id, name: selectedItem.name },
},
}));
}}
value={atendimento.related.payer?.id || ""}
label={"Fonte Pagadora"}
isEditing={!!appointmentId}
/>
</div>
<div className={EstiloNovoAtendimento.container}>
<DropdownSelect
endpoint="patients/find?skip=0&limit=2000"
parseData={(data) =>
data.result.list.map((item: any) => ({
id: item.id,
name: item.name,
}))
}
onSelect={(selectedItem) => {
setAtendimento((prev) => ({
...prev,
related: {
...prev.related,
patient: { id: selectedItem.id, name: selectedItem.name },
},
}));
}}
value={atendimento.related.patient?.id || ""}
label={"Paciente"}
isEditing={!!appointmentId}
/>
<DropdownSelect
endpoint="places/find?skip=0&limit=2000&place=true"
parseData={(data) =>
data.result.list.map((local: any) => ({
id: local.id,
name: local.name,
}))
}
onSelect={(selectedItem) => {
setAtendimento((prev) => ({
...prev,
related: {
...prev.related,
place: { id: selectedItem.id, name: selectedItem.name },
},
}));
}}
value={atendimento.related.place?.id || ""}
label={"Local de Atendimento"}
isEditing={!!appointmentId}
/>
</div>
<div className={EstiloNovoAtendimento.container}>
<div className={EstiloNovoAtendimento.organizador}>
<span>Código da guia (opcional)</span>
<input
className={EstiloNovoAtendimento.input300}
type="text"
name="codigo"
placeholder="Digite"
value={atendimento.serviceInfo.guideCode}
onChange={(e) => {
const codigo = e.target.value;
setAtendimento((prev) => ({
...prev,
serviceInfo: {
...prev.serviceInfo,
guideCode: codigo,
},
}));
}}
/>
</div>
<div className={EstiloNovoAtendimento.organizador}>
<span>Data</span>
<input
className={EstiloNovoAtendimento.inputData}
type="date"
name="data"
placeholder="dd/mm/yyyy"
value={atendimento.serviceInfo.date}
onChange={(e) => {
const data = e.target.value;
setAtendimento((prev) => ({
...prev,
serviceInfo: {
...prev.serviceInfo,
date: data,
},
}));
}}
/>
</div>
</div>
</form>
<div className={EstiloNovoAtendimento.divbutton}>
<button
type="button"
onClick={() => {
const novoProcedimento: ProcedureDTO = {
id: uuidv4(),
createdAt: new Date(),
updatedAt: new Date(),
cbhpmCode: "",
cbhpmName: "",
expectedValue: 0,
glossedValue: 0,
lostValue: 0,
paidValue: 0,
placeId: atendimento.related.place?.id || "",
payerId: atendimento.related.payer?.id || "",
patientId: atendimento.related.patient?.id || "",
statusOfActivity: "draft",
attachments: [],
};
setAtendimento((prev) => ({
...prev,
procedures: [...prev.procedures, novoProcedimento],
}));
}}
className={EstiloNovoAtendimento.buttonProcedimento}
>
Adicionar Procedimento
</button>
</div>
<div className={EstiloNovoAtendimento.divValores2}>
<div className={EstiloNovoAtendimento.inputProcedimentos}>
{[
atendimento.paymentInfo.info.totalProcedures.expected,
atendimento.paymentInfo.info.totalProcedures.glossed,
atendimento.paymentInfo.info.totalProcedures.lost,
atendimento.paymentInfo.info.totalProcedures.paid,
].map((valor, index) => (
<input
key={index}
type="number"
value={valor.toFixed(0)}
placeholder="0"
style={{ color: CoresInput[index] }}
/>
))}
</div>
<div className={EstiloNovoAtendimento.divBarraGrafico}>
<div className={EstiloNovoAtendimento.divTotal}>
<img
src="/procedimento.png"
alt=""
className={EstiloNovoAtendimento.icone}
/>
<label className={EstiloNovoAtendimento.labelProcedimento}>
<label>{atendimento.procedures.length}</label> Procedimento
{atendimento.procedures.length !== 1 ? "s" : ""}
</label>
</div>
<div className={EstiloNovoAtendimento.graficoRepresentativo}>
<div className={EstiloNovoAtendimento.barraFixa}>
{[
atendimento.paymentInfo.info.totalProcedures.expected,
atendimento.paymentInfo.info.totalProcedures.glossed,
atendimento.paymentInfo.info.totalProcedures.lost,
atendimento.paymentInfo.info.totalProcedures.paid,
].map((valor, index) => {
const totalProcedures = atendimento.procedures.length;
const isAllZero =
atendimento.paymentInfo.info.totalProcedures.expected === 0 &&
atendimento.paymentInfo.info.totalProcedures.glossed === 0 &&
atendimento.paymentInfo.info.totalProcedures.lost === 0 &&
atendimento.paymentInfo.info.totalProcedures.paid === 0;
const width =
totalProcedures > 0 ? (valor / totalProcedures) * 100 : 0;
const minWidth = 5;
const displayWidth = isAllZero ? 0 : Math.max(width, minWidth);
return (
<div
key={`grafico-${index}`}
style={{
backgroundColor: isAllZero
? "transparent"
: CoresInput[index],
width: `${displayWidth}%`,
height: "100%",
}}
/>
);
})}
</div>
</div>
<div
className={`${EstiloNovoAtendimento.expandirProcedimentos} ${
atendimento.procedures.length === 0
? EstiloNovoAtendimento.disabled
: ""
}`}
onClick={() =>
atendimento.procedures.length > 0 && setMostrarCard(!mostrarCard)
}
style={{
opacity: atendimento.procedures.length === 0 ? "0.5" : "1",
}}
>
<img
src="/setaBaixo.png"
alt="Expandir/recolher"
className={EstiloNovoAtendimento.iconSeta}
/>
<label className={EstiloNovoAtendimento.labelExpandir}>
{mostrarCard ? "Recolher" : "Expandir"}
</label>
</div>
</div>
</div>
{mostrarCard && atendimento.procedures.length > 0 && (
<div className={EstiloNovoAtendimento.procedimentosContainer}>
{atendimento.procedures.map((proc, index) => (
<CardProcedimento
key={proc.id}
index={index}
procedure={proc}
updateProcedimento={updateProcedimento}
handleExcluir={(id) => {
const novosProcedimentos = atendimento.procedures.filter(
(p) => p.id !== id
);
setAtendimento((prev) => ({
...prev,
procedures: novosProcedimentos,
}));
}}
/>
))}
</div>
)}
<Anexo
attachments={atendimento.attachments || []}
setAttachments={(novosAnexos) => {
setAtendimento((prev) => ({
...prev,
attachments: novosAnexos,
}));
}}
/>
<div className={EstiloNovoAtendimento.divbutton}>
{errorMessage && (
<div className={EstiloNovoAtendimento.errorMessage}>
{errorMessage}
</div>
)}
<button
className={EstiloNovoAtendimento.buttonSalvar}
disabled={loading}
onClick={enviarDadosAtendimento}
>
{loading ? "Salvando" : "Salvar"}
</button>
</div>
</div>
);
};
export default EditarAtendimento;