Entendi! Para atender ao seu requisito, você pode continuar exibindo a lista de anexos existentes, mas desabilitar a funcionalidade de adicionar novos anexos quando não estiver no modo de edição. Para isso, precisamos modificar a maneira como o componente Anexo é renderizado.
A lógica será a seguinte:
- Sempre exibir os anexos existentes no componente
Anexo.
- Desabilitar a opção de adicionar novos anexos se o usuário não estiver em modo de edição.
Aqui está como você pode ajustar o seu componente EditarProcedimento para alcançar esse comportamento:
Código Ajustado
import React, { useEffect, useState } from "react";
import EstiloNovoAtendimento from "./NovoAtendimento.module.css";
import { ProcedureDTO } from "./types";
import Anexo from "../ui/Anexo";
interface Procedimento {
procedure: ProcedureDTO;
index: number;
updateProcedimento: (index: number, novosDados: ProcedureDTO) => void;
handleExcluir: (id: string) => void; // Função para excluir um procedimento
}
const EditarProcedimento: React.FC<Procedimento> = ({
procedure,
index,
updateProcedimento,
handleExcluir,
}) => {
const [procedimento, setProcedimento] = useState<ProcedureDTO>({
...procedure,
});
const [isEditable, setIsEditable] = useState(false); // Estado para controle de edição
// estados para os valores formatados
const [expectedValue, setExpectedValue] = useState("0,00");
const [glossedValue, setGlossedValue] = useState("0,00");
const [paidValue, setPaidValue] = useState("0,00");
const [lostValue, setLostValue] = useState("0,00");
// Atualização dos valores formatados ao proceder o estado
useEffect(() => {
setExpectedValue(
(procedimento.expectedValue || 0).toLocaleString("pt-BR", {
minimumFractionDigits: 2,
})
);
setGlossedValue(
(procedimento.glossedValue || 0).toLocaleString("pt-BR", {
minimumFractionDigits: 2,
})
);
setPaidValue(
(procedimento.paidValue || 0).toLocaleString("pt-BR", {
minimumFractionDigits: 2,
})
);
setLostValue(
(procedimento.lostValue || 0).toLocaleString("pt-BR", {
minimumFractionDigits: 2,
})
);
}, [procedimento]);
const handleValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const inputValue = e.target.value;
const name = e.target.name;
const numericValue = inputValue.replace(/[^\d]/g, "").trim();
const parsedValue =
numericValue.length > 0 ? parseFloat(numericValue) / 100 : 0;
const formattedValue = parsedValue.toLocaleString("pt-BR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
setProcedimento((prevProcedimento) => ({
...prevProcedimento,
[name]: parsedValue,
}));
// Atualiza o estado dos valores com formato
if (name === "expectedValue") {
setExpectedValue(formattedValue);
} else if (name === "glossedValue") {
setGlossedValue(formattedValue);
} else if (name === "paidValue") {
setPaidValue(formattedValue);
} else if (name === "lostValue") {
setLostValue(formattedValue);
}
};
const handleEditClick = () => {
setIsEditable(true);
console.log("lapis clicado do editar procedimento");
};
const handleCancelClick = () => {
setProcedimento({ ...procedure }); // Reseta o procedimento para o estado original
setIsEditable(false);
};
const handleConfirmClick = () => {
updateProcedimento(index, procedimento); // Atualiza o procedimento
setIsEditable(false); // Desabilita edição
};
const statusMap: { [key: string]: string } = {
draft: "Rascunho",
readyToValidate: "Pronto para Validação",
validated: "Validado",
toDerive: "Para Faturar",
derived: "Faturado",
finished: "Finalizado",
};
const currentStatus = procedimento.statusOfActivity;
const handleStatusChange = (
status:
| "draft"
| "glossed"
| "validated"
| "toDerive"
| "derived"
| "lost"
| "finished"
) => {
if (isEditable) {
setProcedimento((prev) => ({
...prev,
statusOfActivity: prev.statusOfActivity === status ? "draft" : status, // Se já está ativo, troque para "draft"; senão, atualize para o novo status
}));
}
};
return (
<div className={EstiloNovoAtendimento.Card}>
<div className={EstiloNovoAtendimento.CardTop}>
<div>
<span className={EstiloNovoAtendimento.id}>ID: {procedure.id}</span>
</div>
<div className={EstiloNovoAtendimento.buttonCard}>
<button onClick={() => handleExcluir(procedure.id)}>
<img
src="/lixeira.png"
alt="Excluir"
className={EstiloNovoAtendimento.icon}
/>
</button>
<button onClick={handleEditClick}>
<img
src="/lapisEditor.png" // Ícone do lápis
alt="Editar"
className={EstiloNovoAtendimento.icon}
/>
</button>
</div>
</div>
<div className={EstiloNovoAtendimento.divDoCard}>
{/* Campos de entrada aqui */}
<Anexo
attachments={procedimento.attachments}
setAttachments={(novosAnexos) => {
setProcedimento((prev) => ({
...prev,
attachments: novosAnexos,
}));
}}
isEditable={isEditable} // Passando o estado de edição para Anexo
/>
<label className={EstiloNovoAtendimento.labelStatus}>
Status de pagamento:
</label>
<div className={EstiloNovoAtendimento.divflex}>
{procedure.expectedValue > 0 && (
<label className={EstiloNovoAtendimento.statusPagamento}>
<img
src="/cifrao.png"
alt=""
className={EstiloNovoAtendimento.iconStatus}
/>
Previsto
</label>
)}
{procedure.glossedValue > 0 && (
<label className={EstiloNovoAtendimento.statusPagamento}>
<img
src="/cifrao.png"
alt=""
className={EstiloNovoAtendimento.iconStatus}
/>
Glosado
</label>
)}
{procedure.paidValue > 0 && (
<label className={EstiloNovoAtendimento.statusPagamento}>
<img
src="/cifrao.png"
alt=""
className={EstiloNovoAtendimento.iconStatus}
/>
Valor Pago
</label>
)}
{procedure.lostValue > 0 && (
<label className={EstiloNovoAtendimento.statusPagamento}>
<img
src="/cifrao.png"
alt=""
className={EstiloNovoAtendimento.iconStatus}
/>
Valor Perdido
</label>
)}
</div>
<label className={EstiloNovoAtendimento.labelStatus}>
Status de atividade:
</label>
<div className={EstiloNovoAtendimento.divflex}>
{Object.keys(statusMap).map((statusItem) => (
<label
key={statusItem}
className={`${EstiloNovoAtendimento.labelBorda} ${
isEditable ? EstiloNovoAtendimento.labelBordaEditavel : ""
}`}
>
<input
type="checkbox"
className={EstiloNovoAtendimento.customCheckbox}
value={statusItem}
checked={currentStatus === statusItem} // Verifica se o status está incluído
onChange={() => handleStatusChange(statusItem as any)} // Altera para este status, permitindo apenas um a ser ativo
disabled={!isEditable} // Desabilita se não estiver em modo editável
/>
<span className={EstiloNovoAtendimento.labelAtividade}>
{statusMap[statusItem]}
</span>
</label>
))}
</div>
</div>
{/* Botões de "Confirmar" e "Cancelar" */}
{isEditable && (
<div className={EstiloNovoAtendimento.CardBotton}>
<button onClick={handleConfirmClick}>Confirmar</button>
<button onClick={handleCancelClick}>Cancelar</button>
</div>
)}
</div>
);
};
export default EditarProcedimento;
Alterações no Componente Anexo
Agora, precisamos ajustar o componente Anexo para que ele utilize a prop isEditable para bloquear a adição de novos anexos quando não estiver em modo de edição:
import React, { useState } from "react";
import { useApi } from "../../lib/doctorApi";
import EstiloNovoAtendimento from "../Atendimentos/NovoAtendimento.module.css";
import { AppointmentRequestDTO, Attachment } from "../Atendimentos/types";
import { v4 as uuidv4 } from "uuid";
interface AnexoInterface {
attachments: Attachment[];
setAttachments: (anexos: Attachment[]) => void;
isEditable: boolean; // Adicione isto para controlar a edição
}
const Anexo: React.FC<AnexoInterface> = ({ attachments, setAttachments, isEditable }) => {
const [loading, setLoading] = useState(false);
const [showPopup, setShowPopup] = useState(false);
const [DownloadPopup, setDownloadPopup] = useState(false);
const [fileToDelete, setFileToDelete] = useState<Attachment | null>(null);
const [fileToDownload, setFileToDownload] = useState<Attachment | null>(null);
const [confirmationInput, setConfirmationInput] = useState("");
const api = useApi();
const [id] = useState(uuidv4());
const handleFileChange = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
if (!isEditable) return; // Impede a adição de novos anexos se não estiver em modo editável
setLoading(true);
const formData = new FormData();
const files = event.target.files;
if (files) {
Array.from(files).forEach((file) => {
formData.append("files", file);
});
try {
const uploadResult = await api.post("files/upload", formData);
if (
uploadResult.data.success &&
Array.isArray(uploadResult.data.result)
) {
const novosAnexos = [...attachments, ...uploadResult.data.result];
setAttachments(novosAnexos);
}
} catch (error) {
console.error("Erro ao enviar anexos:", error);
}
}
setLoading(false);
};
const initiateDelete = (anexo: Attachment) => {
setFileToDelete(anexo);
setShowPopup(true);
};
const initiateDownload = (anexo: Attachment) => {
setFileToDownload(anexo);
setDownloadPopup(true);
};
const handleDelete = async () => {
if (fileToDelete) {
try {
await api.del(`files/delete/${fileToDelete.id}`);
const novosAnexos = attachments.filter(
(anexo) => anexo.id !== fileToDelete.id
);
setAttachments(novosAnexos);
} catch (error) {
console.error("Erro ao excluir anexo:", error);
} finally {
setShowPopup(false);
setFileToDelete(null);
setConfirmationInput("");
}
}
};
const handleDownload = async () => {
if (fileToDownload) {
try {
// Fazendo um GET para o arquivo
const response = await api.get(`files/download/${fileToDownload.id}`, {
responseType: "blob", // Define o tipo de resposta como blob
});
// Criar um link temporário para o download
const url = window.URL.createObjectURL(new Blob([response.data]));
// Criar um elemento <a> para fazer o download
const a = document.createElement("a");
a.style.display = "none"; // Não exibe o link
a.href = url;
a.download = fileToDownload.fileName; // Define o nome do arquivo
// Anexa o elemento ao body da página
document.body.appendChild(a);
a.click(); // Dispara o download
// Limpa o URL criado
window.URL.revokeObjectURL(url);
setDownloadPopup(false);
} catch (error) {
console.error("Erro ao baixar o arquivo:", error);
}
}
};
return (
<div className={EstiloNovoAtendimento.divAnexosNew}>
<input
type="file"
multiple
onChange={handleFileChange}
style={{ display: "none" }}
id={`fileInput-${id}`}
/>
<label
htmlFor={`fileInput-${id}`}
className={EstiloNovoAtendimento.anexar}
style={{ pointerEvents: isEditable ? "auto" : "none", opacity: isEditable ? 1 : 0.5 }} // Desabilitar interação quando não está editável
>
<img src="/+.png" alt="" className={EstiloNovoAtendimento.iconAnexar} />
<i>Adicionar Novo Anexo</i>
</label>
<div className={EstiloNovoAtendimento.divSalvarAnexo}>
<label className={EstiloNovoAtendimento.labelAnexo}>Anexos:</label>
<div className={EstiloNovoAtendimento.divArquivoId}>
{attachments.length > 0 &&
attachments.map((anexo) => (
<div className={EstiloNovoAtendimento.divArquivo} key={anexo.id}>
<label className={EstiloNovoAtendimento.Arquivo}>
{anexo.fileName}
</label>
<div className={EstiloNovoAtendimento.divButton}>
<button
className={EstiloNovoAtendimento.divButton}
onClick={() => initiateDelete(anexo)}
>
<img src="lixeira.png" alt="Excluir" />
<p>Excluir</p>
</button>
<button
className={EstiloNovoAtendimento.divButton}
onClick={() => initiateDownload(anexo)} // Ação de download
>
<img src="baixarCinza.png" alt="Baixar" />
<p>Baixar</p>
</button>
</div>
</div>
))}
</div>
</div>
{/* Popup de confirmação */}
{showPopup && (
<>
<div className={EstiloNovoAtendimento.overlay} />
<div className={EstiloNovoAtendimento.popup}>
<strong className={EstiloNovoAtendimento.ArquivoPopup}>
{fileToDelete?.fileName}
</strong>
<p className={EstiloNovoAtendimento.p1}>
Deseja excluir o arquivo?
</p>
<p className={EstiloNovoAtendimento.p2}>
Para confirmar a exclusão
</p>
<p className={EstiloNovoAtendimento.p2}>
permanente deste arquivo, digite
</p>
<strong>"apagar"</strong>
<input
className={EstiloNovoAtendimento.inputExcluir}
type="text"
value={confirmationInput}
onChange={(e) => setConfirmationInput(e.target.value)}
placeholder="'apagar'"
/>
<button
className={`${EstiloNovoAtendimento.buttonExcluir} ${
confirmationInput === "apagar"
? EstiloNovoAtendimento.avaliado
: ""
}`}
onClick={handleDelete}
disabled={confirmationInput !== "apagar"}
>
<div className={EstiloNovoAtendimento.detalhe}>
<p>Excluir</p>
<img src="lixoPng.png" alt="" />
</div>
</button>
<button
className={EstiloNovoAtendimento.buttonCancelar}
onClick={() => setShowPopup(false)}
>
Cancelar
</button>
</div>
</>
)}
{DownloadPopup && (
<>
<div className={EstiloNovoAtendimento.overlay} />
<div className={EstiloNovoAtendimento.popup}>
<strong className={EstiloNovoAtendimento.ArquivoPopup}>
{fileToDownload?.fileName}
</strong>
<p className={EstiloNovoAtendimento.p1}>
Deseja Baixar este arquivo?
</p>
<button
className={EstiloNovoAtendimento.buttonCancelar}
onClick={handleDownload}
>
Baixar Arquivo
</button>
<button
className={EstiloNovoAtendimento.buttonExcluir}
onClick={() => setDownloadPopup(false)}
>
Cancelar
</button>
</div>
</>
)}
</div>
);
};
export default Anexo;
Resumo das Alterações
-
Componente EditarProcedimento:
- O componente
Anexo é sempre renderizado, e agora você está passando o estado isEditable para ele.
-
Componente Anexo:
- O botão para adicionar novos anexos foi modificado para que o elemento
<label> que ativa o input de arquivo seja desabilitado de interações (grayscale effect) quando não está em modo de edição (isEditable), mas ainda assim é possível ver os anexos existentes.
- O manipulador de arquivos verifica se está em modo editável e evita que novos anexos sejam adicionados caso contrário.
Com essas alterações, o componente só permitirá adicionar anexos enquanto estiver em modo editável, mas ainda exibirá todos os anexos que já foram adicionados previamente.