Compare commits

...

4 Commits

4 changed files with 368 additions and 10 deletions

View File

@ -0,0 +1,207 @@
// @ts-check
import { useState, useEffect } from "react";
import { createElement as h } from "react";
export default function TabelaDocumentos() {
const [documentos, setDocumentos] = useState([]);
function loadDocuments() {
const docs = JSON.parse(localStorage.getItem('documentos') || '[]');
// Ordena por timestamp mais recente primeiro
const sortedDocs = docs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
setDocumentos(sortedDocs);
}
function clearAllDocuments() {
localStorage.removeItem('documentos');
setDocumentos([]);
}
function removeDocument(index) {
const updatedDocs = documentos.filter((_, i) => i !== index);
localStorage.setItem('documentos', JSON.stringify(updatedDocs));
setDocumentos(updatedDocs);
}
useEffect(() => {
// Carrega documentos ao montar o componente
loadDocuments();
// Escuta evento customizado para recarregar quando novo documento é criado
function handleDocumentCreated() {
loadDocuments();
}
window.addEventListener('documentoCreated', handleDocumentCreated);
return () => {
window.removeEventListener('documentoCreated', handleDocumentCreated);
};
}, []);
if (documentos.length === 0) {
return h('div', { style: { padding: '20px', textAlign: 'center', color: '#666' } },
'Nenhum documento encontrado'
);
}
return h('div', { style: { padding: '20px' } }, [
// Cabeçalho com botão limpar
h('div', {
key: 'header',
style: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '20px'
}
}, [
h('span', { key: 'count' }, `Total: ${documentos.length} documento(s)`),
h('button', {
key: 'clear-btn',
onClick: clearAllDocuments,
style: {
background: '#dc3545',
color: 'white',
border: 'none',
borderRadius: '3px',
padding: '5px 10px',
cursor: 'pointer'
}
}, 'Limpar Todos')
]),
// Tabela
h('div', { key: 'table-container', style: { overflowX: 'auto' } },
h('table', {
style: {
width: '100%',
borderCollapse: 'collapse',
border: '1px solid #ddd'
}
}, [
// Cabeçalho da tabela
h('thead', { key: 'thead' },
h('tr', { style: { backgroundColor: '#f8f9fa' } }, [
h('th', {
key: 'th-id',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'left'
}
}, 'ID'),
h('th', {
key: 'th-situacao',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'left'
}
}, 'Situação'),
h('th', {
key: 'th-arquivo',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'left'
}
}, 'Arquivo Atual'),
h('th', {
key: 'th-chave',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'left'
}
}, 'Chave'),
h('th', {
key: 'th-data',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'left'
}
}, 'Data/Hora'),
h('th', {
key: 'th-acoes',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'center'
}
}, 'Ações')
])
),
// Corpo da tabela
h('tbody', { key: 'tbody' },
documentos.map((doc, index) =>
h('tr', {
key: index,
style: { backgroundColor: index % 2 === 0 ? 'white' : '#f8f9fa' }
}, [
h('td', {
key: 'td-id',
style: {
border: '1px solid #ddd',
padding: '12px'
}
}, doc.id || 'N/A'),
h('td', {
key: 'td-situacao',
style: {
border: '1px solid #ddd',
padding: '12px'
}
}, doc.situacao || 'N/A'),
h('td', {
key: 'td-arquivo',
style: {
border: '1px solid #ddd',
padding: '12px'
}
}, doc.arquivoAtual || 'N/A'),
h('td', {
key: 'td-chave',
style: {
border: '1px solid #ddd',
padding: '12px'
}
}, doc.chave || 'N/A'),
h('td', {
key: 'td-data',
style: {
border: '1px solid #ddd',
padding: '12px'
}
}, new Date(doc.timestamp).toLocaleString('pt-BR')),
h('td', {
key: 'td-acoes',
style: {
border: '1px solid #ddd',
padding: '12px',
textAlign: 'center'
}
},
h('button', {
onClick: () => removeDocument(index),
style: {
background: '#dc3545',
color: 'white',
border: 'none',
borderRadius: '3px',
padding: '4px 8px',
cursor: 'pointer',
fontSize: '12px'
}
}, 'Remover')
)
])
)
)
])
)
]);
}

View File

@ -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<HTMLInputElement>} */
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",
),
]);
}

View File

@ -21,7 +21,8 @@ import nextApp from "next/app.js";
import nextHead from "next/head.js";
import { createElement as h, Fragment } from "react";
let token = process.env.API_TOKEN;
let token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NSIsImVtYWlsIjoibXJlaXNAZ3J1cG9pbWFnZXRlY2guY29tLmJyIiwibm9tZSI6Ik1lbGFuaWUgWMOqbmlhIiwibm9tZUNvbXBsZXRvIjoiTWVsYW5pZSBYw6puaWEgRmVycmVpcmEgUmVpcyIsInBlcm1pdGVBdHJpYnVpckRvY3VtZW50byI6IlMiLCJ0eXBlIjoiYXV0aCIsInZpbmN1bG9zIjpbeyJ1bmlkYWRlIjoxMiwiY2FyZ29GdW5jYW8iOlsiNCIsIjciXX0seyJ1bmlkYWRlIjoyOCwiY2FyZ29GdW5jYW8iOlsiNyJdfV0sImVtcHJlc2FzIjpbeyJub21lIjoiaW1hZ2V0ZWNoIiwiY29kaWdvIjoiR0VPSTIifSx7Im5vbWUiOiJzaG9wIiwiY29kaWdvIjoiU0hPT1AifV0sImlhdCI6MTc1NjQwNzM4NSwiZXhwIjoxNzg3OTY0OTg1fQ.EBiLSnRtdpMP57LEIPelGpDQiwwvFy3g77123sAQQpg";
const createApolloClient = (cache = {}) =>
new ApolloClient({

View File

@ -8,6 +8,7 @@ import Header from "../components/Header.mjs";
import Page from "../components/Page.mjs";
import Section from "../components/Section.mjs";
import CriarDocumento from "../components/criarDocumento.mjs";
import TabelaDocumentos from "../components/TabelaDocumentos.mjs";
export default function IndexPage() {
return h(
@ -21,6 +22,11 @@ export default function IndexPage() {
h(Margin, null, h(CriarDocumento)),
),
h(Section, null),
h(Section, null, h(Header, null, h(Heading, null, "Documentos Recentes"))),
h(
Section,
null,
h(Header, null, h(Heading, null, "Documentos Recentes")),
h(Margin, null, h(TabelaDocumentos)),
),
);
}