From bda4109f0fa6ac35eb4c983a3a7402afe17da18b Mon Sep 17 00:00:00 2001 From: jos3duardo Date: Thu, 28 Aug 2025 23:39:46 -0400 Subject: [PATCH] Add multiple file upload UI and localStorage save to CriarDocumento --- app/components/criarDocumento.mjs | 160 ++++++++++++++++++++++++++++-- 1 file changed, 152 insertions(+), 8 deletions(-) diff --git a/app/components/criarDocumento.mjs b/app/components/criarDocumento.mjs index 9206ebe..9b8c00b 100644 --- a/app/components/criarDocumento.mjs +++ b/app/components/criarDocumento.mjs @@ -3,36 +3,180 @@ import { gql } from "@apollo/client/core"; import { useApolloClient } from "@apollo/client/react/hooks/useApolloClient.js"; import { useMutation } from "@apollo/client/react/hooks/useMutation.js"; +import { useState } from "react"; import { createElement as h } from "react"; const CRIAR_DOCUMENTO = gql` mutation CriarDocumento($arquivo: [Upload!]!, $input: CreateDocumentoInput!) { criarDocumento(arquivo: $arquivo, input: $input) { id + situacao + arquivoAtual + chave } } `; export default function CriarDocumento() { - const [multipleUploadMutation] = useMutation(CRIAR_DOCUMENTO); + const [multipleUploadMutation, { loading }] = useMutation(CRIAR_DOCUMENTO); const apolloClient = useApolloClient(); + const [selectedFiles, setSelectedFiles] = useState([]); /** @type {import("react").ChangeEventHandler} */ - function onChange({ target: { validity, files } }) { - if (validity.valid && files && files[0]) { - multipleUploadMutation({ + function onChange({ target: { validity, files }, target }) { + if (validity.valid && files && files.length > 0) { + // Adiciona os novos arquivos aos já selecionados + const newFiles = Array.from(files); + setSelectedFiles((prevFiles) => [...prevFiles, ...newFiles]); + + // Limpa o input para permitir selecionar os mesmos arquivos novamente + target.value = ""; + } + } + + function removeFile(indexToRemove) { + setSelectedFiles((prevFiles) => + prevFiles.filter((_, index) => index !== indexToRemove), + ); + } + + function saveDocumentToStorage(document) { + const existingDocs = JSON.parse(localStorage.getItem("documentos") || "[]"); + const updatedDocs = [ + ...existingDocs, + { ...document, timestamp: new Date().toISOString() }, + ]; + localStorage.setItem("documentos", JSON.stringify(updatedDocs)); + } + + async function handleSubmit() { + if (selectedFiles.length === 0) { + alert("Selecione pelo menos um arquivo"); + return; + } + + try { + const result = await multipleUploadMutation({ variables: { - arquivo: Array.from(files), + arquivo: selectedFiles, input: { modeloId: 26, fluxoId: 33, }, }, - }).then(() => { - apolloClient.resetStore(); }); + + // Salva o documento no localStorage + if (result.data && result.data.criarDocumento) { + saveDocumentToStorage(result.data.criarDocumento); + } + + // Limpa os arquivos selecionados após o envio + setSelectedFiles([]); + + // Reseta o store do Apollo + apolloClient.resetStore(); + + alert("Documentos enviados com sucesso!"); + + // Dispara evento customizado para atualizar a tabela + window.dispatchEvent(new CustomEvent("documentoCreated")); + } catch (error) { + console.error("Erro ao enviar documentos:", error); + alert("Erro ao enviar documentos. Tente novamente."); } } - return h("input", { type: "file", multiple: true, required: true, onChange }); + return h("div", { style: { padding: "20px" } }, [ + // Input para selecionar arquivos + h("div", { key: "input-section", style: { marginBottom: "20px" } }, [ + h( + "label", + { key: "label", style: { display: "block", marginBottom: "10px" } }, + "Selecionar Arquivos:", + ), + h("input", { + key: "file-input", + type: "file", + multiple: true, + onChange, + style: { marginBottom: "10px" }, + }), + ]), + + // Lista de arquivos selecionados + selectedFiles.length > 0 && + h( + "div", + { + key: "files-section", + style: { marginBottom: "20px" }, + }, + [ + h( + "h3", + { key: "title" }, + `Arquivos selecionados (${selectedFiles.length}):`, + ), + h( + "ul", + { key: "files-list", style: { listStyle: "none", padding: 0 } }, + selectedFiles.map((file, index) => + h( + "li", + { + key: index, + style: { + display: "flex", + justifyContent: "space-between", + alignItems: "center", + padding: "5px 0", + borderBottom: "1px solid #eee", + }, + }, + [ + h("span", { key: "filename" }, file.name), + h( + "button", + { + key: "remove-btn", + onClick: () => removeFile(index), + style: { + background: "#ff4444", + color: "white", + border: "none", + borderRadius: "3px", + padding: "2px 8px", + cursor: "pointer", + }, + }, + "Remover", + ), + ], + ), + ), + ), + ], + ), + + // Botão de envio + h( + "button", + { + key: "submit-btn", + onClick: handleSubmit, + disabled: loading || selectedFiles.length === 0, + style: { + background: selectedFiles.length === 0 ? "#ccc" : "#007bff", + color: "white", + border: "none", + borderRadius: "5px", + padding: "10px 20px", + fontSize: "16px", + cursor: selectedFiles.length === 0 ? "not-allowed" : "pointer", + }, + }, + loading ? "Enviando..." : "Enviar Documentos", + ), + ]); }